ZhouWenTao/.obsidian/plugins/editing-toolbar/main.js

12 lines
682 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use strict";var e=require("obsidian"),t=require("@codemirror/language"),o=require("@codemirror/state"),n=require("@codemirror/view");const i=["Custom","editingToolbar","editingToolbarSub","editingToolbarAdd","editingToolbarDelete","editingToolbarReload","codeblock-glyph","underline-glyph","superscript-glyph","subscript-glyph","bot-glyph","header-1","header-2","header-3","header-4","header-5","header-6","header-n","obsidian","obsidian-new","accessibility","activity","air-vent","airplay","alarm-check","alarm-clock-off","alarm-clock","alarm-minus","alarm-plus","album","alert-circle","alert-octagon","alert-triangle","align-center-horizontal","align-center-vertical","align-center","align-end-horizontal","align-end-vertical","align-horizontal-distribute-center","align-horizontal-distribute-end","align-horizontal-distribute-start","align-horizontal-justify-center","align-horizontal-justify-end","align-horizontal-justify-start","align-horizontal-space-around","align-horizontal-space-between","align-justify","align-left","align-right","align-start-horizontal","align-start-vertical","align-vertical-distribute-center","align-vertical-distribute-end","align-vertical-distribute-start","align-vertical-justify-center","align-vertical-justify-end","align-vertical-justify-start","align-vertical-space-around","align-vertical-space-between","anchor","angry","annoyed","aperture","apple","archive-restore","archive","armchair","arrow-big-down","arrow-big-left","arrow-big-right","arrow-big-up","arrow-down-circle","arrow-down-left","arrow-down-right","arrow-down","arrow-left-circle","arrow-left-right","arrow-left","arrow-right-circle","arrow-right","arrow-up-circle","arrow-up-left","arrow-up-right","arrow-up","asterisk","at-sign","award","axe","axis-3d","baby","backpack","baggage-claim","banana","banknote","bar-chart-2","bar-chart-3","bar-chart-4","bar-chart-horizontal","bar-chart","baseline","bath","battery-charging","battery-full","battery-low","battery-medium","battery","beaker","bed-double","bed-single","bed","beer","bell-minus","bell-off","bell-plus","bell-ring","bell","bike","binary","bitcoin","bluetooth-connected","bluetooth-off","bluetooth-searching","bluetooth","bold","bomb","bone","book-open","book","bookmark-minus","bookmark-plus","bookmark","bot","box-select","box","boxes","briefcase","brush","bug","building-2","building","bus","cake","calculator","calendar-check-2","calendar-check","calendar-clock","calendar-days","calendar-heart","calendar-minus","calendar-off","calendar-plus","calendar-range","calendar-search","calendar-x2","calendar-x","calendar","camera-off","camera","car","carrot","cast","check-circle-2","check-circle","check-square","check","chef-hat","cherry","chevron-down","chevron-first","chevron-last","chevron-left","chevron-right","chevron-up","chevrons-down-up","chevrons-down","chevrons-left-right","chevrons-left","chevrons-right-left","chevrons-right","chevrons-up-down","chevrons-up","chrome","cigarette-off","cigarette","circle-dot","circle-ellipsis","circle-slashed","circle","citrus","clapperboard","clipboard-check","clipboard-copy","clipboard-edit","clipboard-list","clipboard-signature","clipboard-type","clipboard-x","clipboard","clock-1","clock-10","clock-11","clock-12","clock-2","clock-3","clock-4","clock-5","clock-6","clock-7","clock-8","clock-9","clock","cloud-cog","cloud-drizzle","cloud-fog","cloud-hail","cloud-lightning","cloud-moon-rain","cloud-moon","cloud-off","cloud-rain-wind","cloud-rain","cloud-snow","cloud-sun-rain","cloud-sun","cloud","cloudy","clover","code-2","code","codepen","codesandbox","coffee","cog","coins","columns","command","compass","component","contact","contrast","cookie","copy","copyleft","copyright","corner-down-left","corner-down-right","corner-left-down","corner-left-up","corner-right-down","corner-right-up","corner-up-left","corner-up-right","cpu","credit-card","croissant","crop","cross","crosshair","crown","cup-soda","curly-braces","currency","database","delete","diamond","dice-1","dice-2","dice-3","dice-4","dice-5","dice-6","dices","diff","disc","divide-circle","divide-square","divide","dollar-sign","download-cloud","download","dribbble","droplet","droplets","drumstick","edit-2","edit-3","edit","egg-fried","egg","equal-not","equal","eraser","euro","expand","external-link","eye-off","eye","facebook","factory","fast-forward","feather","figma","file-archive","file-audio-2","file-audio","file-axis-3d","file-badge-2","file-badge","file-bar-chart-2","file-bar-chart","file-box","file-check-2","file-check","file-clock","file-code","file-cog-2","file-cog","file-diff","file-digit","file-down","file-edit","file-heart","file-image","file-input","file-json-2","file-json","file-key-2","file-key","file-line-chart","file-lock-2","file-lock","file-minus-2","file-minus","file-output","file-pie-chart","file-plus-2","file-plus","file-question","file-scan","file-search-2","file-search","file-signature","file-spreadsheet","file-symlink","file-terminal","file-text","file-type-2","file-type","file-up","file-video-2","file-video","file-volume-2","file-volume","file-warning","file-x2","file-x","file","files","film","filter","fingerprint","flag-off","flag-triangle-left","flag-triangle-right","flag","flame","flashlight-off","flashlight","flask-conical","flask-round","flip-horizontal-2","flip-horizontal","flip-vertical-2","flip-vertical","flower-2","flower","focus","folder-archive","folder-check","folder-clock","folder-closed","folder-cog-2","folder-cog","folder-down","folder-edit","folder-heart","folder-input","folder-key","folder-lock","folder-minus","folder-open","folder-output","folder-plus","folder-search-2","folder-search","folder-symlink","folder-tree","folder-up","folder-x","folder","folders","form-input","forward","frame","framer","frown","fuel","function-square","gamepad-2","gamepad","gauge","gavel","gem","ghost","gift","git-branch-plus","git-branch","git-commit","git-compare","git-fork","git-merge","git-pull-request-closed","git-pull-request-draft","git-pull-request","github","gitlab","glass-water","glasses","globe-2","globe","grab","graduation-cap","grape","grid","grip-horizontal","grip-vertical","hammer","hand-metal","hand","hard-drive","hard-hat","hash","haze","headphones","heart-crack","heart-handshake","heart-off","heart-pulse","heart","help-circle","hexagon","highlighter","history","home","hourglass","ice-cream","image-minus","image-off","image-plus","image","import","inbox","indent","indian-rupee","infinity","info","inspect","instagram","italic","japanese-yen","joystick","key","keyboard","lamp-ceiling","lamp-desk","lamp-floor","lamp-wall-down","lamp-wall-up","lamp","landmark","languages","laptop-2","laptop","lasso-select","lasso","laugh","layers","layout-dashboard","layout-grid","layout-list","layout-template","layout","leaf","library","life-buoy","lightbulb-off","lightbulb","line-chart","link-2off","link-2","link","linkedin","list-checks","list-end","list-minus","list-music","list-ordered","list-plus","list-start","list-video","list-x","list","loader-2","loader","locate-fixed","locate-off","locate","lock","log-in","log-out","luggage","magnet","mail-check","mail-minus","mail-open","mail-plus","mail-question","mail-search","mail-warning","mail-x","mail","mails","map-pin-off","map-pin","map","martini","maximize-2","maximize","medal","megaphone-off","megaphone","meh","menu","message-circle","message-square","mic-2","mic-off","mic","microscope","milestone","minimize-2","minimize","minus-circle","minus-square","minus","monitor-off","monitor-speaker","monitor","moon","more-horizontal","more-vertical","mountain-snow","mountain","mouse-pointer-2","mouse-pointer-click","mouse-pointer","mouse","move-3d","move-diagonal-2","move-diagonal","move-horizontal","move-vertical","move","music-2","music-3","music-4","music","navigation-2off","navigation-2","navigation-off","navigation","network","newspaper","octagon","option","outdent","package-2","package-check","package-minus","package-open","package-plus","package-search","package-x","package","paint-bucket","paintbrush-2","paintbrush","palette","palmtree","paperclip","party-popper","pause-circle","pause-octagon","pause","pen-tool","pencil","percent","person-standing","phone-call","phone-forwarded","phone-incoming","phone-missed","phone-off","phone-outgoing","phone","pie-chart","piggy-bank","pin-off","pin","pipette","pizza","plane","play-circle","play","plug-zap","plus-circle","plus-square","plus","pocket","podcast","pointer","pound-sterling","power-off","power","printer","puzzle","qr-code","quote","radio-receiver","radio","recycle","redo-2","redo","refresh-ccw","refresh-cw","regex","repeat-1","repeat","reply-all","reply","rewind","rocket","rocking-chair","rotate-3d","rotate-ccw","rotate-cw","rss","ruler","russian-ruble","save","scale-3d","scale","scaling","scan-face","scan-line","scan","scissors","screen-share-off","screen-share","scroll","search","send","separator-horizontal","separator-vertical","server-cog","server-crash","server-off","server","settings-2","settings","share-2","share","sheet","shield-alert","shield-check","shield-close","shield-off","shield","shirt","shopping-bag","shopping-cart","shovel","shrink","shrub","shuffle","sidebar-close","sidebar-open","sidebar","sigma","signal-high","signal-low","signal-medium","signal-zero","signal","siren","skip-back","skip-forward","skull","slack","slash","slice","sliders-horizontal","sliders","smartphone-charging","smartphone","smile-plus","smile","snowflake","sofa","sort-asc","sort-desc","speaker","sprout","square","star-half","star-off","star","stethoscope","sticker","sticky-note","stop-circle","stretch-horizontal","stretch-vertical","strikethrough","subscript","sun-dim","sun-medium","sun-moon","sun-snow","sun","sunrise","sunset","superscript","swiss-franc","switch-camera","sword","swords","syringe","table-2","table","tablet","tag","tags","target","tent","terminal-square","terminal","text-cursor-input","text-cursor","thermometer-snowflake","thermometer-sun","thermometer","thumbs-down","thumbs-up","ticket","timer-off","timer-reset","timer","toggle-left","toggle-right","tornado","toy-brick","train","trash-2","trash","tree-deciduous","tree-pine","trees","trello","trending-down","trending-up","triangle","trophy","truck","tv-2","tv","twitch","twitter","type","umbrella","underline","undo-2","undo","unlink-2","unlink","unlock","upload-cloud","upload","usb","user-check","user-cog","user-minus","user-plus","user-x","user","users","utensils-crossed","utensils","venetian-mask","verified","vibrate-off","vibrate","video-off","video","view","voicemail","volume-1","volume-2","volume-x","volume","wallet","wand-2","wand","watch","waves","webcam","webhook","wifi-off","wifi","wind","wine","wrap-text","wrench","x-circle","x-octagon","x-square","x","youtube","zap-off","zap","zoom-in","zoom-out","create-new","trash","search","right-triangle","document","folder","pencil","left-arrow","right-arrow","three-horizontal-bars","dot-network","audio-file","image-file","pdf-file","gear","documents","blocks","go-to-file","presentation","cross-in-box","microphone","microphone-filled","two-columns","link","popup-open","checkmark","hashtag","left-arrow-with-tail","right-arrow-with-tail","up-arrow-with-tail","down-arrow-with-tail","lines-of-text","vertical-three-dots","pin","magnifying-glass","info","horizontal-split","vertical-split","calendar-with-checkmark","folder-minus","sheets-in-box","up-and-down-arrows","broken-link","cross","any-key","reset","star","crossed-star","dice","filled-pin","enter","help","vault","open-vault","paper-plane","bullet-list","uppercase-lowercase-a","star-list","expand-vertically","languages","switch","pane-layout","install","sync","check-in-circle","sync-small","check-small","paused","forward-arrow","stacked-levels","bracket-glyph","note-glyph","tag-glyph","price-tag-glyph","heading-glyph","bold-glyph","italic-glyph","strikethrough-glyph","highlight-glyph","code-glyph","quote-glyph","link-glyph","bullet-list-glyph","number-list-glyph","checkbox-glyph","undo-glyph","redo-glyph","up-chevron-glyph","down-chevron-glyph","left-chevron-glyph","right-chevron-glyph","percent-sign-glyph","keyboard-glyph","double-up-arrow-glyph","double-down-arrow-glyph","image-glyph","wrench-screwdriver-glyph","clock","plus-with-circle","minus-with-circle","indent-glyph","unindent-glyph","fullscreen","exit-fullscreen","cloud","run-command","compress-glyph","enlarge-glyph","scissors-glyph","up-curly-arrow-glyph","down-curly-arrow-glyph","plus-minus-glyph","links-going-out","links-coming-in","add-note-glyph","duplicate-glyph","clock-glyph","calendar-glyph","command-glyph","dice-glyph","file-explorer-glyph","graph-glyph","import-glyph","navigate-glyph","open-elsewhere-glyph","presentation-glyph","paper-plane-glyph","question-mark-glyph","restore-file-glyph","search-glyph","star-glyph","play-audio-glyph","stop-audio-glyph","tomorrow-glyph","wand-glyph","workspace-glyph","yesterday-glyph","box-glyph","merge-files-glyph","merge-files","two-blank-pages","scissors","paste","paste-text","split","select-all-text","wand","github-glyph","reading-glasses","user-manual-filled","discord-filled","chat-bubbles-filled","experiment-filled","bracket-glyph","box-glyph","check-small","dice-glyph","dice","discord","right-triangle","heading-glyph","help","keyboard-toggle","broken-link","experiment","left-arrow","link","link-glyph","links-coming-in","links-going-out","open-vault","paused","question-mark-glyph","right-arrow","sidebar-left","sidebar-right","sheets-in-box","star-list","sync-small","tabs","uppercase-lowercase-a","vault","stack-horizontal","stack-vertical","stretch-horizontal","stretch-vertical","distribute-space-horizontal","distribute-space-vertical"];function a(e){let t=Date.now().toString(36);return t+=Math.random().toString(36).substr(3,e),t}function s(e,t,o,n){let i,a={index:-1,subindex:-1},s=n;return o?s.forEach((e,o)=>{if("SubmenuCommands"in e&&(i=e.SubmenuCommands.findIndex(e=>e.id==t.id),i>=0))return a={index:o,subindex:i},a}):(i=s.findIndex(e=>e.id==t.id),a={index:i,subindex:-1}),a}function r(e,t){const o=t.getLine(t.getCursor().line);let n,i="";const a=/^(\s*(?:>\s*)*(?:\[[!\w]+\]\s*)?)#{1,6}\s+/,s=/^(?:\s*(?:>\s*)*(?:\[[!\w]+\]\s*)?)?(?:(?:#{1,6}\s+)|(?:[-+*]\s+)|(?:\d+\.\s+)|(?:\[[ xX]\]\s+))+/,r=o.match(a),l=r?.[0]?.trim();e===l||""===e?n=o.replace(a,"$1"):(n=o.replace(s,"").trimStart(),n=`${e} ${n}`),i=""!==n?t.getRange(t.getCursor(),{line:t.getCursor().line,ch:o.length}):t.getRange(t.getCursor(),{line:t.getCursor().line,ch:0}),t.setLine(t.getCursor().line,n),t.setCursor({line:t.getCursor().line,ch:Number(n.length-i.length)})}function l(e,t){if(!t)return;const o=t.getSelection();if(!o||""===o.trim())return void this.plugin.setLastExecutedCommand("editing-toolbar:change-font-color");const n=/<font\s+color=["']?[^"'>]+["']?>(.*?)<\/font>/gms,i=n.test(o);if(a=o,new RegExp(`^<font\\s+color=["']?${e}["']?>(.+)<\\/font>$`,"ms").test(a.trim()))return;var a;const s=o.replace(n,(t,o)=>o.split("\n").map(t=>t.trim()?`<font color="${e}">${t}</font>`:t).join("\n")),r=s===o?o.split("\n").map(t=>t.trim()?`<font color="${e}">${t}</font>`:t).join("\n"):s,l=t.listSelections().map(t=>{const o=i?0:`<font color="${e}"></font>`.length;return t.anchor.line<t.head.line||t.anchor.line===t.head.line&&t.anchor.ch<t.head.ch?{anchor:{line:t.anchor.line,ch:t.anchor.ch},head:{line:t.head.line,ch:t.head.ch+o}}:{anchor:{line:t.anchor.line,ch:t.anchor.ch+o},head:{line:t.head.line,ch:t.head.ch}}});t.replaceSelection(r),t.setSelections(l)}function c(e,t){if(!t)return;const o=t.getSelection();if(!o||""===o.trim())return;const n=/<mark\s+style=["']?background:(?:#[0-9a-fA-F]{3,6}|rgba?\([^)]+\))["']?>([\s\S]*?)<\/mark>/g.test(o);if(((e,t)=>{const o=t.replace(/([()[{*+.$^\\|?])/g,"\\$1");return new RegExp(`^<mark\\s+style=["']?background:${o}["']?>([sS]+)<\\/mark>$`).test(e.trim())})(o,e))return;let i;i=n?o.replace(/(background:)(?:#[0-9a-fA-F]{3,6}|rgba?\([^)]+\))/gi,`$1${e}`):o.split("\n").map(t=>t.trim()?`<mark style="background:${e}">${t}</mark>`:t).join("\n");const a=t.listSelections().map(t=>{const o=n?0:`<mark style="background:${e}"></mark>`.length;return t.anchor.line<t.head.line||t.anchor.line===t.head.line&&t.anchor.ch<t.head.ch?{anchor:{line:t.anchor.line,ch:t.anchor.ch},head:{line:t.head.line,ch:t.head.ch+o}}:{anchor:{line:t.anchor.line,ch:t.anchor.ch+o},head:{line:t.head.line,ch:t.head.ch}}});t.replaceSelection(i),t.setSelections(a)}function d(o,n,i){let a=!1;for(const e of o)if(/^\s*\d+\.\s/.test(e.trim())){a=!0;break}if(!a)return;const s=app.workspace.getActiveViewOfType(e.MarkdownView)?.editor.cm;if(!s)return;const r=s.state,l=t.syntaxTree(r),c=i.posToOffset({line:n,ch:0});let d=-1;if(l.iterate({from:0,to:c,enter:e=>{"OrderedList"===e.name&&(d=e.to)}}),d>=0){const e=i.offsetToPos(d).line+1;e<n&&!/^\s*$/.test(i.getLine(e).trim())&&(i.replaceRange("\n",{line:e,ch:0},{line:e,ch:0}),n++)}let u=!0,m=[],p=-1;for(const e of o){const t=e.trim();if(/^\d+\.\s/.test(t)){const o=e.match(/^\s*/)?.[0].length||0,n=parseInt(t.match(/^\d+/)[0],10);if(m[o]=o!==p?1:(m[o]||1)+1,n!==m[o]){u=!1;break}p=o}}let h=[];const g=n-1,f=g>=0?i.getLine(g).trim():"";if(f&&!/^\s*$/.test(f)&&!f.includes("")&&(h.push(""),h.push("")),u)h.push(...o);else{let e={},t=-1;for(const n of o){const o=n.trim(),i=/^\d+\.\s/.test(o),a=n.match(/^\s*/)?.[0]||"";if(i){const n=a.length;e[n]=n!==t?1:(e[n]||1)+1,h.push(`${a}${e[n]}. ${o.replace(/^\d+\.\s/,"")}`),t=n}else h.push(n),t=-1}}i.replaceRange(h.join("\n"),{line:n,ch:0},{line:n+o.length-1,ch:i.getLine(n+o.length-1).length})}function u(e,t,o){const n=[];for(let i=t;i<=o;i++)n.push(e.getLine(i));d(n,t,e)}let m;const p=t=>{m=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;["top","following","fixed"].forEach(e=>{m.querySelectorAll(`.editingToolbarModalBar[data-toolbar-style="${e}"]`).forEach(e=>{t?(e.style.display="",e.style.visibility="visible"):e.style.display="none"})});const o=m.getElementById("editingToolbarModalBar");o&&(t?(o.style.display="",o.style.visibility="visible"):o.style.display="none")},h=t=>{m=e.requireApiVersion("0.15.0")?activeWindow.document:window.document,m.documentElement.style.setProperty("--toolbar-vertical-offset",`${t.verticalPosition}px`)},g=t=>{m=e.requireApiVersion("0.15.0")?activeWindow.document:window.document,m.documentElement.style.setProperty("--toolbar-horizontal-offset",`${t.horizontalPosition}px`)};var f={"Editing Toolbar Append Method":"Editing Toolbar Append Method","Choose where Editing Toolbar will append upon regeneration. To see the change, hit the refresh button below, or in the status bar menu.":"Choose where Editing Toolbar will append upon regeneration. To see the change, hit the refresh button below, or in the status bar menu.","Editing Toolbar aesthetic":"Editing Toolbar aesthetic","Choose between a glass morphism, tiny and default style for Editing Toolbar. To see the change, hit the refresh button below, or in the status bar menu.":"Choose between a glass morphism, tiny and default style for Editing Toolbar. To see the change, hit the refresh button below, or in the status bar menu.","Editing Toolbar position":"Editing Toolbar position","Choose between fixed position or cursor following mode.":"Choose between fixed position, cursor following or Top mode.","Editing Toolbar Columns":"Editing Toolbar Columns","Choose the number of columns per row to display on Editing Toolbar.":"Choose the number of columns per row to display on Editing Toolbar.","Editing Toolbar refresh":"Editing Toolbar refresh","Editing Toolbar Commands":"Editing Toolbar Commands","Add a command onto Editing Toolbar from Obsidian's commands library. To reorder the commands, drag and drop the command items. To delete them, use the delete buttom to the right of the command item. Editing Toolbar will not automaticaly refresh after reordering commands. Use the refresh button above.":"Add a command onto Editing Toolbar from Obsidian's commands library. To reorder the commands, drag and drop the command items. To delete them, use the delete buttom to the right of the command item. Editing Toolbar will not automaticaly refresh after reordering commands. Use the refresh button above.","Format Brush Off!":"Format Brush Off!","Hide & Show":"Hide & Show","Editing Toolbar will only refresh automatically after you have either added or deleted a command from it. To see UI changes to editingToolbar (above settings changes) use the refresh button. If you forget to refresh in settings, no worries. There is also a refresh button in the editingToolbar status bar menu.":"Editing Toolbar will only refresh automatically after you have either added or deleted a command from it. To see UI changes to editingToolbar (above settings changes) use the refresh button. If you forget to refresh in settings, no worries. There is also a refresh button in the editingToolbar status bar menu.","Font-Color formatting brush ON!":"Font-Color formatting brush ON!",More:"More","Copy commands from selected style.":"Copy commands from selected style.","Font Colors":"Font Colors","Format Brush":"Format Brush","Background Color":"Background color",Refresh:"Refresh",Add:"Add",Delete:"Delete","Change Command Name":"Change Command Name","Change Submenu Name":"Change Submenu Name","Button Submenu":"Button Submenu","Dropdown Menu":"Dropdown Menu","Menu type changed to":"Menu type changed to","Add Submenu":"Add Submenu","Add Separator":"Add Separator","Enter the icon code, it looks like <svg>.... </svg> format":"Enter the icon code, it looks like <svg>.... </svg> format","Please enter a new name: ":"Please enter a new name: ","Drag the slider to move the position":"Drag the slider to move the position","Plugin Settings":"Plugin Settings","Background-color formatting brush ON!":"Background-color formatting brush ON!\nClick the mouse middle or right key to close the formatting-brush","Clear formatting brush ON!":"Clear formatting brush ON!","Clear formatting brush ON!\nClick the mouse middle or right key to close the formatting-brush":"Clear formatting brush ON!\nClick the mouse middle or right key to close the formatting-brush","The toolbar is displayed when the mouse moves over it, otherwise it is automatically hidden":"The toolbar is displayed when the mouse moves over it, otherwise it is automatically hidden","Editing Toolbar Auto-hide":"Editing Toolbar Auto-hide","Editing Toolbar Centred Display":"Editing Toolbar Centred Display","Whether the toolbar is centred or full-width, the default is full-width.":"Whether the toolbar is centred or full-width, the default is full-width.","Custom Backgroud Color":"Custom Backgroud Color","Custom Font Color":"Custom Font Color","🎨 Set Custom Background":"🎨 Set Custom Background","🖌 Set Custom Font Color":"🖌 Set Custom Font Color","Click on the picker to adjust the color":"Click on the picker to adjust the color","Mobile Enabled or Not":"Mobile Enabled or Not","Whether to enable the plugin for the mobile client, the default is enabled.":"Whether to enable the plugin for the mobile client, the default is enabled.","Whether to enable on mobile devices with device width less than 768px.":"Whether to enable on mobile devices with device width less than 768px, the default is disable.",Reset:"Reset",Fix:"Fix","Fix Editing Toolbar":"Fix Editing Toolbar",General:"General",Appearance:"Appearance",Commands:"Commands","Choose between fixed position or cursor following mode":"Choose between fixed position, cursor following or Top mode.","Add and manage commands":"Add and manage commands","Choose where Editing Toolbar will append upon regeneration.":"Choose where Editing Toolbar will append upon regeneration.","Whether to enable on mobile devices with device width less than 768px":"Whether to enable on mobile devices with device width less than 768px","Choose between a glass morphism, tiny and default style.":"Choose between a glass morphism, tiny and default style.","Refresh Toolbar":"Refresh Toolbar","Add Command":"Add Command",Settings:"Settings","Position Style":"Position Style",Columns:"Columns","Drag to Adjust Position":"Drag to Adjust Position","Vertical Position":"Vertical Position","Horizontal Position":"Horizontal Position","Toolbar Position":"Toolbar Position","Choose an icon":"Choose an icon","Search for an icon...":"Search for an icon...",All:"All",Obsidian:"Obsidian",Glyph:"Glyph",Custom:"Custom","Choose a command":"Choose a command","The command":"The command","already exists":"already exists","Enter the icon code, format as <svg>.... </svg>":"Enter the icon code, format as <svg>.... </svg>","No matching icons found":"No matching icons found","Custom Commands":"Custom Commands","Toolbar Commands":"Toolbar Commands",ID:"ID",Prefix:"Prefix",Suffix:"Suffix",Pattern:"Pattern","Custom Format Commands":"Custom Format Commands","Add, edit or delete custom format commands.":"Add, edit or delete custom format commands.",Edit:"Edit","Command ID":"Command ID",'Unique identifier, no spaces, e.g.: "my-custom-format"':'Unique identifier, no spaces, e.g.: "my-custom-format"',"Displayed name in toolbar and menu":"Displayed name in toolbar and menu","Add content before selected text":"Add content before selected text","Add content after selected text":"Add content after selected text","Character offset of cursor after formatting":"Character offset of cursor after formatting","Line offset of cursor after formatting":"Line offset of cursor after formatting","Whether to insert at the beginning of the next line":"Whether to insert at the beginning of the next line","Command icon (click to select)":"Command icon (click to select)","Choose Icon":"Choose Icon",Save:"Save",Cancel:"Cancel","Edit Custom Command":"Edit Custom Command","Add Custom Command":"Add Custom Command","Command ID and command name cannot be empty":"Command ID and command name cannot be empty","Command ID cannot contain spaces":"Command ID cannot contain spaces",'Command ID "${this.commandId}" already exists':'Command ID "${this.commandId}" already exists',"Cursor Position Offset":"Cursor Position Offset","Line Offset":"Line Offset","Line Head Format":"Line Head Format",Icon:"Icon","Command Name":"Command Name","Are you sure you want to restore all settings to default? This will lose all your custom configurations.":"Are you sure you want to restore all settings to default? This will lose all your custom configurations.","Restore default":"Restore default","Restore default settings":"Restore default settings","🔄Restore default settings":"🔄Restore default settings","🔧Data repair":"🔧Data repair","Command IDs have been successfully repaired!":"Command IDs have been successfully repaired!","No command IDs need to be repaired":"No command IDs need to be repaired","Error repairing command IDs, please check the console for details":"Error repairing command IDs, please check the console for details","Error restoring default settings, please check the console for details":"Error restoring default settings, please check the console for details","Successfully restored default settings!":"Successfully restored default settings!",Close:"Close",Tips:"Tips","This update changed the ID of some commands, please click this button to repair the commands to ensure the toolbar works properly":"This update changed the ID of some commands, please click this button to repair the commands to ensure the toolbar works properly","Repair command ID":"Repair command ID","This will reset all your custom configurations":"This will reset all your custom configurations","Notice:":"Notice:","This update rebuilds the entire code, reducing resource consumption":"This update rebuilds the entire code, reducing resource consumption","Optimized mobile usage, added canvas support, and added custom commands":"Optimized mobile usage, added canvas support, and added custom commands","This update is not compatible with 2.x version command ids, please click [Repair command] to be compatible":"This update is not compatible with 2.x version command ids, please click [Repair command] to be compatible","If you want to restore the default settings, please click [Restore default settings]":"If you want to restore the default settings, please click [Restore default settings]","Please execute a editingToolbar format command first, then enable the format brush":"Please execute a editingToolbar format command first, then enable the format brush","Format brush ON! Select text to apply":"Format brush ON! Select text to apply","format":"format\nClick the mouse right key to close the formatting-brush","Add to Toolbar":"Add to Toolbar","This command is already in the toolbar.":"This command is already in the toolbar.","Command added to toolbar":"Command added to toolbar","Add this command to the toolbar.":"Add this command to the toolbar.","Callout Type":"Callout Type",Title:"Title","Optional, leave blank for default title":"Optional, leave blank for default title","Input title":"Input title","Collapse State":"Collapse State",Open:"Open",Closed:"Closed",Default:"Default",Content:"Content",Insert:"Insert","Input content":"Input content","Link Text":"Link Text","Link Alias":"Link Alias","Link URL":"Link URL","Embed Content":"Embed Content","Image Size":"Image Size","Insert New Line":"Insert New Line","Paste and Parse":"Paste and Parse","URL Format Error":"URL Format Error","Image Width":"Image Width","Image Height":"Image Height","If it is an image, turn on":"If it is an image, turn on","Insert a link on the next line":"Insert a link on the next line","Link Title(optional)":"Link Title(optional)",Alias:"Alias",Optional:"Optional","Default 0, format will keep the text selected":"Default 0, format will keep the text selected","to insert":"to insert","Latest Changes":"Latest Changes","📋View full changelog":"📋View full changelog","Open changelog":"Open changelog","Loading changelog...":"Loading changelog...","Open the complete changelog in your browser":"Open the complete changelog in your browser","Enable Multiple Configurations":"Enable Multiple Configurations","Enable different command configurations for each position style (following, top, fixed).":"Enable different command configurations for each position style (following, top, fixed).","Currently editing commands for":"Currently editing commands for","position style":"position style","Current Configuration":"Current Configuration","Switch between different command configurations.":"Switch between different command configurations.","Following Style":"Following Style","Top Style":"Top Style","Fixed Style":"Fixed Style","Mobile Style":"Mobile Style",configuration:"configuration","Deploy command to configurations":"Deploy command to configurations","All Configurations":"All Configurations",Deploy:"Deploy","Command deployed to selected configurations":"Command deployed to selected configurations","No configuration selected for deployment":"No configuration selected for deployment","Command already exists in selected configurations":"Command already exists in selected configurations","Command deployed to: ":"Command deployed to: ","Command Deleted":"Command Deleted","Confirm Delete?":"Confirm Delete?",Confirm:"Confirm","Are you sure you want to restore all settings to default? But custom commands will be preserved.":"Are you sure you want to restore all settings to default? But custom commands will be preserved.","Successfully restored default settings! (Custom commands preserved)":"Successfully restored default settings! (Custom commands preserved)","This will reset all your custom configurations, but custom commands will be preserved":"This will reset all your custom configurations, but custom commands will be preserved","Import/Export":"Import/Export","Export Configuration":"Export Configuration","Export your toolbar configuration to share with others.":"Export your toolbar configuration to share with others.",Export:"Export","Import Configuration":"Import Configuration","Import toolbar configuration from JSON.":"Import toolbar configuration from JSON.",Import:"Import","Usage Instructions":"Usage Instructions","Export: Generate a JSON configuration that you can save or share.":"Export: Generate a JSON configuration that you can save or share.","Import: Paste a previously exported JSON configuration.":"Import: Paste a previously exported JSON configuration.","You can choose to export all settings, only toolbar commands, or only custom commands":"You can choose to export all settings, only toolbar commands, or only custom commands","When importing, the plugin will only update the settings included in the import data":"When importing, the plugin will only update the settings included in the import data","Warning: Importing configuration will overwrite your current settings. Consider exporting your current configuration first as a backup.":"Warning: Importing configuration will overwrite your current settings. Consider exporting your current configuration first as a backup.","Export Type":"Export Type","Choose what to export":"Choose what to export","All Settings":"All Settings","Toolbar Commands Only":"Toolbar Commands Only","Custom Commands Only":"Custom Commands Only","Export Content":"Export Content","Copy this content to share with others":"Copy this content to share with others","Loading...":"Loading...","Copy to Clipboard":"Copy","Configuration copied to clipboard":"Configuration copied to clipboard","Failed to copy configuration":"Failed to copy configuration","Paste the configuration JSON here":"Paste the configuration JSON here","Paste configuration here...":"Paste configuration here...","Invalid import data":"Invalid import data","Configuration imported successfully":"Configuration imported successfully","No valid configuration found in import data":"No valid configuration found in import data","Failed to import configuration. Invalid format.":"Failed to import configuration. Invalid format.","Import Mode":"Import Mode","Choose how to import the configuration":"Choose how to import the configuration","Update Mode (Add new items and update existing ones)":"Update Mode (Add new items and update existing ones)","Overwrite Mode (Replace all settings with imported ones)":"Overwrite Mode (Replace all settings with imported ones)","Configuration imported successfully (Overwrite mode)":"Configuration imported successfully (Overwrite mode)","Configuration imported successfully (Update mode)":"Configuration imported successfully (Update mode)","Warning: Overwrite mode will completely replace your current settings with the imported ones. Consider exporting your current configuration first as a backup.":"Warning: Overwrite mode will completely replace your current settings with the imported ones. Consider exporting your current configuration first as a backup.","Warning: Update mode will add new items and update existing ones based on the imported configuration.":"Warning: Update mode will add new items and update existing ones based on the imported configuration.","Add Format Command":"Add Format Command",Regex:"Regex","Prefix/Suffix":"Prefix/Suffix","Insert Special Char":"Insert Special Char","Add Regex Command":"Add Regex Command","Switch Regex Command Window":"Switch Regex Command Window","Please select text first":"Please select text first","Place the cursor in a paragraph or select text first.":"Place the cursor in a paragraph or select text first.","Current line is empty, please select text or move to a non-empty line":"Current line is empty, please select text or move to a non-empty line","Use current line for regex commands":"Use current line for regex commands","When no text is selected, regex commands will use the current line instead of clipboard content":"When no text is selected, regex commands will use the current line instead of clipboard content","The selected text does not meet the condition requirements":"The selected text does not meet the condition requirements","Regex command execution error: ":"Regex command execution error: ","Copy code":"Copy code","Copied!":"Copied!","Explain the syntax of JavaScript regular expressions":"Explain the syntax of JavaScript regular expressions","Apply regular expression replacement":"Apply regular expression replacement","Conditional matching":"Conditional matching","Complete regular expression code (copy to AI for explanation)":"Complete regular expression code (copy to AI for explanation)","Error: ":"Error: ","Regex pattern cannot be empty":"Regex pattern cannot be empty","Command already exists":"Command already exists","Choose icon":"Choose icon","URL to Markdown link":"URL to Markdown link","Convert MM/DD/YYYY to YYYY-MM-DD":"Convert MM/DD/YYYY to YYYY-MM-DD","Add bold to keywords":"Add bold to keywords","Format phone number":"Format phone number","Remove extra spaces":"Remove extra spaces","Convert HTML bold tags to Markdown format":"Convert HTML bold tags to Markdown format","Convert quoted text to quote block":"Convert quoted text to quote block","Convert CSV to Markdown table row":"Convert CSV to Markdown table row","Add uniform alias to Markdown links":"Add uniform alias to Markdown links","Delete empty lines (multiline mode)":"Delete empty lines (multiline mode)","Add list symbol to each line (multiline mode)":"Add list symbol to each line (multiline mode)","If the text contains important, set the text highlight (conditional format)":"If the text contains important, set the text highlight (conditional format)","Matching pattern":"Matching pattern","Regex pattern to match":"Regex pattern to match","Replacement pattern (use $1, $2, etc. to reference capture groups)":"Replacement pattern (use $1, $2, etc. to reference capture groups)","Ignore case":"Ignore case","Global replace":"Global replace","Multiline mode":"Multiline mode","Use condition":"Use condition","Condition pattern":"Condition pattern","Only apply custom command when text matches the condition":"Only apply custom command when text matches the condition","Must exist regular expression or text":"Must exist regular expression or text","Replacement pattern":"Replacement pattern","Match case-insensitive":"Match case-insensitive","^ and $ match the start and end of each line":"^ and $ match the start and end of each line","Replace all matches":"Replace all matches",Command:"Command","Input example text to view the formatting effect of the command...":"Input example text to view the formatting effect of the command...",Description:"Description","[Example]":"[Example]","[Requirements]":"[Requirements]","[Output]":"[Output]","AI question template:":"AI question template:","I need to convert the url to a markdown format link":"I need to convert the url to a markdown format link","For example, convert https://example.com to [https://example.com](https://example.com)":"For example, convert https://example.com to [https://example.com](https://example.com)","Use js regular expression to implement, and output the parameters in the following format (the result does not need to be escaped with json)":"Use js regular expression to implement, and output the parameters in the following format (the result does not need to be escaped with json)","[Description]":"[Description]","How to use AI to get regular expressions?":"How to use AI to get regular expressions?","Regular expression examples":"Regular expression examples","Edit regular expression command":"Edit regular expression command","Add regular expression command":"Add regular expression command","Result: ":"Result: ","Example text:":"Example text:",Preview:"Preview",Result:"Result","Please select text or copy text to clipboard first":"Please select text or copy text to clipboard first","Overwrite Import":"Overwrite Import","Update Import":"Update Import","Importing configuration...":"Importing configuration...","Following Style Only":"Following Style Only","Top Style Only":"Top Style Only","Fixed Style Only":"Fixed Style Only","Mobile Style Only":"Mobile Style Only","Unknown import type":"Unknown import type","All Toolbar Commands":"All Toolbar Commands","Initialize Commands":"Initialize Commands","Copy commands from the main menu configuration":"Copy commands from the main menu configuration","Initialize commands to default settings":"Initialize commands to default settings","Reset Commands":"Reset Commands","Commands reset successfully":"Commands reset successfully","Following style commands initialized from current menu commands":"Following style commands initialized from current menu commands","Commands initialized successfully":"Commands initialized successfully","Reset to Menu Commands":"Reset to Menu Commands","Are you sure you want to reset the current configuration?":"Are you sure you want to reset the current configuration?","Following style commands successfully initialized":"Following style commands successfully initialized","Top style commands successfully initialized":"Top style commands successfully initialized","Fixed style commands successfully initialized":"Fixed style commands successfully initialized","Mobile style commands successfully initialized":"Mobile style commands successfully initialized","Reset commands to default settings":"Reset commands to default settings",Clear:"Clear","Remove all commands from this configuration.":"Remove all commands from this configuration.","Are you sure you want to clear all commands under the current style?":"Are you sure you want to clear all commands under the current style?","Current style commands have been cleared":"Current style commands have been cleared","Manage Commands":"Manage Commands","Reset or clear all commands in this configuration":"Reset or clear all commands in this configuration","One-click Clear":"One-click Clear","Import Commands from Other Styles":"Import Commands from Other Styles","Copy commands from another style configuration.":"Copy commands from another style configuration.","Main menu only":"Main menu only","This import will update:":"This import will update:","Custom commands":"Custom commands","Toolbar commands":"Toolbar commands","General settings":"General settings","Please paste configuration data first":"Please paste configuration data first","Invalid import data format":"Invalid import data format","Import From":"Import From","This import will:":"This import will:","Update general settings":"Update general settings","Update Main Menu Commands":"Update Main Menu Commands","Update Custom Commands":"Update Custom Commands","Update Following Style Commands":"Update Following Style Commands","Update Top Style Commands":"Update Top Style Commands","Update Fixed Style Commands":"Update Fixed Style Commands","Update Mobile Style Commands":"Update Mobile Style Commands","Clear all Main Menu Commands":"Clear all Main Menu Commands","Clear all Custom Commands":"Clear all Custom Commands","Clear all Following Style Commands":"Clear all Following Style Commands","Clear all Top Style Commands":"Clear all Top Style Commands","Clear all Fixed Style Commands":"Clear all Fixed Style Commands","Clear all Mobile Style Commands":"Clear all Mobile Style Commands","Overwrite Mode (Replace settings with imported ones)":"Overwrite Mode (Replace settings with imported ones)","Warning: Overwrite mode will replace existing settings with imported ones.":"Warning: Overwrite mode will replace existing settings with imported ones.","Warning: Update mode will add new items and update existing ones.":"Warning: Update mode will add new items and update existing ones.","Enable Multiple Config":"Enable Multiple Config","Set Multiple Config to:":"Set Multiple Config to:",Enable:"Enable",Disable:"Disable","Set Position Style to:":"Set Position Style to:",Following:"Following",Top:"Top",Fixed:"Fixed",Mobile:"Mobile","All commands":"All commands"," Overwrite mode will replace existing settings with imported ones.":" Overwrite mode will replace existing settings with imported ones."," Update mode will merge imported settings with existing ones.":" Update mode will merge imported settings with existing ones.","Do you want to continue?":"Do you want to continue?","Imported settings:":"Imported settings:","Imported commands:":"Imported commands:","Disable toolbar for this view":"Disable toolbar for this view","Enable toolbar for this view":"Enable toolbar for this view","Manage all view types":"Manage all view types","Current View: ":"Current View: ","Appearance Style":"Appearance Style","Position Settings":"Position Settings","All commands have been removed.":"All commands have been removed.","Join the Community":"Join the Community","Share your toolbar settings and styles in our":"Share your toolbar settings and styles in our","Get inspired by what others have created or showcase your own customizations.":"Get inspired by what others have created or showcase your own customizations.","Toolbar Preview (With a hypothetical command configuration.)":"Toolbar Preview (With a hypothetical command configuration.)","Toolbar Theme":"Toolbar Theme","Select a preset toolbar theme, automatically setting the background color, icon color, and size for the selected style.":"Select a preset toolbar theme, automatically setting the background color, icon color, and size for the selected style.","Toolbar Background Color":"Toolbar Background Color","Set the background color of the toolbar.":"Set the background color of the toolbar.","Toolbar Icon Color":"Toolbar Icon Color","Set the color of the toolbar icon.":"Set the color of the toolbar icon.","Toolbar Icon Size":"Toolbar Icon Size","Set the size of the toolbar icon (px); default: 18px":"Set the size of the toolbar icon (px); default: 18px","Custom Theme":"Custom Theme","Fixed Position Offset":"Fixed Position Offset","Choose the offset of the Editing Toolbar in the fixed position.":"Choose the offset of the Editing Toolbar in the fixed position.","Renumber List":"Renumber List","Fetch Remote Title":"Fetch Remote Title","Please enter a URL first":"Please enter a URL first","Failed to fetch title for":"Failed to fetch title for","Link Title (optional)":"Link Title (optional)","Unable to detect editor width":"Unable to detect editor width","Fit Editor Width":"Fit Editor Width","Please execute a format command or select format text first, then enable the format brush":"Please execute a format command or select format text first, then enable the format brush","Use \\n to represent line breaks":"Use \\n to represent line breaks","Use to represent line breaks":"Use to represent line breaks","Top Toolbar":"Top Toolbar","Enable the toolbar positioned at the top.":"Enable the toolbar positioned at the top.","Following Toolbar":"Following Toolbar","Enable the toolbar that appears upon text selection.":"Enable the toolbar that appears upon text selection.","Fixed Toolbar":"Fixed Toolbar","Enable the toolbar whose position may be fixed where you please.":"Enable the toolbar whose position may be fixed where you please.","Toolbar Settings":"Toolbar Settings","Choose which toolbar style's appearance you want to edit.":"Choose which toolbar style's appearance you want to edit.","Vertical Split":"Vertical Split","Text Enhancement Tools":"Text Enhancement Tools","Get Plain Text":"Get Plain Text","Full Half Converter":"Full Half Converter","Insert Blank Lines":"Insert Blank Lines","Remove Blank Lines":"Remove Blank Lines","Split Lines":"Split Lines","Dedupe Lines":"Dedupe Lines","Add Prefix/Suffix":"Add Prefix/Suffix","Number Lines (Custom)":"Number Lines (Custom)","Trim Line Ends":"Trim Line Ends","Shrink Extra Spaces":"Shrink Extra Spaces","Remove All Whitespace":"Remove All Whitespace","Extract Between Strings":"Extract Between Strings","Merge Lines":"Merge Lines","List to Table":"List to Table","Table to List":"Table to List","Line Operations":"Line Operations","Text Processing":"Text Processing","Advanced Tools":"Advanced Tools","Align Text Right":"Align Text Right",Bold:"Bold",Checklist:"Checklist","Clear Text Formatting":"Clear Text Formatting",Copy:"Copy",Cut:"Cut",Embed:"Embed","Header 1":"Header 1","Header 2":"Header 2","Header 3":"Header 3","Header 4":"Header 4","Header 5":"Header 5","Header 6":"Header 6",Highlight:"Highlight","Horizontal Divider":"Horizontal Divider","Indent list":"Indent list","Inline Math":"Inline Math",Italic:"Italic",Link:"Link",MathBlock:"MathBlock","Ordered List":"Ordered List",Paste:"Paste","Redo Edit":"Redo Edit",Strikethrough:"Strikethrough",Underline:"Underline","Undo Edit":"Undo Edit","Unindent List":"Unindent List","Unordered List":"Unordered List","Insert Embed":"Insert Embed","Insert Link":"Insert Link","Insert Tag":"Insert Tag","Insert Internal link":"Insert Internal link","Insert Code":"Insert Code","Insert Blockquote":"Insert Blockquote","Insert Comment":"Insert Comment","Insert Callout":"Insert Callout","Insert MathBlock":"Insert MathBlock","Insert Table":"Insert Table","Swap Line Up":"Swap Line Up","Swap Line Down":"Swap Line Down","Attach File":"Attach File","Clear Formatting":"Clear Formatting","Cycle List and Checklist":"Cycle List and Checklist",Blockquote:"Blockquote",Callout:"Callout",Superscript:"Superscript",Subscript:"Subscript","Inline Code":"Inline Code","Code Block":"Code Block",Wikilink:"Wikilink","Justify Text":"Justify Text","Align Text Left":"Align Text Left","Center Text":"Center Text","Change Font Color":"Change Font Color","Change Background Color":"Change Background Color","Fullscreen Focus Mode":"Fullscreen Focus Mode","Workplace Fullscreen":"Workplace Fullscreen","Renumber Ordered List":"Renumber Ordered List","Toggle Format Brush":"Toggle Format Brush","Toggle Fullscreen Focus Mode":"Toggle Fullscreen Focus Mode","Toggle Workplace Fullscreen Focus":"Toggle Workplace Fullscreen Focus","Enter prefix":"Enter prefix","Enter suffix":"Enter suffix",Delimiter:"Delimiter","Enter delimiter (e.g., comma, tab)":"Enter delimiter (e.g., comma, tab)","Column Number":"Column Number","Enter column number (starting from 1)":"Enter column number (starting from 1)","Start String":"Start String","Enter start string":"Enter start string","End String":"End String","Enter end string":"Enter end string","Number Lines Configuration":"Number Lines Configuration","Start Number":"Start Number",Step:"Step",Separator:"Separator","Merge Lines Settings":"Merge Lines Settings","Separator (leave empty for smart spacing)":"Separator (leave empty for smart spacing)","e.g., comma, pipe, arrow":"e.g., comma, pipe, arrow","Plain text copied to clipboard":"Plain text copied to clipboard","Whitespace cleaning completed":"Whitespace cleaning completed","List pattern detected, auto-split":"List pattern detected, auto-split","No obvious separator or list pattern detected":"No obvious separator or list pattern detected","Paste failed":"Paste failed","Detected Chinese context: converted to full-width symbols":"Detected Chinese context: converted to full-width symbols","Detected code/English context: converted to half-width symbols":"Detected code/English context: converted to half-width symbols","Please select text to dedupe first":"Please select text to dedupe first","Deduplication completed, remaining":"Deduplication completed, remaining",lines:"lines","Prefix/suffix added":"Prefix/suffix added","Please select text to number first":"Please select text to number first","Numbering completed: starting from":"Numbering completed: starting from","Please specify start or end string":"Please specify start or end string",Extracted:"Extracted",matches:"matches","No matches found":"No matches found","Extraction failed":"Extraction failed","Please select lines to merge first":"Please select lines to merge first","Merged with":"Merged with","Merge completed":"Merge completed",Item:"Item","Super conversion completed: context preserved and layout optimized":"Super conversion completed: context preserved and layout optimized","Please select a valid Markdown table":"Please select a valid Markdown table","Table converted to multi-level list":"Table converted to multi-level list","AI Editor":"AI Editor","Enable AI Editor":"Enable AI Editor","Enable AI editor features such as inline completion and selection rewrite.":"Enable AI editor features such as inline completion and selection rewrite.","Try AI Editing":"Try AI Editing","Unlock inline completion, rewrite, frontmatter, and canvas generation right inside your toolbar.":"Unlock inline completion, rewrite, frontmatter, and canvas generation right inside your toolbar.","Sign in to PKMer AI for free managed AI, or use your own compatible model.":"Sign in to PKMer AI for free managed AI, or use your own compatible model.","What you get":"What you get","Inline completion while you write":"Inline completion while you write","Rewrite, summarize, and continue text in place":"Rewrite, summarize, and continue text in place","Generate frontmatter, lists, tables, and canvas drafts":"Generate frontmatter, lists, tables, and canvas drafts","Before you enable AI":"Before you enable AI","The plugin itself does not intentionally store your note content.":"The plugin itself does not intentionally store your note content.","AI requests are sent only to the provider you choose, such as PKMer AI or your custom model.":"AI requests are sent only to the provider you choose, such as PKMer AI or your custom model.","Those requests remain subject to the provider privacy policy, terms, and model rules.":"Those requests remain subject to the provider privacy policy, terms, and model rules.","You can turn AI off at any time in settings.":"You can turn AI off at any time in settings.","Agree & Enable AI":"Agree & Enable AI","Not now":"Not now","AI editing is now enabled. The plugin does not intentionally store your note content, and requests follow your chosen provider policies.":"AI editing is now enabled. The plugin does not intentionally store your note content, and requests follow your chosen provider policies.",Enabled:"Enabled",Disabled:"Disabled","Completion Mode":"Completion Mode","Choose whether completion is triggered manually or automatically after a short pause.":"Choose whether completion is triggered manually or automatically after a short pause.","Enable Inline Completion":"Enable Inline Completion","Show ghost text suggestions inside the editor.":"Show ghost text suggestions inside the editor.","Completion Delay (ms)":"Completion Delay (ms)","Delay before auto-triggering inline completion.":"Delay before auto-triggering inline completion.","Completion Max Tokens":"Completion Max Tokens","Upper bound for one inline completion response. Increase it if completions feel cut off.":"Upper bound for one inline completion response. Increase it if completions feel cut off.",Manual:"Manual",Auto:"Auto","Text Tools":"Text Tools","AI Tools":"AI Tools","Inline Completion":"Inline Completion","Select text to see more tools":"Select text to see more tools","AI Assistant":"AI Assistant","AI module is ready":"AI module is ready","Use AI enhancements directly from the toolbar.":"Use AI enhancements directly from the toolbar.","Place the cursor for inline completion, or select text to unlock rewrite actions.":"Place the cursor for inline completion, or select text to unlock rewrite actions.","Selected text detected. Rewrite actions are ready.":"Selected text detected. Rewrite actions are ready.","AI Continue Writing":"AI Continue Writing","AI Summarize Selection":"AI Summarize Selection","AI Explain Selection":"AI Explain Selection","At Cursor":"At Cursor","On Selection":"On Selection","Continue writing at the current cursor.":"Continue writing at the current cursor.","Polish tone, wording, and structure.":"Polish tone, wording, and structure.","Extend from the selected passage.":"Extend from the selected passage.","Turn long text into concise points.":"Turn long text into concise points.","Explain the meaning and key ideas.":"Explain the meaning and key ideas.","Use your own prompt on the selection.":"Use your own prompt on the selection.","Custom Model":"Custom Model",Unavailable:"Unavailable","Checking...":"Checking...",AI:"AI","AI Complete":"AI Complete","AI Rewrite":"AI Rewrite","AI Continue":"AI Continue","AI Summarize":"AI Summarize","AI Explain":"AI Explain","AI Translate":"AI Translate","AI Tone":"AI Tone","AI Fix":"AI Fix","AI Shorten":"AI Shorten","AI Expand":"AI Expand","AI Simplify":"AI Simplify","AI Professional":"AI Professional","AI Casual":"AI Casual","AI Custom":"AI Custom",Tone:"Tone",Translate:"Translate",Generate:"Generate","Improve writing":"Improve writing","Fix spelling & grammar":"Fix spelling & grammar","Make shorter":"Make shorter","Make longer":"Make longer","Simplify language":"Simplify language","Professional tone":"Professional tone","Casual tone":"Casual tone",English:"English",Chinese:"Chinese",Japanese:"Japanese",German:"German",French:"French",Spanish:"Spanish","Explain this":"Explain this",Summarize:"Summarize","Continue writing":"Continue writing","Press Enter to send, Shift+Enter for newline, Esc to close.":"Press Enter to send, Shift+Enter for newline, Esc to close.Type [[]] to reference document content.","Type [[]] to reference document content.":"Type [[]] to reference document content.","Enter inserts a newline. Tap Send to submit.":"Enter inserts a newline. Tap Send to submit.","Open AI Settings":"Open AI Settings","Trigger AI Inline Completion":"Trigger AI Inline Completion","AI Improve Selection":"AI Improve Selection","AI Custom Rewrite":"AI Custom Rewrite",Send:"Send","Selected text":"Selected text","Current document":"Current document",characters:"characters","Login to PKMer AI":"Login to PKMer AI","PKMer AI":"PKMer AI","Sign in to PKMer to use managed AI without manual model setup.":"Sign in to PKMer to use managed AI without manual model setup.","Log in to PKMer AI to get free AI features without manual model setup.":"Log in to PKMer AI to get free AI features without manual model setup.","Log in to PKMer AI and you can start using free AI features right away.":"Log in to PKMer AI and you can start using free AI features right away.","Need a PKMer AI account?":"Need a PKMer AI account?","Open PKMer AI":"Open PKMer AI","PKMer Account":"PKMer Account",Login:"Login",Logout:"Logout","Refresh Quota":"Refresh Quota","Check Quota":"Check Quota","More Quota":"More Quota","PKMer AI is ready. You can use AI now and check your quota here.":"PKMer AI is ready. You can use AI now and check your quota here.","PKMer managed defaults are used automatically after sign-in.":"PKMer managed defaults are used automatically after sign-in.","Checking current AI route...":"Checking current AI route...","Current route: PKMer AI. If unavailable, it falls back to your custom model.":"Current route: PKMer AI. If unavailable, it falls back to your custom model.","Current route: PKMer AI.":"Current route: PKMer AI.","Current route: Custom model.":"Current route: Custom model.","No provider available. Log in to PKMer or complete the custom model settings.":"No provider available. Log in to PKMer or complete the custom model settings.","No provider available. Log in to PKMer to enable AI.":"No provider available. Log in to PKMer to enable AI.","Unable to determine current AI route.":"Unable to determine current AI route.",Account:"Account",Complete:"Complete","Quick Trigger":"Quick Trigger","Improve Selection":"Improve Selection","Custom Rewrite":"Custom Rewrite","Logout from PKMer":"Logout from PKMer","Editor Features":"Editor Features","PKMer Model":"PKMer Model","Choose models by task.":"Choose models by task.",Mode:"Mode","Light tasks use the light model. Complex tasks use the reasoning model.":"Light tasks use the light model. Complex tasks use the reasoning model.",Completion:"Completion",Rewrite:"Rewrite",Reasoning:"Reasoning",Structured:"Structured","Used for inline completion.":"Used for inline completion.","Used for normal rewrite.":"Used for normal rewrite.","Used for explain, summarize, and custom prompts.":"Used for explain, summarize, and custom prompts.","Used for frontmatter and canvas.":"Used for frontmatter and canvas.","PKMer route only.":"PKMer route only.","Light model":"Light model","Reasoning model":"Reasoning model","Inline completion":"Inline completion","Configure inline completion and rewrite after your AI provider is ready.":"Configure inline completion and rewrite after your AI provider is ready.","Custom Model (Optional)":"Custom Model (Optional)","Custom model is used automatically when PKMer AI is unavailable.":"Custom model is used automatically when PKMer AI is unavailable.","Enable Custom Model":"Enable Custom Model","Use your own OpenAI-compatible provider as a fallback.":"Use your own OpenAI-compatible provider as a fallback.","Custom API Format":"Custom API Format","Choose whether the custom model uses an OpenAI-compatible endpoint or the native Ollama API.":"Choose whether the custom model uses an OpenAI-compatible endpoint or the native Ollama API.","OpenAI-compatible":"OpenAI-compatible",Ollama:"Ollama","Custom API Base URL":"Custom API Base URL","OpenAI-compatible endpoint for your own provider.":"OpenAI-compatible endpoint for your own provider.","Native Ollama endpoint. The root URL, /api, /api/chat, or /api/generate are all supported.":"Native Ollama endpoint. The root URL, /api, /api/chat, or /api/generate are all supported.","Custom Model Name":"Custom Model Name","Model identifier used for inline completion and rewrite requests.":"Model identifier used for inline completion and rewrite requests.","Detected Ollama Models":"Detected Ollama Models","Fetch available models from your Ollama service.":"Fetch available models from your Ollama service.","Choose a detected Ollama model to fill the model field.":"Choose a detected Ollama model to fill the model field.","Select a detected model":"Select a detected model","Custom API Key":"Custom API Key","Optional for Ollama. Leave empty unless your gateway requires authentication.":"Optional for Ollama. Leave empty unless your gateway requires authentication.","Stored securely in Obsidian secret storage.":"Stored securely in Obsidian secret storage.","Will be stored securely in Obsidian secret storage.":"Will be stored securely in Obsidian secret storage.","Current Obsidian version does not support secure secret storage.":"Current Obsidian version does not support secure secret storage.","Stored securely":"Stored securely","Enter API key":"Enter API key",Temperature:"Temperature","Lower values are more stable; higher values are more creative.":"Lower values are more stable; higher values are more creative.","Test Connection":"Test Connection","Send a lightweight request to verify your custom model settings.":"Send a lightweight request to verify your custom model settings.","Please fill in the required custom model settings first.":"Please fill in the required custom model settings first.","No Ollama models found at this endpoint.":"No Ollama models found at this endpoint.","Failed to load Ollama models:":"Failed to load Ollama models:","Please fill in Custom API Base URL, Custom Model Name, and Custom API Key first.":"Please fill in Custom API Base URL, Custom Model Name, and Custom API Key first.","Testing...":"Testing...","Testing custom model connection...":"Testing custom model connection...","Custom model connection succeeded.":"Custom model connection succeeded.","Custom model connection failed:":"Custom model connection failed:","Unknown connection error.":"Unknown connection error.","PKMer AI request failed because your quota is insufficient. Please get more quota in PKMer and try again.":"PKMer AI request failed because your quota is insufficient. Please get more quota in PKMer and try again.","Available Variables":"Available Variables","Document path":"Document path","Full document content":"Full document content",Date:"Date",Time:"Time","Date and time":"Date and time","Vault name":"Vault name","Linked note references":"Linked note references","Use [[note name]] to reference the content of other notes.":"Use [[note name]] to reference the content of other notes.","Manual Completion Shortcut":"Manual Completion Shortcut","Default shortcut is Ctrl+J. You can customize it in Obsidian Hotkeys.":"Default shortcut is Ctrl+J. You can customize it in Obsidian Hotkeys.","Open Hotkey Settings":"Open Hotkey Settings","More Options":"More Options",Advanced:"Advanced","Advanced AI settings are usually not needed.":"Advanced AI settings are usually not needed.","Not logged in":"Not logged in","Logged in":"Logged in",Quota:"Quota","Unable to refresh PKMer quota.":"Unable to refresh PKMer quota.","PKMer quota refreshed:":"PKMer quota refreshed:","AI features are disabled in settings.":"AI features are disabled in settings.","Inline completion is disabled in settings.":"Inline completion is disabled in settings.","Current editor does not support AI inline completion.":"Current editor does not support AI inline completion.","Current editor does not support AI rewrite.":"Current editor does not support AI rewrite.","AI Custom Instruction":"AI Custom Instruction",Instruction:"Instruction",Suggestions:"Suggestions","Referenced notes":"Referenced notes","Please enter your custom AI instruction":"Please enter your custom AI instruction","Current Obsidian version does not support secure token storage.":"Current Obsidian version does not support secure token storage.","Login cancelled or timed out.":"Login cancelled or timed out.","PKMer login is already in progress. Please continue in the opened browser window.":"PKMer login is already in progress. Please continue in the opened browser window.","Successfully logged in to PKMer!":"Successfully logged in to PKMer!","Failed to complete login. Please try again.":"Failed to complete login. Please try again.","Login failed. Please try again.":"Login failed. Please try again.","OAuth state mismatch. Please try logging in again.":"OAuth state mismatch. Another Obsidian window may have intercepted the callback. Please close other vaults and try again.","Logged out from PKMer.":"Logged out from PKMer.","AI thinking":"AI thinking","AI generating":"AI generating","Ask AI to edit or generate...":"Ask AI to edit or generate...","Submit custom instruction":"Submit custom instruction","AI is writing...":"AI is writing...","AI is generating":"AI is generating","AI suggestion":"AI suggestion","Press Tab to accept":"Press Tab to accept",Replace:"Replace","Insert below":"Insert below","Try again":"Try again",Discard:"Discard","AI List":"AI List","AI Table":"AI Table","AI Base":"AI Base","AI Canvas":"AI Canvas","AI Canvas Prompt":"AI Canvas Prompt","AI Frontmatter":"AI Frontmatter",Toolbox:"Toolbox","AI Toolbox":"AI Toolbox","Convert to list":"Convert to list","Convert to table":"Convert to table","Convert to base":"Convert to base","Convert to canvas":"Convert to canvas","Generate frontmatter":"Generate frontmatter","Insert at cursor":"Insert at cursor",Create:"Create","Create & Embed":"Create & Embed","AI file suggestion":"AI file suggestion","AI frontmatter suggestion":"AI frontmatter suggestion","AI Base File":"AI Base","AI Canvas File":"AI Canvas","Insert frontmatter":"Insert frontmatter","Replace frontmatter":"Replace frontmatter","Failed to apply frontmatter.":"Failed to apply frontmatter.","Created AI file:":"Created AI file:","Failed to create AI file.":"Failed to create AI file.","AI file creation is unavailable.":"AI file creation is unavailable.","AI generated content is empty.":"AI generated content is empty.","AI returned invalid Canvas JSON.":"AI returned invalid Canvas JSON.","AI Canvas Expand":"AI Canvas Expand",Canvas:"Canvas","Expand Current Node":"Expand Current Node","Global Prompt":"Global Prompt","Expand current canvas node":"Expand current node prompt","Canvas Tools":"Canvas Tools","Canvas global prompt":"Canvas global prompt","Connect related nodes":"Connect related nodes","Add missing branches":"Add missing branches","Clarify structure":"Clarify structure","Generate next steps":"Generate next steps","Add risks and dependencies":"Add risks and dependencies","Selected nodes":"Selected nodes",Focused:"Focused",Selected:"Selected","Tidy selected layout":"Tidy selected layout","Reorganize the selected nodes into a clearer local hierarchy with tidy spacing and fewer edge crossings. Reuse current nodes instead of adding new ones.":"Reorganize the selected nodes into a clearer local hierarchy with tidy spacing and fewer edge crossings. Reuse current nodes instead of adding new ones.","Connect selected nodes":"Connect selected nodes","Connect the selected nodes with the most meaningful relationships.":"Connect the selected nodes with the most meaningful relationships.","Add the missing branches around the selected nodes.":"Add the missing branches around the selected nodes.","Clarify the structure around the selected nodes and remove ambiguity.":"Clarify the structure around the selected nodes and remove ambiguity.","Generate the next actionable steps from the selected nodes.":"Generate the next actionable steps from the selected nodes.","Add the risks, dependencies, and constraints related to the selected nodes.":"Add the risks, dependencies, and constraints related to the selected nodes.","Generate the next actionable steps from the current canvas node.":"Generate the next actionable steps from the current canvas node.","Add the risks, dependencies, and constraints related to the current canvas node.":"Add the risks, dependencies, and constraints related to the current canvas node.","Add the missing branches around the current canvas node.":"Add the missing branches around the current canvas node.","Clarify the structure around the current canvas node and remove ambiguity.":"Clarify the structure around the current canvas node and remove ambiguity.","Organize canvas layout":"Organize canvas layout","Reorganize this canvas into a clean hierarchy with tidy spacing, aligned sibling nodes, and fewer edge crossings. Reuse current nodes instead of adding new ones.":"Reorganize this canvas into a clean hierarchy with tidy spacing, aligned sibling nodes, and fewer edge crossings. Reuse current nodes instead of adding new ones.","Reduce edge crossings":"Reduce edge crossings","Reorganize the canvas to reduce edge crossings, keep related nodes close, and make the reading path clearer. Reuse current nodes instead of adding new ones.":"Reorganize the canvas to reduce edge crossings, keep related nodes close, and make the reading path clearer. Reuse current nodes instead of adding new ones.","Canvas to article":"Canvas to article","Convert this canvas into a polished Markdown article draft.":"Convert this canvas into a polished Markdown article draft.","Canvas to slides":"Canvas to slides","Convert this canvas into Obsidian Slides Markdown.":"Convert this canvas into Obsidian Slides Markdown.","Convert the referenced content into a structured canvas with one central topic, main branches, supporting details, and explicit relations.":"Convert the referenced content [[]] into a structured canvas with one central topic, main branches, supporting details, and explicit relations.","Reorganize board":"Reorganize board","Reorganize the whole canvas into a clearer hierarchy with better grouping.":"Reorganize the whole canvas into a clearer hierarchy with better grouping.","Reorganize the existing canvas nodes into a clearer hierarchy and grouping. Reuse current nodes instead of adding new ones.":"Reorganize the existing canvas nodes into a clearer hierarchy and grouping. Reuse current nodes instead of adding new ones.","Connect board clusters":"Connect board clusters","Connect the related clusters across the whole canvas and add missing bridge nodes.":"Connect the related clusters across the whole canvas and add missing bridge nodes.","Summarize main narrative":"Summarize main narrative","Identify the main narrative of this canvas and improve the section flow.":"Identify the main narrative of this canvas and improve the section flow.","e.g. split into next steps, risks, dependencies":"e.g. split into next steps, risks, dependencies","e.g. connect related nodes, add missing branches, clarify structure":"e.g. connect related nodes, add missing branches, clarify structure","e.g. tidy selected layout, connect selected nodes, add missing branches":"e.g. tidy selected layout, connect selected nodes, add missing branches","e.g. tidy selected layout, connect selected nodes, add missing branches, convert [[a note]] to canvas":"e.g. tidy selected layout, connect selected nodes, add missing branches, convert [[a note]] to canvas","e.g. reorganize the board, turn this canvas into an article, turn this canvas into Obsidian Slides":"e.g. reorganize the board, turn this canvas into an article, turn this canvas into Obsidian Slides","e.g. reorganize the board, turn this canvas into an article, turn [[a note]] into canvas":"e.g. reorganize the board, turn this canvas into an article, turn [[a note]] into canvas","Canvas AI requires an active Canvas file.":"Canvas AI requires an active Canvas file.","Please select a canvas node first.":"Please select a canvas node first.","Please enter your canvas instruction.":"Please enter your canvas instruction.","Please reference at least one note with [[...]] before converting to canvas.":"Please reference at least one note with [[...]] before converting to canvas.","Canvas AI is expanding the current node...":"Canvas AI is expanding the current node...","Canvas AI is processing the board...":"Canvas AI is processing the board...","Canvas AI is reorganizing the board...":"Canvas AI is reorganizing the board...","Canvas AI is structuring the referenced content...":"Canvas AI is structuring the referenced content...","Canvas AI is drafting an article...":"Canvas AI is drafting an article...","Canvas AI is drafting slides...":"Canvas AI is drafting slides...","Canvas AI added":"Canvas AI added","Canvas AI updated the board:":"Canvas AI updated the board:","Canvas AI reorganized the board:":"Canvas AI reorganized the board:",nodes:"nodes",links:"links","nodes moved":"nodes moved","links rebuilt":"links rebuilt","nodes to the board.":"nodes to the board.","Expand the current node into the most useful next neighboring nodes.":"Expand the current node into the most useful next neighboring nodes.","Canvas AI returned invalid JSON.":"Canvas AI returned invalid JSON.","Canvas AI did not return any usable nodes.":"Canvas AI did not return any usable nodes.","Canvas AI did not return any usable actions.":"Canvas AI did not return any usable actions.","Canvas AI did not return any usable Markdown.":"Canvas AI did not return any usable Markdown.","The focused canvas node no longer exists.":"The focused canvas node no longer exists.","AI Article Draft":"AI Article Draft","AI Slides":"AI Slides","Failed to read the current canvas data.":"Failed to read the current canvas data.","Unable to allocate a file name for the generated artifact.":"Unable to allocate a file name for the generated artifact.",Untitled:"Untitled"},b={"Editing Toolbar Append Method":"","Choose where Editing Toolbar will append upon regeneration. To see the change, hit the refresh button below, or in the status bar menu.":"Obsidianbody","Editing Toolbar aesthetic":"","Choose between a glass morphism, tiny and default style for Editing Toolbar. To see the change, hit the refresh button below, or in the status bar menu.":",","Editing Toolbar position":"","Choose between fixed position or cursor following mode.":",","Editing Toolbar Columns":"","Choose the number of columns per row to display on Editing Toolbar.":"Editing Toolbar","Editing Toolbar refresh":"","Editing Toolbar Commands":"","Add a command onto Editing Toolbar from Obsidian's commands library. To reorder the commands, drag and drop the command items. To delete them, use the delete buttom to the right of the command item. Editing Toolbar will not automaticaly refresh after reordering commands. Use the refresh button above.":"Obsidian使Custom","Format Brush Off!":"","Hide & Show":" & ","Editing Toolbar will only refresh automatically after you have either added or deleted a command from it. To see UI changes to editingToolbar (above settings changes) use the refresh button. If you forget to refresh in settings, no worries. There is also a refresh button in the editingToolbar status bar menu.":"使","Font-Color formatting brush ON!":"\n",More:"","Copy commands from selected style.":"","Font Colors":"","Format Brush":"","Background Color":"",Refresh:"",Add:"",Delete:"","Change Command Name":"","Change Submenu Name":"","Button Submenu":"","Dropdown Menu":"","Menu type changed to":"","Add Submenu":"","Add Separator":"线","Enter the icon code, it looks like <svg>.... </svg> format":"<svg>.... </svg>","Please enter a new name: ":"","Drag the slider to move the position":"","Plugin Settings":"","Background-color formatting brush ON!":"","Clear formatting brush ON!":"","Clear formatting brush ON!\nClick the mouse middle or right key to close the formatting-brush":"\n","The toolbar is displayed when the mouse moves over it, otherwise it is automatically hidden":"","Editing Toolbar Auto-hide":"","Editing Toolbar Centred Display":"","Whether the toolbar is centred or full-width, the default is full-width.":"","Custom Backgroud Color":"","Custom Font Color":"","🎨 Set Custom Background":"🎨 ","🖌 Set Custom Font Color":"🖌 ","Click on the picker to adjust the color":"","Mobile Enabled or Not":"","Whether to enable on mobile devices with device width less than 768px.":"768",Reset:"",Fix:"","Fix Editing Toolbar":"",General:"",Appearance:"",Commands:"","Choose between fixed position or cursor following mode":"","Add and manage commands":"","Choose where Editing Toolbar will append upon regeneration.":"Obsidian","Whether to enable on mobile devices with device width less than 768px":"","Choose between a glass morphism, tiny and default style":",","Refresh Toolbar":"","Add Command":"",Settings:"","Adjust Toolbar Position[Fixed mode]":"[]","Position Style":"",Columns:"","Drag to Adjust Position":"","Vertical Position":"","Horizontal Position":"","Toolbar Position":"","Choose an icon":"","Search for an icon...":"...",All:"",Obsidian:"Obsidian",Glyph:"Glyph","Choose a command":"","The command":"","already exists":"","Enter the icon code, format as <svg>.... </svg>":" <svg>.... </svg>","No matching icons found":"","Custom Commands":"","Toolbar Commands":"",ID:"ID",Prefix:"",Suffix:"","Custom Format Commands":"","Add, edit or delete custom format commands.":"","Command ID":"ID",'Unique identifier, no spaces, e.g.: "my-custom-format"':'"my-custom-format"',"Displayed name in toolbar and menu":"","Add content before selected text":"","Add content after selected text":"","Character offset of cursor after formatting":"","Line offset of cursor after formatting":"","Whether to insert at the beginning of the next line":"","Command icon (click to select)":"","Choose Icon":"",Save:"",Cancel:"","Edit Custom Command":"","Add Custom Command":"","Command ID and command name cannot be empty":"ID","Command ID cannot contain spaces":"ID",'Command ID "${this.commandId}" already exists':'ID "${this.commandId}" ',"Command Name":"","Cursor Position Offset":"","Line Offset":"","Line Head Format":"",Icon:"","Are you sure you want to restore all settings to default? This will lose all your custom configurations.":"","Restore default":"","Restore default settings":"","🔄Restore default settings":"🔄","🔧Data repair":"🔧","Command IDs have been successfully repaired!":"ID","No command IDs need to be repaired":"ID","Error repairing command IDs, please check the console for details":"ID","Error restoring default settings, please check the console for details":"","Successfully restored default settings!":"",Close:"",Tips:"","This update changed the ID of some commands, please click this button to repair the commands to ensure the toolbar works properly":"ID","Repair command ID":"ID","This will reset all your custom configurations":"","Notice:":"","This update rebuilds the entire code, reducing resource consumption":"","Optimized mobile usage, added canvas support, and added custom commands":"canvas","This update is not compatible with 2.x version command ids, please click [Repair command] to be compatible":"2.xid","If you want to restore the default settings, please click [Restore default settings]":"","Please execute a editingToolbar format command first, then enable the format brush":"","Format brush ON! Select text to apply":"\n","format":"\n","Add to Toolbar":"","This command is already in the toolbar.":"","Command added to toolbar":"","Add this command to the toolbar.":"","Callout Type":"Callout ",Title:"","Optional, leave blank for default title":"使","Input title":"","Collapse State":"",Open:"",Closed:"",Content:"",Insert:"","Input content":"","Link Text":"","Link Alias":"","Link URL":"","Embed Content":"","Image Size":"","Insert New Line":"","Paste and Parse":"","URL Format Error":"URL","Image Width":"","Image Height":"","Insert a link on the next line":"","If it is an image, turn on":"","Link Title(optional)":"()",Alias:"",Optional:"","Default 0, format will keep the text selected":"0","to insert":"","Latest Changes":"","📋View full changelog":"📋","Open changelog":"","Loading changelog...":"...","Open the complete changelog in your browser":"","Enable Multiple Configurations":"","Enable different command configurations for each position style (following, top, fixed).":"followingtopfixed","Currently editing commands for":"","position style":"","Current Configuration":"","Switch between different command configurations.":"","Following Style":"","Top Style":"","Fixed Style":"","Mobile Style":"",configuration:"","Deploy command to configurations":"","All Configurations":"",Deploy:"","Command deployed to selected configurations":"","No configuration selected for deployment":"","Command already exists in selected configurations":"","Command deployed to: ":"","Command Deleted":"","Confirm Delete?":"","Are you sure you want to restore all settings to default? But custom commands will be preserved.":"","Successfully restored default settings! (Custom commands preserved)":"","This will reset all your custom configurations, but custom commands will be preserved":"","Import/Export":"/","Export Configuration":"","Export your toolbar configuration to share with others.":"",Export:"","Import Configuration":"","Import toolbar configuration from JSON.":"JSON",Import:"","Usage Instructions":"使","Export: Generate a JSON configuration that you can save or share.":"JSON","Import: Paste a previously exported JSON configuration.":"JSON","You can choose to export all settings, only toolbar commands, or only custom commands":"","When importing, the plugin will only update the settings included in the import data":"","Warning: Importing configuration will overwrite your current settings. Consider exporting your current configuration first as a backup.":"","Export Type":"","Choose what to export":"","All Settings":"","Toolbar Commands Only":"","Custom Commands Only":"","Export Content":"","Copy this content to share with others":"","Loading...":"...","Copy to Clipboard":"","Configuration copied to clipboard":"","Failed to copy configuration":"","Paste the configuration JSON here":"JSON","Paste configuration here...":"...","Invalid import data":"","Configuration imported successfully":"","No valid configuration found in import data":"","Failed to import configuration. Invalid format.":"","Import Mode":"","Choose how to import the configuration":"","Update Mode (Add new items and update existing ones)":"","Overwrite Mode (Replace all settings with imported ones)":"","Configuration imported successfully (Overwrite mode)":"","Configuration imported successfully (Update mode)":"","Warning: Overwrite mode will completely replace your current settings with the imported ones. Consider exporting your current configuration first as a backup.":"","Warning: Update mode will add new items and update existing ones based on the imported configuration.":"","Add Format Command":"",Regex:"","Prefix/Suffix":"/","Insert Special Char":"","Add Regex Command":"","Switch Regex Command Window":"","Please select text first":"","Place the cursor in a paragraph or select text first.":"","Current line is empty, please select text or move to a non-empty line":"","Use current line for regex commands":"使","When no text is selected, regex commands will use the current line instead of clipboard content":"使","The selected text does not meet the condition requirements":"","Regex command execution error: ":"","Copy code":"","Copied!":"","Explain the syntax of JavaScript regular expressions":"JavaScript","Apply regular expression replacement":"","Conditional matching":"","Complete regular expression code (copy to AI for explanation)":"AI","Error: ":"","Regex pattern cannot be empty":"","Command already exists":"","Choose icon":"","URL to Markdown link":"URLMarkdown","Convert MM/DD/YYYY to YYYY-MM-DD":"MM/DD/YYYYYYYY-MM-DD","Add bold to keywords":"","Format phone number":"","Remove extra spaces":"","Convert HTML bold tags to Markdown format":"HTMLMarkdown","Convert quoted text to quote block":"","Convert CSV to Markdown table row":"CSVMarkdown","Add uniform alias to Markdown links":"Markdown","Delete empty lines (multiline mode)":"","Add list symbol to each line (multiline mode)":"","If the text contains important, set the text highlight (conditional format)":"","Matching pattern":"","Regex pattern to match":"","Replacement pattern (use $1, $2, etc. to reference capture groups)":"使$1, $2","Ignore case":"","Global replace":"","Multiline mode":"","Use condition":"使","Condition pattern":"","Only apply custom command when text matches the condition":"","Must exist regular expression or text":"","Replacement pattern":"","Match case-insensitive":"","^ and $ match the start and end of each line":"^ $ ","Replace all matches":"",Command:"","Input example text to view the formatting effect of the command...":"...",Description:"","[Example]":"[]","[Requirements]":"[]","[Output]":"[]","AI question template:":"AI","I need to convert the url to a markdown format link":"URLMarkdown","For example, convert https://example.com to [https://example.com](https://example.com)":"https://example.com[https://example.com](https://example.com)","Use js regular expression to implement, and output the parameters in the following format (the result does not need to be escaped with json)":"使jsjson","[Description]":"[]","How to use AI to get regular expressions?":"使AI","Regular expression examples":"","Edit regular expression command":"","Add regular expression command":"","Result:":"","Example text:":"",Preview:"",Result:"","Update Import":"","Overwrite Import":"","Importing configuration...":"...","Following Style Only":"Following","Top Style Only":"Top","Fixed Style Only":"Fixed","Mobile Style Only":"Mobile","Unknown import type":"","All Toolbar Commands":"","Following style commands successfully initialized":"Following","Top style commands successfully initialized":"Top","Fixed style commands successfully initialized":"Fixed","Mobile style commands successfully initialized":"Mobile","Commands initialized successfully":"","Reset Commands":"","Are you sure you want to reset the current configuration?":"","Commands reset successfully":"","Initialize Commands":"","Initialize commands to default settings":"","Reset commands to default settings":"",Clear:"","Remove all commands from this configuration.":"","Are you sure you want to clear all commands under the current style?":"","Current style commands have been cleared":"","Manage Commands":"","Reset or clear all commands in this configuration":"","Import Commands from Other Styles":"","Copy commands from another style configuration.":"","Main menu only":"Main menu only","This import will update:":"","Custom commands":"","Toolbar commands":"","All settings":"","Following style only":"","Top style only":"","Fixed style only":"","Mobile style only":"","Main Menu Commands":"","Following Style Commands":"","Top Style Commands":"","Fixed Style Commands":"","Mobile Style Commands":"","General settings":"","Please paste configuration data first":"","Invalid import data format":"","Do you want to continue?":"","Warning: Update mode will add new items and update existing ones.":"","Warning: Overwrite mode will completely replace your current settings with the imported ones.":"","Overwrite Mode (Replace settings with imported ones)":"","Warning: Overwrite mode will replace existing settings with imported ones.":"","Enable Multiple Config":"","One-click Clear":"","This import will:":"","Update general settings":"","Update Main Menu Commands":"","Update Custom Commands":"","Update Following Style Commands":"","Update Top Style Commands":"","Update Fixed Style Commands":"","Clear all Main Menu Commands":"","Clear all Custom Commands":"","Clear all Following Style Commands":"","Clear all Top Style Commands":"","Clear all Fixed Style Commands":"","Clear all Mobile Style Commands":"","Set Multiple Config to:":"",Enable:"",Disable:"","Set Position Style to:":"",Following:"",Top:"",Fixed:"",Mobile:"","All commands":""," Overwrite mode will replace existing settings with imported ones.":" "," Update mode will merge imported settings with existing ones.":" ","Imported settings:":"","Imported commands:":"","Disable toolbar for this view":"","Enable toolbar for this view":"","Manage all view types":"","Current View: ":"","Appearance Style":"","Position Settings":"","Join the Community":"","Share your toolbar settings and styles in our":"","section!":"","Get inspired by what others have created or showcase your own customizations.":"","Toolbar Preview (With a hypothetical command configuration.)":"","Toolbar Theme":"","Select a preset toolbar theme, automatically setting the background color, icon color, and size for the selected style.":"","Toolbar Background Color":"","Set the background color of the toolbar.":"","Toolbar Icon Color":"","Set the color of the toolbar icon.":"","Toolbar Icon Size":"","Set the size of the toolbar icon (px); default: 18px":"px18px","Custom theme":"","Fixed Position Offset":"","Choose the offset of the Editing Toolbar in the fixed position.":"","Renumber List":"","Insert link":"","Please enter a URL first":"URL","Failed to fetch title for":"","Link Title (optional)":"","Unable to detect editor width":"","Fit Editor Width":"","Fetch Remote Title":"URL","Please execute a format command or select format text first, then enable the format brush":"",Confirm:"","Use \\n to represent line breaks":"使\\n","Use to represent line breaks":"使","All commands have been removed.":"","Top Toolbar":"","Enable the toolbar positioned at the top.":"","Following Toolbar":"","Enable the toolbar that appears upon text selection.":"","Fixed Toolbar":"","Enable the toolbar whose position may be fixed where you please.":"","Toolbar Settings":"","Choose which toolbar style's appearance you want to edit.":"","Vertical Split":"","Text Enhancement Tools":"","Get Plain Text":"","Full Half Converter":"","Insert Blank Lines":"","Remove Blank Lines":"","Split Lines":"","Dedupe Lines":"","Add Prefix/Suffix":"","Number Lines (Custom)":"","Trim Line Ends":"","Shrink Extra Spaces":"","Remove All Whitespace":"","Extract Between Strings":"","Merge Lines":"","List to Table":"","Table to List":"","Line Operations":"","Text Processing":"","Advanced Tools":"","Align Text Right":"",Bold:"",Checklist:"","Clear Text Formatting":"",Copy:"",Cut:"",Embed:"","Header 1":" 1","Header 2":" 2","Header 3":" 3","Header 4":" 4","Header 5":" 5","Header 6":" 6",Highlight:"","Horizontal Divider":"线","Indent list":"","Inline Math":"",Italic:"",Link:"",MathBlock:"","Ordered List":"",Paste:"","Redo Edit":"",Strikethrough:"线",Underline:"线","Undo Edit":"","Unindent List":"","Unordered List":"","Insert Embed":"","Insert Link":"","Insert Tag":"","Insert Internal link":"","Insert Code":"","Insert Blockquote":"","Insert Comment":"","Insert Callout":" Callout","Insert MathBlock":"","Insert Table":"","Swap Line Up":"","Swap Line Down":"","Attach File":"","Clear Formatting":"","Cycle List and Checklist":"",Blockquote:"",Callout:"Callout",Superscript:"",Subscript:"","Inline Code":"","Code Block":"",Wikilink:"","Justify Text":"","Align Text Left":"","Center Text":"","Change Font Color":"","Change Background Color":"","Fullscreen Focus Mode":"","Workplace Fullscreen":"","Renumber Ordered List":"","Toggle Format Brush":"","Toggle Fullscreen Focus Mode":"","Toggle Workplace Fullscreen Focus":"","Enter prefix":"","Enter suffix":"",Delimiter:"","Enter delimiter (e.g., comma, tab)":"","Column Number":"","Enter column number (starting from 1)":"1","Start String":"","Enter start string":"","End String":"","Enter end string":"","Number Lines Configuration":"","Start Number":"",Step:"",Separator:"","Merge Lines Settings":"","Separator (leave empty for smart spacing)":" ()","e.g., comma, pipe, arrow":": , | ","Plain text copied to clipboard":"","Whitespace cleaning completed":"","List pattern detected, auto-split":"","No obvious separator or list pattern detected":"","Paste failed":"","Detected Chinese context: converted to full-width symbols":"","Detected code/English context: converted to half-width symbols":"/","Please select text to dedupe first":"","Deduplication completed, remaining":"",lines:"","Prefix/suffix added":"","Please select text to number first":"","Numbering completed: starting from":"","Please specify start or end string":"",Extracted:"",matches:"","No matches found":"","Extraction failed":"","Please select lines to merge first":"","Merged with":"","Merge completed":"",Item:"","Super conversion completed: context preserved and layout optimized":"","Please select a valid Markdown table":" Markdown ","Table converted to multi-level list":"","AI Editor":"AI ","Enable AI Editor":" AI ","Enable AI editor features such as inline completion and selection rewrite.":" AI ","Try AI Editing":" AI ","Unlock inline completion, rewrite, frontmatter, and canvas generation right inside your toolbar.":"Frontmatter Canvas 稿","Sign in to PKMer AI for free managed AI, or use your own compatible model.":" PKMer AI 使 AI","What you get":"","Inline completion while you write":"","Rewrite, summarize, and continue text in place":"","Generate frontmatter, lists, tables, and canvas drafts":" Frontmatter Canvas 稿","Before you enable AI":"","The plugin itself does not intentionally store your note content.":"","AI requests are sent only to the provider you choose, such as PKMer AI or your custom model.":"AI PKMer AI ","Those requests remain subject to the provider privacy policy, terms, and model rules.":"","You can turn AI off at any time in settings.":" AI","Agree & Enable AI":" AI","Not now":"","AI editing is now enabled. The plugin does not intentionally store your note content, and requests follow your chosen provider policies.":"AI AI ",Enabled:"",Disabled:"","Completion Mode":"","Choose whether completion is triggered manually or automatically after a short pause.":"","Enable Inline Completion":"","Show ghost text suggestions inside the editor.":"","Completion Delay (ms)":"","Delay before auto-triggering inline completion.":"","Completion Max Tokens":" Tokens","Upper bound for one inline completion response. Increase it if completions feel cut off.":"",Manual:"",Auto:"","Text Tools":"","AI Tools":"AI ","Inline Completion":"","Select text to see more tools":"","AI Assistant":"AI ","AI module is ready":"AI ","Use AI enhancements directly from the toolbar.":"使 AI ","Place the cursor for inline completion, or select text to unlock rewrite actions.":"使","Selected text detected. Rewrite actions are ready.":"使","AI Continue Writing":"AI ","AI Summarize Selection":"AI ","AI Explain Selection":"AI ","At Cursor":"","On Selection":"","Continue writing at the current cursor.":"","Polish tone, wording, and structure.":"","Extend from the selected passage.":"","Turn long text into concise points.":"","Explain the meaning and key ideas.":"","Use your own prompt on the selection.":"使","Custom Model":"",Unavailable:"","Checking...":"...",AI:"AI","AI Complete":"AI","AI Rewrite":"AI","AI Continue":"AI","AI Summarize":"AI","AI Explain":"AI","AI Translate":"AI","AI Tone":"AI","AI Fix":"AI","AI Shorten":"AI","AI Expand":"AI","AI Simplify":"AI","AI Professional":"AI","AI Casual":"AI","AI Custom":"AI",Custom:"",Edit:"",Tone:"",Translate:"",Generate:"","Improve writing":"","Fix spelling & grammar":"","Make shorter":"","Make longer":"","Simplify language":"","Professional tone":"","Casual tone":"",English:"",Chinese:"",Japanese:"",German:"",French:"",Spanish:"西","Explain this":"",Summarize:"","Continue writing":"","Press Enter to send, Shift+Enter for newline, Esc to close.":"Shift+Enter Esc [[]]","Type [[]] to reference document content.":" [[]] ","Enter inserts a newline. Tap Send to submit.":"","Open AI Settings":" AI ","Trigger AI Inline Completion":" AI ","AI Improve Selection":"AI ","AI Custom Rewrite":"AI ",History:"","No history":"",Send:"","Selected text":"","Current document":"",characters:"","Custom Prompt Templates":"","Manage quick-access templates for custom AI prompts":"访 AI ","Edit Template":"","Add Template":"","Template Name":"","Prompt Content":"","Enter template name":"","Enter prompt content":"","Template name and content cannot be empty":"","Describe what you want AI to do...":" AI ...","Manage Templates":"","Login to PKMer AI":" PKMer AI","PKMer AI":"PKMer AI","Sign in to PKMer to use managed AI without manual model setup.":" PKMer 使 AI","Log in to PKMer AI to get free AI features without manual model setup.":" PKMer AI 使 AI ","Log in to PKMer AI and you can start using free AI features right away.":" PKMer AI 使 AI ","Need a PKMer AI account?":" PKMer AI ","Open PKMer AI":" PKMer AI","PKMer Account":"PKMer ",Login:"",Logout:"退","Refresh Quota":"","Check Quota":"","More Quota":"","PKMer AI is ready. You can use AI now and check your quota here.":"PKMer AI 使 AI","PKMer managed defaults are used automatically after sign-in.":"使 PKMer ","Checking current AI route...":" AI ...","Current route: PKMer AI. If unavailable, it falls back to your custom model.":"使 PKMer AI退","Current route: PKMer AI.":"PKMer AI","Current route: Custom model.":"","No provider available. Log in to PKMer or complete the custom model settings.":" provider PKMer","No provider available. Log in to PKMer to enable AI.":" provider PKMer AI","Unable to determine current AI route.":" AI ",Account:"",Complete:"","Quick Trigger":"","Improve Selection":"","Custom Rewrite":"","Logout from PKMer":"退 PKMer","Editor Features":"","PKMer Model":"PKMer ","Choose models by task.":"",Mode:"","Light tasks use the light model. Complex tasks use the reasoning model.":"",Completion:"",Rewrite:"",Reasoning:"",Structured:"","Used for inline completion.":"","Used for normal rewrite.":"","Used for explain, summarize, and custom prompts.":"","Used for frontmatter and canvas.":" Frontmatter Canvas","PKMer route only.":" PKMer ","Light model":"","Reasoning model":"","Inline completion":"","Configure inline completion and rewrite after your AI provider is ready.":" AI provider ","Custom Model (Optional)":"","Custom model is used automatically when PKMer AI is unavailable.":" PKMer AI 使","Enable Custom Model":"","Use your own OpenAI-compatible provider as a fallback.":" OpenAI ","Custom API Format":"","Choose whether the custom model uses an OpenAI-compatible endpoint or the native Ollama API.":"使 OpenAI Ollama API","OpenAI-compatible":"OpenAI ",Ollama:"Ollama","Custom API Base URL":" API ","OpenAI-compatible endpoint for your own provider.":" OpenAI ","Native Ollama endpoint. The root URL, /api, /api/chat, or /api/generate are all supported.":" Ollama /api/api/chat /api/generate","Custom Model Name":"","Model identifier used for inline completion and rewrite requests.":"","Detected Ollama Models":" Ollama ","Fetch available models from your Ollama service.":" Ollama ","Choose a detected Ollama model to fill the model field.":" Ollama ","Select a detected model":"","Custom API Key":" API Key","Optional for Ollama. Leave empty unless your gateway requires authentication.":"Ollama ","Stored securely in Obsidian secret storage.":" Obsidian ","Will be stored securely in Obsidian secret storage.":" Obsidian ","Current Obsidian version does not support secure secret storage.":" Obsidian ","Stored securely":"","Enter API key":" API Key",Temperature:"","Lower values are more stable; higher values are more creative.":"","Test Connection":"","Send a lightweight request to verify your custom model settings.":"","Please fill in the required custom model settings first.":"","No Ollama models found at this endpoint.":" Ollama ","Failed to load Ollama models:":" Ollama ","Please fill in Custom API Base URL, Custom Model Name, and Custom API Key first.":" API API Key","Testing...":"...","Testing custom model connection...":"...","Custom model connection succeeded.":"","Custom model connection failed:":"","Unknown connection error.":"","PKMer AI request failed because your quota is insufficient. Please get more quota in PKMer and try again.":"PKMer AI PKMer ","Available Variables":"","Document path":"","Full document content":"",Date:"",Time:"","Date and time":"","Vault name":"","Linked note references":"","Use [[note name]] to reference the content of other notes.":"使 [[]] ","Manual Completion Shortcut":"","Default shortcut is Ctrl+J. You can customize it in Obsidian Hotkeys.":" Ctrl+J Obsidian ","Open Hotkey Settings":"","More Options":"",Advanced:"","Advanced AI settings are usually not needed.":" AI ","Not logged in":"","Logged in":"",Quota:"","Unable to refresh PKMer quota.":" PKMer ","PKMer quota refreshed:":"PKMer ","AI features are disabled in settings.":"AI ","Inline completion is disabled in settings.":"","Current editor does not support AI inline completion.":" AI ","Current editor does not support AI rewrite.":" AI ","AI Custom Instruction":"AI ",Instruction:"",Suggestions:"","Referenced notes":"","Please enter your custom AI instruction":" AI ","Current Obsidian version does not support secure token storage.":" Obsidian ","Login cancelled or timed out.":"","PKMer login is already in progress. Please continue in the opened browser window.":"PKMer ","Successfully logged in to PKMer!":" PKMer","Failed to complete login. Please try again.":"","Login failed. Please try again.":"","OAuth state mismatch. Please try logging in again.":"OAuth Obsidian ","Logged out from PKMer.":"退 PKMer ","AI thinking":"AI ","AI generating":"AI ","Ask AI to edit or generate...":" AI ","Submit custom instruction":"","AI is writing...":"AI ","AI is generating":"AI ","AI suggestion":"AI ","Press Tab to accept":" Tab ",Replace:"","Insert below":"","Try again":"",Discard:"","AI List":"AI ","AI Table":"AI ","AI Base":"AI Base","AI Canvas":"AI Canvas","AI Canvas Prompt":"AI ","AI Frontmatter":"AI ",Toolbox:"","AI Toolbox":"AI ","Convert to list":"","Convert to table":"","Convert to base":" Base","Convert to canvas":" Canvas","Generate frontmatter":" Frontmatter","Insert at cursor":"",Create:"","Create & Embed":"","AI file suggestion":"AI ","AI frontmatter suggestion":"AI ","AI Base File":"AI Base","AI Canvas File":"AI Canvas","Insert frontmatter":" Frontmatter","Replace frontmatter":" Frontmatter","Failed to apply frontmatter.":" Frontmatter ","Created AI file:":" AI ","Failed to create AI file.":" AI ","AI file creation is unavailable.":" AI ","AI generated content is empty.":"AI ","AI returned invalid Canvas JSON.":"AI Canvas JSON ","AI Canvas Expand":"AI ",Canvas:"","Expand Current Node":"","Global Prompt":"","Expand current canvas node":"","Canvas Tools":"","Canvas global prompt":"","Connect related nodes":"","Add missing branches":"","Clarify structure":"","Generate next steps":"","Add risks and dependencies":"","Selected nodes":"",Focused:"",Selected:"","Tidy selected layout":"","Reorganize the selected nodes into a clearer local hierarchy with tidy spacing and fewer edge crossings. Reuse current nodes instead of adding new ones.":"线","Connect selected nodes":"","Connect the selected nodes with the most meaningful relationships.":"线","Add the missing branches around the selected nodes.":"","Clarify the structure around the selected nodes and remove ambiguity.":"","Generate the next actionable steps from the selected nodes.":"","Add the risks, dependencies, and constraints related to the selected nodes.":"","Generate the next actionable steps from the current canvas node.":"","Add the risks, dependencies, and constraints related to the current canvas node.":"","Add the missing branches around the current canvas node.":"","Clarify the structure around the current canvas node and remove ambiguity.":"","Organize canvas layout":"","Reorganize this canvas into a clean hierarchy with tidy spacing, aligned sibling nodes, and fewer edge crossings. Reuse current nodes instead of adding new ones.":"线","Reduce edge crossings":"线","Reorganize the canvas to reduce edge crossings, keep related nodes close, and make the reading path clearer. Reuse current nodes instead of adding new ones.":"线","Canvas to article":"","Convert this canvas into a polished Markdown article draft.":" Markdown 稿","Canvas to slides":"","Convert this canvas into Obsidian Slides Markdown.":" Obsidian Slides Markdown","Convert the referenced content into a structured canvas with one central topic, main branches, supporting details, and explicit relations.":"[[]]","Reorganize board":"","Reorganize the whole canvas into a clearer hierarchy with better grouping.":"","Reorganize the existing canvas nodes into a clearer hierarchy and grouping. Reuse current nodes instead of adding new ones.":"","Connect board clusters":"","Connect the related clusters across the whole canvas and add missing bridge nodes.":"","Summarize main narrative":"线","Identify the main narrative of this canvas and improve the section flow.":"线","e.g. split into next steps, risks, dependencies":"","e.g. connect related nodes, add missing branches, clarify structure":"","e.g. tidy selected layout, connect selected nodes, add missing branches":"","e.g. tidy selected layout, connect selected nodes, add missing branches, convert [[a note]] to canvas":" [[]] ","e.g. reorganize the board, turn this canvas into an article, turn this canvas into Obsidian Slides":" Obsidian Slides","e.g. reorganize the board, turn this canvas into an article, turn [[a note]] into canvas":" [[]] ","Canvas AI requires an active Canvas file.":"Canvas AI ","Please select a canvas node first.":"","Please enter your canvas instruction.":"","Please reference at least one note with [[...]] before converting to canvas.":" [[...]] ","Canvas AI is expanding the current node...":"Canvas AI ","Canvas AI is processing the board...":"Canvas AI ","Canvas AI is reorganizing the board...":"Canvas AI ","Canvas AI is structuring the referenced content...":"Canvas AI ","Canvas AI is drafting an article...":"Canvas AI 稿","Canvas AI is drafting slides...":"Canvas AI 稿","Canvas AI added":"Canvas AI ","Canvas AI updated the board:":"Canvas AI ","Canvas AI reorganized the board:":"Canvas AI ",nodes:"",links:"线","nodes moved":"","links rebuilt":"线","nodes to the board.":"","Expand the current node into the most useful next neighboring nodes.":"","Canvas AI returned invalid JSON.":"Canvas AI JSON","Canvas AI did not return any usable nodes.":"Canvas AI ","Canvas AI did not return any usable actions.":"Canvas AI ","Canvas AI did not return any usable Markdown.":"Canvas AI Markdown","The focused canvas node no longer exists.":"","AI Article Draft":"AI 稿","AI Slides":"AI ","Failed to read the current canvas data.":"","Unable to allocate a file name for the generated artifact.":"",Untitled:""},y={...b};const C={ar:{},cs:{},da:{},de:{},en:f,"en-gb":{"Editing Toolbar Append Method":"Editing Toolbar Append Method","Choose where Editing Toolbar will append upon regeneration. To see the change, hit the refresh button below, or in the status bar menu.":"Choose where Editing Toolbar will append upon regeneration. To see the change, hit the refresh button below, or in the status bar menu.","Editing Toolbar aesthetic":"Editing Toolbar aesthetic","Choose between a glass morphism, tiny and default style for Editing Toolbar. To see the change, hit the refresh button below, or in the status bar menu.":"Choose between a glass morphism, tiny and default style for Editing Toolbar. To see the change, hit the refresh button below, or in the status bar menu.","Editing Toolbar position":"Editing Toolbar position","Choose between fixed position or cursor following mode.":"Choose between fixed position, cursor following or Top mode.","Editing Toolbar Columns":"Editing Toolbar Columns","Choose the number of columns per row to display on Editing Toolbar.":"Choose the number of columns per row to display on Editing Toolbar.","Editing Toolbar refresh":"Editing Toolbar refresh","Editing Toolbar Commands":"Editing Toolbar Commands","Add a command onto Editing Toolbar from Obsidian's commands library. To reorder the commands, drag and drop the command items. To delete them, use the delete buttom to the right of the command item. Editing Toolbar will not automaticaly refresh after reordering commands. Use the refresh button above.":"Add a command onto Editing Toolbar from Obsidian's commands library. To reorder the commands, drag and drop the command items. To delete them, use the delete buttom to the right of the command item. Editing Toolbar will not automaticaly refresh after reordering commands. Use the refresh button above.","Format Brush Off!":"Format Brush Off!","Hide & Show":"Hide & Show","Editing Toolbar will only refresh automatically after you have either added or deleted a command from it. To see UI changes to editingToolbar (above settings changes) use the refresh button. If you forget to refresh in settings, no worries. There is also a refresh button in the editingToolbar status bar menu.":"Editing Toolbar will only refresh automatically after you have either added or deleted a command from it. To see UI changes to editingToolbar (above settings changes) use the refresh button. If you forget to refresh in settings, no worries. There is also a refresh button in the editingToolbar status bar menu.","Font-Color formatting brush ON!":"Font-Colour formatting brush ON!",More:"More","Font Colors":"Font Colours","Format Brush":"Format Brush","Background color":"Background colour",Refresh:"Refresh",Add:"Add",Delete:"Delete","Change Command Name":"Change Command Name","Add Submenu":"Add Submenu","Add Separator":"Add Separator","Enter the icon code, it looks like <svg>.... </svg> format":"Enter the icon code, it looks like <svg>.... </svg> format","Please enter a new name: ":"Please enter a new name: ","Drag the slider to move the position":"Drag the slider to move the position","Plugin Settings":"Plugin Settings","Background-color formatting brush ON!":"Background-colour formatting brush ON!\nClick the mouse middle or right key to close the formatting-brush","Clear formatting brush ON!":"Clear formatting brush ON!","Clear formatting brush ON!\nClick the mouse middle or right key to close the formatting-brush":"Clear formatting brush ON!\nClick the mouse middle or right key to close the formatting-brush","The toolbar is displayed when the mouse moves over it, otherwise it is automatically hidden":"The toolbar is displayed when the mouse moves over it, otherwise it is automatically hidden","Editing Toolbar Auto-hide":"Editing Toolbar Auto-hide","Editing Toolbar Centred Display":"Editing Toolbar Centred Display","Whether the toolbar is centred or full-width, the default is full-width.":"Whether the toolbar is centred or full-width, the default is full-width.","Custom Backgroud Color":"Custom Backgroud Colour","Custom Font Color":"Custom Font Colour","🎨 Set Custom Background":"🎨 Set Custom Background","🖌 Set Custom Font Color":"🖌 Set Custom Font Colour","Click on the picker to adjust the color":"Click on the picker to adjust the colour","Mobile Enabled or Not":"Mobile Enabled or Not","Whether to enable the plugin for the mobile client, the default is enabled.":"Whether to enable the plugin for the mobile client, the default is enabled.","Whether to enable on mobile devices with device width less than 768px.":"Whether to enable on mobile devices with device width less than 768px, the default is disable.",Reset:"Reset",Fix:"Fix","Fix Editing Toolbar":"Fix Editing Toolbar",General:"General",Appearance:"Appearance",Commands:"Commands","Choose between fixed position or cursor following mode":"Choose between fixed position, cursor following or Top mode.","Add and manage commands":"Add and manage commands","Choose where Editing Toolbar will append upon regeneration.":"Choose where Editing Toolbar will append upon regeneration.","Whether to enable on mobile devices with device width less than 768px":"Whether to enable on mobile devices with device width less than 768px","Choose between a glass morphism, tiny and default style.":"Choose between a glass morphism, tiny and default style.","Refresh Toolbar":"Refresh Toolbar","Add Command":"Add Command",Settings:"Settings","Position Style":"Position Style",Columns:"Columns","Drag to Adjust Position":"Drag to Adjust Position","Vertical Position":"Vertical Position","Horizontal Position":"Horizontal Position","Toolbar Position":"Toolbar Position","Choose an icon":"Choose an icon","Search for an icon...":"Search for an icon...",All:"All",Obsidian:"Obsidian",Glyph:"Glyph",Custom:"Custom","Choose a command":"Choose a command","The command":"The command","already exists":"already exists","Enter the icon code, format as <svg>.... </svg>":"Enter the icon code, format as <svg>.... </svg>","No matching icons found":"No matching icons found","Custom Commands":"Custom Commands","Toolbar Commands":"Toolbar Commands",ID:"ID",Prefix:"Prefix",Suffix:"Suffix",Pattern:"Pattern","Custom Format Commands":"Custom Format Commands","Add, edit or delete custom format commands.":"Add, edit or delete custom format commands.",Edit:"Edit","Command ID":"Command ID",'Unique identifier, no spaces, e.g.: "my-custom-format"':'Unique identifier, no spaces, e.g.: "my-custom-format"',"Displayed name in toolbar and menu":"Displayed name in toolbar and menu","Add content before selected text":"Add content before selected text","Add content after selected text":"Add content after selected text","Character offset of cursor after formatting":"Character offset of cursor after formatting","Line offset of cursor after formatting":"Line offset of cursor after formatting","Whether to insert at the beginning of the next line":"Whether to insert at the beginning of the next line","Command icon (click to select)":"Command icon (click to select)","Choose Icon":"Choose Icon",Save:"Save",Cancel:"Cancel","Edit Custom Command":"Edit Custom Command","Add Custom Command":"Add Custom Command","Command ID and command name cannot be empty":"Command ID and command name cannot be empty","Command ID cannot contain spaces":"Command ID cannot contain spaces",'Command ID "${this.commandId}" already exists':'Command ID "${this.commandId}" already exists',"Cursor Position Offset":"Cursor Position Offset","Line Offset":"Line Offset","Line Head Format":"Line Head Format",Icon:"Icon","Command Name":"Command Name","Are you sure you want to restore all settings to default? This will lose all your custom configurations.":"Are you sure you want to restore all settings to default? This will lose all your custom configurations.","Restore default":"Restore default","Restore default settings":"Restore default settings","🔄Restore default settings":"🔄Restore default settings","🔧Data repair":"🔧Data repair","Command IDs have been successfully repaired!":"Command IDs have been successfully repaired!","No command IDs need to be repaired":"No command IDs need to be repaired","Error repairing command IDs, please check the console for details":"Error repairing command IDs, please check the console for details","Error restoring default settings, please check the console for details":"Error restoring default settings, please check the console for details","Successfully restored default settings!":"Successfully restored default settings!",Close:"Close",Tips:"Tips","This update changed the ID of some commands, please click this button to repair the commands to ensure the toolbar works properly":"This update changed the ID of some commands, please click this button to repair the commands to ensure the toolbar works properly","Repair command ID":"Repair command ID","This will reset all your custom configurations":"This will reset all your custom configurations","Notice:":"Notice:","This update rebuilds the entire code, reducing resource consumption":"This update rebuilds the entire code, reducing resource consumption","Optimized mobile usage, added canvas support, and added custom commands":"Optimized mobile usage, added canvas support, and added custom commands","This update is not compatible with 2.x version command ids, please click [Repair command] to be compatible":"This update is not compatible with 2.x version command ids, please click [Repair command] to be compatible","If you want to restore the default settings, please click [Restore default settings]":"If you want to restore the default settings, please click [Restore default settings]","Please execute a editingToolbar format command first, then enable the format brush":"Please execute a editingToolbar format command first, then enable the format brush","Format brush ON! Select text to apply":"Format brush ON! Select text to apply","format":"format\nClick the mouse middle or right key to close the formatting-brush","Add to Toolbar":"Add to Toolbar","This command is already in the toolbar.":"This command is already in the toolbar.","Command added to toolbar":"Command added to toolbar","Add this command to the toolbar.":"Add this command to the toolbar.","Callout Type":"Callout Type",Title:"Title","Optional, leave blank for default title":"Optional, leave blank for default title","Input title":"Input title","Collapse State":"Collapse State",Open:"Open",Closed:"Closed",Content:"Content",Insert:"Insert",Default:"Default","Input content":"Input content","Link Text":"Link Text","Link Alias":"Link Alias","Link URL":"Link URL","Embed Content":"Embed Content","Image Size":"Image Size","Insert New Line":"Insert New Line","Paste and Parse":"Paste and Parse","URL Format Error":"URL Format Error","Image Width":"Image Width","Image Height":"Image Height","If it is an image, turn on":"If it is an image, turn on","Insert a link on the next line":"Insert a link on the next line","Link Title(optional)":"Link Title(optional)",Alias:"Alias",Optional:"Optional","Default 0, format will keep the text selected":"Default 0, format will keep the text selected","to insert":"to insert","Latest Changes":"Latest Changes","📋View full changelog":"📋View full changelog","Open changelog":"Open changelog","Loading changelog...":"Loading changelog...","Open the complete changelog in your browser":"Open the complete changelog in your browser","Enable Multiple Configurations":"Enable Multiple Configurations","Enable different command configurations for each position style (following, top, fixed).":"Enable different command configurations for each position style (following, top, fixed).","Currently editing commands for":"Currently editing commands for","position style":"position style","Current Configuration":"Current Configuration","Switch between different command configurations.":"Switch between different command configurations.","Following Style":"Following Style","Top Style":"Top Style","Fixed Style":"Fixed Style","Mobile Style":"Mobile Style",configuration:"configuration","Deploy command to configurations":"Deploy command to configurations","All Configurations":"All Configurations",Deploy:"Deploy","Command deployed to selected configurations":"Command deployed to selected configurations","No configuration selected for deployment":"No configuration selected for deployment","Command already exists in selected configurations":"Command already exists in selected configurations","Command deployed to: ":"Command deployed to: ","Command Deleted.":"Command Deleted.","Confirm Delete?":"Confirm Delete?",Confirm:"Confirm","Are you sure you want to restore all settings to default? But custom commands will be preserved.":"Are you sure you want to restore all settings to default? But custom commands will be preserved.","Successfully restored default settings! (Custom commands preserved)":"Successfully restored default settings! (Custom commands preserved)","This will reset all your custom configurations, but custom commands will be preserved":"This will reset all your custom configurations, but custom commands will be preserved","Import/Export":"Import/Export","Export Configuration":"Export Configuration","Export your toolbar configuration to share with others.":"Export your toolbar configuration to share with others.",Export:"Export","Import Configuration":"Import Configuration","Import toolbar configuration from JSON.":"Import toolbar configuration from JSON.",Import:"Import","Usage Instructions":"Usage Instructions","Export: Generate a JSON configuration that you can save or share.":"Export: Generate a JSON configuration that you can save or share.","Import: Paste a previously exported JSON configuration.":"Import: Paste a previously exported JSON configuration.","You can choose to export all settings, only toolbar commands, or only custom commands":"You can choose to export all settings, only toolbar commands, or only custom commands","When importing, the plugin will only update the settings included in the import data":"When importing, the plugin will only update the settings included in the import data","Warning: Importing configuration will overwrite your current settings. Consider exporting your current configuration first as a backup.":"Warning: Importing configuration will overwrite your current settings. Consider exporting your current configuration first as a backup.","Export Type":"Export Type","Choose what to export":"Choose what to export","All Settings":"All Settings","Toolbar Commands Only":"Toolbar Commands Only","Custom Commands Only":"Custom Commands Only","Export Content":"Export Content","Copy this content to share with others":"Copy this content to share with others","Loading...":"Loading...","Copy to Clipboard":"Copy","Configuration copied to clipboard":"Configuration copied to clipboard","Failed to copy configuration":"Failed to copy configuration","Paste the configuration JSON here":"Paste the configuration JSON here","Paste configuration here...":"Paste configuration here...","Invalid import data":"Invalid import data","Configuration imported successfully":"Configuration imported successfully","No valid configuration found in import data":"No valid configuration found in import data","Failed to import configuration. Invalid format.":"Failed to import configuration. Invalid format.","Import Mode":"Import Mode","Choose how to import the configuration":"Choose how to import the configuration","Update Mode (Add new items and update existing ones)":"Update Mode (Add new items and update existing ones)","Overwrite Mode (Replace all settings with imported ones)":"Overwrite Mode (Replace all settings with imported ones)","Configuration imported successfully (Overwrite mode)":"Configuration imported successfully (Overwrite mode)","Configuration imported successfully (Update mode)":"Configuration imported successfully (Update mode)","Warning: Overwrite mode will completely replace your current settings with the imported ones. Consider exporting your current configuration first as a backup.":"Warning: Overwrite mode will completely replace your current settings with the imported ones. Consider exporting your current configuration first as a backup.","Warning: Update mode will add new items and update existing ones based on the imported configuration.":"Warning: Update mode will add new items and update existing ones based on the imported configuration.","Add Format Command":"Add Format Command",Regex:"Regex","Prefix/Suffix":"Prefix/Suffix","Insert Special Char":"Insert Special Char","Add Regex Command":"Add Regex Command","Switch Regex Command Window":"Switch Regex Command Window","Please select text first":"Please select text first","The selected text does not meet the condition requirements":"The selected text does not meet the condition requirements","Regex command execution error: ":"Regex command execution error: ","Copy code":"Copy code","Copied!":"Copied!","Explain the syntax of JavaScript regular expressions":"Explain the syntax of JavaScript regular expressions","Apply regular expression replacement":"Apply regular expression replacement","Conditional matching":"Conditional matching","Complete regular expression code (copy to AI for explanation)":"Complete regular expression code (copy to AI for explanation)","Error: ":"Error: ","Regex pattern cannot be empty":"Regex pattern cannot be empty","Command already exists":"Command already exists","Choose icon":"Choose icon","URL to Markdown link":"URL to Markdown link","Convert MM/DD/YYYY to YYYY-MM-DD":"Convert MM/DD/YYYY to YYYY-MM-DD","Add bold to keywords":"Add bold to keywords","Format phone number":"Format phone number","Remove extra spaces":"Remove extra spaces","Convert HTML bold tags to Markdown format":"Convert HTML bold tags to Markdown format","Convert quoted text to quote block":"Convert quoted text to quote block","Convert CSV to Markdown table row":"Convert CSV to Markdown table row","Add uniform alias to Markdown links":"Add uniform alias to Markdown links","Delete empty lines (multiline mode)":"Delete empty lines (multiline mode)","Add list symbol to each line (multiline mode)":"Add list symbol to each line (multiline mode)","If the text contains important, set the text highlight (conditional format)":"If the text contains important, set the text highlight (conditional format)","Matching pattern":"Matching pattern","Regex pattern to match":"Regex pattern to match","Replacement pattern (use $1, $2, etc. to reference capture groups)":"Replacement pattern (use $1, $2, etc. to reference capture groups)","Ignore case":"Ignore case","Global replace":"Global replace","Multiline mode":"Multiline mode","Use condition":"Use condition","Condition pattern":"Condition pattern","Only apply custom command when text matches the condition":"Only apply custom command when text matches the condition","Must exist regular expression or text":"Must exist regular expression or text","Replacement pattern":"Replacement pattern","Match case-insensitive":"Match case-insensitive","^ and $ match the start and end of each line":"^ and $ match the start and end of each line","Replace all matches":"Replace all matches",Command:"Command","Input example text to view the formatting effect of the command...":"Input example text to view the formatting effect of the command...",Description:"Description","[Example]":"[Example]","[Requirements]":"[Requirements]","[Output]":"[Output]","AI question template:":"AI question template:","I need to convert the url to a markdown format link":"I need to convert the url to a markdown format link","For example, convert https://example.com to [https://example.com](https://example.com)":"For example, convert https://example.com to [https://example.com](https://example.com)","Use js regular expression to implement, and output the parameters in the following format (the result does not need to be escaped with json)":"Use js regular expression to implement, and output the parameters in the following format (the result does not need to be escaped with json)","[Description]":"[Description]","How to use AI to get regular expressions?":"How to use AI to get regular expressions?","Regular expression examples":"Regular expression examples","Edit regular expression command":"Edit regular expression command","Add regular expression command":"Add regular expression command","Result: ":"Result: ","Example text:":"Example text:",Preview:"Preview",Result:"Result","Please select text or copy text to clipboard first":"Please select text or copy text to clipboard first","Overwrite Import":"Overwrite Import","Update Import":"Update Import","Importing configuration...":"Importing configuration...","Following Style Only":"Following Style Only","Top Style Only":"Top Style Only","Fixed Style Only":"Fixed Style Only","Mobile Style Only":"Mobile Style Only","Unknown import type":"Unknown import type","All Toolbar Commands":"All Toolbar Commands","Initialize Commands":"Initialize Commands","Copy commands from the main menu configuration":"Copy commands from the main menu configuration","Initialize commands to default settings":"Initialize commands to default settings","Reset Commands":"Reset Commands","Commands reset successfully":"Commands reset successfully","Following style commands initialized from current menu commands":"Following style commands initialized from current menu commands","Commands initialized successfully":"Commands initialized successfully","Reset to Menu Commands":"Reset to Menu Commands","Are you sure you want to reset the current configuration?":"Are you sure you want to reset the current configuration?","Following style commands successfully initialized":"Following style commands successfully initialized","Top style commands successfully initialized":"Top style commands successfully initialized","Fixed style commands successfully initialized":"Fixed style commands successfully initialized","Mobile style commands successfully initialized":"Mobile style commands successfully initialized","Reset commands to default settings":"Reset commands to default settings",Clear:"Clear","Remove all commands from this configuration.":"Remove all commands from this configuration.","Are you sure you want to clear all commands under the current style?":"Are you sure you want to clear all commands under the current style?","Current style commands have been cleared":"Current style commands have been cleared","Manage Commands":"Manage Commands","Reset or clear all commands in this configuration":"Reset or clear all commands in this configuration","One-click Clear":"One-click Clear","Import Commands from Other Styles":"Import Commands from Other Styles","Copy commands from another style configuration.":"Copy commands from another style configuration.","Main menu only":"Main menu only","This import will update:":"This import will update:","Custom commands":"Custom commands","Toolbar commands":"Toolbar commands","General settings":"General settings","Please paste configuration data first":"Please paste configuration data first","Invalid import data format":"Invalid import data format","Import From":"Import From","This import will:":"This import will:","Update general settings":"Update general settings","Update Main Menu Commands":"Update Main Menu Commands","Update Custom Commands":"Update Custom Commands","Update Following Style Commands":"Update Following Style Commands","Update Top Style Commands":"Update Top Style Commands","Update Fixed Style Commands":"Update Fixed Style Commands","Update Mobile Style Commands":"Update Mobile Style Commands","Clear all Main Menu Commands":"Clear all Main Menu Commands","Clear all Custom Commands":"Clear all Custom Commands","Clear all Following Style Commands":"Clear all Following Style Commands","Clear all Top Style Commands":"Clear all Top Style Commands","Clear all Fixed Style Commands":"Clear all Fixed Style Commands","Clear all Mobile Style Commands":"Clear all Mobile Style Commands","Overwrite Mode (Replace settings with imported ones)":"Overwrite Mode (Replace settings with imported ones)","Warning: Overwrite mode will replace existing settings with imported ones.":"Warning: Overwrite mode will replace existing settings with imported ones.","Warning: Update mode will add new items and update existing ones.":"Warning: Update mode will add new items and update existing ones.","Enable Multiple Config":"Enable Multiple Config","Set Multiple Config to:":"Set Multiple Config to:",Enable:"Enable",Disable:"Disable","Set Position Style to:":"Set Position Style to:",Following:"Following",Top:"Top",Fixed:"Fixed",Mobile:"Mobile","All commands":"All commands"," Overwrite mode will replace existing settings with imported ones.":" Overwrite mode will replace existing settings with imported ones."," Update mode will merge imported settings with existing ones.":" Update mode will merge imported settings with existing ones.","Do you want to continue?":"Do you want to continue?","Imported settings:":"Imported settings:","Imported commands:":"Imported commands:","Disable toolbar for this view":"Disable toolbar for this view","Enable toolbar for this view":"Enable toolbar for this view","Manage all view types":"Manage all view types","Current View: ":"Current View: ","Appearance Style":"Appearance Style","Position Settings":"Position Settings","All commands have been removed.":"All commands have been removed.","Join the Community":"Join the Community","Share your toolbar settings and styles in our":"Share your toolbar settings and styles in our","Get inspired by what others have created or showcase your own customizations.":"Get inspired by what others have created or showcase your own customisations.","Toolbar Preview (With a hypothetical command configuration.)":"Toolbar Preview (With a hypothetical command configuration.)","Toolbar Theme":"Toolbar Theme","Select a preset toolbar theme, automatically setting the background color, icon color, and size for the selected style.":"Select a preset toolbar theme, automatically setting the background colour, icon colour, and size for the selected style.","Toolbar Background Color":"Toolbar Background Colour","Set the background color of the toolbar.":"Set the background colour of the toolbar.","Toolbar Icon Color":"Toolbar Icon Colour","Set the color of the toolbar icon.":"Set the colour of the toolbar icon.","Toolbar Icon Size":"Toolbar Icon Size","Set the size of the toolbar icon (px); default: 18px":"Set the size of the toolbar icon (px); default: 18px","Custom Theme":"Custom Theme","Fixed Position Offset":"Fixed Position Offset","Choose the offset of the Editing Toolbar in the fixed position.":"Choose the offset of the Editing Toolbar in the fixed position.","Renumber List":"Renumber List","Fetch Remote Title":"Fetch Remote Title","Please enter a URL first":"Please enter a URL first","Failed to fetch title for":"Failed to fetch title for","Link Title (optional)":"Link Title (optional)","Unable to detect editor width":"Unable to detect editor width","Fit Editor Width":"Fit Editor Width","Please execute a format command or select format text first, then enable the format brush":"Please execute a format command or select format text first, then enable the format brush","Use \\n to represent line breaks":"Use \\n to represent line breaks","Use to represent line breaks":"Use to represent line breaks","Top Toolbar":"Top Toolbar","Enable the toolbar positioned at the top.":"Enable the toolbar positioned at the top.","Following Toolbar":"Following Toolbar","Enable the toolbar that appears upon text selection.":"Enable the toolbar that appears upon text selection.","Fixed Toolbar":"Fixed Toolbar","Enable the toolbar whose position may be fixed where you please.":"Enable the toolbar whose position may be fixed where you please.","Toolbar Settings":"Toolbar Settings","Choose which toolbar style's appearance you want to edit.":"Choose which toolbar style's appearance you want to edit.","Vertical Split":"Vertical Split"},es:{},fr:{},hi:{},id:{},it:{},ja:{},ko:{},nl:{},nn:{},pl:{},pt:{},"pt-br":{"Editing Toolbar Append Method":"Método de Inserção da Barra de Ferramentas","Choose where Editing Toolbar will append upon regeneration. To see the change, hit the refresh button below, or in the status bar menu.":"Escolha onde a Barra de Ferramentas será inserida ao regenerar. Para ver a alteração, clique no botão de atualização abaixo, ou no menu da barra de status.","Editing Toolbar aesthetic":"Estilo da Barra de Ferramentas","Choose between a glass morphism, tiny and default style for Editing Toolbar. To see the change, hit the refresh button below, or in the status bar menu.":"Escolha entre um estilo de vidro, pequeno e padrão para a Barra de Ferramentas. Para ver a alteração, clique no botão de atualização abaixo, ou no menu da barra de status.","Editing Toolbar position":"Posição da Barra de Ferramentas","Choose between fixed position or cursor following mode.":"Escolha entre posição fixa ou modo contextual.","Editing Toolbar Columns":"Colunas da Barra de Ferramentas","Choose the number of columns per row to display on Editing Toolbar.":"Escolha o número de colunas por linha para exibir na Barra de Ferramentas.","Editing Toolbar refresh":"Atualizar Barra de Ferramentas","Editing Toolbar Commands":"Comandos da Barra de Ferramentas","Add a command onto Editing Toolbar from Obsidian's commands library. To reorder the commands, drag and drop the command items. To delete them, use the delete buttom to the right of the command item. Editing Toolbar will not automaticaly refresh after reordering commands. Use the refresh button above.":"Adicione um comando na Barra de Ferramentas a partir da biblioteca de comandos do Obsidian. Para reordenar os comandos, arraste e solte os itens do comando. Para deletar, use o botão de deletar à direita do item do comando. A Barra de Ferramentas não atualizará automaticamente após reordenar os comandos. Use o botão de atualização acima.","Format Brush Off!":"Pincel de formatação desligado!","Hide & Show":"Ocultar & Mostrar","Editing Toolbar will only refresh automatically after you have either added or deleted a command from it. To see UI changes to editingToolbar (above settings changes) use the refresh button. If you forget to refresh in settings, no worries. There is also a refresh button in the editingToolbar status bar menu.":"A barra de edição só atualizará automaticamente após você ter adicionado ou deletado um comando dela. Para ver as alterações na interface do editingToolbar (alterações acima das configurações) use o botão de atualização. Se você esquecer de atualizar nas configurações, não se preocupe. Também há um botão de atualização na barra de status da Barra de Edição.","Font-Color formatting brush ON!":"Pincel de cor da fonte ativado!",More:"Mais","Font Colors":"Cores de Texto","Format Brush":"Pincel de formatação","Background Color":"Cor de Fundo",Refresh:"Atualizar",Add:"Adicionar",Delete:"Deletar","Change Command Name":"Alterar Nome do Comando","Add Submenu":"Adicionar Submenu","Add Separator":"Adicionar Separador","Enter the icon code, it looks like <svg>.... </svg> format":"Digite o código do ícone, parece com o formato <svg>.... </svg>","Please enter a new name: ":"Por favor, digite um novo nome: ","Drag the slider to move the position":"Arraste o slider para mover a posição","Plugin Settings":"Configurações do Plugin","Background-color formatting brush ON!":"Pincel de cor de fundo ativado!\nClique com o botão do meio ou direito do mouse para sair do modo.","Clear formatting brush ON!":"Pincel de formatação ativado!","Clear formatting brush ON!\nClick the mouse middle or right key to close the formatting-brush":"Pincel de formatação ativado!\nClique com o botão do meio ou direito do mouse para sair do modo de formatação.","The toolbar is displayed when the mouse moves over it, otherwise it is automatically hidden":"A barra de ferramentas é exibida quando o mouse passa por cima dela, caso contrário, ela é automaticamente oculta.","Editing Toolbar Auto-hide":"Auto-ocultação da Barra de Ferramentas","Editing Toolbar Centred Display":"Exibição Centralizada da Barra de Ferramentas","Whether the toolbar is centred or full-width, the default is full-width.":"Define se a barra de ferramentas é centralizada ou ocupa toda a largura. O padrão é largura completa.","Custom Backgroud Color":"Cor de Fundo Personalizada","Custom Font Color":"Cor de Texto Personalizada","🎨 Set Custom Background":"🎨 Definir Cor de Fundo Personalizada","🖌 Set Custom Font Color":"🖌 Definir Cor de Texto Personalizada","Click on the picker to adjust the color":"Clique no seletor para ajustar a cor","Mobile Enabled or Not":"Habilitar em dispositivos móveis","Whether to enable the plugin for the mobile client, the default is enabled.":"Habilitar o plugin para dispositivos móveis, o padrão é habilitado.","Whether to enable on mobile devices with device width less than 768px.":"Habilitar o plugin para dispositivos móveis com largura de dispositivo menor que 768px, o padrão é desabilitado.",Reset:"Reiniciar",Fix:"Ajustar","Fix Editing Toolbar":"Ajustar Barra de Ferramentas",General:"Geral",Appearance:"Aparência",Commands:"Comandos","Choose between fixed position or cursor following mode":"Escolha entre posição fixa ou modo contextual.","Add and manage commands":"Adicionar e gerenciar comandos","Choose where Editing Toolbar will append upon regeneration.":"Escolha onde a Barra de Ferramentas será inserida ao regenerar.","Whether to enable on mobile devices with device width less than 768px":"Habilitar o plugin para dispositivos móveis com largura de dispositivo menor que 768px","Choose between a glass morphism, tiny and default style.":"Escolha entre um estilo de vidro, pequeno e padrão.","Refresh Toolbar":"Atualizar Barra de Ferramentas","Add Command":"Adicionar Comando",Settings:"Configurações","Position Style":"Estilo de Posição",Columns:"Colunas","Drag to Adjust Position":"Arraste para ajustar a posição","Vertical Position":"Posição Vertical","Horizontal Position":"Posição Horizontal","Toolbar Position":"Posição da Barra de Ferramentas","Choose an icon":"Escolha um ícone","Search for an icon...":"Pesquisar por um ícone...",All:"Todos",Obsidian:"Obsidian",Glyph:"Ícone",Custom:"Personalizado","Choose a command":"Escolha um comando","The command":"O comando","already exists":"já existe","Enter the icon code, format as <svg>.... </svg>":"Digite o código do ícone, formato como <svg>.... </svg>","No matching icons found":"Nenhum ícone correspondente encontrado","Custom Commands":"Comandos Personalizados","Toolbar Commands":"Comandos da Barra de Ferramentas",ID:"ID",Prefix:"Prefixo",Suffix:"Sufixo",Pattern:"Padrão","Custom Format Commands":"Comandos de Formatação Personalizados","Add, edit or delete custom format commands.":"Adicionar, editar ou deletar comandos de formatação personalizados.",Edit:"Editar","Command ID":"ID do Comando",'Unique identifier, no spaces, e.g.: "my-custom-format"':'Identificador único, sem espaços, exemplo: "meu-comando-personalizado"',"Displayed name in toolbar and menu":"Nome exibido na barra de ferramentas e menu","Add content before selected text":"Adicionar conteúdo antes do texto selecionado","Add content after selected text":"Adicionar conteúdo depois do texto selecionado","Character offset of cursor after formatting":"Deslocamento do cursor após a formatação","Line offset of cursor after formatting":"Deslocamento da linha do cursor após a formatação","Whether to insert at the beginning of the next line":"Inserir no início da próxima linha","Command icon (click to select)":"Ícone do comando (clique para selecionar)","Choose Icon":"Escolha um ícone",Save:"Salvar",Cancel:"Cancelar","Edit Custom Command":"Editar Comando Personalizado","Add Custom Command":"Adicionar Comando Personalizado","Command ID and command name cannot be empty":"ID do Comando e nome do comando não podem ser vazios","Command ID cannot contain spaces":"ID do Comando não pode conter espaços",'Command ID "${this.commandId}" already exists':'ID do Comando "${this.commandId}" já existe',"Cursor Position Offset":"Deslocamento do cursor","Line Offset":"Deslocamento da linha","Line Head Format":"Formatação de linha inicial",Icon:"Ícone","Command Name":"Nome do Comando","Are you sure you want to restore all settings to default? This will lose all your custom configurations.":"Tem certeza que deseja restaurar todas as configurações para a configuração padrão? Isso irá apagar todas as suas configurações personalizadas.","Restore default":"Restaurar padrão","Restore default settings":"Restaurar configurações padrão","🔄Restore default settings":"🔄Restaurar configurações padrão","🔧Data repair":"🔧Reparar dados","Command IDs have been successfully repaired!":"IDs de comando foram reparadas com sucesso!","No command IDs need to be repaired":"Nenhuma ID de comando precisa ser reparada","Error repairing command IDs, please check the console for details":"Erro ao reparar IDs de comando, por favor verifique o console para mais detalhes","Error restoring default settings, please check the console for details":"Erro ao restaurar configurações padrão, por favor verifique o console para mais detalhes","Successfully restored default settings!":"Configurações padrão restauradas com sucesso!",Close:"Fechar",Tips:"Dicas","This update changed the ID of some commands, please click this button to repair the commands to ensure the toolbar works properly":"Esta atualização alterou o ID de alguns comandos. Clique neste botão para repará-los e garantir que a barra de ferramentas funcione corretamente.","Repair command ID":"Reparar ID do Comando","This will reset all your custom configurations":"Isso irá resetar todas as suas configurações personalizadas","Notice:":"Nota:","This update rebuilds the entire code, reducing resource consumption":"Esta atualização recompila todo o código, reduzindo o consumo de recursos","Optimized mobile usage, added canvas support, and added custom commands":"Otimizado para uso em dispositivos móveis, adicionando suporte para o canvas e adicionado comandos personalizados","This update is not compatible with 2.x version command ids, please click [Repair command] to be compatible":"Esta atualização não é compatível com IDs de comando da versão 2.x. Clique em [Reparar comando] para corrigir a compatibilidade.","If you want to restore the default settings, please click [Restore default settings]":"Se você quiser restaurar as configurações padrão, por favor clique em [Restaurar configurações padrão].","Please execute a editingToolbar format command first, then enable the format brush":"Execute um comando de formatação da barra de edição antes de ativar o pincel de formatação.","Format brush ON! Select text to apply":"Pincel de formatação ativado! Selecione o texto para aplicar","format":"\nClique com o botão do meio ou direito do mouse para sair do modo de formatação.","Add to Toolbar":"Adicionar à Barra de Edição","This command is already in the toolbar.":"Este comando já está na barra de ferramentas.","Command added to toolbar":"Comando adicionado à barra de ferramentas","Add this command to the toolbar.":"Adicionar este comando à barra de ferramentas.","Callout Type":"Tipo de Callout",Title:"Título","Optional, leave blank for default title":"Opcional, deixe em branco para o título padrão","Input title":"Digite o título","Collapse State":"Estado de Colapso",Open:"Abrir",Closed:"Fechado",Content:"Conteúdo",Insert:"Inserir",Default:"Padrão","Input content":"Digite o conteúdo","Link Text":"Texto do Link","Link Alias":"Alias do Link","Link URL":"URL do Link","Embed Content":"Conteúdo Embutido","Image Size":"Tamanho da Imagem","Insert New Line":"Inserir Nova Linha","Paste and Parse":"Colar e Analisar","URL Format Error":"Erro de Formato de URL","Image Width":"Largura da Imagem","Image Height":"Altura da Imagem","If it is an image, turn on":"Se for uma imagem, ative","Insert a link on the next line":"Inserir um link na próxima linha","Link Title(optional)":"Título do Link(opcional)",Alias:"Alias",Optional:"Opcional","Default 0, format will keep the text selected":"Padrão 0, o formato manterá o texto selecionado","to insert":"para inserir","Latest Changes":"Últimas Alterações","📋View full changelog":"📋Ver o registro de alterações completo","Open changelog":"Abrir registro de alterações","Loading changelog...":"Carregando registro de alterações...","Open the complete changelog in your browser":"Abrir o registro de alterações completo no seu navegador","Enable Multiple Configurations":"Habilitar Múltiplas Configurações","Enable different command configurations for each position style (following, top, fixed).":"Habilitar configurações de comandos diferentes para cada modo de posição (following, top, fixed).","Currently editing commands for":"Atualmente editando comandos para","position style":"estilo de posição","Current Configuration":"Configuração Atual","Switch between different command configurations.":"Trocar entre configurações de comando diferentes.","Following Style":"Estilo Contextual","Top Style":"Estilo de Topo","Fixed Style":"Estilo Fixo","Mobile Style":"Estilo Mobile",configuration:"configuração","Deploy command to configurations":"Implantar comando para configurações","All Configurations":"Todas as Configurações",Deploy:"Implantar","Command deployed to selected configurations":"Comando implantado para configurações selecionadas","No configuration selected for deployment":"Nenhuma configuração selecionada para implantação","Command already exists in selected configurations":"Comando já existe nas configurações selecionadas","Command deployed to: ":"Comando implantado para: ","Command Deleted":"Comando Deletado","Confirm Delete?":"Confirmar Deleção?",Confirm:"Confirmar","Are you sure you want to restore all settings to default? But custom commands will be preserved.":"Tem certeza que deseja restaurar todas as configurações para a configuração padrão? Mas os comandos personalizados serão preservados.","Successfully restored default settings! (Custom commands preserved)":"Configurações padrão restauradas com sucesso! (Comandos personalizados preservados)","This will reset all your custom configurations, but custom commands will be preserved":"Isso redefinirá todas as suas configurações personalizadas, mas os comandos personalizados serão preservados.","Import/Export":"Importar/Exportar","Export Configuration":"Exportar Configuração","Export your toolbar configuration to share with others.":"Exportar sua configuração da barra de ferramentas para compartilhar com outros.",Export:"Exportar","Import Configuration":"Configuração de Importação","Import toolbar configuration from JSON.":"Importar configuração da barra de ferramentas em formato JSON.",Import:"Importar","Usage Instructions":"Instruções de Uso","Export: Generate a JSON configuration that you can save or share.":"Exportar: Gerar uma configuração em formato JSON para salvar ou compartilhar.","Import: Paste a previously exported JSON configuration.":"Importar: Colar uma configuração em formato JSON exportada anteriormente.","You can choose to export all settings, only toolbar commands, or only custom commands":"Você pode escolher exportar todas as configurações, apenas comandos da barra de ferramentas, ou apenas comandos personalizados","When importing, the plugin will only update the settings included in the import data":"Ao importar, o plugin irá atualizar apenas as configurações incluídas nos dados de importação","Warning: Importing configuration will overwrite your current settings. Consider exporting your current configuration first as a backup.":"Aviso: A importação de configuração irá sobrescrever suas configurações atuais. Considere exportar sua configuração atual primeiro como backup.","Export Type":"Tipo de Exportação","Choose what to export":"Escolha o que exportar","All Settings":"Todas as Configurações","Toolbar Commands Only":"Apenas Comandos da Barra de Ferramentas","Custom Commands Only":"Apenas Comandos Personalizados","Export Content":"Conteúdo de Exportação","Copy this content to share with others":"Copiar este conteúdo para compartilhar com outros","Loading...":"Carregando...","Copy to Clipboard":"Copiar para a área de transferência","Configuration copied to clipboard":"Configuração copiada para a área de transferência","Failed to copy configuration":"Falha ao copiar configuração","Paste the configuration JSON here":"Colar a configuração JSON aqui","Paste configuration here...":"Colar configuração aqui...","Invalid import data":"Dados de importação inválidos","Configuration imported successfully":"Configuração importada com sucesso","No valid configuration found in import data":"Nenhuma configuração válida encontrada nos dados de importação","Failed to import configuration. Invalid format.":"Falha ao importar configuração. Formato inválido.","Import Mode":"Modo de Importação","Choose how to import the configuration":"Escolha como importar a configuração","Update Mode (Add new items and update existing ones)":"Modo de Atualização (Adicionar novos itens e atualizar os existentes)","Overwrite Mode (Replace all settings with imported ones)":"Modo de Sobrescrever (Substituir todas as configurações com as importadas)","Configuration imported successfully (Overwrite mode)":"Configuração importada com sucesso (Modo de Sobrescrever)","Configuration imported successfully (Update mode)":"Configuração importada com sucesso (Modo de Atualização)","Warning: Overwrite mode will completely replace your current settings with the imported ones. Consider exporting your current configuration first as a backup.":"Aviso: O modo de sobrescrever irá substituir todas as suas configurações atuais com as importadas. Considere exportar sua configuração atual primeiro como backup.","Warning: Update mode will add new items and update existing ones based on the imported configuration.":"Aviso: O modo de atualização irá adicionar novos itens e atualizar os existentes com base na configuração importada.","Add Format Command":"Adicionar formatação",Regex:"Regex","Prefix/Suffix":"Prefixo/Sufixo","Insert Special Char":"Inserir Caractere Especial","Add Regex Command":"Adicionar regex","Switch Regex Command Window":"Trocar para Janela de Comando de Regex","Please select text first":"Por favor selecione o texto primeiro","Current line is empty, please select text or move to a non-empty line":"A linha atual está vazia, por favor selecione o texto ou mova para uma linha não vazia","Use current line for regex commands":"Usar a linha atual para comandos de regex","When no text is selected, regex commands will use the current line instead of clipboard content":"Quando não houver texto selecionado, comandos de regex usarão a linha atual em vez do conteúdo da área de transferência","The selected text does not meet the condition requirements":"O texto selecionado não atende aos requisitos da condição","Regex command execution error: ":"Erro ao executar comando de regex: ","Copy code":"Copiar código","Copied!":"Copiado!","Explain the syntax of JavaScript regular expressions":"Explicar a sintaxe das expressões regulares em JavaScript","Apply regular expression replacement":"Aplicar substituição de expressão regular","Conditional matching":"Ocorrência Condicional","Complete regular expression code (copy to AI for explanation)":"Código de expressão regular completo (copiar para explicação com IA)","Error: ":"Erro: ","Regex pattern cannot be empty":"Padrão de regex não pode estar vazio","Command already exists":"Comando já existe","Choose icon":"Escolha um ícone","URL to Markdown link":"URL para Link Markdown","Convert MM/DD/YYYY to YYYY-MM-DD":"Converter MM/DD/YYYY para YYYY-MM-DD","Add bold to keywords":"Adicionar negrito a palavras-chave","Format phone number":"Formatar número de telefone","Remove extra spaces":"Remover espaços extra","Convert HTML bold tags to Markdown format":"Converter tags HTML de negrito para negrito em Markdown","Convert quoted text to quote block":"Converter texto citado para bloco de citação","Convert CSV to Markdown table row":"Converter CSV para linha de tabela Markdown","Add uniform alias to Markdown links":"Adicionar um alias uniforme aos links Markdown","Delete empty lines (multiline mode)":"Deletar linhas vazias (modo multilinha)","Add list symbol to each line (multiline mode)":"Adicionar símbolo de lista a cada linha (modo multilinha)","If the text contains important, set the text highlight (conditional format)":'Se o texto contiver "importante", aplicar destaque ao texto (formatação condicional)',"Matching pattern":"Padrão de correspondência","Regex pattern to match":"Padrão de regex a ser correspondido","Replacement pattern (use $1, $2, etc. to reference capture groups)":"Padrão de substituição (use $1, $2, etc. para referenciar grupos de captura)","Ignore case":"Ignorar maiúsculas e minúsculas","Global replace":"Substituir globalmente","Multiline mode":"Modo multilinha","Use condition":"Usar condição","Condition pattern":"Padrão de condição","Only apply custom command when text matches the condition":"Aplicar o comando personalizado apenas quando o texto corresponder à condição","Must exist regular expression or text":"Deve existir expressão regular ou texto","Replacement pattern":"Padrão de substituição","Match case-insensitive":"Ignorar maiúsculas e minúsculas","^ and $ match the start and end of each line":"^ e $ correspondem ao início e ao fim de cada linha","Replace all matches":"Substituir todas as ocorrências",Command:"Comando","Input example text to view the formatting effect of the command...":"Digite um texto de exemplo para visualizar o efeito do comando...",Description:"Descrição","[Example]":"[Exemplo]","[Requirements]":"[Requisitos]","[Output]":"[Saída]","AI question template:":"Modelo de pergunta para IA:","I need to convert the url to a markdown format link":"Preciso converter a URL para um link no formato Markdown","For example, convert https://example.com to [https://example.com](https://example.com)":"Por exemplo, converter https://exemplo.com para [https://exemplo.com](https://exemplo.com)","Use js regular expression to implement, and output the parameters in the following format (the result does not need to be escaped with json)":"Usar expressões regulares em JavaScript para implementar e gerar os parâmetros no formato abaixo (o resultado não precisa ser escapado em JSON).","[Description]":"[Descrição]","How to use AI to get regular expressions?":"Como usar IA para obter expressões regulares?","Regular expression examples":"Exemplos de expressões regulares","Edit regular expression command":"Editar comando de expressão regular","Add regular expression command":"Adicionar comando de expressão regular","Result: ":"Resultado: ","Example text:":"Texto de exemplo:",Preview:"Visualizar",Result:"Resultado","Please select text or copy text to clipboard first":"Por favor selecione o texto ou copie o texto para a área de transferência primeiro","Overwrite Import":"Sobrescrever Importação","Update Import":"Atualizar Importação","Importing configuration...":"Importando configuração...","Following Style Only":"Disponível apenas no modo contextual","Top Style Only":"Disponível apenas no modo de topo","Fixed Style Only":"Disponível apenas no modo fixo","Mobile Style Only":"Disponível apenas no modo mobile","Unknown import type":"Tipo de importação desconhecido","All Toolbar Commands":"Todos os Comandos da Barra de Ferramentas","Initialize Commands":"Inicializar Comandos","Copy commands from the main menu configuration":"Copiar comandos do menu principal","Initialize commands to default settings":"Inicializar comandos para configurações padrão","Reset Commands":"Resetar Comandos","Commands reset successfully":"Comandos resetados com sucesso","Following style commands initialized from current menu commands":"Comandos de estilo contextual inicializados a partir dos comandos do menu principal","Commands initialized successfully":"Comandos inicializados com sucesso","Reset to Menu Commands":"Resetar para Comandos do Menu","Are you sure you want to reset the current configuration?":"Tem certeza que deseja resetar a configuração atual?","Following style commands successfully initialized":"Comandos de estilo contextual inicializados com sucesso","Top style commands successfully initialized":"Comandos de estilo de topo inicializados com sucesso","Fixed style commands successfully initialized":"Comandos de estilo fixo inicializados com sucesso","Mobile style commands successfully initialized":"Comandos de estilo mobile inicializados com sucesso","Reset commands to default settings":"Resetar comandos para configurações padrão",Clear:"Limpar","Remove all commands from this configuration.":"Remover todos os comandos desta configuração.","Are you sure you want to clear all commands under the current style?":"Tem certeza que deseja limpar todos os comandos sob o estilo atual?","Current style commands have been cleared":"Comandos do estilo atual foram limpos","Manage Commands":"Gerenciar Comandos","Reset or clear all commands in this configuration":"Resetar ou limpar todos os comandos nesta configuração","One-click Clear":"Limpar com um clique","Import Commands from Other Styles":"Importar Comandos de Outros Estilos","Copy commands from another style configuration.":"Copiar comandos de outra configuração de estilo.","Main menu only":"Apenas para o menu principal","This import will update:":"Esta importação irá atualizar:","Custom commands":"Comandos Personalizados","Toolbar commands":"Comandos da Barra de Ferramentas","General settings":"Configurações Gerais","Please paste configuration data first":"Por favor coloque os dados da configuração primeiro","Invalid import data format":"Formato de dados de importação inválido","Import From":"Importar de","This import will:":"Esta importação irá:","Update general settings":"Atualizar configurações gerais","Update Main Menu Commands":"Atualizar Comandos do Menu Principal","Update Custom Commands":"Atualizar Comandos Personalizados","Update Following Style Commands":"Atualizar Comandos de Estilo Contextual","Update Top Style Commands":"Atualizar Comandos de Estilo de Topo","Update Fixed Style Commands":"Atualizar Comandos de Estilo Fixo","Update Mobile Style Commands":"Atualizar Comandos de Estilo Mobile","Clear all Main Menu Commands":"Limpar todos os Comandos do Menu Principal","Clear all Custom Commands":"Limpar todos os Comandos Personalizados","Clear all Following Style Commands":"Limpar todos os Comandos de Estilo Contextual","Clear all Top Style Commands":"Limpar todos os Comandos de Estilo de Topo","Clear all Fixed Style Commands":"Limpar todos os Comandos de Estilo Fixo","Clear all Mobile Style Commands":"Limpar todos os Comandos de Estilo Mobile","Overwrite Mode (Replace settings with imported ones)":"Modo de Sobrescrever (Substituir configurações com as importadas)","Warning: Overwrite mode will replace existing settings with imported ones.":"Aviso: O modo de sobrescrever irá substituir todas as suas configurações atuais com as importadas.","Warning: Update mode will add new items and update existing ones.":"Aviso: O modo de atualização irá adicionar novos itens e atualizar os existentes com base na configuração importada.","Enable Multiple Config":"Habilitar Múltiplas Configurações","Set Multiple Config to:":"Definir Múltiplas Configurações para:",Enable:"Habilitar",Disable:"Desabilitar","Set Position Style to:":"Definir Estilo de Posição para:",Following:"Contextual",Top:"Topo",Fixed:"Fixo",Mobile:"Mobile","All commands":"Todos os Comandos"," Overwrite mode will replace existing settings with imported ones.":" O modo de sobrescrever irá substituir todas as suas configurações atuais com as importadas."," Update mode will merge imported settings with existing ones.":" O modo de atualização irá adicionar novos itens e atualizar os existentes com base na configuração importada.","Do you want to continue?":"Deseja continuar?","Imported settings:":"Configurações importadas:","Imported commands:":"Comandos importados:","Disable toolbar for this view":"Desabilitar barra de ferramentas para esta visualização","Enable toolbar for this view":"Habilitar barra de ferramentas para esta visualização","Manage all view types":"Gerenciar todos os tipos de visualização","Current View: ":"Visualização Atual: ","Appearance Style":"Estilo de Aparência","Position Settings":"Configurações de Posição","All commands have been removed.":"Todos os comandos foram removidos.","Join the Community":"Juntar-se à Comunidade","Share your toolbar settings and styles in our":"Compartilhe suas configurações e estilos da barra de ferramentas em nossa","Get inspired by what others have created or showcase your own customizations.":"Inspire-se com o que outros criaram ou mostre suas próprias personalizações.","Toolbar Preview (With a hypothetical command configuration.)":"Visualização da barra de ferramentas (com uma configuração de comandos hipotética).","Toolbar Theme":"Estilo da Barra de Ferramentas","Select a preset toolbar theme, automatically setting the background color, icon color, and size for the selected style.":"Selecione um estilo de barra de ferramentas pré-definido, automaticamente definindo a cor de fundo, cor do ícone e tamanho para o estilo selecionado.","Toolbar Background Color":"Cor de Fundo da Barra de Ferramentas","Set the background color of the toolbar.":"Definir a cor de fundo da barra de ferramentas.","Toolbar Icon Color":"Cor do Ícone da Barra de Ferramentas","Set the color of the toolbar icon.":"Definir a cor do ícone da barra de ferramentas.","Toolbar Icon Size":"Tamanho do Ícone da Barra de Ferramentas","Set the size of the toolbar icon (px); default: 18px":"Definir o tamanho do ícone da barra de ferramentas (px); padrão: 18px","Custom Theme":"Estilo Personalizado","Fixed Position Offset":"Deslocamento Fixo","Choose the offset of the Editing Toolbar in the fixed position.":"Escolha o deslocamento da Barra de Edição na posição fixa.","Renumber List":"Renumerar Lista","Fetch Remote Title":"Obter Título Remoto","Please enter a URL first":"Por favor digite uma URL primeiro","Failed to fetch title for":"Falha ao obter título para","Link Title (optional)":"Título do Link (opcional)","Unable to detect editor width":"Não foi possível detectar a largura do editor","Fit Editor Width":"Ajustar Largura do Editor","Please execute a format command or select format text first, then enable the format brush":"Execute um comando de formatação ou selecione um texto já formatado antes de ativar o pincel de formatação.","Use \\n to represent line breaks":"Use \\n para representar quebras de linha","Use to represent line breaks":"Use para representar quebras de linha","Top Toolbar":"Barra de Ferramentas de Topo","Enable the toolbar positioned at the top.":"Habilitar a barra de ferramentas posicionada no topo.","Following Toolbar":"Barra de Ferramentas Contextual","Enable the toolbar that appears upon text selection.":"Habilitar a barra de ferramentas que aparece ao selecionar texto.","Fixed Toolbar":"Barra de Ferramentas Fixa","Enable the toolbar whose position may be fixed where you please.":"Habilitar a barra de ferramentas cuja posição pode ser fixa onde você preferir.","Toolbar Settings":"Configurações da Barra de Ferramentas","Choose which toolbar style's appearance you want to edit.":"Escolha qual estilo de barra de ferramentas você deseja editar.","Vertical Split":"Divisão Vertical"},ro:{},ru:{},tr:{},"zh-cn":b,"zh-tw":y}[e.moment.locale()];function v(e){return"string"!=typeof e||0===e.length?"":C&&C[e]||f[e]||e}class w extends e.FuzzySuggestModal{constructor(e,t,o=!1,n,i){super(e.app),this.customCallback=null,this.plugin=e,this.command=t,this.issub=o,this.customCallback=n||null,this.setPlaceholder(v("Choose an icon")),this.currentEditingConfig=i||""}capitalJoin(e){return e.split(" ").map(e=>e[0].toUpperCase()+e.substring(1)).join(" ")}getItems(){return i}getItemText(e){return this.capitalJoin(e.replace("feather-","").replace("remix-","").replace("bx-","").replace(/([A-Z])/g," $1").trim().replace(/-/gi," "))}renderSuggestion(t,o){const n=createSpan({cls:"editingToolbarIconPick"});o.appendChild(n),e.setIcon(n,t.item),super.renderSuggestion(t,o)}async onChooseItem(e){if("Custom"===e)return this.customCallback?void new x(this.app,this.plugin,{id:this.command.id,name:this.command.name,icon:""},this.issub,e=>{this.customCallback(e)}).open():void new x(this.app,this.plugin,this.command,this.issub,null,this.currentEditingConfig).open();if(this.customCallback)return void this.customCallback(e);const t=this.plugin.getCurrentCommands(this.currentEditingConfig);if(this.command.icon){let o=s(this.plugin,this.command,this.issub,t);this.issub?t[o.index].SubmenuCommands[o.subindex].icon=e:t[o.index].icon=e,this.plugin.updateCurrentCommands(t,this.currentEditingConfig)}else this.command.icon=e,t.push(this.command),this.plugin.updateCurrentCommands(t,this.currentEditingConfig);await this.plugin.saveSettings(),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100),console.log(`%c '${this.command.name}' `,"color: Violet")}}class x extends e.Modal{constructor(e,t,o,n,i,a){super(e),this.customCallback=null,this.plugin=t,this.item=o,this.issub=n,this.customCallback=i||null,this.currentEditingConfig=a||"",this.containerEl.addClass("editingToolbar-Modal"),this.containerEl.addClass("customicon")}onOpen(){const{contentEl:e}=this;e.createEl("b",{text:v("Enter the icon code, format as <svg>.... </svg>")});const t=document.createElement("textarea");t.className="wideInputPromptInputEl",t.placeholder="",t.value=this.item.icon||"",t.style.width="100%",t.style.height="200px",e.appendChild(t),t.addEventListener("input",async()=>{const e=t.value;if(this.customCallback)return void(this.item.icon=e);this.item.icon=e;const o=this.plugin.getCurrentCommands(this.currentEditingConfig),n=s(this.plugin,this.item,this.issub,o);if(this.issub){let t=n.subindex;-1===t?this.plugin.settings.menuCommands[n.index].SubmenuCommands.push(this.item):this.plugin.settings.menuCommands[n.index].SubmenuCommands[t].icon=e}else{let e=n.index;-1===e?this.plugin.settings.menuCommands.push(this.item):this.plugin.settings.menuCommands[e].icon=this.item.icon}await this.plugin.saveSettings()}),this.submitEnterCallback&&t.addEventListener("keydown",this.submitEnterCallback)}onClose(){const{contentEl:e}=this;e.empty(),this.customCallback?this.customCallback(this.item.icon||""):setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100)}}class k extends e.FuzzySuggestModal{constructor(e,t){super(e.app),this.plugin=e,this.app,this.setPlaceholder(v("Choose a command")),this.currentEditingConfig=t||""}getItems(){return app.commands.listCommands()}getItemText(e){return v(e.name)}async onChooseItem(t){const o=this.plugin.getCurrentCommands(this.currentEditingConfig);o.findIndex(e=>e.id==t.id)>-1?new e.Notice(v("The command")+v(t.name)+v("already exists"),3e3):t.icon?(o.push(t),this.plugin.updateCurrentCommands(o,this.currentEditingConfig),await this.plugin.saveSettings(),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100),console.log(`%c '${t.name}' `,"color: Violet")):new w(this.plugin,t,!1,null,this.currentEditingConfig).open()}}class S extends e.Modal{constructor(e,t,o,n,i){super(t.app),this.plugin=t,this.item=o,this.issub=n,this.currentEditingConfig=i||"",this.containerEl.addClass("editingToolbar-Modal"),this.containerEl.addClass("changename")}onOpen(){const{contentEl:t}=this;t.createEl("b",{text:v("Please enter a new name: ")});const o=new e.TextComponent(t);o.inputEl.classList.add("InputPromptInputEl"),o.setPlaceholder("").setValue(this.item.name??"").onChange(e.debounce(async e=>{const t=this.plugin.getCurrentCommands(this.currentEditingConfig);let o=s(this.plugin,this.item,this.issub,t);if(this.item.name=e,this.issub){let n=o.subindex;-1===n?t[o.index].SubmenuCommands.push(this.item):t[o.index].SubmenuCommands[n].name=e}else{let e=o.index;-1===e?t.push(this.item):t[e].name=this.item.name}this.plugin.updateCurrentCommands(t),await this.plugin.saveSettings()},100,!0)).inputEl.addEventListener("keydown",this.submitEnterCallback)}onClose(){const{contentEl:e}=this;e.empty(),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100)}}class T extends e.Modal{constructor(e,t){super(t.app),this.needSave=!1,this.plugin=t,this.containerEl.addClass("editingToolbar-Modal")}onOpen(){const{contentEl:t}=this;t.createEl("p",{text:v("Drag the slider to move the position")});const o=t.createDiv({cls:"slider-container"}),n=o.createDiv({cls:"vertical-slider-container"});n.createEl("p",{text:v("Vertical Position")});const i=o.createDiv({cls:"horizontal-slider-container"});i.createEl("p",{text:v("Horizontal Position")});const a=o.createDiv({cls:"columns-slider-container"});a.createEl("p",{text:v("Editing Toolbar Columns")});const s=document.body.clientHeight,r=document.body.clientWidth,l=Math.floor(s/3),c=-Math.floor(s),d=Math.floor(r/2),u=-Math.floor(r/2),m=new e.SliderComponent(n).setLimits(c,l,5).setValue(this.plugin.settings.verticalPosition||0).onChange(e.debounce(e=>{this.needSave=!0,this.plugin.settings.verticalPosition=e,h(this.plugin.settings)},100,!0)).setDynamicTooltip(),p=new e.SliderComponent(i).setLimits(u,d,10).setValue(this.plugin.settings.horizontalPosition||0).onChange(e.debounce(e=>{this.needSave=!0,this.plugin.settings.horizontalPosition=e,g(this.plugin.settings)},100,!0)).setDynamicTooltip(),f=new e.SliderComponent(a).setLimits(1,32,1).setValue(this.plugin.settings.cMenuNumRows||12).onChange(e.debounce(async e=>{this.needSave=!0,this.plugin.settings.cMenuNumRows=e,await this.plugin.saveSettings(),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100)},100,!0)).setDynamicTooltip();o.createDiv({cls:"reset-container"}).createEl("button",{text:v("Reset"),cls:"reset-button"}).addEventListener("click",()=>{this.needSave=!0,m.setValue(0),p.setValue(0),f.setValue(12),this.plugin.settings.verticalPosition=0,this.plugin.settings.horizontalPosition=0,this.plugin.settings.cMenuNumRows=12,h(this.plugin.settings),g(this.plugin.settings)})}async onClose(){const{contentEl:e}=this;e.empty(),this.needSave&&await this.plugin.saveSettings()}}function E(){return e.moment.locale()}function I(e=E()){const t=e.toLowerCase();return"zh"===t||t.startsWith("zh-")}const A=[{value:"04-fast",label:"04-fast"},{value:"03-agent",label:"03-agent"}],M={mode:"smart",completion:"04-fast",rewrite:"04-fast",reasoning:"03-agent",artifact:"03-agent"};function P(e,t){const o=e.pkmerModelRouting??M;if("smart"===o.mode)return M[t];const n=o[t]?.trim();return n||M[t]}const N=[{id:"template-demo-variables",name:"📝 ",prompt:" {{file:content}} ,:\n{{selection}}\n\n:\n1. \n2. \n3. ",icon:"lucide-sparkles"},{id:"template-task-variables",name:"",prompt:'{{date}} {{file:content}} :\n{{selection}}\n\n Obsidian Tasks \n\n- [ ] /🔼/🔽/ \n- [ ] 📅 YYYY-MM-DD \n- [ ] YYYY-MM-DD HH:mm \n- [ ] 🛫 YYYY-MM-DD \n- [ ] 🔁 every day/week/month \n- [ ] # #\n\n\n1. "///" \n2. "//" 🔼\n3. 📅 YYYY-MM-DD \n4. YYYY-MM-DD HH:mm \n5. 🔁 every week/month\n6. # # #\n\n\n- [ ] 📅 2026-04-25 #\n- [ ] 🔁 every week on Monday 09:00 #\n- [ ] 🔼 📅 2026-04-23 #',icon:"lucide-sparkles"},{id:"template-dataview",name:" Dataview",prompt:", Obsidian Dataview :\n1. 使 DataviewJS DQL \n2. \n3. \n4. ,使 DataviewJS\n\n:",icon:"lucide-database"},{id:"template-templater",name:" Templater ",prompt:" Obsidian Templater :\n1. 使 Templater (<% %>)\n2. \n3. \n4. \n5. \n\n:",icon:"lucide-file-code"},{id:"template-mermaid",name:" Mermaid ",prompt:" {{selection}}, Mermaid :\n1. (///)\n2. 使\n3. \n4. \n",icon:"lucide-workflow"},{id:"template-metadata",name:" YAML",prompt:" {{file:content}}, YAML Frontmatter :\n1. \n2. (tags, aliases, date)\n3. \n4. \n\n:",icon:"lucide-file-json"},{id:"template-callout",name:"使Callout",prompt:" {{selection}},使 Obsidian Callout :\n1. callout (note/tip/warning/danger)\n2. \n3. \n4. \n\n:",icon:"lucide-message-square"}],D=[{id:"template-demo-variables",name:"📝 Summarize Key Points",prompt:"Analyze the structure of {{file:content}} and focus on:\n{{selection}}\n\nPlease provide:\n1. A concise overview\n2. The key points\n3. Suggestions for improvement",icon:"lucide-sparkles"},{id:"template-task-variables",name:"Extract Tasks",prompt:"Today's date is {{date}}. Extract all actionable tasks from {{file:content}}, with special attention to:\n{{selection}}\n\nPlease output strictly in Obsidian Tasks plugin format, one task per line:\n\n- [ ] Task description /🔼/🔽/ priority\n- [ ] Task description 📅 YYYY-MM-DD due date\n- [ ] Task description YYYY-MM-DD HH:mm reminder\n- [ ] Task description 🛫 YYYY-MM-DD start date\n- [ ] Task description 🔁 every day/week/month recurrence\n- [ ] Task description #tag #project\n\nExtraction rules:\n1. If the text implies urgency such as urgent, ASAP, immediately, or today, add .\n2. If it implies near-term timing such as tomorrow, this week, or soon, add 🔼.\n3. Convert explicit dates to 📅 YYYY-MM-DD.\n4. Convert explicit times to YYYY-MM-DD HH:mm when possible.\n5. Add recurrence for repeated work such as 🔁 every week/month.\n6. Add practical tags for each task.\n\nExample output:\n- [ ] Finish project report 📅 2026-04-25 #work\n- [ ] Weekly team sync 🔁 every week on Monday 09:00 #meeting\n- [ ] Follow up on client request 🔼 📅 2026-04-23 #follow-up",icon:"lucide-sparkles"},{id:"template-dataview",name:"Generate Dataview",prompt:"Help me generate an Obsidian Dataview query block based on my requirement. Requirements:\n1. Use DataviewJS or DQL syntax.\n2. Include the necessary filters and sorting.\n3. Add short comments explaining each part.\n4. Use DataviewJS if the logic is complex.\n\nMy requirement:",icon:"lucide-database"},{id:"template-templater",name:"Design Templater Template",prompt:"Help me design an Obsidian Templater template. Requirements:\n1. Use Templater syntax (<% %>).\n2. Include dynamic date, time, and similar variables.\n3. Support user input prompts.\n4. Add necessary conditionals and loops.\n5. Comment the purpose of each section.\n\nTemplate purpose:",icon:"lucide-file-code"},{id:"template-mermaid",name:"Create Mermaid Diagram",prompt:"Based on my selected text {{selection}}, generate Mermaid diagram code. Requirements:\n1. Choose an appropriate diagram type such as flowchart, sequence, class, or gantt.\n2. Use clear node names.\n3. Add useful styling and comments when needed.\n4. Ensure the syntax is valid and renderable.\n",icon:"lucide-workflow"},{id:"template-metadata",name:"Design YAML",prompt:"Based on the current note content {{file:content}}, help me design a suitable YAML Frontmatter structure for this note. Requirements:\n1. Recommend fields that fit the note content.\n2. Include common fields such as tags, aliases, and date.\n3. Suggest useful custom fields.\n4. Briefly explain the purpose of each field.\n\nNote type:",icon:"lucide-file-json"},{id:"template-callout",name:"Wrap with Callout",prompt:"Based on my selected text {{selection}}, wrap it using an Obsidian Callout block. Requirements:\n1. Choose an appropriate callout type such as note, tip, warning, or danger.\n2. Support nesting and folding when helpful.\n3. Include a title and content.\n4. Allow code blocks or lists when needed.\n\nContent requirement:",icon:"lucide-message-square"}];function L(e=E()){return(I(e)?N:D).map(e=>({...e}))}const F={enabled:!1,consentAccepted:!1,onboardingShown:!1,providerMode:"pkmer-first",enableInlineCompletion:!0,inlineCompletionHintLearned:!1,completionTrigger:"manual",completionDelay:500,enableRewrite:!0,showRewriteToolbarOnSelection:!1,rewriteMinSelectionLength:1,pkmerApiBaseUrl:"https://newapi.pkmer.cn",pkmerModel:"04-fast",pkmerModelRouting:M,pkmer:{tokenExpiresAt:0,userInfo:null},enableCustomModel:!1,customModel:{apiFormat:"openai-compatible",baseUrl:"",apiKey:"",model:"",temperature:.2},customPromptHistory:[],customPromptTemplates:L("zh-cn")},O=[{instruction:"improve",label:"Improve writing",group:"Edit"},{instruction:"fix-grammar",label:"Fix spelling & grammar",group:"Edit"},{instruction:"make-shorter",label:"Make shorter",group:"Edit"},{instruction:"make-longer",label:"Make longer",group:"Edit"},{instruction:"simplify",label:"Simplify language",group:"Edit"},{instruction:"professional",label:"Professional tone",group:"Tone"},{instruction:"casual",label:"Casual tone",group:"Tone"},{instruction:"translate-en",label:"English",group:"Translate"},{instruction:"translate-zh",label:"Chinese",group:"Translate"},{instruction:"translate-ja",label:"Japanese",group:"Translate"},{instruction:"translate-de",label:"German",group:"Translate"},{instruction:"translate-fr",label:"French",group:"Translate"},{instruction:"translate-es",label:"Spanish",group:"Translate"},{instruction:"explain",label:"Explain this",group:"Generate"},{instruction:"summarize",label:"Summarize",group:"Generate"},{instruction:"continue",label:"Continue writing",group:"Generate"}],R="editing-toolbar-pkmer-access-token",q="editing-toolbar-pkmer-refresh-token",B="editing-toolbar-pkmer-ai-token",$="editing-toolbar-custom-model-api-key",_="https://api.pkmer.cn/api/v1/oauth/authorize",z="https://api.pkmer.cn/api/v1/oauth/token",U="https://api.pkmer.cn/api/v1/oauth/userinfo",V="pkmer_dd2a562c8653ca0112a050150d974ccd",H="openid profile email ai:token",W="http://localhost:10891/editing-toolbar/callback",j="obsidian://editing-toolbar-pkmer-auth",K=10891,Y=["body","workspace"],G=["default","tiny","glass","custom"],J=["following","top","fixed"],Z={lastVersion:"0.0.0",aestheticStyle:"default",positionStyle:"top",menuCommands:[{id:"editing-toolbar:editor-undo",name:"Undo Edit",icon:"undo-glyph"},{id:"editing-toolbar:editor-redo",name:"Redo Edit",icon:"redo-glyph"},{id:"editing-toolbar:toggle-format-brush",name:"Format Brush",icon:"paintbrush"},{id:"editing-toolbar:format-eraser",name:"Clear Text Formatting",icon:"eraser"},{id:"editing-toolbar:header2-text",name:"Header 2",icon:"header-2"},{id:"editing-toolbar:header3-text",name:"Header 3",icon:"header-3"},{id:"SubmenuCommands-header",name:"submenu",icon:"header-n",SubmenuCommands:[{id:"editing-toolbar:header1-text",name:"Header 1",icon:"header-1"},{id:"editing-toolbar:header4-text",name:"Header 4",icon:"header-4"},{id:"editing-toolbar:header5-text",name:"Header 5",icon:"header-5"},{id:"editing-toolbar:header6-text",name:"Header 6",icon:"header-6"}]},{id:"editing-toolbar:toggle-bold",name:"Bold",icon:"bold-glyph"},{id:"editing-toolbar:toggle-italics",name:"Italic",icon:"italic-glyph"},{id:"editing-toolbar:toggle-strikethrough",name:"Strikethrough",icon:"strikethrough-glyph"},{id:"editing-toolbar:underline",name:"Underline",icon:"underline-glyph"},{id:"editing-toolbar:toggle-highlight",name:"Highlight",icon:"highlight-glyph"},{id:"SubmenuCommands-text-tools",name:"Text Tools",icon:"box",menuType:"dropdown",SubmenuCommands:[{id:"editing-toolbar:get-plain-text",name:"Get Plain Text",icon:"lucide-file-text"},{id:"editing-toolbar:smart-symbols",name:"Full Half Converter",icon:"lucide-at-sign"},{id:"editingToolbar-Divider-Line",name:"Line Operations",icon:"vertical-split"},{id:"editing-toolbar:insert-blank-lines",name:"Insert Blank Lines",icon:"lucide-space"},{id:"editing-toolbar:remove-blank-lines",name:"Remove Blank Lines",icon:"lucide-minimize-2"},{id:"editing-toolbar:split-lines",name:"Split Lines",icon:"lucide-split"},{id:"editing-toolbar:merge-lines",name:"Merge Lines",icon:"lucide-merge"},{id:"editing-toolbar:dedupe-lines",name:"Dedupe Lines",icon:"lucide-filter"},{id:"editingToolbar-Divider-Line",name:"Text Processing",icon:"vertical-split"},{id:"editing-toolbar:add-wrap",name:"Add Prefix/Suffix",icon:"lucide-wrap-text"},{id:"editing-toolbar:number-lines",name:"Number Lines (Custom)",icon:"lucide-list-ordered"},{id:"editing-toolbar:remove-whitespace-trim",name:"Trim Line Ends",icon:"lucide-scissors"},{id:"editing-toolbar:remove-whitespace-compress",name:"Shrink Extra Spaces",icon:"lucide-minimize"},{id:"editing-toolbar:remove-whitespace-all",name:"Remove All Whitespace",icon:"lucide-eraser"},{id:"editingToolbar-Divider-Line",name:"Advanced Tools",icon:"vertical-split"},{id:"editing-toolbar:list-to-table",name:"List to Table",icon:"lucide-table"},{id:"editing-toolbar:table-to-list",name:"Table to List",icon:"lucide-list"},{id:"editing-toolbar:extract-between",name:"Extract Between Strings",icon:"lucide-brackets"}]},{id:"SubmenuCommands-lucdf3en5",name:"submenu",icon:"edit",SubmenuCommands:[{id:"editing-toolbar:editor-cut",name:"Cut",icon:"lucide-scissors"},{id:"editing-toolbar:editor-copy",name:"Copy",icon:"lucide-copy"},{id:"editing-toolbar:editor-paste",name:"Paste",icon:"lucide-clipboard-type"},{id:"editing-toolbar:editor:swap-line-down",name:"Swap Line Down",icon:"lucide-corner-right-down"},{id:"editing-toolbar:editor:swap-line-up",name:"Swap Line Up",icon:"lucide-corner-right-up"}]},{id:"editing-toolbar:editor:attach-file",name:"Attach File",icon:"lucide-paperclip"},{id:"editing-toolbar:editor:insert-table",name:"Insert Table",icon:"lucide-table"},{id:"editing-toolbar:editor:cycle-list-checklist",name:"Cycle List and Checklist",icon:"check-circle"},{id:"SubmenuCommands-luc8efull",name:"submenu",icon:"message-square",SubmenuCommands:[{id:"editing-toolbar:editor:toggle-blockquote",name:"Blockquote",icon:"lucide-text-quote"},{id:"editing-toolbar:insert-callout",name:"Callout",icon:"lucide-quote"}]},{id:"SubmenuCommands-mdcmder",name:"submenu",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M464 608 l0 -568 q0 -3 -2.5 -5.5 q-2.5 -2.5 -5.5 -2.5 l-80 0 q-3 0 -5.5 2.5 q-2.5 2.5 -2.5 5.5 l0 568 l-232 0 q-3 0 -5.5 2.5 q-2.5 2.5 -2.5 5.5 l0 80 q0 3 2.5 5.5 q2.5 2.5 5.5 2.5 l560 0 q3 0 5.5 -2.5 q2.5 -2.5 2.5 -5.5 l0 -80 q0 -3 -2.5 -5.5 q-2.5 -2.5 -5.5 -2.5 l-232 0 ZM864 696 q17 0 28.5 11.5 q11.5 11.5 11.5 28.5 q0 17 -11.5 28.5 q-11.5 11.5 -28.5 11.5 q-17 0 -28.5 -11.5 q-11.5 -11.5 -11.5 -28.5 q0 -17 11.5 -28.5 q11.5 -11.5 28.5 -11.5 ZM864 640 q-40 0 -68 28 q-28 28 -28 68 q0 40 28 68 q28 28 68 28 q40 0 68 -28 q28 -28 28 -68 q0 -40 -28 -68 q-28 -28 -68 -28 ZM576 322 l0 -63 q0 -3 2 -5 l89 -70 l-89 -70 q-2 -2 -2 -5 l0 -63 q0 -4 3.5 -5.5 q3.5 -1.5 6.5 0.5 l170 133 q4 3 4.5 8.5 q0.5 5.5 -2.5 9.5 l-2 2 l-170 133 q-3 2 -6.5 0.5 q-3.5 -1.5 -3.5 -5.5 ZM256 322 l0 -63 q0 -3 -2 -5 l-89 -70 l89 -70 q2 -2 2 -5 l0 -63 q0 -4 -3.5 -5.5 q-3.5 -1.5 -6.5 0.5 l-170 133 q-4 3 -4.5 8.5 q-0.5 5.5 2.5 9.5 l2 2 l170 133 q3 2 6.5 0.5 q3.5 -1.5 3.5 -5.5 Z"></path></g></svg>',SubmenuCommands:[{id:"editing-toolbar:superscript",name:"Superscript",icon:"superscript-glyph"},{id:"editing-toolbar:subscript",name:"Subscript",icon:"subscript-glyph"},{id:"editing-toolbar:editor:toggle-code",name:"Inline Code",icon:"code-glyph"},{id:"editing-toolbar:codeblock",name:"Code Block",icon:"codeblock-glyph"},{id:"editing-toolbar:editor:insert-wikilink",name:"Wikilink",icon:'<svg width="15" height="15" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M306 134 l91 0 q1 0 1 -8 l0 -80 q0 -8 -1 -8 l-91 0 q-1 0 -1 7 q0 -8 -5 -8 l-45 0 q-5 0 -5 8 l0 784 q0 8 5 8 l45 0 q5 0 5 -8 q0 8 1 8 l91 0 q1 0 1 -8 l0 -80 q0 -8 -1 -8 l-91 0 q-1 0 -1 8 l0 -623 q0 8 1 8 ZM139 134 l91 0 q1 0 1 -8 l0 -80 q0 -8 -1 -8 l-91 0 q-1 0 -1 7 q0 -8 -5 -8 l-45 0 q-5 0 -5 8 l0 784 q0 8 5 8 l45 0 q5 0 5 -8 q0 8 1 8 l91 0 q1 0 1 -8 l0 -80 q0 -8 -1 -8 l-91 0 q-1 0 -1 8 l0 -623 q0 8 1 8 ZM711 134 q1 0 1 -8 l0 623 q0 -8 -1 -8 l-91 0 q-1 0 -1 8 l0 80 q0 8 1 8 l91 0 q1 0 1 -8 q0 8 4 8 l46 0 q4 0 4 -8 l0 -784 q0 -8 -4 -8 l-46 0 q-4 0 -4 8 q0 -7 -1 -7 l-91 0 q-1 0 -1 8 l0 80 q0 8 1 8 l91 0 ZM878 134 q1 0 1 -8 l0 623 q0 -8 -1 -8 l-91 0 q-1 0 -1 8 l0 80 q0 8 1 8 l91 0 q1 0 1 -8 q0 8 5 8 l45 0 q4 0 4 -8 l0 -784 q0 -8 -4 -8 l-45 0 q-5 0 -5 8 q0 -7 -1 -7 l-91 0 q-1 0 -1 8 l0 80 q0 8 1 8 l91 0 Z"></path></g></svg>'},{id:"editing-toolbar:editor:insert-embed",name:"Embed",icon:"note-glyph"},{id:"editing-toolbar:insert-link",name:"Link",icon:"link-glyph"},{id:"editing-toolbar:hrline",name:"Horizontal Divider",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M912 424 l0 -80 q0 -3 -2.5 -5.5 q-2.5 -2.5 -5.5 -2.5 l-784 0 q-3 0 -5.5 2.5 q-2.5 2.5 -2.5 5.5 l0 80 q0 3 2.5 5.5 q2.5 2.5 5.5 2.5 l784 0 q3 0 5.5 -2.5 q2.5 -2.5 2.5 -5.5 Z"></path></g></svg>'},{id:"editing-toolbar:toggle-inline-math",name:"Inline Math",icon:"lucide-sigma"},{id:"editing-toolbar:editor:insert-mathblock",name:"MathBlock",icon:"lucide-sigma-square"}]},{id:"SubmenuCommands-list",name:"submenu-list",icon:"bullet-list-glyph",SubmenuCommands:[{id:"editing-toolbar:editor:toggle-checklist-status",name:"Checklist",icon:"checkbox-glyph"},{id:"editing-toolbar:renumber-ordered-list",name:"Renumber Ordered List",icon:"list-restart"},{id:"editing-toolbar:toggle-numbered-list",name:"Ordered List",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M860 424 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-457 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l457 0 ZM860 756 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-457 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l457 0 ZM860 92 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-457 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l457 0 ZM264 136 l-3 -3 l-51 -57 l56 0 q14 0 24.5 -10 q10.5 -10 11.5 -25 l0 -1 q0 -15 -10.5 -25.5 q-10.5 -10.5 -24.5 -10.5 l-137 0 q-15 0 -25 10 q-10 10 -11 24.5 q-1 14.5 9 25.5 l63 70 l49 54 q7 7 7 16.5 q0 9.5 -7.5 16.5 q-7.5 7 -18.5 7 q-11 0 -18.5 -6.5 q-7.5 -6.5 -8.5 -16.5 l0 0 q0 -15 -10.5 -25.5 q-10.5 -10.5 -25.5 -10.5 q-15 0 -25.5 10.5 q-10.5 10.5 -10.5 25.5 q0 26 13.5 47.5 q13.5 21.5 36 34.5 q22.5 13 49 13 q26.5 0 49.5 -13 q23 -13 36 -34.5 q13 -21.5 13 -47.5 q0 -20 -7.5 -37.5 q-7.5 -17.5 -21.5 -30.5 l-1 -1 ZM173 794 q11 11 25 10.5 q14 -0.5 24.5 -10.5 q10.5 -10 10.5 -25 l0 -293 q0 -15 -10 -25.5 q-10 -10.5 -25 -10.5 q-15 0 -25.5 10 q-10.5 10 -11.5 25 l0 211 q-10 -8 -23.5 -7 q-13.5 1 -22.5 11 l-1 0 q-10 11 -9.5 25.5 q0.5 14.5 10.5 24.5 l58 54 Z"></path></g></svg>'},{id:"editing-toolbar:toggle-bullet-list",name:"Unordered List",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M860 424 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-477 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l477 0 ZM860 756 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-477 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l477 0 ZM860 92 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-477 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l477 0 ZM176 716 l0 0 ZM112 716 q0 -27 18.5 -45.5 q18.5 -18.5 45.5 -18.5 q27 0 45.5 18.5 q18.5 18.5 18.5 45.5 q0 27 -18.5 45.5 q-18.5 18.5 -45.5 18.5 q-27 0 -45.5 -18.5 q-18.5 -18.5 -18.5 -45.5 ZM176 384 l0 0 ZM112 384 q0 -27 18.5 -45.5 q18.5 -18.5 45.5 -18.5 q27 0 45.5 18.5 q18.5 18.5 18.5 45.5 q0 27 -18.5 45.5 q-18.5 18.5 -45.5 18.5 q-27 0 -45.5 -18.5 q-18.5 -18.5 -18.5 -45.5 ZM176 52 l0 0 ZM112 52 q0 -27 18.5 -45.5 q18.5 -18.5 45.5 -18.5 q27 0 45.5 18.5 q18.5 18.5 18.5 45.5 q0 27 -18.5 45.5 q-18.5 18.5 -45.5 18.5 q-27 0 -45.5 -18.5 q-18.5 -18.5 -18.5 -45.5 Z"></path></g></svg>'},{id:"editing-toolbar:undent-list",name:"Unindent List",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M872 302 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-429 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l429 0 ZM872 542 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-429 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l429 0 ZM872 784 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 ZM872 62 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 ZM244 534 l-123 -122 q-8 -7 -8 -18 q0 -11 8 -18 l123 -122 q8 -7 19 -7 q11 0 18.5 7.5 q7.5 7.5 7.5 18.5 l0 242 q0 11 -7.5 18.5 q-7.5 7.5 -18.5 7.5 q-11 0 -19 -7 Z"></path></g></svg>'},{id:"editing-toolbar:indent-list",name:"Indent list",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M872 302 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-429 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l429 0 ZM872 542 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-429 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l429 0 ZM872 784 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 ZM872 62 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 ZM158 534 l124 -122 q7 -7 7 -18 q0 -11 -7 -18 l-124 -122 q-7 -7 -18 -7 q-11 0 -19 7.5 q-8 7.5 -8 18.5 l0 242 q0 11 8 18.5 q8 7.5 19 7.5 q11 0 18 -7 Z"></path></g></svg>'}]},{id:"SubmenuCommands-aligin",name:"submenu-aligin",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M724 304 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-421 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l421 0 ZM872 540 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 ZM724 776 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-421 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l421 0 ZM872 68 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 Z"></path></g></svg>',SubmenuCommands:[{id:"editing-toolbar:justify",name:"Justify Text",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M112 736 l0 0 ZM120 736 l784 0 q8 0 8 -8 l0 -80 q0 -8 -8 -8 l-784 0 q-8 0 -8 8 l0 80 q0 8 8 8 ZM112 331 l0 0 ZM120 331 l784 0 q8 0 8 -8 l0 -80 q0 -8 -8 -8 l-784 0 q-8 0 -8 8 l0 80 q0 8 8 8 ZM112 128 l0 0 ZM120 128 l784 0 q8 0 8 -8 l0 -80 q0 -8 -8 -8 l-784 0 q-8 0 -8 8 l0 80 q0 8 8 8 ZM112 533 l0 0 ZM120 533 l784 0 q8 0 8 -8 l0 -80 q0 -8 -8 -8 l-784 0 q-8 0 -8 8 l0 80 q0 8 8 8 Z"></path></g></svg>'},{id:"editing-toolbar:left",name:"Align Text Left",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M572 304 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-421 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l421 0 ZM872 540 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 ZM572 776 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-421 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l421 0 ZM872 68 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 Z"></path></g></svg>'},{id:"editing-toolbar:center",name:"Center Text",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M724 304 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-421 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l421 0 ZM872 540 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 ZM724 776 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-421 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l421 0 ZM872 68 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 Z"></path></g></svg>'},{id:"editing-toolbar:right",name:"Align Text Right",icon:'<svg width="18" height="18" focusable="false" fill="currentColor" viewBox="0 0 1024 1024"><g transform="scale(1, -1) translate(0, -896) scale(0.9, 0.9) "><path class="path" d="M872 304 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-421 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l421 0 ZM872 540 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 ZM872 776 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-421 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l421 0 ZM872 68 q17 0 28.5 -11.5 q11.5 -11.5 11.5 -28 q0 -16.5 -11.5 -28.5 q-11.5 -12 -27.5 -12 l-721 0 q-17 0 -28.5 11.5 q-11.5 11.5 -11.5 28 q0 16.5 11.5 28.5 q11.5 12 27.5 12 l721 0 Z"></path></g></svg>'}]},{id:"editing-toolbar:change-font-color",name:"Change Font Color",icon:'<svg width="24" height="24" viewBox="0 0 24 24" focusable="false" fill="currentColor"><g fill-rule="evenodd"><path id="change-font-color-icon" d="M3 18h18v3H3z" style="fill:#2DC26B"></path><path d="M8.7 16h-.8a.5.5 0 01-.5-.6l2.7-9c.1-.3.3-.4.5-.4h2.8c.2 0 .4.1.5.4l2.7 9a.5.5 0 01-.5.6h-.8a.5.5 0 01-.4-.4l-.7-2.2c0-.3-.3-.4-.5-.4h-3.4c-.2 0-.4.1-.5.4l-.7 2.2c0 .3-.2.4-.4.4zm2.6-7.6l-.6 2a.5.5 0 00.5.6h1.6a.5.5 0 00.5-.6l-.6-2c0-.3-.3-.4-.5-.4h-.4c-.2 0-.4.1-.5.4z"></path></g></svg>'},{id:"editing-toolbar:change-background-color",name:"Change Background Color",icon:'<svg width="18" height="24" viewBox="0 0 256 256" version="1.1" xmlns="http://www.w3.org/2000/svg"><g stroke="none" stroke-width="1" fill="currentColor" fill-rule="evenodd"><g ><g fill="currentColor"><g transform="translate(119.502295, 137.878331) rotate(-135.000000) translate(-119.502295, -137.878331) translate(48.002295, 31.757731)" ><path d="M100.946943,60.8084699 L43.7469427,60.8084699 C37.2852111,60.8084699 32.0469427,66.0467383 32.0469427,72.5084699 L32.0469427,118.70847 C32.0469427,125.170201 37.2852111,130.40847 43.7469427,130.40847 L100.946943,130.40847 C107.408674,130.40847 112.646943,125.170201 112.646943,118.70847 L112.646943,72.5084699 C112.646943,66.0467383 107.408674,60.8084699 100.946943,60.8084699 Z M93.646,79.808 L93.646,111.408 L51.046,111.408 L51.046,79.808 L93.646,79.808 Z" fill-rule="nonzero"></path><path d="M87.9366521,16.90916 L87.9194966,68.2000001 C87.9183543,69.4147389 86.9334998,70.399264 85.7187607,70.4 L56.9423078,70.4 C55.7272813,70.4 54.7423078,69.4150264 54.7423078,68.2 L54.7423078,39.4621057 C54.7423078,37.2523513 55.5736632,35.1234748 57.0711706,33.4985176 L76.4832996,12.4342613 C78.9534987,9.75382857 83.1289108,9.5834005 85.8093436,12.0535996 C87.1658473,13.303709 87.9372691,15.0644715 87.9366521,16.90916 Z" fill-rule="evenodd"></path><path d="M131.3,111.241199 L11.7,111.241199 C5.23826843,111.241199 0,116.479467 0,122.941199 L0,200.541199 C0,207.002931 5.23826843,212.241199 11.7,212.241199 L131.3,212.241199 C137.761732,212.241199 143,207.002931 143,200.541199 L143,122.941199 C143,116.479467 137.761732,111.241199 131.3,111.241199 Z M124,130.241 L124,193.241 L19,193.241 L19,130.241 L124,130.241 Z" fill-rule="nonzero"></path></g></g><path d="M51,218 L205,218 C211.075132,218 216,222.924868 216,229 C216,235.075132 211.075132,240 205,240 L51,240 C44.9248678,240 40,235.075132 40,229 C40,222.924868 44.9248678,218 51,218 Z" id="change-background-color-icon" style="fill:#FA541C"></path></g></g></svg>'},{id:"editing-toolbar:fullscreen-focus",name:"Fullscreen Focus Mode",icon:"fullscreen"},{id:"editing-toolbar:workplace-fullscreen-focus",name:"Workplace Fullscreen",icon:"exit-fullscreen"}],followingCommands:[],topCommands:[],fixedCommands:[],mobileCommands:[],enableMultipleConfig:!1,enableTopToolbar:!1,enableFollowingToolbar:!1,enableFixedToolbar:!1,appendMethod:"workspace",shouldShowMenuOnSelect:!1,cMenuVisibility:!0,cMenuBottomValue:4.25,cMenuNumRows:12,cMenuWidth:610,cMenuFontColor:"#2DC26B",cMenuBackgroundColor:"#d3f8b6",autohide:!1,Iscentered:!1,custom_bg1:"#FFB78B8C",custom_bg2:"#CDF4698C",custom_bg3:"#A0CCF68C",custom_bg4:"#F0A7D88C",custom_bg5:"#ADEFEF8C",custom_fc1:"#D83931",custom_fc2:"#DE7802",custom_fc3:"#245BDB",custom_fc4:"#6425D0",custom_fc5:"#646A73",isLoadOnMobile:!1,horizontalPosition:0,verticalPosition:0,formatBrushes:{},customCommands:[],viewTypeSettings:{},appearanceByStyle:{top:{toolbarBackgroundColor:"rgba(var(--background-secondary-rgb), 0.7)",toolbarIconColor:"var(--text-normal)",toolbarIconSize:18,aestheticStyle:"default"},following:{toolbarBackgroundColor:"rgba(var(--background-secondary-rgb), 0.7)",toolbarIconColor:"var(--text-normal)",toolbarIconSize:18,aestheticStyle:"default"},fixed:{toolbarBackgroundColor:"rgba(var(--background-secondary-rgb), 0.7)",toolbarIconColor:"var(--text-normal)",toolbarIconSize:18,aestheticStyle:"default"},mobile:{toolbarBackgroundColor:"rgba(var(--background-secondary-rgb), 0.7)",toolbarIconColor:"var(--text-normal)",toolbarIconSize:18,aestheticStyle:"default"}},toolbarBackgroundColor:"rgba(var(--background-secondary-rgb), 0.7)",toolbarIconColor:"var(--text-normal)",toolbarIconSize:18,useCurrentLineForRegex:!1,ai:F};class X{static isAllowedViewType(e,t){if(!e)return!1;const o=e.getViewType(),n=window.app?.plugins?.plugins?.["editing-toolbar"];if(n?.settings?.viewTypeSettings&&void 0!==n.settings.viewTypeSettings[o])return n.settings.viewTypeSettings[o];return(t||["markdown","canvas","thino_view","meld-encrypted-view"]).includes(o)}static isSourceMode(e){return!!e&&"source"===e.getMode?.()}}const Q="editing-toolbar:ai-tools";const ee=[{id:"list",label:"Convert to list",icon:"lucide-list-tree"},{id:"table",label:"Convert to table",icon:"lucide-table-properties"},{id:"frontmatter",label:"Generate frontmatter",icon:"lucide-file-badge-2"},{id:"canvas",label:"Convert to canvas",icon:"lucide-waypoints"}],te=["Obsidian Markdown rules:","- Preserve valid Obsidian flavored Markdown whenever relevant.","- Preserve wikilinks like [[Note]], embeds like ![[Note]], tags, task lists, callouts, tables, and inline formatting if they appear in the source.","- For internal links use [[wikilinks]] rather than Markdown links whenever the target looks like a vault note.","- Use standard Markdown headings, lists, blockquotes, tables, and code fences only when they fit the content naturally."].join("\n"),oe=["Obsidian Bases skill requirements:","- Output a valid .base file body in YAML only. No explanations. No code fences.","- A base file may contain top-level filters, formulas, properties, summaries, and views.","- filters can be a single filter string or nested and/or/not filter objects.","- formulas is a mapping from formula name to expression string.","- properties config can include displayName for note, file, and formula properties.","- views must be an array. Each view should have a useful type such as table, cards, list, or map, plus a name and order.","- Use practical property names inferred from the source content, and use formula.* when referencing formula properties in views.","- Common file properties include file.name, file.basename, file.path, file.folder, file.ext, file.ctime, file.mtime, file.tags, file.links, file.backlinks, file.embeds, file.properties.","- Keep YAML valid: quote strings when needed, keep indentation consistent, and do not reference undefined formulas.","- Prefer concise but actually usable output over placeholders.","- If the source describes tabular entities, create at least one table view.","- If the source suggests browsing or grouping, consider cards or list views too.","- If filtering logic is unclear, you may omit filters rather than inventing weak ones.","- If there are date-like fields, formulas may use date(), now(), today(), and duration .days accessors.","- Return one complete semantic .base file ready to save and open in Obsidian.","Suggested schema pattern:","filters:"," and: []","formulas:"," formula_name: 'expression'","properties:"," property_name:",' displayName: "Display Name"',"views:"," - type: table",' name: "Overview"'," order:"," - file.name"," - property_name"].join("\n"),ne=["Obsidian JSON Canvas skill requirements:","- Output valid JSON only. No explanations. No code fences.","- The top-level object must contain arrays named nodes and edges.","- Every node needs id, type, x, y, width, and height.","- Every edge must reference existing node ids using fromNode and toNode.","- Use unique 16-character lowercase hexadecimal ids for all nodes and edges.","- Valid node types are text, file, link, and group.","- Prefer text nodes unless a file node or link node is clearly required by the source.","- Text nodes should contain concise, structured Markdown-friendly text.","- Use \\n inside JSON strings for line breaks. Never emit literal \\\\n.","- If useful, use one group node to organize the canvas, but do not overuse groups.","- Layout should be readable: align to a loose grid, leave about 50-100px spacing between nodes, and avoid overlaps.","- Coordinates can be negative, but prefer a clean left-to-right or center-out layout.","- A good canvas usually has a clear central node and connected supporting nodes rather than isolated fragments.","- Unless the source is tiny, create a meaningful structure with several nodes instead of only one or two.","- Use edge labels only when they add real meaning.","- Return a canvas that is ready to save as a .canvas file and open directly in Obsidian.","Reference shape:","{",' "nodes": [',' { "id": "6f0ad84f44ce9c17", "type": "text", "x": 0, "y": 0, "width": 360, "height": 180, "text": "# Topic\\n\\n- point" }'," ],",' "edges": [',' { "id": "0123456789abcdef", "fromNode": "6f0ad84f44ce9c17", "toNode": "a1b2c3d4e5f67890", "toEnd": "arrow" }'," ]","}"].join("\n");let ie;const ae={markdown:".markdown-source-view",thino_view:".markdown-source-view",canvas:".canvas-wrapper",excalidraw:".view-header",image:".image-container",pdf:".view-content",meld_encrypted_view:".markdown-source-view"};function se(t){ie=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;const o=function(){const t=[];t.push(app.workspace.rootSplit);const o=app.workspace.floatingSplit;return o?.children.forEach(o=>{o instanceof e.WorkspaceWindow&&t.push(o)}),t}(),n=e=>{const t=e.querySelectorAll(".editingToolbarModalBar"),o=e.querySelectorAll(".editingToolbarPopoverBar");t.forEach(e=>{e.firstChild&&e.removeChild(e.firstChild),e.remove()}),o.forEach(e=>{e.firstChild&&e.removeChild(e.firstChild),e.remove()})};n(ie),o&&o.forEach(e=>{e?.containerEl&&n(e.containerEl)}),t&&t.clearToolbarCache()}function re(t,o,n,i){const a=i||t.workspace.activeLeaf?.view?.containerEl?.ownerDocument||(e.requireApiVersion("0.15.0")?activeWindow.document:window.document);ie=a;const s=n||o.positionStyle||o.settings.positionStyle||"top";if("top"!==s){const e=o.getCachedToolbar(s);if(e&&e.ownerDocument===a)return e}const r=`.editingToolbarModalBar[data-toolbar-style="${s}"]`;let l=null;return l="top"===s?t.workspace.activeLeaf?.view.containerEl?.querySelector(r)||null:a.querySelector(r),l&&"top"!==s&&o.setCachedToolbar(s,l),l||null}const le=(e,t)=>t.reduce((e,t)=>e&&"undefined"!==e[t]?e[t]:void 0,e);function ce(e,t){return e&&void 0!==e[1][0]?t+e.flat(2).join("+").replace("Mod","Ctrl")+t:t+""+t}function de(e,t,o=!1){let n=e.commands.findCommand(t),i=o?"*":"";if(n){let t=n.hotkeys?[[le(n.hotkeys,[0,"modifiers"])],[le(n.hotkeys,[0,"key"])]]:void 0,o=e.hotkeyManager.customKeys[n.id];var a=o?[[le(o,[0,"modifiers"])],[le(o,[0,"key"])]]:void 0;return a?ce(a,i):ce(t,"")}return""}function ue(e){return/<[^>]+>/g.test(e)}function me(t,o){return o?ue(o)?(t.setIcon("lucide-square"),void(t.iconEl&&(t.iconEl.empty(),t.iconEl.innerHTML=o))):(t.setIcon(o),void(t.iconEl&&0===t.iconEl.childElementCount&&e.setIcon(t.iconEl,o))):(t.setIcon(""),void(t.iconEl&&t.iconEl.empty()))}function pe(e,t,o,n){const i=n.commandsManager.getActiveEditor(),a=i&&i.somethingSelected();0==t.cMenuVisibility?e.style.visibility="hidden":"following"===o?a||(e.style.visibility="hidden"):e.style.visibility="visible"}const he={improve:"lucide-wand-2","fix-grammar":"lucide-spell-check-2","make-shorter":"lucide-minimize-2","make-longer":"lucide-maximize-2",simplify:"lucide-align-left",professional:"lucide-briefcase",casual:"lucide-message-circle-more","translate-en":"lucide-languages","translate-zh":"lucide-languages","translate-ja":"lucide-languages","translate-de":"lucide-languages","translate-fr":"lucide-languages","translate-es":"lucide-languages",explain:"lucide-info",summarize:"lucide-file-text",continue:"lucide-pencil-line",custom:"lucide-message-square"},ge={"editing-toolbar:ai-inline-completion":"AI Complete","editing-toolbar:ai-canvas-expand":"AI Canvas Expand","editing-toolbar:ai-canvas-global-prompt":"AI Canvas Prompt","editing-toolbar:ai-rewrite-improve":"AI Rewrite","editing-toolbar:ai-rewrite-continue":"AI Continue","editing-toolbar:ai-rewrite-custom":"AI Custom","editing-toolbar:ai-tools:improve":"AI Rewrite","editing-toolbar:ai-tools:fix-grammar":"AI Fix","editing-toolbar:ai-tools:make-shorter":"AI Shorten","editing-toolbar:ai-tools:make-longer":"AI Expand","editing-toolbar:ai-tools:simplify":"AI Simplify","editing-toolbar:ai-tools:professional":"AI Professional","editing-toolbar:ai-tools:casual":"AI Casual","editing-toolbar:ai-tools:translate-en":"AI Translate","editing-toolbar:ai-tools:translate-zh":"AI Translate","editing-toolbar:ai-tools:translate-ja":"AI Translate","editing-toolbar:ai-tools:translate-de":"AI Translate","editing-toolbar:ai-tools:translate-fr":"AI Translate","editing-toolbar:ai-tools:translate-es":"AI Translate","editing-toolbar:ai-tools:explain":"AI Explain","editing-toolbar:ai-tools:summarize":"AI Summarize","editing-toolbar:ai-tools:continue":"AI Continue","editing-toolbar:ai-tools:custom":"AI Custom","editing-toolbar:ai-toolbox:list":"AI List","editing-toolbar:ai-toolbox:table":"AI Table","editing-toolbar:ai-toolbox:frontmatter":"AI Frontmatter","editing-toolbar:ai-toolbox:canvas":"AI Canvas"},fe=new Set(["editing-toolbar:ai-canvas-expand","editing-toolbar:ai-canvas-global-prompt"]);function be(e,t){e.lastExecutedCommand=t,e.lastExecutedCommandName=v(ge[t]?ge[t]:"AI")}function ye(e){return!!e&&fe.has(e)}function Ce(e){const t=e.lastExecutedCommand,o="canvas"===e.app.workspace.activeLeaf?.view?.getViewType?.(),n=e.commandsManager?.getActiveEditor?.();return t&&!ye(t)||!o||n?t&&ge[t]&&(!ye(t)||o)?v(ge[t]):t?.startsWith("editing-toolbar:ai")&&e.lastExecutedCommandName&&(!ye(t)||o)?e.lastExecutedCommandName:v("AI"):v("AI Canvas Prompt")}function ve(t,o,n,i,a){if(n<=100)return!1;return t+o+6*Math.max(1,Math.round(t/Math.max(i,1)))+(i+12)+("following"===a?i+10:0)+(e.Platform.isMobileApp||"mobile"===a?14:0)>=Math.max(n-16,2*i)}function we(t,o,n){ie=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;const i=o.commandsManager.getActiveEditor();let a=re(t,o),s=a?.querySelector("#"+n);if(s){let e=s.rows,t=e.length;for(let a=1;a<t;a++){let t=e[a].cells;for(let e=0;e<t.length;e++)t[e].onclick=function(){let e=this.style.backgroundColor;if(""!=e){if(e=xe(e),"x-color-picker-table"==n){o.settings.cMenuFontColor=e,l(e,i),ie.querySelectorAll("#change-font-color-icon").forEach(t=>{t.style.fill=e})}else if("x-backgroundcolor-picker-table"==n){o.settings.cMenuBackgroundColor=e,c(e,i),ie.querySelectorAll("#change-background-color-icon").forEach(t=>{t.style.fill=e})}o.saveSettings()}}}}}const xe=function(e){let t=e;if(/^(rgb|RGB)/.test(t)){let e=t.replace(/(?:\(|\)|rgb|RGB)*/g,"").split(","),o="#";for(let t=0;t<e.length;t++){let n=Number(e[t]).toString(16);"0"===n&&(n+=n),1==n.length&&(n="0"+n),o+=n}return 7!==o.length&&(o=t),o}if(!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(t))return t;{let e=t.replace(/#/,"").split("");if(6===e.length)return t;if(3===e.length){let t="#";for(let o=0;o<e.length;o+=1)t+=e[o]+e[o];return t}}};function ke(t,o,n){const i=t.workspace.getActiveViewOfType(e.ItemView);if(!X.isAllowedViewType(i))return;if(!o.IS_MORE_Button)return;const a=n.getAttribute("data-toolbar-style"),s=a?n.ownerDocument?.querySelector(`.editingToolbarPopoverBar[data-toolbar-style="${a}"]`):i.containerEl.querySelector("#editingToolbarPopoverBar");if(!s)return void o.setIS_MORE_Button(!1);let r=n.createEl("span");r.addClass("more-menu");let l=new e.ButtonComponent(r);return l.setClass("editingToolbarCommandItem").setTooltip(v("More")).onClick(()=>{"hidden"==s.style.visibility?(s.style.visibility="visible",s.style.height="32px",((e,t,o)=>{if("following"!==o)return void(e=>{e.style.removeProperty("left"),e.style.removeProperty("top"),e.style.removeProperty("right"),e.style.removeProperty("bottom"),e.style.removeProperty("transform"),e.style.removeProperty("margin"),e.style.removeProperty("position")})(t);const n=t.ownerDocument.defaultView??window,i=e.getBoundingClientRect(),a=Math.max(t.offsetWidth,t.scrollWidth),s=Math.max(t.offsetHeight,t.scrollHeight),r=Math.max(12,n.innerWidth-a-12);let l=i.right-a;a<=0&&(l=i.left),l=Math.min(Math.max(l,12),r);let c=i.bottom+8;s>0&&c+s>n.innerHeight-12&&(c=Math.max(12,i.top-s-8)),t.style.position="fixed",t.style.left=`${l}px`,t.style.top=`${c}px`,t.style.right="auto",t.style.bottom="auto",t.style.transform="none",t.style.margin="0"})(l.buttonEl,s,a)):(s.style.visibility="hidden",s.style.height="0")}),l.buttonEl.innerHTML='<svg width="14" height="14" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" enable-background="new 0 0 1024 1024" xml:space="preserve"><path fill="#666" d="M510.29 14.13 q17.09 -15.07 40.2 -14.07 q23.12 1 39.2 18.08 l334.66 385.92 q25.12 30.15 34.16 66.83 q9.04 36.68 0.5 73.87 q-8.54 37.19 -32.66 67.34 l-335.67 390.94 q-15.07 18.09 -38.69 20.1 q-23.62 2.01 -41.71 -13.07 q-18.08 -15.08 -20.09 -38.19 q-2.01 -23.12 13.06 -41.21 l334.66 -390.94 q11.06 -13.06 11.56 -29.65 q0.5 -16.58 -10.55 -29.64 l-334.67 -386.92 q-15.07 -17.09 -13.56 -40.7 q1.51 -23.62 19.59 -38.7 ZM81.17 14.13 q17.08 -15.07 40.19 -14.07 q23.11 1 39.2 18.08 l334.66 385.92 q25.12 30.15 34.16 66.83 q9.04 36.68 0.5 73.87 q-8.54 37.19 -32.66 67.34 l-335.67 390.94 q-15.07 18.09 -38.69 20.6 q-23.61 2.51 -41.7 -12.57 q-18.09 -15.08 -20.1 -38.69 q-2.01 -23.62 13.06 -41.71 l334.66 -390.94 q11.06 -13.06 11.56 -29.65 q0.5 -16.58 -10.55 -29.64 l-334.66 -386.92 q-15.08 -17.09 -13.57 -40.7 q1.51 -23.62 19.6 -38.7 Z"/></svg>',o.setIS_MORE_Button(!1),r}function Se(e){e.quiteAllFormatBrushes()}function Te(e,t){let o=t.getSelection();if(!o||""===o.trim())return;if(o.match(/^>\s*\[\![\w\s]*\]/m)){let e=o.split("\n"),n=[],i=!1,a=0,s=!1;for(let t=0;t<e.length;t++){let o=e[t],r=o.match(/^(>+)\s*\[\!([\w\s]*)\]\s*(.*?)$/);if(!r||s)if(i){let e=o.match(/^(>+)\s*/);if(e&&e[1].length>=a){let e=o.replace(new RegExp(`^>{${a}}\\s*`),"");n.push(e)}else i=!1,n.push(o)}else n.push(o);else a=r[1].length,s=!0,r[3].trim()&&n.push(r[3].trim()),i=!0}return void t.replaceSelection(n.join("\n"))}o=o.replace(/(^#+\s|^#(?=\s)|^\>|^\- \[( |x)\]|^\+ |\<[^\<\>]+?\>|^1\. |^\s*\- |^\-+$|^\*+$)/gm,""),o=o.replace(/^[ ]+|[ ]+$/gm,""),o=o.replace(/\!?\[\[([^\[\]\|]*\|)*([^\(\)\[\]]+)\]\]/g,"$2"),o=o.replace(/\!?\[+([^\[\]\(\)]+)\]+\(([^\(\)]+)\)/g,"$1"),o=o.replace(/`([^`]+)`/g,"$1"),o=o.replace(/_([^_]+)_/g,"$1"),o=o.replace(/==([^=]+)==/g,"$1"),o=o.replace(/\*\*\*([^\*]+)\*\*\*/g,"$1"),o=o.replace(/\*\*?([^\*]+)\*\*?/g,"$1"),o=o.replace(/~~([^~]+)~~/g,"$1"),t.replaceSelection(o)}function Ee(t,o,n,i,a=!1,s){const r=s||i?.cm?.dom?.ownerDocument||i?.cm?.contentDOM?.ownerDocument||t.workspace.activeLeaf?.view?.containerEl?.ownerDocument||(e.requireApiVersion("0.15.0")?activeWindow.document:window.document);let l=re(t,n,"following",r);const c=t.workspace.getActiveViewOfType(e.ItemView);if(!X.isAllowedViewType(c))return void(l&&(l.style.visibility="hidden"));if(!(n.settings.enableFollowingToolbar||!n.settings.enableTopToolbar&&!n.settings.enableFixedToolbar&&"following"===n.positionStyle))return;l||(Ie(t,n,"following",r),l=re(t,n,"following",r));const d=c?.getViewType(),u="markdown"===d;let m=30;if(m="tiny"===n.settings.aestheticStyle?30:o+14,u)if(X.isSourceMode(c)){if(l){const e=a||i.somethingSelected();l.style.visibility=e?"visible":"hidden","visible"===l.style.visibility&&(l.style.height=m+"px",l.addClass("editingToolbarFlex"),l.removeClass("editingToolbarGrid"),function(e,t){const o=t.containerEl.getBoundingClientRect(),n=e.offsetWidth,i=e.offsetHeight,a=12,s=e.ownerDocument.defaultView?.innerWidth??window.innerWidth,r=t.getCursor("from");t.getCursor("to");const l=t.coordsAtPos(r),c=ie.getElementsByClassName("mod-left-split")[0]?.clientWidth??0,d=ie.getElementsByClassName("side-dock-ribbon mod-left")[0]?.clientWidth??0,u=c+d;let m=l.left-u-28;m+n>s-u&&(m=s-u-n-a);m=Math.max(0,m);let p=function(e,t,o,n){const i=e.getCursor("from"),a=e.getCursor("to"),s=e.coordsAtPos(a),r=i.line===a.line;let l=t.top-n-10;if(r)l<=o.top&&(l=s.bottom+10);else{if(e.getCursor("head").ch==e.getCursor("from").ch)l=t.top-n-10,l<=o.top&&(l=o.top+2*n);else{const t=(e=>{let t,o=e.getCursor("head");if(e.getCursor("head").ch!==e.getCursor("from").ch&&(o.ch=Math.max(0,o.ch-1)),e.cursorCoords)t=e.cursorCoords(!0,"window");else{if(!e.coordsAtPos)return;{const n=e.posToOffset(o);t=e.cm.coordsAtPos?.(n)??e.coordsAtPos(n)}}return t})(e);l=t.bottom+10,l>=o.bottom-n&&(l=o.bottom-2*n)}}return l}(t,l,o,i);p=Math.max(0,p),e.style.left=`${m}px`,e.style.top=`${p}px`}(l,i))}}else l&&(l.style.visibility="hidden");else l&&(l.style.visibility="visible",l.style.height=m+"px",l.addClass("editingToolbarFlex"),l.removeClass("editingToolbarGrid"))}function Ie(t,o,n,i){const a=o.settings,s=i||t.workspace.activeLeaf?.view?.containerEl?.ownerDocument||(e.requireApiVersion("0.15.0")?activeWindow.document:window.document);if(ie=s,!n){const e=[];if(a.enableTopToolbar&&e.push("top"),a.enableFollowingToolbar&&e.push("following"),a.enableFixedToolbar&&e.push("fixed"),0===e.length){const t=o.positionStyle||o.settings.positionStyle||"top";e.push(t)}return void e.forEach(e=>{Ie(t,o,e,s)})}const r=n;if(!a.cMenuVisibility){const e=re(t,o,r,s);return void(e&&(e.style.display="none"))}const l=(a.appearanceByStyle||{})[r]||{},c=l.toolbarIconSize??o.toolbarIconSize??18,d=l.aestheticStyle??a.aestheticStyle??"default",u="custom"===d?l.toolbarBackgroundColor??a.toolbarBackgroundColor:void 0,m="custom"===d?l.toolbarIconColor??a.toolbarIconColor:void 0,p={default:"editingToolbarDefaultAesthetic",tiny:"editingToolbarTinyAesthetic",glass:"editingToolbarGlassAesthetic",custom:"editingToolbarCustomAesthetic"};!function(){function n(e,t){Object.values(p).forEach(t=>{e.removeClass(t)});const o=p[t]||p.default;e.addClass(o)}const i=()=>{let i=0,l=0,p=c+8,h=createEl("div");if(h)if(h.addClass("editingToolbarModalBar"),h.setAttribute("data-toolbar-style",r),"top"===r)h.className+=" top",a.autohide&&(h.className+=" autohide"),a.Iscentered&&(h.className+=" centered");else if("following"===r)h.style.visibility="hidden";else if("fixed"===r){const e=c||18,t=`left: calc(50% - calc(${a.cMenuNumRows*(e+10)}px / 2));\n bottom: 4.25em; \n grid-template-columns: repeat(${a.cMenuNumRows}, ${e+10}px);\n gap: ${(e-18)/4}px`;h.setAttribute("style",t)}h.setAttribute("id","editingToolbarModalBar");let g=createEl("div");if(g.addClass("editingToolbarpopover"),g.addClass("editingToolbarTinyAesthetic"),g.addClass("editingToolbarPopoverBar"),g.setAttribute("data-toolbar-style",r),g.setAttribute("id","editingToolbarPopoverBar"),g.style.visibility="hidden",g.style.height="0",n(h,d),n(g,d),u&&(h.style.setProperty("--editing-toolbar-background-color",u),g.style.setProperty("--editing-toolbar-background-color",u)),m&&(h.style.setProperty("--editing-toolbar-icon-color",m),g.style.setProperty("--editing-toolbar-icon-color",m)),c&&(h.style.setProperty("--toolbar-icon-size",`${c}px`),g.style.setProperty("--toolbar-icon-size",`${c}px`)),"top"===r){let e=t.workspace.activeLeaf.view.containerEl,o=null;const n=t.workspace.activeLeaf.view.getViewType(),i=ae[n];if(i&&(o=e?.querySelector(i)),!o){const t=e?.querySelector(".view-content");if(t){const e=t.querySelectorAll(":scope > div");o=e.length>0?e[0]:t}}if(!o)return void console.log("Editing Toolbar: Failed to find target DOM element for toolbar insertion");const a="canvas"===n?e?.querySelector(".view-content"):null;"canvas"===n&&a?(a.insertAdjacentElement("beforebegin",h),e?.querySelector("#editingToolbarPopoverBar")||a.insertAdjacentElement("beforebegin",g)):(e?.querySelector("#editingToolbarPopoverBar")||("excalidraw"==n?o.insertAdjacentElement("afterend",g):o.insertAdjacentElement("afterbegin",g)),"excalidraw"==n?o.insertAdjacentElement("afterend",h):o.insertAdjacentElement("afterbegin",h));const r=[o?.clientWidth||o?.offsetWidth||0,e?.clientWidth||e?.getBoundingClientRect().width||0,s.defaultView?.innerWidth||0].filter(e=>e>0);l=r.length>0?Math.min(...r):0}else if("body"==a.appendMethod){s.querySelector(`.editingToolbarPopoverBar[data-toolbar-style="${r}"]`)||s.body.appendChild(g),s.body.appendChild(h),l=s.defaultView?.innerWidth||s.body?.clientWidth||0}else if("workspace"==a.appendMethod){const e=s.body?.querySelector(".mod-vertical.mod-root");if(!e)return;e.querySelector(`.editingToolbarPopoverBar[data-toolbar-style="${r}"]`)||e.insertAdjacentElement("afterbegin",g),e.insertAdjacentElement("afterbegin",h);const t=[s.body?.clientWidth||0,s.defaultView?.innerWidth||0].filter(e=>e>0);l=t.length>0?Math.min(...t):0}let f="top"===r?t.workspace.activeLeaf.view.containerEl?.querySelector("#editingToolbarPopoverBar"):s.querySelector(`.editingToolbarPopoverBar[data-toolbar-style="${r}"]`);const b=e=>e?f||(console.warn(`Editing Toolbar: missing popover host for style "${r}", falling back to toolbar host.`),h):h,y=o.getCurrentCommands(r),C=e=>v(e),w=(e,t)=>{const o=C(e);return""===t?o:`${o}(${t})`};y.forEach((n,s)=>{let c;if("SubmenuCommands"in n){let d;ve(i,p,l,p,r)?(o.setIS_MORE_Button(!0),d=new e.ButtonComponent(b(!0))):d=new e.ButtonComponent(h),d.setClass("editingToolbarCommandsubItem"+s),s>=a.cMenuNumRows?d.setClass("editingToolbarSecond"):"top"!==r&&d.buttonEl.setAttribute("aria-label-position","top"),ue(n.icon)?d.buttonEl.innerHTML=n.icon:d.setIcon(n.icon),i+=p+2;if("dropdown"===(n.menuType||"submenu")){d.setClass("editingToolbarDropdownButton");let i=de(t,n.id);c=w(n.name,i),d.setTooltip(c),d.onClick(i=>{const s=new e.Menu;n.SubmenuCommands.forEach(e=>{"editingToolbar-Divider-Line"===e.id?(s.addSeparator(),s.addItem(t=>{t.setTitle(v(e.name)).setDisabled(!0),me(t,"")})):s.addItem(n=>{const i=de(t,e.id,!1),s=v(e.name),l=""!==i?`${s}`:s;if(n.setTitle(l).onClick(()=>{t.commands.executeCommandById(e.id);const n=o.commandsManager.getActiveEditor(),i=n&&n.somethingSelected();0==a.cMenuVisibility?h.style.visibility="hidden":"following"===r?i||(h.style.visibility="hidden"):h.style.visibility="visible"}),me(n,e.icon),""!==i){n.dom.createSpan({cls:"menu-item-hotkey"}).setText(i)}})}),s.dom.addClass("editing-toolbar-dropdown-menu"),s.showAtMouseEvent(i)})}else{let i=function(e){let t=createEl("div");return t.addClass(e),t}("subitem");i&&n.SubmenuCommands.forEach(n=>{let l=de(t,n.id);c=w(n.name,l);let u=new e.ButtonComponent(i).setTooltip(c).setClass("menu-item").onClick(()=>{t.commands.executeCommandById(n.id);const e=o.commandsManager.getActiveEditor(),i=e&&e.somethingSelected();0==a.cMenuVisibility?h.style.visibility="hidden":"following"===r?i||(h.style.visibility="hidden"):h.style.visibility="visible"});s<a.cMenuNumRows&&"top"!==r&&u.buttonEl.setAttribute("aria-label-position","top"),"editingToolbar-Divider-Line"==n.id&&(u.setClass("editingToolbar-Divider-Line"),u.buttonEl.setAttribute("aria-label",C(n.name))),ue(n.icon)?u.buttonEl.innerHTML=n.icon:u.setIcon(n.icon),d.buttonEl.insertAdjacentElement("afterbegin",i)})}}else if(n.id==Q){const c=function(e,t,o){if("fixed"===t)return o+6;const n=Ce(e),i=Math.min(Math.max(6.2*n.length,12),32);return Math.max(o+i+18,57)}(o,r,p),d=ve(i,c,l,p,r);d&&o.setIS_MORE_Button(!0);const u=b(d);let m=new e.ButtonComponent(u);m.setClass("editingToolbarCommandsubItem"+s).setClass("editingToolbarDropdownButton").setClass("editingToolbarCommandsubItem-ai").setTooltip(v("AI Tools")),s>=a.cMenuNumRows?m.setClass("editingToolbarSecond"):"top"!==r&&m.buttonEl.setAttribute("aria-label-position","top"),ue(n.icon)?m.buttonEl.innerHTML=n.icon:m.setIcon(n.icon);const g="fixed"===r;m.setClass(g?"editing-toolbar-ai-button-fixed":"editing-toolbar-ai-button-inline");let f=null;if(!g){const e=document.createElement("span");e.className="editing-toolbar-ai-button-main",f=document.createElement("span"),f.className="editing-toolbar-ai-button-label",f.textContent=Ce(o),e.appendChild(f),m.buttonEl.appendChild(e)}const y=document.createElement("span");y.className="editing-toolbar-ai-button-arrow",y.setAttribute("aria-hidden","true"),y.textContent=String.fromCharCode(9662),m.buttonEl.appendChild(y),i+=c;const C=async n=>{w=Date.now()+240;const i="unavailable"!==await o.aiManager.getToolbarRouteState(),s=o.commandsManager.getActiveEditor(),l="canvas"===t.workspace.activeLeaf?.view?.getViewType?.(),c=de(t,"editing-toolbar:ai-inline-completion",!1),d=c.includes("+")?c:"",u=new e.Menu,m=()=>{u.hide()},p=t=>{const n=async()=>{if(!i)return void new e.Notice(await o.aiManager.getProviderRouteStatusText());!1!==await t.action()&&(m(),t.commandIdForLabel&&(be(o,t.commandIdForLabel),f&&(f.textContent=Ce(o))),pe(h,a,r,o))};u.addItem(e=>{if(e.setTitle(v(t.title)).setIcon(t.icon).onClick(n),t.hotkey){e.dom.createSpan({cls:"menu-item-hotkey"}).setText(t.hotkey)}})},g=(t,n,s)=>{u.addItem(l=>{l.setTitle(v(t)).setIcon(n);const c=l.setSubmenu();s.forEach(t=>{c.addItem(n=>{if(n.setTitle(v(t.title)).setIcon(t.icon).onClick(async()=>{if(!i)return void new e.Notice(await o.aiManager.getProviderRouteStatusText());!1!==await t.action()&&(m(),t.commandIdForLabel&&(be(o,t.commandIdForLabel),f&&(f.textContent=Ce(o))),pe(h,a,r,o))}),t.hotkey){n.dom.createSpan({cls:"menu-item-hotkey"}).setText(t.hotkey)}})})})};if(l&&(p({title:v("Canvas global prompt"),icon:"lucide-sparkles",commandIdForLabel:"editing-toolbar:ai-canvas-global-prompt",action:()=>o.aiManager.openCanvasGlobalPromptModal()}),p({title:v("Expand current canvas node"),icon:"lucide-waypoints",commandIdForLabel:"editing-toolbar:ai-canvas-expand",action:()=>o.aiManager.openCanvasNodeExpansionModal()})),!l||s){p({title:"Trigger AI Inline Completion",icon:"lucide-sparkles",hotkey:d||void 0,commandIdForLabel:"editing-toolbar:ai-inline-completion",action:()=>o.aiManager.triggerInlineCompletion(s)});const e=new Map;O.forEach(t=>{const o=e.get(t.group)??[];o.push(t),e.set(t.group,o)});const t={Edit:"lucide-wand-sparkles",Tone:"lucide-messages-square",Translate:"lucide-languages",Generate:"lucide-bot"};e.forEach((e,n)=>{g(n,t[n]??"lucide-sparkles",e.map(e=>({title:e.label,icon:he[e.instruction],commandIdForLabel:`editing-toolbar:ai-tools:${e.instruction}`,action:async()=>{await o.aiManager.startRewrite(s,e.instruction)}})))}),l||p({title:"AI Custom Rewrite",icon:he.custom,commandIdForLabel:"editing-toolbar:ai-tools:custom",action:()=>o.aiManager.openCustomRewrite(s)}),g("AI Toolbox","lucide-boxes",ee.map(e=>({title:e.label,icon:e.icon,commandIdForLabel:`editing-toolbar:ai-toolbox:${e.id}`,action:async()=>o.aiManager.runToolboxAction(s,e.id)})))}u.dom.addClass("editing-toolbar-dropdown-menu"),u.dom.addClass("editing-toolbar-ai-dropdown-menu"),u.showAtMouseEvent(n)};let w=0;y.addEventListener("click",async e=>{e.preventDefault(),e.stopPropagation(),await C(e)}),m.buttonEl.addEventListener("click",async n=>{if(n.preventDefault(),n.stopPropagation(),Date.now()<w)return;const i=n.target;if(i?.closest(".editing-toolbar-ai-button-arrow"))return void await C(n);if(e.Platform.isMobileApp||"mobile"===r)return void await C(n);const s=o.commandsManager.getActiveEditor(),l="canvas"===t.workspace.activeLeaf?.view?.getViewType?.(),c=o.lastExecutedCommand,d=l&&!s?"editing-toolbar:ai-canvas-expand"===c||"editing-toolbar:ai-canvas-global-prompt"===c||"editing-toolbar:ai-tools:custom"===c||"editing-toolbar:ai-rewrite-custom"===c?c:"editing-toolbar:ai-canvas-global-prompt":ge[c||""]&&!ye(c)?c:"editing-toolbar:ai-inline-completion",u=await async function(t,o,n){if("unavailable"===await t.aiManager.getToolbarRouteState())return new e.Notice(await t.aiManager.getProviderRouteStatusText()),!1;if("editing-toolbar:ai-canvas-expand"===o)return t.aiManager.openCanvasNodeExpansionModal();if("editing-toolbar:ai-canvas-global-prompt"===o)return t.aiManager.openCanvasGlobalPromptModal();if("editing-toolbar:ai-inline-completion"===o)return t.aiManager.triggerInlineCompletion(n);if("editing-toolbar:ai-tools:custom"===o||"editing-toolbar:ai-rewrite-custom"===o)return"canvas"!==t.app.workspace.activeLeaf?.view?.getViewType?.()||n?t.aiManager.openCustomRewrite(n):t.aiManager.openCanvasGlobalPromptModal();if(o.startsWith("editing-toolbar:ai-toolbox:"))return t.aiManager.runToolboxAction(n,o.replace("editing-toolbar:ai-toolbox:",""));const i=o.startsWith("editing-toolbar:ai-tools:")?o.replace("editing-toolbar:ai-tools:",""):"editing-toolbar:ai-rewrite-improve"===o?"improve":"editing-toolbar:ai-rewrite-continue"===o?"continue":null;return i?t.aiManager.startRewrite(n,i):t.aiManager.triggerInlineCompletion(n)}(o,d,s);!1!==u&&f&&(f.textContent=Ce(o)),pe(h,a,r,o)})}else if("editing-toolbar:change-font-color"==n.id){let s=new e.ButtonComponent(h);s.setClass("editingToolbarCommandsubItem-font-color").setTooltip(v("Font Colors")).onClick(()=>{t.commands.executeCommandById(n.id);const e=o.commandsManager.getActiveEditor(),i=e&&e.somethingSelected();0==a.cMenuVisibility?h.style.visibility="hidden":"following"===r?i||(h.style.visibility="hidden"):h.style.visibility="visible"}),ue(n.icon)?s.buttonEl.innerHTML=n.icon:s.setIcon(n.icon),i+=p;let l=createEl("div");if(l.addClass("subitem"),l){l.innerHTML=function(e){return`<div class='x-color-picker-wrapper'>\n<div class='x-color-picker' >\n <table class="x-color-picker-table" id='x-color-picker-table'>\n <tbody>\n <tr>\n <th colspan="10" class="ui-widget-content">Theme Colors</th>\n </tr>\n <tr>\n <td style="background-color:#ffffff"><span></span></td>\n <td style="background-color:#000000"><span></span></td>\n <td style="background-color:#eeece1"><span></span></td>\n <td style="background-color:#1f497d"><span></span></td>\n <td style="background-color:#4f81bd"><span></span></td>\n <td style="background-color:#c0504d"><span></span></td>\n <td style="background-color:#9bbb59"><span></span></td>\n <td style="background-color:#8064a2"><span></span></td>\n <td style="background-color:#4bacc6"><span></span></td>\n <td style="background-color:#f79646"><span></span></td>\n </tr>\n <tr>\n <th colspan="10"></th>\n </tr>\n <tr class="top">\n <td style="background-color:#f2f2f2"><span></span></td>\n <td style="background-color:#7f7f7f"><span></span></td>\n <td style="background-color:#ddd9c3"><span></span></td>\n <td style="background-color:#c6d9f0"><span></span></td>\n <td style="background-color:#dbe5f1"><span></span></td>\n <td style="background-color:#f2dcdb"><span></span></td>\n <td style="background-color:#ebf1dd"><span></span></td>\n <td style="background-color:#e5e0ec"><span></span></td>\n <td style="background-color:#dbeef3"><span></span></td>\n <td style="background-color:#fdeada"><span></span></td>\n </tr>\n <tr class="in">\n <td style="background-color:#d8d8d8"><span></span></td>\n <td style="background-color:#595959"><span></span></td>\n <td style="background-color:#c4bd97"><span></span></td>\n <td style="background-color:#8db3e2"><span></span></td>\n <td style="background-color:#b8cce4"><span></span></td>\n <td style="background-color:#e5b9b7"><span></span></td>\n <td style="background-color:#d7e3bc"><span></span></td>\n <td style="background-color:#ccc1d9"><span></span></td>\n <td style="background-color:#b7dde8"><span></span></td>\n <td style="background-color:#fbd5b5"><span></span></td>\n </tr>\n <tr class="in">\n <td style="background-color:#bfbfbf"><span></span></td>\n <td style="background-color:#3f3f3f"><span></span></td>\n <td style="background-color:#938953"><span></span></td>\n <td style="background-color:#548dd4"><span></span></td>\n <td style="background-color:#95b3d7"><span></span></td>\n <td style="background-color:#d99694"><span></span></td>\n <td style="background-color:#c3d69b"><span></span></td>\n <td style="background-color:#b2a2c7"><span></span></td>\n <td style="background-color:#92cddc"><span></span></td>\n <td style="background-color:#fac08f"><span></span></td>\n </tr>\n <tr class="in">\n <td style="background-color:#a5a5a5"><span></span></td>\n <td style="background-color:#262626"><span></span></td>\n <td style="background-color:#494429"><span></span></td>\n <td style="background-color:#17365d"><span></span></td>\n <td style="background-color:#366092"><span></span></td>\n <td style="background-color:#953734"><span></span></td>\n <td style="background-color:#76923c"><span></span></td>\n <td style="background-color:#5f497a"><span></span></td>\n <td style="background-color:#31859b"><span></span></td>\n <td style="background-color:#e36c09"><span></span></td>\n </tr>\n <tr class="bottom">\n <td style="background-color:#7f7f7f"><span></span></td>\n <td style="background-color:#0c0c0c"><span></span></td>\n <td style="background-color:#1d1b10"><span></span></td>\n <td style="background-color:#0f243e"><span></span></td>\n <td style="background-color:#244061"><span></span></td>\n <td style="background-color:#632423"><span></span></td>\n <td style="background-color:#4f6128"><span></span></td>\n <td style="background-color:#3f3151"><span></span></td>\n <td style="background-color:#205867"><span></span></td>\n <td style="background-color:#974806"><span></span></td>\n </tr>\n <tr>\n <th colspan="10"></th>\n </tr>\n <tr>\n <th colspan="10" class="ui-widget-content">Standard Colors</th>\n </tr>\n <tr>\n <td style="background-color:#c00000"><span></span></td>\n <td style="background-color:#ff0000"><span></span></td>\n <td style="background-color:#ffc000"><span></span></td>\n <td style="background-color:#ffff00"><span></span></td>\n <td style="background-color:#92d050"><span></span></td>\n <td style="background-color:#00b050"><span></span></td>\n <td style="background-color:#00b0f0"><span></span></td>\n <td style="background-color:#0070c0"><span></span></td>\n <td style="background-color:#002060"><span></span></td>\n <td style="background-color:#7030a0"><span></span></td>\n </tr>\n <tr>\n <th colspan="10" class="ui-widget-content">Custom Font Colors</th>\n </tr>\n <tr>\n <td style="background-color:${e.settings.custom_fc1}"><span></span></td>\n <td style="background-color:${e.settings.custom_fc2}"><span></span></td>\n <td style="background-color:${e.settings.custom_fc3}"><span></span></td>\n <td style="background-color:${e.settings.custom_fc4}"><span></span></td>\n <td style="background-color:${e.settings.custom_fc5}"><span></span></td>\n </tr>\n </tbody>\n </table>\n</div>\n</div>`}(o),s.buttonEl.insertAdjacentElement("afterbegin",l),we(t,o,"x-color-picker-table");let n=l.querySelector(".x-color-picker-wrapper");new e.ButtonComponent(n).setIcon("paintbrush").setTooltip(v("Format Brush")).onClick(()=>{Se(o),o.setEN_FontColor_Format_Brush(!0),o.Temp_Notice=new e.Notice(v("Font-Color formatting brush ON!"),0)}),new e.ButtonComponent(n).setIcon("palette").setTooltip(v("Custom Font Color")).onClick(()=>{t.setting.open(),t.setting.openTabById("editing-toolbar"),setTimeout(()=>{const e=t.setting.activeTab.containerEl.querySelector(".editing-toolbar-tabs");if(e){const o=e.children[0];o?.click(),setTimeout(()=>{let e=t.setting.activeTab.containerEl.querySelector(".custom_font");e&&e.addClass?.("toolbar-cta")},100)}},200)})}}else if("editing-toolbar:change-background-color"==n.id){let s=new e.ButtonComponent(h);s.setClass("editingToolbarCommandsubItem-font-color").setTooltip(v("Background Color")).onClick(()=>{t.commands.executeCommandById(n.id);const e=o.commandsManager.getActiveEditor(),i=e&&e.somethingSelected();0==a.cMenuVisibility?h.style.visibility="hidden":"following"===r?i||(h.style.visibility="hidden"):h.style.visibility="visible"}),ue(n.icon)?s.buttonEl.innerHTML=n.icon:s.setIcon(n.icon),i+=p;let l=createEl("div");if(l.addClass("subitem"),l){l.innerHTML=function(e){return`<div class='x-color-picker-wrapper'>\n<div class='x-color-picker' >\n <table class="x-color-picker-table" id='x-backgroundcolor-picker-table'>\n <tbody>\n <tr>\n <th colspan="5" class="ui-widget-content">Translucent Colors</th>\n </tr>\n <tr class="top">\n <td style="background-color:rgba(140, 140, 140, 0.12)"><span></span></td>\n <td style="background-color:rgba(92, 92, 92, 0.2)"><span></span></td>\n <td style="background-color:rgba(163, 67, 31, 0.2)"><span></span></td>\n <td style="background-color:rgba(240, 107, 5, 0.2)"><span></span></td>\n <td style="background-color:rgba(240, 200, 0, 0.2)"><span></span></td>\n </tr>\n <tr class="bottom">\n <td style="background-color:rgba(3, 135, 102, 0.2)"><span></span></td>\n <td style="background-color:rgba(3, 135, 102, 0.2)"><span></span></td>\n <td style="background-color:rgba(5, 117, 197, 0.2)"><span></span></td>\n <td style="background-color:rgba(74, 82, 199, 0.2)"><span></span></td>\n <td style="background-color:rgba(136, 49, 204, 0.2)"><span></span></td>\n </tr>\n\n <tr>\n <th colspan="5" class="ui-widget-content">Highlighter Colors</th>\n </tr>\n \n <tr class="top">\n <td style="background-color:rgb(255, 248, 143)"><span></span></td>\n <td style="background-color:rgb(211, 248, 182)"><span></span></td>\n <td style="background-color:rgb(175, 250, 209)"><span></span></td>\n <td style="background-color:rgb(177, 255, 255)"><span></span></td>\n <td style="background-color:rgb(253, 191, 255)"><span></span></td>\n </tr>\n <tr class="bottom">\n <td style="background-color:rgb(210, 203, 255);"><span></span></td>\n <td style="background-color:rgb(64, 169, 255);"><span></span></td>\n <td style="background-color:rgb(255, 77, 79);"><span></span></td>\n <td style="background-color:rgb(212, 177, 6);"><span></span></td>\n <td style="background-color:rgb(146, 84, 222);"><span></span></td>\n </tr>\n <tr>\n <th colspan="5" class="ui-widget-content">Custom Colors</th>\n </tr>\n <tr class="bottom">\n <td style="background-color: ${e.settings.custom_bg1};"><span></span></td>\n <td style="background-color:${e.settings.custom_bg2};"><span></span></td>\n <td style="background-color:${e.settings.custom_bg3};"><span></span></td>\n <td style="background-color:${e.settings.custom_bg4};"><span></span></td>\n <td style="background-color:${e.settings.custom_bg5};"><span></span></td>\n </tr>\n </tbody>\n </table>\n</div>\n</div>`}(o),s.buttonEl.insertAdjacentElement("afterbegin",l),we(t,o,"x-backgroundcolor-picker-table");let n=l.querySelector(".x-color-picker-wrapper");new e.ButtonComponent(n).setIcon("paintbrush").setTooltip(v("Format Brush")).onClick(()=>{Se(o),o.setEN_BG_Format_Brush(!0),o.Temp_Notice=new e.Notice(v("Font-Color formatting brush ON!"),0)}),new e.ButtonComponent(n).setIcon("palette").setTooltip(v("Custom Backgroud Color")).onClick(()=>{t.setting.open(),t.setting.openTabById("editing-toolbar"),setTimeout(()=>{const e=t.setting.activeTab.containerEl.querySelector(".editing-toolbar-tabs");if(e){const o=e.children[0];o?.click(),setTimeout(()=>{let e=t.setting.activeTab.containerEl.querySelector(".custom_bg");e&&e.addClass?.("toolbar-cta")},100)}},200)})}}else{let d;ve(i,p,l,p,r)?(o.setIS_MORE_Button(!0),d=new e.ButtonComponent(b(!0))):d=new e.ButtonComponent(h);let u=de(t,n.id);c=w(n.name,u),d.setTooltip(c).onClick(()=>{t.commands.executeCommandById(n.id);const e=o.commandsManager.getActiveEditor(),i=e&&e.somethingSelected();0==a.cMenuVisibility?h.style.visibility="hidden":"following"===r?i||(h.style.visibility="hidden"):h.style.visibility="visible"}),d.setClass("editingToolbarCommandItem"),s>=a.cMenuNumRows?d.setClass("editingToolbarSecond"):"top"!==r&&d.buttonEl.setAttribute("aria-label-position","top"),"editingToolbar-Divider-Line"==n.id&&d.setClass("editingToolbar-Divider-Line"),ue(n.icon)?d.buttonEl.innerHTML=n.icon:d.setIcon(n.icon),i+=p}}),ke(t,o,h),Math.abs(o.settings.cMenuWidth-Number(i))>i+4&&(o.settings.cMenuWidth=Number(i),setTimeout(()=>{o.saveSettings()},100))};if(!o.isLoadMobile())return;const l=t.workspace.getActiveViewOfType(e.ItemView);if(X.isAllowedViewType(l)){const n=re(t,o,r,s);if(n&&"top"!==r)return a.cMenuVisibility?"following"===r?(n.style.visibility="hidden",n.style.display=""):(n.style.visibility="visible",n.style.display=""):n.style.display="none",u&&n.style.setProperty("--editing-toolbar-background-color",u),m&&n.style.setProperty("--editing-toolbar-icon-color",m),void(c&&n.style.setProperty("--toolbar-icon-size",`${c}px`));if(i(),"top"!==r){const e=re(t,o,r,s);e&&o.setCachedToolbar(r,e)}g(o.settings),h(o.settings),function(t,o){ie=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;const n=ie.querySelectorAll("#change-font-color-icon"),i=ie.querySelectorAll("#change-background-color-icon");n.length>0&&n.forEach(e=>{e.style.fill=t});i.length>0&&i.forEach(e=>{e.style.fill=o})}
/**!
* Sortable 1.15.7
* @author RubaXa <trash@rubaxa.org>
* @author owenm <owen23355@gmail.com>
* @license MIT
*/(a.cMenuFontColor,a.cMenuBackgroundColor)}}()}function Ae(e,t,o){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var n=o.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function Me(){return Me=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)({}).hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},Me.apply(null,arguments)}function Pe(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),o.push.apply(o,n)}return o}function Ne(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{};t%2?Pe(Object(o),!0).forEach(function(t){Ae(e,t,o[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):Pe(Object(o)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(o,t))})}return e}function De(e){return De="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},De(e)}function Le(e){if("undefined"!=typeof window&&window.navigator)return!!navigator.userAgent.match(e)}var Fe=Le(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),Oe=Le(/Edge/i),Re=Le(/firefox/i),qe=Le(/safari/i)&&!Le(/chrome/i)&&!Le(/android/i),Be=Le(/iP(ad|od|hone)/i),$e=Le(/chrome/i)&&Le(/android/i),_e={capture:!1,passive:!1};function ze(e,t,o){e.addEventListener(t,o,!Fe&&_e)}function Ue(e,t,o){e.removeEventListener(t,o,!Fe&&_e)}function Ve(e,t){if(t){if(">"===t[0]&&(t=t.substring(1)),e)try{if(e.matches)return e.matches(t);if(e.msMatchesSelector)return e.msMatchesSelector(t);if(e.webkitMatchesSelector)return e.webkitMatchesSelector(t)}catch(e){return!1}return!1}}function He(e){return e.host&&e!==document&&e.host.nodeType&&e.host!==e?e.host:e.parentNode}function We(e,t,o,n){if(e){o=o||document;do{if(null!=t&&(">"===t[0]?e.parentNode===o&&Ve(e,t):Ve(e,t))||n&&e===o)return e;if(e===o)break}while(e=He(e))}return null}var je,Ke=/\s+/g;function Ye(e,t,o){if(e&&t)if(e.classList)e.classList[o?"add":"remove"](t);else{var n=(" "+e.className+" ").replace(Ke," ").replace(" "+t+" "," ");e.className=(n+(o?" "+t:"")).replace(Ke," ")}}function Ge(e,t,o){var n=e&&e.style;if(n){if(void 0===o)return document.defaultView&&document.defaultView.getComputedStyle?o=document.defaultView.getComputedStyle(e,""):e.currentStyle&&(o=e.currentStyle),void 0===t?o:o[t];t in n||-1!==t.indexOf("webkit")||(t="-webkit-"+t),n[t]=o+("string"==typeof o?"":"px")}}function Je(e,t){var o="";if("string"==typeof e)o=e;else do{var n=Ge(e,"transform");n&&"none"!==n&&(o=n+" "+o)}while(!t&&(e=e.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(o)}function Ze(e,t,o){if(e){var n=e.getElementsByTagName(t),i=0,a=n.length;if(o)for(;i<a;i++)o(n[i],i);return n}return[]}function Xe(){var e=document.scrollingElement;return e||document.documentElement}function Qe(e,t,o,n,i){if(e.getBoundingClientRect||e===window){var a,s,r,l,c,d,u;if(e!==window&&e.parentNode&&e!==Xe()?(s=(a=e.getBoundingClientRect()).top,r=a.left,l=a.bottom,c=a.right,d=a.height,u=a.width):(s=0,r=0,l=window.innerHeight,c=window.innerWidth,d=window.innerHeight,u=window.innerWidth),(t||o)&&e!==window&&(i=i||e.parentNode,!Fe))do{if(i&&i.getBoundingClientRect&&("none"!==Ge(i,"transform")||o&&"static"!==Ge(i,"position"))){var m=i.getBoundingClientRect();s-=m.top+parseInt(Ge(i,"border-top-width")),r-=m.left+parseInt(Ge(i,"border-left-width")),l=s+a.height,c=r+a.width;break}}while(i=i.parentNode);if(n&&e!==window){var p=Je(i||e),h=p&&p.a,g=p&&p.d;p&&(l=(s/=g)+(d/=g),c=(r/=h)+(u/=h))}return{top:s,left:r,bottom:l,right:c,width:u,height:d}}}function et(e,t,o){for(var n=at(e,!0),i=Qe(e)[t];n;){var a=Qe(n)[o];if(!("top"===o||"left"===o?i>=a:i<=a))return n;if(n===Xe())break;n=at(n,!1)}return!1}function tt(e,t,o,n){for(var i=0,a=0,s=e.children;a<s.length;){if("none"!==s[a].style.display&&s[a]!==co.ghost&&(n||s[a]!==co.dragged)&&We(s[a],o.draggable,e,!1)){if(i===t)return s[a];i++}a++}return null}function ot(e,t){for(var o=e.lastElementChild;o&&(o===co.ghost||"none"===Ge(o,"display")||t&&!Ve(o,t));)o=o.previousElementSibling;return o||null}function nt(e,t){var o=0;if(!e||!e.parentNode)return-1;for(;e=e.previousElementSibling;)"TEMPLATE"===e.nodeName.toUpperCase()||e===co.clone||t&&!Ve(e,t)||o++;return o}function it(e){var t=0,o=0,n=Xe();if(e)do{var i=Je(e),a=i.a,s=i.d;t+=e.scrollLeft*a,o+=e.scrollTop*s}while(e!==n&&(e=e.parentNode));return[t,o]}function at(e,t){if(!e||!e.getBoundingClientRect)return Xe();var o=e,n=!1;do{if(o.clientWidth<o.scrollWidth||o.clientHeight<o.scrollHeight){var i=Ge(o);if(o.clientWidth<o.scrollWidth&&("auto"==i.overflowX||"scroll"==i.overflowX)||o.clientHeight<o.scrollHeight&&("auto"==i.overflowY||"scroll"==i.overflowY)){if(!o.getBoundingClientRect||o===document.body)return Xe();if(n||t)return o;n=!0}}}while(o=o.parentNode);return Xe()}function st(e,t){return Math.round(e.top)===Math.round(t.top)&&Math.round(e.left)===Math.round(t.left)&&Math.round(e.height)===Math.round(t.height)&&Math.round(e.width)===Math.round(t.width)}function rt(e,t){return function(){if(!je){var o=arguments;1===o.length?e.call(this,o[0]):e.apply(this,o),je=setTimeout(function(){je=void 0},t)}}}function lt(e,t,o){e.scrollLeft+=t,e.scrollTop+=o}function ct(e){var t=window.Polymer,o=window.jQuery||window.Zepto;return t&&t.dom?t.dom(e).cloneNode(!0):o?o(e).clone(!0)[0]:e.cloneNode(!0)}function dt(e,t,o){var n={};return Array.from(e.children).forEach(function(i){var a,s,r,l;if(We(i,t.draggable,e,!1)&&!i.animated&&i!==o){var c=Qe(i);n.left=Math.min(null!==(a=n.left)&&void 0!==a?a:1/0,c.left),n.top=Math.min(null!==(s=n.top)&&void 0!==s?s:1/0,c.top),n.right=Math.max(null!==(r=n.right)&&void 0!==r?r:-1/0,c.right),n.bottom=Math.max(null!==(l=n.bottom)&&void 0!==l?l:-1/0,c.bottom)}}),n.width=n.right-n.left,n.height=n.bottom-n.top,n.x=n.left,n.y=n.top,n}var ut="Sortable"+(new Date).getTime();function mt(){var e,t=[];return{captureAnimationState:function(){(t=[],this.options.animation)&&[].slice.call(this.el.children).forEach(function(e){if("none"!==Ge(e,"display")&&e!==co.ghost){t.push({target:e,rect:Qe(e)});var o=Ne({},t[t.length-1].rect);if(e.thisAnimationDuration){var n=Je(e,!0);n&&(o.top-=n.f,o.left-=n.e)}e.fromRect=o}})},addAnimationState:function(e){t.push(e)},removeAnimationState:function(e){t.splice(function(e,t){for(var o in e)if(e.hasOwnProperty(o))for(var n in t)if(t.hasOwnProperty(n)&&t[n]===e[o][n])return Number(o);return-1}(t,{target:e}),1)},animateAll:function(o){var n=this;if(!this.options.animation)return clearTimeout(e),void("function"==typeof o&&o());var i=!1,a=0;t.forEach(function(e){var t=0,o=e.target,s=o.fromRect,r=Qe(o),l=o.prevFromRect,c=o.prevToRect,d=e.rect,u=Je(o,!0);u&&(r.top-=u.f,r.left-=u.e),o.toRect=r,o.thisAnimationDuration&&st(l,r)&&!st(s,r)&&(d.top-r.top)/(d.left-r.left)===(s.top-r.top)/(s.left-r.left)&&(t=function(e,t,o,n){return Math.sqrt(Math.pow(t.top-e.top,2)+Math.pow(t.left-e.left,2))/Math.sqrt(Math.pow(t.top-o.top,2)+Math.pow(t.left-o.left,2))*n.animation}(d,l,c,n.options)),st(r,s)||(o.prevFromRect=s,o.prevToRect=r,t||(t=n.options.animation),n.animate(o,d,r,t)),t&&(i=!0,a=Math.max(a,t),clearTimeout(o.animationResetTimer),o.animationResetTimer=setTimeout(function(){o.animationTime=0,o.prevFromRect=null,o.fromRect=null,o.prevToRect=null,o.thisAnimationDuration=null},t),o.thisAnimationDuration=t)}),clearTimeout(e),i?e=setTimeout(function(){"function"==typeof o&&o()},a):"function"==typeof o&&o(),t=[]},animate:function(e,t,o,n){if(n){Ge(e,"transition",""),Ge(e,"transform","");var i=Je(this.el),a=i&&i.a,s=i&&i.d,r=(t.left-o.left)/(a||1),l=(t.top-o.top)/(s||1);e.animatingX=!!r,e.animatingY=!!l,Ge(e,"transform","translate3d("+r+"px,"+l+"px,0)"),this.forRepaintDummy=function(e){return e.offsetWidth}(e),Ge(e,"transition","transform "+n+"ms"+(this.options.easing?" "+this.options.easing:"")),Ge(e,"transform","translate3d(0,0,0)"),"number"==typeof e.animated&&clearTimeout(e.animated),e.animated=setTimeout(function(){Ge(e,"transition",""),Ge(e,"transform",""),e.animated=!1,e.animatingX=!1,e.animatingY=!1},n)}}}}var pt=[],ht={initializeByDefault:!0},gt={mount:function(e){for(var t in ht)ht.hasOwnProperty(t)&&!(t in e)&&(e[t]=ht[t]);pt.forEach(function(t){if(t.pluginName===e.pluginName)throw"Sortable: Cannot mount plugin ".concat(e.pluginName," more than once")}),pt.push(e)},pluginEvent:function(e,t,o){var n=this;this.eventCanceled=!1,o.cancel=function(){n.eventCanceled=!0};var i=e+"Global";pt.forEach(function(n){t[n.pluginName]&&(t[n.pluginName][i]&&t[n.pluginName][i](Ne({sortable:t},o)),t.options[n.pluginName]&&t[n.pluginName][e]&&t[n.pluginName][e](Ne({sortable:t},o)))})},initializePlugins:function(e,t,o,n){for(var i in pt.forEach(function(n){var i=n.pluginName;if(e.options[i]||n.initializeByDefault){var a=new n(e,t,e.options);a.sortable=e,a.options=e.options,e[i]=a,Me(o,a.defaults)}}),e.options)if(e.options.hasOwnProperty(i)){var a=this.modifyOption(e,i,e.options[i]);void 0!==a&&(e.options[i]=a)}},getEventProperties:function(e,t){var o={};return pt.forEach(function(n){"function"==typeof n.eventProperties&&Me(o,n.eventProperties.call(t[n.pluginName],e))}),o},modifyOption:function(e,t,o){var n;return pt.forEach(function(i){e[i.pluginName]&&i.optionListeners&&"function"==typeof i.optionListeners[t]&&(n=i.optionListeners[t].call(e[i.pluginName],o))}),n}};var ft=["evt"],bt=function(e,t){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=o.evt,i=function(e,t){if(null==e)return{};var o,n,i=function(e,t){if(null==e)return{};var o={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(-1!==t.indexOf(n))continue;o[n]=e[n]}return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(n=0;n<a.length;n++)o=a[n],-1===t.indexOf(o)&&{}.propertyIsEnumerable.call(e,o)&&(i[o]=e[o])}return i}(o,ft);gt.pluginEvent.bind(co)(e,t,Ne({dragEl:Ct,parentEl:vt,ghostEl:wt,rootEl:xt,nextEl:kt,lastDownEl:St,cloneEl:Tt,cloneHidden:Et,dragStarted:$t,putSortable:Dt,activeSortable:co.active,originalEvent:n,oldIndex:It,oldDraggableIndex:Mt,newIndex:At,newDraggableIndex:Pt,hideGhostForTarget:ao,unhideGhostForTarget:so,cloneNowHidden:function(){Et=!0},cloneNowShown:function(){Et=!1},dispatchSortableEvent:function(e){yt({sortable:t,name:e,originalEvent:n})}},i))};function yt(e){!function(e){var t=e.sortable,o=e.rootEl,n=e.name,i=e.targetEl,a=e.cloneEl,s=e.toEl,r=e.fromEl,l=e.oldIndex,c=e.newIndex,d=e.oldDraggableIndex,u=e.newDraggableIndex,m=e.originalEvent,p=e.putSortable,h=e.extraEventProperties;if(t=t||o&&o[ut]){var g,f=t.options,b="on"+n.charAt(0).toUpperCase()+n.substr(1);!window.CustomEvent||Fe||Oe?(g=document.createEvent("Event")).initEvent(n,!0,!0):g=new CustomEvent(n,{bubbles:!0,cancelable:!0}),g.to=s||o,g.from=r||o,g.item=i||o,g.clone=a,g.oldIndex=l,g.newIndex=c,g.oldDraggableIndex=d,g.newDraggableIndex=u,g.originalEvent=m,g.pullMode=p?p.lastPutMode:void 0;var y=Ne(Ne({},h),gt.getEventProperties(n,t));for(var C in y)g[C]=y[C];o&&o.dispatchEvent(g),f[b]&&f[b].call(t,g)}}(Ne({putSortable:Dt,cloneEl:Tt,targetEl:Ct,rootEl:xt,oldIndex:It,oldDraggableIndex:Mt,newIndex:At,newDraggableIndex:Pt},e))}var Ct,vt,wt,xt,kt,St,Tt,Et,It,At,Mt,Pt,Nt,Dt,Lt,Ft,Ot,Rt,qt,Bt,$t,_t,zt,Ut,Vt,Ht=!1,Wt=!1,jt=[],Kt=!1,Yt=!1,Gt=[],Jt=!1,Zt=[],Xt="undefined"!=typeof document,Qt=Be,eo=Oe||Fe?"cssFloat":"float",to=Xt&&!$e&&!Be&&"draggable"in document.createElement("div"),oo=function(){if(Xt){if(Fe)return!1;var e=document.createElement("x");return e.style.cssText="pointer-events:auto","auto"===e.style.pointerEvents}}(),no=function(e,t){var o=Ge(e),n=parseInt(o.width)-parseInt(o.paddingLeft)-parseInt(o.paddingRight)-parseInt(o.borderLeftWidth)-parseInt(o.borderRightWidth),i=tt(e,0,t),a=tt(e,1,t),s=i&&Ge(i),r=a&&Ge(a),l=s&&parseInt(s.marginLeft)+parseInt(s.marginRight)+Qe(i).width,c=r&&parseInt(r.marginLeft)+parseInt(r.marginRight)+Qe(a).width;if("flex"===o.display)return"column"===o.flexDirection||"column-reverse"===o.flexDirection?"vertical":"horizontal";if("grid"===o.display)return o.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(i&&s.float&&"none"!==s.float){var d="left"===s.float?"left":"right";return!a||"both"!==r.clear&&r.clear!==d?"horizontal":"vertical"}return i&&("block"===s.display||"flex"===s.display||"table"===s.display||"grid"===s.display||l>=n&&"none"===o[eo]||a&&"none"===o[eo]&&l+c>n)?"vertical":"horizontal"},io=function(e){function t(e,o){return function(n,i,a,s){var r=n.options.group.name&&i.options.group.name&&n.options.group.name===i.options.group.name;if(null==e&&(o||r))return!0;if(null==e||!1===e)return!1;if(o&&"clone"===e)return e;if("function"==typeof e)return t(e(n,i,a,s),o)(n,i,a,s);var l=(o?n:i).options.group.name;return!0===e||"string"==typeof e&&e===l||e.join&&e.indexOf(l)>-1}}var o={},n=e.group;n&&"object"==De(n)||(n={name:n}),o.name=n.name,o.checkPull=t(n.pull,!0),o.checkPut=t(n.put),o.revertClone=n.revertClone,e.group=o},ao=function(){!oo&&wt&&Ge(wt,"display","none")},so=function(){!oo&&wt&&Ge(wt,"display","")};Xt&&!$e&&document.addEventListener("click",function(e){if(Wt)return e.preventDefault(),e.stopPropagation&&e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),Wt=!1,!1},!0);var ro=function(e){if(Ct){e=e.touches?e.touches[0]:e;var t=(i=e.clientX,a=e.clientY,jt.some(function(e){var t=e[ut].options.emptyInsertThreshold;if(t&&!ot(e)){var o=Qe(e),n=i>=o.left-t&&i<=o.right+t,r=a>=o.top-t&&a<=o.bottom+t;return n&&r?s=e:void 0}}),s);if(t){var o={};for(var n in e)e.hasOwnProperty(n)&&(o[n]=e[n]);o.target=o.rootEl=t,o.preventDefault=void 0,o.stopPropagation=void 0,t[ut]._onDragOver(o)}}var i,a,s},lo=function(e){Ct&&Ct.parentNode[ut]._isOutsideThisEl(e.target)};function co(e,t){if(!e||!e.nodeType||1!==e.nodeType)throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(e));this.el=e,this.options=t=Me({},t),e[ut]=this;var o={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(e.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return no(e,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(e,t){e.setData("Text",t.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:!1!==co.supportPointer&&"PointerEvent"in window&&(!qe||Be),emptyInsertThreshold:5};for(var n in gt.initializePlugins(this,e,o),o)!(n in t)&&(t[n]=o[n]);for(var i in io(t),this)"_"===i.charAt(0)&&"function"==typeof this[i]&&(this[i]=this[i].bind(this));this.nativeDraggable=!t.forceFallback&&to,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?ze(e,"pointerdown",this._onTapStart):(ze(e,"mousedown",this._onTapStart),ze(e,"touchstart",this._onTapStart)),this.nativeDraggable&&(ze(e,"dragover",this),ze(e,"dragenter",this)),jt.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),Me(this,mt())}function uo(e,t,o,n,i,a,s,r){var l,c,d=e[ut],u=d.options.onMove;return!window.CustomEvent||Fe||Oe?(l=document.createEvent("Event")).initEvent("move",!0,!0):l=new CustomEvent("move",{bubbles:!0,cancelable:!0}),l.to=t,l.from=e,l.dragged=o,l.draggedRect=n,l.related=i||t,l.relatedRect=a||Qe(t),l.willInsertAfter=r,l.originalEvent=s,e.dispatchEvent(l),u&&(c=u.call(d,l,s)),c}function mo(e){e.draggable=!1}function po(){Jt=!1}function ho(e){for(var t=e.tagName+e.className+e.src+e.href+e.textContent,o=t.length,n=0;o--;)n+=t.charCodeAt(o);return n.toString(36)}function go(e){return setTimeout(e,0)}function fo(e){return clearTimeout(e)}co.prototype={constructor:co,_isOutsideThisEl:function(e){this.el.contains(e)||e===this.el||(_t=null)},_getDirection:function(e,t){return"function"==typeof this.options.direction?this.options.direction.call(this,e,t,Ct):this.options.direction},_onTapStart:function(e){if(e.cancelable){var t=this,o=this.el,n=this.options,i=n.preventOnFilter,a=e.type,s=e.touches&&e.touches[0]||e.pointerType&&"touch"===e.pointerType&&e,r=(s||e).target,l=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||r,c=n.filter;if(function(e){Zt.length=0;var t=e.getElementsByTagName("input"),o=t.length;for(;o--;){var n=t[o];n.checked&&Zt.push(n)}}(o),!Ct&&!(/mousedown|pointerdown/.test(a)&&0!==e.button||n.disabled)&&!l.isContentEditable&&(this.nativeDraggable||!qe||!r||"SELECT"!==r.tagName.toUpperCase())&&!((r=We(r,n.draggable,o,!1))&&r.animated||St===r)){if(It=nt(r),Mt=nt(r,n.draggable),"function"==typeof c){if(c.call(this,e,r,this))return yt({sortable:t,rootEl:l,name:"filter",targetEl:r,toEl:o,fromEl:o}),bt("filter",t,{evt:e}),void(i&&e.preventDefault())}else if(c&&(c=c.split(",").some(function(n){if(n=We(l,n.trim(),o,!1))return yt({sortable:t,rootEl:n,name:"filter",targetEl:r,fromEl:o,toEl:o}),bt("filter",t,{evt:e}),!0})))return void(i&&e.preventDefault());n.handle&&!We(l,n.handle,o,!1)||this._prepareDragStart(e,s,r)}}},_prepareDragStart:function(e,t,o){var n,i=this,a=i.el,s=i.options,r=a.ownerDocument;if(o&&!Ct&&o.parentNode===a){var l=Qe(o);if(xt=a,vt=(Ct=o).parentNode,kt=Ct.nextSibling,St=o,Nt=s.group,co.dragged=Ct,Lt={target:Ct,clientX:(t||e).clientX,clientY:(t||e).clientY},qt=Lt.clientX-l.left,Bt=Lt.clientY-l.top,this._lastX=(t||e).clientX,this._lastY=(t||e).clientY,Ct.style["will-change"]="all",n=function(){bt("delayEnded",i,{evt:e}),co.eventCanceled?i._onDrop():(i._disableDelayedDragEvents(),!Re&&i.nativeDraggable&&(Ct.draggable=!0),i._triggerDragStart(e,t),yt({sortable:i,name:"choose",originalEvent:e}),Ye(Ct,s.chosenClass,!0))},s.ignore.split(",").forEach(function(e){Ze(Ct,e.trim(),mo)}),ze(r,"dragover",ro),ze(r,"mousemove",ro),ze(r,"touchmove",ro),s.supportPointer?(ze(r,"pointerup",i._onDrop),!this.nativeDraggable&&ze(r,"pointercancel",i._onDrop)):(ze(r,"mouseup",i._onDrop),ze(r,"touchend",i._onDrop),ze(r,"touchcancel",i._onDrop)),Re&&this.nativeDraggable&&(this.options.touchStartThreshold=4,Ct.draggable=!0),bt("delayStart",this,{evt:e}),!s.delay||s.delayOnTouchOnly&&!t||this.nativeDraggable&&(Oe||Fe))n();else{if(co.eventCanceled)return void this._onDrop();s.supportPointer?(ze(r,"pointerup",i._disableDelayedDrag),ze(r,"pointercancel",i._disableDelayedDrag)):(ze(r,"mouseup",i._disableDelayedDrag),ze(r,"touchend",i._disableDelayedDrag),ze(r,"touchcancel",i._disableDelayedDrag)),ze(r,"mousemove",i._delayedDragTouchMoveHandler),ze(r,"touchmove",i._delayedDragTouchMoveHandler),s.supportPointer&&ze(r,"pointermove",i._delayedDragTouchMoveHandler),i._dragStartTimer=setTimeout(n,s.delay)}}},_delayedDragTouchMoveHandler:function(e){var t=e.touches?e.touches[0]:e;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){Ct&&mo(Ct),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var e=this.el.ownerDocument;Ue(e,"mouseup",this._disableDelayedDrag),Ue(e,"touchend",this._disableDelayedDrag),Ue(e,"touchcancel",this._disableDelayedDrag),Ue(e,"pointerup",this._disableDelayedDrag),Ue(e,"pointercancel",this._disableDelayedDrag),Ue(e,"mousemove",this._delayedDragTouchMoveHandler),Ue(e,"touchmove",this._delayedDragTouchMoveHandler),Ue(e,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(e,t){t=t||"touch"==e.pointerType&&e,!this.nativeDraggable||t?this.options.supportPointer?ze(document,"pointermove",this._onTouchMove):ze(document,t?"touchmove":"mousemove",this._onTouchMove):(ze(Ct,"dragend",this),ze(xt,"dragstart",this._onDragStart));try{document.selection?go(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch(e){}},_dragStarted:function(e,t){if(Ht=!1,xt&&Ct){bt("dragStarted",this,{evt:t}),this.nativeDraggable&&ze(document,"dragover",lo);var o=this.options;!e&&Ye(Ct,o.dragClass,!1),Ye(Ct,o.ghostClass,!0),co.active=this,e&&this._appendGhost(),yt({sortable:this,name:"start",originalEvent:t})}else this._nulling()},_emulateDragOver:function(){if(Ft){this._lastX=Ft.clientX,this._lastY=Ft.clientY,ao();for(var e=document.elementFromPoint(Ft.clientX,Ft.clientY),t=e;e&&e.shadowRoot&&(e=e.shadowRoot.elementFromPoint(Ft.clientX,Ft.clientY))!==t;)t=e;if(Ct.parentNode[ut]._isOutsideThisEl(e),t)do{if(t[ut]){if(t[ut]._onDragOver({clientX:Ft.clientX,clientY:Ft.clientY,target:e,rootEl:t})&&!this.options.dragoverBubble)break}e=t}while(t=He(t));so()}},_onTouchMove:function(e){if(Lt){var t=this.options,o=t.fallbackTolerance,n=t.fallbackOffset,i=e.touches?e.touches[0]:e,a=wt&&Je(wt,!0),s=wt&&a&&a.a,r=wt&&a&&a.d,l=Qt&&Vt&&it(Vt),c=(i.clientX-Lt.clientX+n.x)/(s||1)+(l?l[0]-Gt[0]:0)/(s||1),d=(i.clientY-Lt.clientY+n.y)/(r||1)+(l?l[1]-Gt[1]:0)/(r||1);if(!co.active&&!Ht){if(o&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))<o)return;this._onDragStart(e,!0)}if(wt){a?(a.e+=c-(Ot||0),a.f+=d-(Rt||0)):a={a:1,b:0,c:0,d:1,e:c,f:d};var u="matrix(".concat(a.a,",").concat(a.b,",").concat(a.c,",").concat(a.d,",").concat(a.e,",").concat(a.f,")");Ge(wt,"webkitTransform",u),Ge(wt,"mozTransform",u),Ge(wt,"msTransform",u),Ge(wt,"transform",u),Ot=c,Rt=d,Ft=i}e.cancelable&&e.preventDefault()}},_appendGhost:function(){if(!wt){var e=this.options.fallbackOnBody?document.body:xt,t=Qe(Ct,!0,Qt,!0,e),o=this.options;if(Qt){for(Vt=e;"static"===Ge(Vt,"position")&&"none"===Ge(Vt,"transform")&&Vt!==document;)Vt=Vt.parentNode;Vt!==document.body&&Vt!==document.documentElement?(Vt===document&&(Vt=Xe()),t.top+=Vt.scrollTop,t.left+=Vt.scrollLeft):Vt=Xe(),Gt=it(Vt)}Ye(wt=Ct.cloneNode(!0),o.ghostClass,!1),Ye(wt,o.fallbackClass,!0),Ye(wt,o.dragClass,!0),Ge(wt,"transition",""),Ge(wt,"transform",""),Ge(wt,"box-sizing","border-box"),Ge(wt,"margin",0),Ge(wt,"top",t.top),Ge(wt,"left",t.left),Ge(wt,"width",t.width),Ge(wt,"height",t.height),Ge(wt,"opacity","0.8"),Ge(wt,"position",Qt?"absolute":"fixed"),Ge(wt,"zIndex","100000"),Ge(wt,"pointerEvents","none"),co.ghost=wt,e.appendChild(wt),Ge(wt,"transform-origin",qt/parseInt(wt.style.width)*100+"% "+Bt/parseInt(wt.style.height)*100+"%")}},_onDragStart:function(e,t){var o=this,n=e.dataTransfer,i=o.options;bt("dragStart",this,{evt:e}),co.eventCanceled?this._onDrop():(bt("setupClone",this),co.eventCanceled||((Tt=ct(Ct)).removeAttribute("id"),Tt.draggable=!1,Tt.style["will-change"]="",this._hideClone(),Ye(Tt,this.options.chosenClass,!1),co.clone=Tt),o.cloneId=go(function(){bt("clone",o),co.eventCanceled||(o.options.removeCloneOnHide||xt.insertBefore(Tt,Ct),o._hideClone(),yt({sortable:o,name:"clone"}))}),!t&&Ye(Ct,i.dragClass,!0),t?(Wt=!0,o._loopId=setInterval(o._emulateDragOver,50)):(Ue(document,"mouseup",o._onDrop),Ue(document,"touchend",o._onDrop),Ue(document,"touchcancel",o._onDrop),n&&(n.effectAllowed="move",i.setData&&i.setData.call(o,n,Ct)),ze(document,"drop",o),Ge(Ct,"transform","translateZ(0)")),Ht=!0,o._dragStartId=go(o._dragStarted.bind(o,t,e)),ze(document,"selectstart",o),$t=!0,window.getSelection().removeAllRanges(),qe&&Ge(document.body,"user-select","none"))},_onDragOver:function(e){var t,o,n,i,a=this.el,s=e.target,r=this.options,l=r.group,c=co.active,d=Nt===l,u=r.sort,m=Dt||c,p=this,h=!1;if(!Jt){if(void 0!==e.preventDefault&&e.cancelable&&e.preventDefault(),s=We(s,r.draggable,a,!0),M("dragOver"),co.eventCanceled)return h;if(Ct.contains(e.target)||s.animated&&s.animatingX&&s.animatingY||p._ignoreWhileAnimating===s)return N(!1);if(Wt=!1,c&&!r.disabled&&(d?u||(n=vt!==xt):Dt===this||(this.lastPutMode=Nt.checkPull(this,c,Ct,e))&&l.checkPut(this,c,Ct,e))){if(i="vertical"===this._getDirection(e,s),t=Qe(Ct),M("dragOverValid"),co.eventCanceled)return h;if(n)return vt=xt,P(),this._hideClone(),M("revert"),co.eventCanceled||(kt?xt.insertBefore(Ct,kt):xt.appendChild(Ct)),N(!0);var g=ot(a,r.draggable);if(!g||function(e,t,o){var n=Qe(ot(o.el,o.options.draggable)),i=dt(o.el,o.options,wt),a=10;return t?e.clientX>i.right+a||e.clientY>n.bottom&&e.clientX>n.left:e.clientY>i.bottom+a||e.clientX>n.right&&e.clientY>n.top}(e,i,this)&&!g.animated){if(g===Ct)return N(!1);if(g&&a===e.target&&(s=g),s&&(o=Qe(s)),!1!==uo(xt,a,Ct,t,s,o,e,!!s))return P(),g&&g.nextSibling?a.insertBefore(Ct,g.nextSibling):a.appendChild(Ct),vt=a,D(),N(!0)}else if(g&&function(e,t,o){var n=Qe(tt(o.el,0,o.options,!0)),i=dt(o.el,o.options,wt),a=10;return t?e.clientX<i.left-a||e.clientY<n.top&&e.clientX<n.right:e.clientY<i.top-a||e.clientY<n.bottom&&e.clientX<n.left}(e,i,this)){var f=tt(a,0,r,!0);if(f===Ct)return N(!1);if(o=Qe(s=f),!1!==uo(xt,a,Ct,t,s,o,e,!1))return P(),a.insertBefore(Ct,f),vt=a,D(),N(!0)}else if(s.parentNode===a){o=Qe(s);var b,y,C,v=Ct.parentNode!==a,w=!function(e,t,o){var n=o?e.left:e.top,i=o?e.right:e.bottom,a=o?e.width:e.height,s=o?t.left:t.top,r=o?t.right:t.bottom,l=o?t.width:t.height;return n===s||i===r||n+a/2===s+l/2}(Ct.animated&&Ct.toRect||t,s.animated&&s.toRect||o,i),x=i?"top":"left",k=et(s,"top","top")||et(Ct,"top","top"),S=k?k.scrollTop:void 0;if(_t!==s&&(y=o[x],Kt=!1,Yt=!w&&r.invertSwap||v),b=function(e,t,o,n,i,a,s,r){var l=n?e.clientY:e.clientX,c=n?o.height:o.width,d=n?o.top:o.left,u=n?o.bottom:o.right,m=!1;if(!s)if(r&&Ut<c*i){if(!Kt&&(1===zt?l>d+c*a/2:l<u-c*a/2)&&(Kt=!0),Kt)m=!0;else if(1===zt?l<d+Ut:l>u-Ut)return-zt}else if(l>d+c*(1-i)/2&&l<u-c*(1-i)/2)return function(e){return nt(Ct)<nt(e)?1:-1}(t);if((m=m||s)&&(l<d+c*a/2||l>u-c*a/2))return l>d+c/2?1:-1;return 0}(e,s,o,i,w?1:r.swapThreshold,null==r.invertedSwapThreshold?r.swapThreshold:r.invertedSwapThreshold,Yt,_t===s),0!==b){var T=nt(Ct);do{T-=b,C=vt.children[T]}while(C&&("none"===Ge(C,"display")||C===wt))}if(0===b||C===s)return N(!1);_t=s,zt=b;var E=s.nextElementSibling,I=!1,A=uo(xt,a,Ct,t,s,o,e,I=1===b);if(!1!==A)return 1!==A&&-1!==A||(I=1===A),Jt=!0,setTimeout(po,30),P(),I&&!E?a.appendChild(Ct):s.parentNode.insertBefore(Ct,I?E:s),k&&lt(k,0,S-k.scrollTop),vt=Ct.parentNode,void 0===y||Yt||(Ut=Math.abs(y-Qe(s)[x])),D(),N(!0)}if(a.contains(Ct))return N(!1)}return!1}function M(r,l){bt(r,p,Ne({evt:e,isOwner:d,axis:i?"vertical":"horizontal",revert:n,dragRect:t,targetRect:o,canSort:u,fromSortable:m,target:s,completed:N,onMove:function(o,n){return uo(xt,a,Ct,t,o,Qe(o),e,n)},changed:D},l))}function P(){M("dragOverAnimationCapture"),p.captureAnimationState(),p!==m&&m.captureAnimationState()}function N(t){return M("dragOverCompleted",{insertion:t}),t&&(d?c._hideClone():c._showClone(p),p!==m&&(Ye(Ct,Dt?Dt.options.ghostClass:c.options.ghostClass,!1),Ye(Ct,r.ghostClass,!0)),Dt!==p&&p!==co.active?Dt=p:p===co.active&&Dt&&(Dt=null),m===p&&(p._ignoreWhileAnimating=s),p.animateAll(function(){M("dragOverAnimationComplete"),p._ignoreWhileAnimating=null}),p!==m&&(m.animateAll(),m._ignoreWhileAnimating=null)),(s===Ct&&!Ct.animated||s===a&&!s.animated)&&(_t=null),r.dragoverBubble||e.rootEl||s===document||(Ct.parentNode[ut]._isOutsideThisEl(e.target),!t&&ro(e)),!r.dragoverBubble&&e.stopPropagation&&e.stopPropagation(),h=!0}function D(){At=nt(Ct),Pt=nt(Ct,r.draggable),yt({sortable:p,name:"change",toEl:a,newIndex:At,newDraggableIndex:Pt,originalEvent:e})}},_ignoreWhileAnimating:null,_offMoveEvents:function(){Ue(document,"mousemove",this._onTouchMove),Ue(document,"touchmove",this._onTouchMove),Ue(document,"pointermove",this._onTouchMove),Ue(document,"dragover",ro),Ue(document,"mousemove",ro),Ue(document,"touchmove",ro)},_offUpEvents:function(){var e=this.el.ownerDocument;Ue(e,"mouseup",this._onDrop),Ue(e,"touchend",this._onDrop),Ue(e,"pointerup",this._onDrop),Ue(e,"pointercancel",this._onDrop),Ue(e,"touchcancel",this._onDrop),Ue(document,"selectstart",this)},_onDrop:function(e){var t=this.el,o=this.options;At=nt(Ct),Pt=nt(Ct,o.draggable),bt("drop",this,{evt:e}),vt=Ct&&Ct.parentNode,At=nt(Ct),Pt=nt(Ct,o.draggable),co.eventCanceled||(Ht=!1,Yt=!1,Kt=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),fo(this.cloneId),fo(this._dragStartId),this.nativeDraggable&&(Ue(document,"drop",this),Ue(t,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),qe&&Ge(document.body,"user-select",""),Ge(Ct,"transform",""),e&&($t&&(e.cancelable&&e.preventDefault(),!o.dropBubble&&e.stopPropagation()),wt&&wt.parentNode&&wt.parentNode.removeChild(wt),(xt===vt||Dt&&"clone"!==Dt.lastPutMode)&&Tt&&Tt.parentNode&&Tt.parentNode.removeChild(Tt),Ct&&(this.nativeDraggable&&Ue(Ct,"dragend",this),mo(Ct),Ct.style["will-change"]="",$t&&!Ht&&Ye(Ct,Dt?Dt.options.ghostClass:this.options.ghostClass,!1),Ye(Ct,this.options.chosenClass,!1),yt({sortable:this,name:"unchoose",toEl:vt,newIndex:null,newDraggableIndex:null,originalEvent:e}),xt!==vt?(At>=0&&(yt({rootEl:vt,name:"add",toEl:vt,fromEl:xt,originalEvent:e}),yt({sortable:this,name:"remove",toEl:vt,originalEvent:e}),yt({rootEl:vt,name:"sort",toEl:vt,fromEl:xt,originalEvent:e}),yt({sortable:this,name:"sort",toEl:vt,originalEvent:e})),Dt&&Dt.save()):At!==It&&At>=0&&(yt({sortable:this,name:"update",toEl:vt,originalEvent:e}),yt({sortable:this,name:"sort",toEl:vt,originalEvent:e})),co.active&&(null!=At&&-1!==At||(At=It,Pt=Mt),yt({sortable:this,name:"end",toEl:vt,originalEvent:e}),this.save())))),this._nulling()},_nulling:function(){bt("nulling",this),xt=Ct=vt=wt=kt=Tt=St=Et=Lt=Ft=$t=At=Pt=It=Mt=_t=zt=Dt=Nt=co.dragged=co.ghost=co.clone=co.active=null;var e=this.el;Zt.forEach(function(t){e.contains(t)&&(t.checked=!0)}),Zt.length=Ot=Rt=0},handleEvent:function(e){switch(e.type){case"drop":case"dragend":this._onDrop(e);break;case"dragenter":case"dragover":Ct&&(this._onDragOver(e),function(e){e.dataTransfer&&(e.dataTransfer.dropEffect="move");e.cancelable&&e.preventDefault()}(e));break;case"selectstart":e.preventDefault()}},toArray:function(){for(var e,t=[],o=this.el.children,n=0,i=o.length,a=this.options;n<i;n++)We(e=o[n],a.draggable,this.el,!1)&&t.push(e.getAttribute(a.dataIdAttr)||ho(e));return t},sort:function(e,t){var o={},n=this.el;this.toArray().forEach(function(e,t){var i=n.children[t];We(i,this.options.draggable,n,!1)&&(o[e]=i)},this),t&&this.captureAnimationState(),e.forEach(function(e){o[e]&&(n.removeChild(o[e]),n.appendChild(o[e]))}),t&&this.animateAll()},save:function(){var e=this.options.store;e&&e.set&&e.set(this)},closest:function(e,t){return We(e,t||this.options.draggable,this.el,!1)},option:function(e,t){var o=this.options;if(void 0===t)return o[e];var n=gt.modifyOption(this,e,t);o[e]=void 0!==n?n:t,"group"===e&&io(o)},destroy:function(){bt("destroy",this);var e=this.el;e[ut]=null,Ue(e,"mousedown",this._onTapStart),Ue(e,"touchstart",this._onTapStart),Ue(e,"pointerdown",this._onTapStart),this.nativeDraggable&&(Ue(e,"dragover",this),Ue(e,"dragenter",this)),Array.prototype.forEach.call(e.querySelectorAll("[draggable]"),function(e){e.removeAttribute("draggable")}),this._onDrop(),this._disableDelayedDragEvents(),jt.splice(jt.indexOf(this.el),1),this.el=e=null},_hideClone:function(){if(!Et){if(bt("hideClone",this),co.eventCanceled)return;Ge(Tt,"display","none"),this.options.removeCloneOnHide&&Tt.parentNode&&Tt.parentNode.removeChild(Tt),Et=!0}},_showClone:function(e){if("clone"===e.lastPutMode){if(Et){if(bt("showClone",this),co.eventCanceled)return;Ct.parentNode!=xt||this.options.group.revertClone?kt?xt.insertBefore(Tt,kt):xt.appendChild(Tt):xt.insertBefore(Tt,Ct),this.options.group.revertClone&&this.animate(Ct,Tt),Ge(Tt,"display",""),Et=!1}}else this._hideClone()}},Xt&&ze(document,"touchmove",function(e){(co.active||Ht)&&e.cancelable&&e.preventDefault()}),co.utils={on:ze,off:Ue,css:Ge,find:Ze,is:function(e,t){return!!We(e,t,e,!1)},extend:function(e,t){if(e&&t)for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o]);return e},throttle:rt,closest:We,toggleClass:Ye,clone:ct,index:nt,nextTick:go,cancelNextTick:fo,detectDirection:no,getChild:tt,expando:ut},co.get=function(e){return e[ut]},co.mount=function(){for(var e=arguments.length,t=new Array(e),o=0;o<e;o++)t[o]=arguments[o];t[0].constructor===Array&&(t=t[0]),t.forEach(function(e){if(!e.prototype||!e.prototype.constructor)throw"Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(e));e.utils&&(co.utils=Ne(Ne({},co.utils),e.utils)),gt.mount(e)})},co.create=function(e,t){return new co(e,t)},co.version="1.15.7";var bo,yo,Co,vo,wo,xo,ko=[],So=!1;function To(){ko.forEach(function(e){clearInterval(e.pid)}),ko=[]}function Eo(){clearInterval(xo)}var Io=rt(function(e,t,o,n){if(t.scroll){var i,a=(e.touches?e.touches[0]:e).clientX,s=(e.touches?e.touches[0]:e).clientY,r=t.scrollSensitivity,l=t.scrollSpeed,c=Xe(),d=!1;yo!==o&&(yo=o,To(),bo=t.scroll,i=t.scrollFn,!0===bo&&(bo=at(o,!0)));var u=0,m=bo;do{var p=m,h=Qe(p),g=h.top,f=h.bottom,b=h.left,y=h.right,C=h.width,v=h.height,w=void 0,x=void 0,k=p.scrollWidth,S=p.scrollHeight,T=Ge(p),E=p.scrollLeft,I=p.scrollTop;p===c?(w=C<k&&("auto"===T.overflowX||"scroll"===T.overflowX||"visible"===T.overflowX),x=v<S&&("auto"===T.overflowY||"scroll"===T.overflowY||"visible"===T.overflowY)):(w=C<k&&("auto"===T.overflowX||"scroll"===T.overflowX),x=v<S&&("auto"===T.overflowY||"scroll"===T.overflowY));var A=w&&(Math.abs(y-a)<=r&&E+C<k)-(Math.abs(b-a)<=r&&!!E),M=x&&(Math.abs(f-s)<=r&&I+v<S)-(Math.abs(g-s)<=r&&!!I);if(!ko[u])for(var P=0;P<=u;P++)ko[P]||(ko[P]={});ko[u].vx==A&&ko[u].vy==M&&ko[u].el===p||(ko[u].el=p,ko[u].vx=A,ko[u].vy=M,clearInterval(ko[u].pid),0==A&&0==M||(d=!0,ko[u].pid=setInterval(function(){n&&0===this.layer&&co.active._onTouchMove(wo);var t=ko[this.layer].vy?ko[this.layer].vy*l:0,o=ko[this.layer].vx?ko[this.layer].vx*l:0;"function"==typeof i&&"continue"!==i.call(co.dragged.parentNode[ut],o,t,e,wo,ko[this.layer].el)||lt(ko[this.layer].el,o,t)}.bind({layer:u}),24))),u++}while(t.bubbleScroll&&m!==c&&(m=at(m,!1)));So=d}},30),Ao=function(e){var t=e.originalEvent,o=e.putSortable,n=e.dragEl,i=e.activeSortable,a=e.dispatchSortableEvent,s=e.hideGhostForTarget,r=e.unhideGhostForTarget;if(t){var l=o||i;s();var c=t.changedTouches&&t.changedTouches.length?t.changedTouches[0]:t,d=document.elementFromPoint(c.clientX,c.clientY);r(),l&&!l.el.contains(d)&&(a("spill"),this.onSpill({dragEl:n,putSortable:o}))}};function Mo(){}function Po(){}Mo.prototype={startIndex:null,dragStart:function(e){var t=e.oldDraggableIndex;this.startIndex=t},onSpill:function(e){var t=e.dragEl,o=e.putSortable;this.sortable.captureAnimationState(),o&&o.captureAnimationState();var n=tt(this.sortable.el,this.startIndex,this.options);n?this.sortable.el.insertBefore(t,n):this.sortable.el.appendChild(t),this.sortable.animateAll(),o&&o.animateAll()},drop:Ao},Me(Mo,{pluginName:"revertOnSpill"}),Po.prototype={onSpill:function(e){var t=e.dragEl,o=e.putSortable||this.sortable;o.captureAnimationState(),t.parentNode&&t.parentNode.removeChild(t),o.animateAll()},drop:Ao},Me(Po,{pluginName:"removeOnSpill"}),co.mount(new function(){function e(){for(var e in this.defaults={scroll:!0,forceAutoScrollFallback:!1,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0},this)"_"===e.charAt(0)&&"function"==typeof this[e]&&(this[e]=this[e].bind(this))}return e.prototype={dragStarted:function(e){var t=e.originalEvent;this.sortable.nativeDraggable?ze(document,"dragover",this._handleAutoScroll):this.options.supportPointer?ze(document,"pointermove",this._handleFallbackAutoScroll):t.touches?ze(document,"touchmove",this._handleFallbackAutoScroll):ze(document,"mousemove",this._handleFallbackAutoScroll)},dragOverCompleted:function(e){var t=e.originalEvent;this.options.dragOverBubble||t.rootEl||this._handleAutoScroll(t)},drop:function(){this.sortable.nativeDraggable?Ue(document,"dragover",this._handleAutoScroll):(Ue(document,"pointermove",this._handleFallbackAutoScroll),Ue(document,"touchmove",this._handleFallbackAutoScroll),Ue(document,"mousemove",this._handleFallbackAutoScroll)),Eo(),To(),clearTimeout(je),je=void 0},nulling:function(){wo=yo=bo=So=xo=Co=vo=null,ko.length=0},_handleFallbackAutoScroll:function(e){this._handleAutoScroll(e,!0)},_handleAutoScroll:function(e,t){var o=this,n=(e.touches?e.touches[0]:e).clientX,i=(e.touches?e.touches[0]:e).clientY,a=document.elementFromPoint(n,i);if(wo=e,t||this.options.forceAutoScrollFallback||Oe||Fe||qe){Io(e,this.options,a,t);var s=at(a,!0);!So||xo&&n===Co&&i===vo||(xo&&Eo(),xo=setInterval(function(){var a=at(document.elementFromPoint(n,i),!0);a!==s&&(s=a,To()),Io(e,o.options,a,t)},10),Co=n,vo=i)}else{if(!this.options.bubbleScroll||at(a,!0)===Xe())return void To();Io(e,this.options,at(a,!1),!1)}}},Me(e,{pluginName:"scroll",initializeByDefault:!0})}),co.mount(Po,Mo);class No extends e.Modal{constructor(e,t){super(e),this.options={title:v("Confirm"),confirmText:v("Confirm"),cancelText:v("Cancel"),...t}}onOpen(){const{contentEl:t}=this;t.addClass("confirm-modal"),t.createEl("h2",{text:this.options.title}),this.options.message.split("\n").forEach(e=>{t.createEl("p",{text:e})});const o=t.createDiv("confirm-modal-buttons");new e.ButtonComponent(o).setButtonText(this.options.cancelText).onClick(()=>this.close()),new e.ButtonComponent(o).setButtonText(this.options.confirmText).setCta().onClick(async()=>{await this.options.onConfirm(),this.close()})}onClose(){const{contentEl:e}=this;e.empty()}static show(e,t){new No(e,t).open()}}class Do extends e.Modal{constructor(e,t){super(e),this.changelogContent="",this.changelogLoaded=!1,this.plugin=t}async loadChangelog(){try{const t=await e.request({url:"https://raw.githubusercontent.com/PKM-er/obsidian-editing-toolbar/master/CHANGELOG.md",method:"GET"});if(!t)throw new Error("无法获取 Changelog 内容");{const e=t.split("\n");let o="",n=[],i=!1;for(const t of e)if(t.startsWith("## ")&&!o)o=t.substring(3).trim(),i=!0,n.push(t);else{if(t.startsWith("## ")&&i)break;i&&n.push(t)}this.changelogContent=n.join("\n")}}catch(e){console.error("加载 Changelog 时出错:",e),this.changelogContent="### 无法加载更新说明\n\n请[点击此处查看最新更新说明](https://github.com/PKM-er/obsidian-editing-toolbar/blob/master/CHANGELOG.md)"}this.changelogLoaded=!0,this.updateChangelogDisplay()}updateChangelogDisplay(){this.changelogContainer&&this.changelogContentEl&&this.changelogLoaded&&(this.changelogContentEl.empty(),e.MarkdownRenderer.renderMarkdown(this.changelogContent,this.changelogContentEl,"",this.plugin))}async fixCommandIds(){try{const t={"editor:toggle-numbered-list":"editing-toolbar:toggle-numbered-list","editor:toggle-bullet-list":"editing-toolbar:toggle-bullet-list","editor:toggle-highlight":"editing-toolbar:toggle-highlight","toggle-highlight":"editing-toolbar:toggle-highlight","editing-toolbar:editor:toggle-bold":"editing-toolbar:toggle-bold","editing-toolbar:editor:toggle-italics":"editing-toolbar:toggle-italics","editing-toolbar:editor:toggle-strikethrough":"editing-toolbar:toggle-strikethrough","editing-toolbar:editor:toggle-inline-math":"editing-toolbar:toggle-inline-math","editing-toolbar:editor:insert-callout":"editing-toolbar:insert-callout","editing-toolbar:editor:insert-link":"editing-toolbar:insert-link","cMenuToolbar-Divider-Line":"editingToolbar-Divider-Line"};let o=!1;const n=this.plugin.settings,i=e=>{e&&Array.isArray(e)&&e.forEach(e=>{e.id&&t[e.id]&&(e.id=t[e.id],o=!0),"editing-toolbar:format-eraser"===e.id&&(e.icon="eraser",o=!0),"editing-toolbar:change-font-color"===e.id&&(e.icon='<svg width="24" height="24" viewBox="0 0 24 24" focusable="false" fill="currentColor"><g fill-rule="evenodd"><path id="change-font-color-icon" d="M3 18h18v3H3z" style="fill:#2DC26B"></path><path d="M8.7 16h-.8a.5.5 0 01-.5-.6l2.7-9c.1-.3.3-.4.5-.4h2.8c.2 0 .4.1.5.4l2.7 9a.5.5 0 01-.5.6h-.8a.5.5 0 01-.4-.4l-.7-2.2c0-.3-.3-.4-.5-.4h-3.4c-.2 0-.4.1-.5.4l-.7 2.2c0 .3-.2.4-.4.4zm2.6-7.6l-.6 2a.5.5 0 00.5.6h1.6a.5.5 0 00.5-.6l-.6-2c0-.3-.3-.4-.5-.4h-.4c-.2 0-.4.1-.5.4z"></path></g></svg>',o=!0),e.SubmenuCommands&&i(e.SubmenuCommands)})},a=e=>{if(!e||!Array.isArray(e))return!1;for(const t of e){if("editing-toolbar:toggle-format-brush"===t.id)return!0;if(t.SubmenuCommands){if(a(t.SubmenuCommands))return!0}}return!1},s=e=>{if(!e||!Array.isArray(e))return!1;if(!a(e)&&e.length>=2){const t={id:"editing-toolbar:toggle-format-brush",name:"Format Brush",icon:"paintbrush"};return e.splice(2,0,t),!0}return!1},r=e=>{if(!e||!Array.isArray(e))return!1;for(const t of e)if("SubmenuCommands-text-tools"===t.id)return!0;return!1},l=e=>{if(!e||!Array.isArray(e))return!1;if(!r(e)){const t=Z.menuCommands.find(e=>"SubmenuCommands-text-tools"===e.id);if(t){const o=11;return e.length>=o?e.splice(o,0,t):e.push(t),!0}}return!1};n.menuCommands&&(i(n.menuCommands),s(n.menuCommands)&&(o=!0),l(n.menuCommands)&&(o=!0)),n.enableMultipleConfig&&(n.followingCommands&&(i(n.followingCommands),s(n.followingCommands)&&(o=!0)),n.topCommands&&(i(n.topCommands),s(n.topCommands)&&(o=!0),l(n.topCommands)&&(o=!0)),n.fixedCommands&&(i(n.fixedCommands),s(n.fixedCommands)&&(o=!0)),n.mobileCommands&&(i(n.mobileCommands),s(n.mobileCommands)&&(o=!0))),o?(await this.plugin.saveSettings(),new e.Notice(v("Command IDs have been successfully repaired!")),dispatchEvent(new Event("editingToolbar-NewCommand"))):new e.Notice(v("No command IDs need to be repaired"))}catch(t){console.error("修复命令ID时出错:",t),new e.Notice(v("Error repairing command IDs, please check the console for details"))}}async reloadPlugin(e){const{plugins:t}=this.app;try{await t.disablePlugin(e),await t.enablePlugin(e)}catch(e){console.error(e)}}async restoreDefaultSettings(){try{const t=this.plugin.settings.lastVersion,o=this.plugin.settings.customCommands;this.plugin.settings={...Z,ai:{...Z.ai,customPromptHistory:[],customPromptTemplates:L()},lastVersion:t,customCommands:o},await this.plugin.saveSettings(),new e.Notice(v("Successfully restored default settings! (Custom commands preserved)")),this.reloadPlugin(this.plugin.manifest.id),this.close()}catch(t){console.error("恢复默认设置时出错:",t),new e.Notice(v("Error restoring default settings, please check the console for details"))}}onOpen(){const{contentEl:t}=this;t.createEl("h2",{text:`${this.plugin.manifest.name} v${this.plugin.manifest.version} · ${v("Tips")}`}),t.createEl("p",{text:v("Notice:")});const o=t.createEl("ul");o.createEl("li",{text:v("⚠This update is not compatible with 2.x version command ids, please click [Repair command] to be compatible")}),o.createEl("li",{text:v("⚠If you want to restore the default settings, please click [Restore default settings]")}),this.changelogContainer=t.createDiv({cls:"changelog-container"}),this.changelogContainer.createEl("h3",{text:v("Latest Changes")}),this.changelogContentEl=this.changelogContainer.createDiv({cls:"changelog-content"}),this.changelogContentEl.setText(v("Loading changelog...")),setTimeout(()=>{this.loadChangelog()},100),new e.Setting(t).setName(v("🔧Data repair")).setDesc(v("This update changed the ID of some commands, please click this button to repair the commands to ensure the toolbar works properly")).addButton(e=>e.setButtonText(v("Repair command ID")).onClick(async()=>{await this.fixCommandIds()})),new e.Setting(t).setName(v("🔄Restore default settings")).setDesc(v("This will reset all your custom configurations, but custom commands will be preserved")).addButton(e=>e.setButtonText(v("Restore default")).onClick(async()=>{No.show(this.app,{message:v("Are you sure you want to restore all settings to default? But custom commands will be preserved."),onConfirm:async()=>{await this.restoreDefaultSettings()}})})),new e.Setting(t).setName(v("📋View full changelog")).setDesc(v("Open the complete changelog in your browser")).addButton(e=>e.setButtonText(v("Open changelog")).onClick(()=>{window.open("https://github.com/PKM-er/obsidian-editing-toolbar/blob/master/CHANGELOG.md","_blank")})),new e.Setting(t).addButton(e=>e.setButtonText(v("Close")).onClick(()=>{this.close()})),t.createEl("style",{text:"\n .changelog-container {\n margin-top: 20px;\n margin-bottom: 20px;\n padding: 10px;\n border: 1px solid var(--background-modifier-border);\n border-radius: 5px;\n max-height: 200px;\n overflow-y: auto;\n }\n .changelog-content {\n padding: 0 10px;\n }\n .changelog-content a {\n text-decoration: underline;\n }\n "})}onClose(){const{contentEl:e}=this;e.empty()}}function Lo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}
/*! Pickr 1.8.4 MIT | https://github.com/Simonwep/pickr */
var Fo=function(e){var t={exports:{}};return e(t,t.exports),t.exports}(function(e,t){self,e.exports=(()=>{var e={d:(t,o)=>{for(var n in o)e.o(o,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:o[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.d(t,{default:()=>N});var o={};function n(e,t,o,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};t instanceof HTMLCollection||t instanceof NodeList?t=Array.from(t):Array.isArray(t)||(t=[t]),Array.isArray(o)||(o=[o]);for(const a of t)for(const t of o)a[e](t,n,{capture:!1,...i});return Array.prototype.slice.call(arguments,1)}e.r(o),e.d(o,{adjustableInputNumbers:()=>d,createElementFromString:()=>s,createFromTemplate:()=>r,eventPath:()=>l,off:()=>a,on:()=>i,resolveElement:()=>c});const i=n.bind(null,"addEventListener"),a=n.bind(null,"removeEventListener");function s(e){const t=document.createElement("div");return t.innerHTML=e.trim(),t.firstElementChild}function r(e){const t=(e,t)=>{const o=e.getAttribute(t);return e.removeAttribute(t),o},o=function(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=t(e,":obj"),a=t(e,":ref"),s=i?n[i]={}:n;a&&(n[a]=e);for(const n of Array.from(e.children)){const e=t(n,":arr"),i=o(n,e?{}:s);e&&(s[e]||(s[e]=[])).push(Object.keys(i).length?i:n)}return n};return o(s(e))}function l(e){let t=e.path||e.composedPath&&e.composedPath();if(t)return t;let o=e.target.parentElement;for(t=[e.target,o];o=o.parentElement;)t.push(o);return t.push(document,window),t}function c(e){return e instanceof Element?e:"string"==typeof e?e.split(/>>/g).reduce((e,t,o,n)=>(e=e.querySelector(t),o<n.length-1?e.shadowRoot:e),document):null}function d(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e=>e;function o(o){const n=[.001,.01,.1][Number(o.shiftKey||2*o.ctrlKey)]*(o.deltaY<0?1:-1);let i=0,a=e.selectionStart;e.value=e.value.replace(/[\d.]+/g,(e,o)=>o<=a&&o+e.length>=a?(a=o,t(Number(e),n,i)):(i++,e)),e.focus(),e.setSelectionRange(a,a),o.preventDefault(),e.dispatchEvent(new Event("input"))}i(e,"focus",()=>i(window,"wheel",o,{passive:!1})),i(e,"blur",()=>a(window,"wheel",o))}const{min:u,max:m,floor:p,round:h}=Math;function g(e,t,o){t/=100,o/=100;const n=p(e=e/360*6),i=e-n,a=o*(1-t),s=o*(1-i*t),r=o*(1-(1-i)*t),l=n%6;return[255*[o,s,a,a,r,o][l],255*[r,o,o,s,a,a][l],255*[a,a,r,o,o,s][l]]}function f(e,t,o){return g(e,t,o).map(e=>h(e).toString(16).padStart(2,"0"))}function b(e,t,o){const n=g(e,t,o),i=n[0]/255,a=n[1]/255,s=n[2]/255,r=u(1-i,1-a,1-s);return[100*(1===r?0:(1-i-r)/(1-r)),100*(1===r?0:(1-a-r)/(1-r)),100*(1===r?0:(1-s-r)/(1-r)),100*r]}function y(e,t,o){const n=(2-(t/=100))*(o/=100)/2;return 0!==n&&(t=1===n?0:n<.5?t*o/(2*n):t*o/(2-2*n)),[e,100*t,100*n]}function C(e,t,o){const n=u(e/=255,t/=255,o/=255),i=m(e,t,o),a=i-n;let s,r;if(0===a)s=r=0;else{r=a/i;const n=((i-e)/6+a/2)/a,l=((i-t)/6+a/2)/a,c=((i-o)/6+a/2)/a;e===i?s=c-l:t===i?s=1/3+n-c:o===i&&(s=2/3+l-n),s<0?s+=1:s>1&&(s-=1)}return[360*s,100*r,100*i]}function v(e,t,o,n){return t/=100,o/=100,[...C(255*(1-u(1,(e/=100)*(1-(n/=100))+n)),255*(1-u(1,t*(1-n)+n)),255*(1-u(1,o*(1-n)+n)))]}function w(e,t,o){t/=100;const n=2*(t*=(o/=100)<.5?o:1-o)/(o+t)*100,i=100*(o+t);return[e,isNaN(n)?0:n,i]}function x(e){return C(...e.match(/.{2}/g).map(e=>parseInt(e,16)))}function k(e){e=e.match(/^[a-zA-Z]+$/)?function(e){if("black"===e.toLowerCase())return"#000";const t=document.createElement("canvas").getContext("2d");return t.fillStyle=e,"#000"===t.fillStyle?null:t.fillStyle}(e):e;const t={cmyk:/^cmyk[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)/i,rgba:/^((rgba)|rgb)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hsla:/^((hsla)|hsl)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hsva:/^((hsva)|hsv)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hexa:/^#?(([\dA-Fa-f]{3,4})|([\dA-Fa-f]{6})|([\dA-Fa-f]{8}))$/i},o=e=>e.map(e=>/^(|\d+)\.\d+|\d+$/.test(e)?Number(e):void 0);let n;e:for(const i in t){if(!(n=t[i].exec(e)))continue;const a=e=>!!n[2]==("number"==typeof e);switch(i){case"cmyk":{const[,e,t,a,s]=o(n);if(e>100||t>100||a>100||s>100)break e;return{values:v(e,t,a,s),type:i}}case"rgba":{const[,,,e,t,s,r]=o(n);if(e>255||t>255||s>255||r<0||r>1||!a(r))break e;return{values:[...C(e,t,s),r],a:r,type:i}}case"hexa":{let[,e]=n;4!==e.length&&3!==e.length||(e=e.split("").map(e=>e+e).join(""));const t=e.substring(0,6);let o=e.substring(6);return o=o?parseInt(o,16)/255:void 0,{values:[...x(t),o],a:o,type:i}}case"hsla":{const[,,,e,t,s,r]=o(n);if(e>360||t>100||s>100||r<0||r>1||!a(r))break e;return{values:[...w(e,t,s),r],a:r,type:i}}case"hsva":{const[,,,e,t,s,r]=o(n);if(e>360||t>100||s>100||r<0||r>1||!a(r))break e;return{values:[e,t,s,r],a:r,type:i}}}}return{values:null,type:null}}function S(){const e=(e,t)=>function(){let o=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;return t(~o?e.map(e=>Number(e.toFixed(o))):e)},t={h:arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,s:arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,v:arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,a:arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,toHSVA(){const o=[t.h,t.s,t.v,t.a];return o.toString=e(o,e=>`hsva(${e[0]}, ${e[1]}%, ${e[2]}%, ${t.a})`),o},toHSLA(){const o=[...y(t.h,t.s,t.v),t.a];return o.toString=e(o,e=>`hsla(${e[0]}, ${e[1]}%, ${e[2]}%, ${t.a})`),o},toRGBA(){const o=[...g(t.h,t.s,t.v),t.a];return o.toString=e(o,e=>`rgba(${e[0]}, ${e[1]}, ${e[2]}, ${t.a})`),o},toCMYK(){const o=b(t.h,t.s,t.v);return o.toString=e(o,e=>`cmyk(${e[0]}%, ${e[1]}%, ${e[2]}%, ${e[3]}%)`),o},toHEXA(){const e=f(t.h,t.s,t.v),o=t.a>=1?"":Number((255*t.a).toFixed(0)).toString(16).toUpperCase().padStart(2,"0");return o&&e.push(o),e.toString=()=>`#${e.join("").toUpperCase()}`,e},clone:()=>S(t.h,t.s,t.v,t.a)};return t}const T=e=>Math.max(Math.min(e,1),0);function E(e){const t={options:Object.assign({lock:null,onchange:()=>0,onstop:()=>0},e),_keyboard(e){const{options:o}=t,{type:n,key:i}=e;if(document.activeElement===o.wrapper){const{lock:o}=t.options,a="ArrowUp"===i,s="ArrowRight"===i,r="ArrowDown"===i,l="ArrowLeft"===i;if("keydown"===n&&(a||s||r||l)){let n=0,i=0;"v"===o?n=a||s?1:-1:"h"===o?n=a||s?-1:1:(i=a?-1:r?1:0,n=l?-1:s?1:0),t.update(T(t.cache.x+.01*n),T(t.cache.y+.01*i)),e.preventDefault()}else i.startsWith("Arrow")&&(t.options.onstop(),e.preventDefault())}},_tapstart(e){i(document,["mouseup","touchend","touchcancel"],t._tapstop),i(document,["mousemove","touchmove"],t._tapmove),e.cancelable&&e.preventDefault(),t._tapmove(e)},_tapmove(e){const{options:o,cache:n}=t,{lock:i,element:a,wrapper:s}=o,r=s.getBoundingClientRect();let l=0,c=0;if(e){const t=e&&e.touches&&e.touches[0];l=e?(t||e).clientX:0,c=e?(t||e).clientY:0,l<r.left?l=r.left:l>r.left+r.width&&(l=r.left+r.width),c<r.top?c=r.top:c>r.top+r.height&&(c=r.top+r.height),l-=r.left,c-=r.top}else n&&(l=n.x*r.width,c=n.y*r.height);"h"!==i&&(a.style.left=`calc(${l/r.width*100}% - ${a.offsetWidth/2}px)`),"v"!==i&&(a.style.top=`calc(${c/r.height*100}% - ${a.offsetHeight/2}px)`),t.cache={x:l/r.width,y:c/r.height};const d=T(l/r.width),u=T(c/r.height);switch(i){case"v":return o.onchange(d);case"h":return o.onchange(u);default:return o.onchange(d,u)}},_tapstop(){t.options.onstop(),a(document,["mouseup","touchend","touchcancel"],t._tapstop),a(document,["mousemove","touchmove"],t._tapmove)},trigger(){t._tapmove()},update(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const{left:n,top:i,width:a,height:s}=t.options.wrapper.getBoundingClientRect();"h"===t.options.lock&&(o=e),t._tapmove({clientX:n+a*e,clientY:i+s*o})},destroy(){const{options:e,_tapstart:o,_keyboard:n}=t;a(document,["keydown","keyup"],n),a([e.wrapper,e.element],"mousedown",o),a([e.wrapper,e.element],"touchstart",o,{passive:!1})}},{options:o,_tapstart:n,_keyboard:s}=t;return i([o.wrapper,o.element],"mousedown",n),i([o.wrapper,o.element],"touchstart",n,{passive:!1}),i(document,["keydown","keyup"],s),t}function I(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e=Object.assign({onchange:()=>0,className:"",elements:[]},e);const t=i(e.elements,"click",t=>{e.elements.forEach(o=>o.classList[t.target===o?"add":"remove"](e.className)),e.onchange(t),t.stopPropagation()});return{destroy:()=>a(...t)}}const A={variantFlipOrder:{start:"sme",middle:"mse",end:"ems"},positionFlipOrder:{top:"tbrl",right:"rltb",bottom:"btrl",left:"lrbt"},position:"bottom",margin:8},M=(e,t,o)=>{const{container:n,margin:i,position:a,variantFlipOrder:s,positionFlipOrder:r}={container:document.documentElement.getBoundingClientRect(),...A,...o},{left:l,top:c}=t.style;t.style.left="0",t.style.top="0";const d=e.getBoundingClientRect(),u=t.getBoundingClientRect(),m={t:d.top-u.height-i,b:d.bottom+i,r:d.right+i,l:d.left-u.width-i},p={vs:d.left,vm:d.left+d.width/2+-u.width/2,ve:d.left+d.width-u.width,hs:d.top,hm:d.bottom-d.height/2-u.height/2,he:d.bottom-u.height},[h,g="middle"]=a.split("-"),f=r[h],b=s[g],{top:y,left:C,bottom:v,right:w}=n;for(const e of f){const o="t"===e||"b"===e,n=m[e],[i,a]=o?["top","left"]:["left","top"],[s,r]=o?[u.height,u.width]:[u.width,u.height],[l,c]=o?[v,w]:[w,v],[d,h]=o?[y,C]:[C,y];if(!(n<d||n+s>l))for(const s of b){const l=p[(o?"v":"h")+s];if(!(l<h||l+r>c))return t.style[a]=l-u[a]+"px",t.style[i]=n-u[i]+"px",e+s}}return t.style.left=l,t.style.top=c,null};function P(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}class N{constructor(e){P(this,"_initializingActive",!0),P(this,"_recalc",!0),P(this,"_nanopop",null),P(this,"_root",null),P(this,"_color",S()),P(this,"_lastColor",S()),P(this,"_swatchColors",[]),P(this,"_setupAnimationFrame",null),P(this,"_eventListener",{init:[],save:[],hide:[],show:[],clear:[],change:[],changestop:[],cancel:[],swatchselect:[]}),this.options=e=Object.assign({...N.DEFAULT_OPTIONS},e);const{swatches:t,components:o,theme:n,sliders:i,lockOpacity:a,padding:s}=e;["nano","monolith"].includes(n)&&!i&&(e.sliders="h"),o.interaction||(o.interaction={});const{preview:r,opacity:l,hue:c,palette:d}=o;o.opacity=!a&&l,o.palette=d||r||l||c,this._preBuild(),this._buildComponents(),this._bindEvents(),this._finalBuild(),t&&t.length&&t.forEach(e=>this.addSwatch(e));const{button:u,app:m}=this._root;this._nanopop=((e,t,o)=>{const n="object"!=typeof e||e instanceof HTMLElement?{reference:e,popper:t,...o}:e;return{update(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n;const{reference:t,popper:o}=Object.assign(n,e);if(!o||!t)throw new Error("Popper- or reference-element missing.");return M(t,o,n)}}})(u,m,{margin:s}),u.setAttribute("role","button"),u.setAttribute("aria-label",this._t("btn:toggle"));const p=this;this._setupAnimationFrame=requestAnimationFrame(function t(){if(!m.offsetWidth)return p._setupAnimationFrame=requestAnimationFrame(t);p.setColor(e.default),p._rePositioningPicker(),e.defaultRepresentation&&(p._representation=e.defaultRepresentation,p.setColorRepresentation(p._representation)),e.showAlways&&p.show(),p._initializingActive=!1,p._emit("init")})}_preBuild(){const{options:e}=this;for(const t of["el","container"])e[t]=c(e[t]);this._root=(e=>{const{components:t,useAsButton:o,inline:n,appClass:i,theme:a,lockOpacity:s}=e.options,l=e=>e?"":'style="display:none" hidden',c=t=>e._t(t),d=r(`\n <div :ref="root" class="pickr">\n\n ${o?"":'<button type="button" :ref="button" class="pcr-button"></button>'}\n\n <div :ref="app" class="pcr-app ${i||""}" data-theme="${a}" ${n?'style="position: unset"':""} aria-label="${c("ui:dialog")}" role="window">\n <div class="pcr-selection" ${l(t.palette)}>\n <div :obj="preview" class="pcr-color-preview" ${l(t.preview)}>\n <button type="button" :ref="lastColor" class="pcr-last-color" aria-label="${c("btn:last-color")}"></button>\n <div :ref="currentColor" class="pcr-current-color"></div>\n </div>\n\n <div :obj="palette" class="pcr-color-palette">\n <div :ref="picker" class="pcr-picker"></div>\n <div :ref="palette" class="pcr-palette" tabindex="0" aria-label="${c("aria:palette")}" role="listbox"></div>\n </div>\n\n <div :obj="hue" class="pcr-color-chooser" ${l(t.hue)}>\n <div :ref="picker" class="pcr-picker"></div>\n <div :ref="slider" class="pcr-hue pcr-slider" tabindex="0" aria-label="${c("aria:hue")}" role="slider"></div>\n </div>\n\n <div :obj="opacity" class="pcr-color-opacity" ${l(t.opacity)}>\n <div :ref="picker" class="pcr-picker"></div>\n <div :ref="slider" class="pcr-opacity pcr-slider" tabindex="0" aria-label="${c("aria:opacity")}" role="slider"></div>\n </div>\n </div>\n\n <div class="pcr-swatches ${t.palette?"":"pcr-last"}" :ref="swatches"></div>\n\n <div :obj="interaction" class="pcr-interaction" ${l(Object.keys(t.interaction).length)}>\n <input :ref="result" class="pcr-result" type="text" spellcheck="false" ${l(t.interaction.input)} aria-label="${c("aria:input")}">\n\n <input :arr="options" class="pcr-type" data-type="HEXA" value="${s?"HEX":"HEXA"}" type="button" ${l(t.interaction.hex)}>\n <input :arr="options" class="pcr-type" data-type="RGBA" value="${s?"RGB":"RGBA"}" type="button" ${l(t.interaction.rgba)}>\n <input :arr="options" class="pcr-type" data-type="HSLA" value="${s?"HSL":"HSLA"}" type="button" ${l(t.interaction.hsla)}>\n <input :arr="options" class="pcr-type" data-type="HSVA" value="${s?"HSV":"HSVA"}" type="button" ${l(t.interaction.hsva)}>\n <input :arr="options" class="pcr-type" data-type="CMYK" value="CMYK" type="button" ${l(t.interaction.cmyk)}>\n\n <input :ref="save" class="pcr-save" value="${c("btn:save")}" type="button" ${l(t.interaction.save)} aria-label="${c("aria:btn:save")}">\n <input :ref="cancel" class="pcr-cancel" value="${c("btn:cancel")}" type="button" ${l(t.interaction.cancel)} aria-label="${c("aria:btn:cancel")}">\n <input :ref="clear" class="pcr-clear" value="${c("btn:clear")}" type="button" ${l(t.interaction.clear)} aria-label="${c("aria:btn:clear")}">\n </div>\n </div>\n </div>\n `),u=d.interaction;return u.options.find(e=>!e.hidden&&!e.classList.add("active")),u.type=()=>u.options.find(e=>e.classList.contains("active")),d})(this),e.useAsButton&&(this._root.button=e.el),e.container.appendChild(this._root.root)}_finalBuild(){const e=this.options,t=this._root;if(e.container.removeChild(t.root),e.inline){const o=e.el.parentElement;e.el.nextSibling?o.insertBefore(t.app,e.el.nextSibling):o.appendChild(t.app)}else e.container.appendChild(t.app);e.useAsButton?e.inline&&e.el.remove():e.el.parentNode.replaceChild(t.root,e.el),e.disabled&&this.disable(),e.comparison||(t.button.style.transition="none",e.useAsButton||(t.preview.lastColor.style.transition="none")),this.hide()}_buildComponents(){const e=this,t=this.options.components,o=(e.options.sliders||"v").repeat(2),[n,i]=o.match(/^[vh]+$/g)?o:[],a=()=>this._color||(this._color=this._lastColor.clone()),s={palette:E({element:e._root.palette.picker,wrapper:e._root.palette.palette,onstop:()=>e._emit("changestop","slider",e),onchange(o,n){if(!t.palette)return;const i=a(),{_root:s,options:r}=e,{lastColor:l,currentColor:c}=s.preview;e._recalc&&(i.s=100*o,i.v=100-100*n,i.v<0&&(i.v=0),e._updateOutput("slider"));const d=i.toRGBA().toString(0);this.element.style.background=d,this.wrapper.style.background=`\n linear-gradient(to top, rgba(0, 0, 0, ${i.a}), transparent),\n linear-gradient(to left, hsla(${i.h}, 100%, 50%, ${i.a}), rgba(255, 255, 255, ${i.a}))\n `,r.comparison?r.useAsButton||e._lastColor||l.style.setProperty("--pcr-color",d):(s.button.style.setProperty("--pcr-color",d),s.button.classList.remove("clear"));const u=i.toHEXA().toString();for(const{el:t,color:o}of e._swatchColors)t.classList[u===o.toHEXA().toString()?"add":"remove"]("pcr-active");c.style.setProperty("--pcr-color",d)}}),hue:E({lock:"v"===i?"h":"v",element:e._root.hue.picker,wrapper:e._root.hue.slider,onstop:()=>e._emit("changestop","slider",e),onchange(o){if(!t.hue||!t.palette)return;const n=a();e._recalc&&(n.h=360*o),this.element.style.backgroundColor=`hsl(${n.h}, 100%, 50%)`,s.palette.trigger()}}),opacity:E({lock:"v"===n?"h":"v",element:e._root.opacity.picker,wrapper:e._root.opacity.slider,onstop:()=>e._emit("changestop","slider",e),onchange(o){if(!t.opacity||!t.palette)return;const n=a();e._recalc&&(n.a=Math.round(100*o)/100),this.element.style.background=`rgba(0, 0, 0, ${n.a})`,s.palette.trigger()}}),selectable:I({elements:e._root.interaction.options,className:"active",onchange(t){e._representation=t.target.getAttribute("data-type").toUpperCase(),e._recalc&&e._updateOutput("swatch")}})};this._components=s}_bindEvents(){const{_root:e,options:t}=this,o=[i(e.interaction.clear,"click",()=>this._clearColor()),i([e.interaction.cancel,e.preview.lastColor],"click",()=>{this.setHSVA(...(this._lastColor||this._color).toHSVA(),!0),this._emit("cancel")}),i(e.interaction.save,"click",()=>{!this.applyColor()&&!t.showAlways&&this.hide()}),i(e.interaction.result,["keyup","input"],e=>{this.setColor(e.target.value,!0)&&!this._initializingActive&&(this._emit("change",this._color,"input",this),this._emit("changestop","input",this)),e.stopImmediatePropagation()}),i(e.interaction.result,["focus","blur"],e=>{this._recalc="blur"===e.type,this._recalc&&this._updateOutput(null)}),i([e.palette.palette,e.palette.picker,e.hue.slider,e.hue.picker,e.opacity.slider,e.opacity.picker],["mousedown","touchstart"],()=>this._recalc=!0,{passive:!0})];if(!t.showAlways){const n=t.closeWithKey;o.push(i(e.button,"click",()=>this.isOpen()?this.hide():this.show()),i(document,"keyup",e=>this.isOpen()&&(e.key===n||e.code===n)&&this.hide()),i(document,["touchstart","mousedown"],t=>{this.isOpen()&&!l(t).some(t=>t===e.app||t===e.button)&&this.hide()},{capture:!0}))}if(t.adjustableNumbers){const t={rgba:[255,255,255,1],hsva:[360,100,100,1],hsla:[360,100,100,1],cmyk:[100,100,100,100]};d(e.interaction.result,(e,o,n)=>{const i=t[this.getColorRepresentation().toLowerCase()];if(i){const t=i[n],a=e+(t>=100?1e3*o:o);return a<=0?0:Number((a<t?a:t).toPrecision(3))}return e})}if(t.autoReposition&&!t.inline){let e=null;const n=this;o.push(i(window,["scroll","resize"],()=>{n.isOpen()&&(t.closeOnScroll&&n.hide(),null===e?(e=setTimeout(()=>e=null,100),requestAnimationFrame(function t(){n._rePositioningPicker(),null!==e&&requestAnimationFrame(t)})):(clearTimeout(e),e=setTimeout(()=>e=null,100)))},{capture:!0}))}this._eventBindings=o}_rePositioningPicker(){const{options:e}=this;if(!e.inline&&!this._nanopop.update({container:document.body.getBoundingClientRect(),position:e.position})){const e=this._root.app,t=e.getBoundingClientRect();e.style.top=(window.innerHeight-t.height)/2+"px",e.style.left=(window.innerWidth-t.width)/2+"px"}}_updateOutput(e){const{_root:t,_color:o,options:n}=this;if(t.interaction.type()){const e=`to${t.interaction.type().getAttribute("data-type")}`;t.interaction.result.value="function"==typeof o[e]?o[e]().toString(n.outputPrecision):""}!this._initializingActive&&this._recalc&&this._emit("change",o,e,this)}_clearColor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const{_root:t,options:o}=this;o.useAsButton||t.button.style.setProperty("--pcr-color","rgba(0, 0, 0, 0.15)"),t.button.classList.add("clear"),o.showAlways||this.hide(),this._lastColor=null,this._initializingActive||e||(this._emit("save",null),this._emit("clear"))}_parseLocalColor(e){const{values:t,type:o,a:n}=k(e),{lockOpacity:i}=this.options,a=void 0!==n&&1!==n;return t&&3===t.length&&(t[3]=void 0),{values:!t||i&&a?null:t,type:o}}_t(e){return this.options.i18n[e]||N.I18N_DEFAULTS[e]}_emit(e){for(var t=arguments.length,o=new Array(t>1?t-1:0),n=1;n<t;n++)o[n-1]=arguments[n];this._eventListener[e].forEach(e=>e(...o,this))}on(e,t){return this._eventListener[e].push(t),this}off(e,t){const o=this._eventListener[e]||[],n=o.indexOf(t);return~n&&o.splice(n,1),this}addSwatch(e){const{values:t}=this._parseLocalColor(e);if(t){const{_swatchColors:e,_root:o}=this,n=S(...t),a=s(`<button type="button" style="--pcr-color: ${n.toRGBA().toString(0)}" aria-label="${this._t("btn:swatch")}"/>`);return o.swatches.appendChild(a),e.push({el:a,color:n}),this._eventBindings.push(i(a,"click",()=>{this.setHSVA(...n.toHSVA(),!0),this._emit("swatchselect",n),this._emit("change",n,"swatch",this)})),!0}return!1}removeSwatch(e){const t=this._swatchColors[e];if(t){const{el:o}=t;return this._root.swatches.removeChild(o),this._swatchColors.splice(e,1),!0}return!1}applyColor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const{preview:t,button:o}=this._root,n=this._color.toRGBA().toString(0);return t.lastColor.style.setProperty("--pcr-color",n),this.options.useAsButton||o.style.setProperty("--pcr-color",n),o.classList.remove("clear"),this._lastColor=this._color.clone(),this._initializingActive||e||this._emit("save",this._color),this}destroy(){cancelAnimationFrame(this._setupAnimationFrame),this._eventBindings.forEach(e=>a(...e)),Object.keys(this._components).forEach(e=>this._components[e].destroy())}destroyAndRemove(){this.destroy();const{root:e,app:t}=this._root;e.parentElement&&e.parentElement.removeChild(e),t.parentElement.removeChild(t),Object.keys(this).forEach(e=>this[e]=null)}hide(){return!!this.isOpen()&&(this._root.app.classList.remove("visible"),this._emit("hide"),!0)}show(){return!this.options.disabled&&!this.isOpen()&&(this._root.app.classList.add("visible"),this._rePositioningPicker(),this._emit("show",this._color),this)}isOpen(){return this._root.app.classList.contains("visible")}setHSVA(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:360,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const a=this._recalc;if(this._recalc=!1,e<0||e>360||t<0||t>100||o<0||o>100||n<0||n>1)return!1;this._color=S(e,t,o,n);const{hue:s,opacity:r,palette:l}=this._components;return s.update(e/360),r.update(n),l.update(t/100,1-o/100),i||this.applyColor(),a&&this._updateOutput(),this._recalc=a,!0}setColor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(null===e)return this._clearColor(t),!0;const{values:o,type:n}=this._parseLocalColor(e);if(o){const e=n.toUpperCase(),{options:i}=this._root.interaction,a=i.find(t=>t.getAttribute("data-type")===e);if(a&&!a.hidden)for(const e of i)e.classList[e===a?"add":"remove"]("active");return!!this.setHSVA(...o,t)&&this.setColorRepresentation(e)}return!1}setColorRepresentation(e){return e=e.toUpperCase(),!!this._root.interaction.options.find(t=>t.getAttribute("data-type").startsWith(e)&&!t.click())}getColorRepresentation(){return this._representation}getColor(){return this._color}getSelectedColor(){return this._lastColor}getRoot(){return this._root}disable(){return this.hide(),this.options.disabled=!0,this._root.button.classList.add("disabled"),this}enable(){return this.options.disabled=!1,this._root.button.classList.remove("disabled"),this}}return P(N,"utils",o),P(N,"version","1.8.4"),P(N,"I18N_DEFAULTS",{"ui:dialog":"color picker dialog","btn:toggle":"toggle color picker dialog","btn:swatch":"color swatch","btn:last-color":"use previous color","btn:save":"Save","btn:cancel":"Cancel","btn:clear":"Clear","aria:btn:save":"save and close","aria:btn:cancel":"cancel and close","aria:btn:clear":"clear and close","aria:input":"color input field","aria:palette":"color selection area","aria:hue":"hue selection slider","aria:opacity":"selection slider"}),P(N,"DEFAULT_OPTIONS",{appClass:null,theme:"classic",useAsButton:!1,padding:8,disabled:!1,comparison:!0,closeOnScroll:!1,outputPrecision:0,lockOpacity:!1,autoReposition:!0,container:"body",components:{interaction:{}},i18n:{},swatches:null,inline:!1,sliders:null,default:"#42445a",defaultRepresentation:null,position:"bottom-middle",adjustableNumbers:!0,showAlways:!1,closeWithKey:"Escape"}),P(N,"create",e=>new N(e)),t.default})()}),Oo=Lo(Fo),Ro=[],qo=[];!function(e,t){if(e&&"undefined"!=typeof document){var o,n=!0===t.prepend?"prepend":"append",i=!0===t.singleTag,a="string"==typeof t.container?document.querySelector(t.container):document.getElementsByTagName("head")[0];if(i){var s=Ro.indexOf(a);-1===s&&(s=Ro.push(a)-1,qo[s]={}),o=qo[s]&&qo[s][n]?qo[s][n]:qo[s][n]=r()}else o=r();65279===e.charCodeAt(0)&&(e=e.substring(1)),o.styleSheet?o.styleSheet.cssText+=e:o.appendChild(document.createTextNode(e))}function r(){var e=document.createElement("style");if(e.setAttribute("type","text/css"),t.attributes)for(var o=Object.keys(t.attributes),i=0;i<o.length;i++)e.setAttribute(o[i],t.attributes[o[i]]);var s="prepend"===n?"afterbegin":"beforeend";return a.insertAdjacentElement(s,e),e}}('/*! Pickr 1.8.4 MIT | https://github.com/Simonwep/pickr */\n.pickr{position:relative;overflow:visible;transform:translateY(0)}.pickr *{box-sizing:border-box;outline:none;border:none;-webkit-appearance:none}.pickr .pcr-button{position:relative;height:2em;width:2em;padding:0.5em;cursor:pointer;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Roboto","Helvetica Neue",Arial,sans-serif;border-radius:.15em;background:url(\'data:image/svg+xml;utf8, <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" stroke="%2342445A" stroke-width="5px" stroke-linecap="round"><path d="M45,45L5,5"></path><path d="M45,5L5,45"></path></svg>\') no-repeat center;background-size:0;transition:all 0.3s}.pickr .pcr-button::before{position:absolute;content:\'\';top:0;left:0;width:100%;height:100%;background:url(\'data:image/svg+xml;utf8, <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2 2"><path fill="white" d="M1,0H2V1H1V0ZM0,1H1V2H0V1Z"/><path fill="gray" d="M0,0H1V1H0V0ZM1,1H2V2H1V1Z"/></svg>\');background-size:.5em;border-radius:.15em;z-index:-1}.pickr .pcr-button::before{z-index:initial}.pickr .pcr-button::after{position:absolute;content:\'\';top:0;left:0;height:100%;width:100%;transition:background 0.3s;background:var(--pcr-color);border-radius:.15em}.pickr .pcr-button.clear{background-size:70%}.pickr .pcr-button.clear::before{opacity:0}.pickr .pcr-button.clear:focus{box-shadow:0 0 0 1px rgba(255,255,255,0.85),0 0 0 3px var(--pcr-color)}.pickr .pcr-button.disabled{cursor:not-allowed}.pickr *,.pcr-app *{box-sizing:border-box;outline:none;border:none;-webkit-appearance:none}.pickr input:focus,.pickr input.pcr-active,.pickr button:focus,.pickr button.pcr-active,.pcr-app input:focus,.pcr-app input.pcr-active,.pcr-app button:focus,.pcr-app button.pcr-active{box-shadow:0 0 0 1px rgba(255,255,255,0.85),0 0 0 3px var(--pcr-color)}.pickr .pcr-palette,.pickr .pcr-slider,.pcr-app .pcr-palette,.pcr-app .pcr-slider{transition:box-shadow 0.3s}.pickr .pcr-palette:focus,.pickr .pcr-slider:focus,.pcr-app .pcr-palette:focus,.pcr-app .pcr-slider:focus{box-shadow:0 0 0 1px rgba(255,255,255,0.85),0 0 0 3px rgba(0,0,0,0.25)}.pcr-app{position:fixed;display:flex;flex-direction:column;z-index:10000;border-radius:0.1em;background:#fff;opacity:0;visibility:hidden;transition:opacity 0.3s, visibility 0s 0.3s;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Roboto","Helvetica Neue",Arial,sans-serif;box-shadow:0 0.15em 1.5em 0 rgba(0,0,0,0.1),0 0 1em 0 rgba(0,0,0,0.03);left:0;top:0}.pcr-app.visible{transition:opacity 0.3s;visibility:visible;opacity:1}.pcr-app .pcr-swatches{display:flex;flex-wrap:wrap;margin-top:0.75em}.pcr-app .pcr-swatches.pcr-last{margin:0}@supports (display: grid){.pcr-app .pcr-swatches{display:grid;align-items:center;grid-template-columns:repeat(auto-fit, 1.75em)}}.pcr-app .pcr-swatches>button{font-size:1em;position:relative;width:calc(1.75em - 5px);height:calc(1.75em - 5px);border-radius:0.15em;cursor:pointer;margin:2.5px;flex-shrink:0;justify-self:center;transition:all 0.15s;overflow:hidden;background:transparent;z-index:1}.pcr-app .pcr-swatches>button::before{position:absolute;content:\'\';top:0;left:0;width:100%;height:100%;background:url(\'data:image/svg+xml;utf8, <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2 2"><path fill="white" d="M1,0H2V1H1V0ZM0,1H1V2H0V1Z"/><path fill="gray" d="M0,0H1V1H0V0ZM1,1H2V2H1V1Z"/></svg>\');background-size:6px;border-radius:.15em;z-index:-1}.pcr-app .pcr-swatches>button::after{content:\'\';position:absolute;top:0;left:0;width:100%;height:100%;background:var(--pcr-color);border:1px solid rgba(0,0,0,0.05);border-radius:0.15em;box-sizing:border-box}.pcr-app .pcr-swatches>button:hover{filter:brightness(1.05)}.pcr-app .pcr-swatches>button:not(.pcr-active){box-shadow:none}.pcr-app .pcr-interaction{display:flex;flex-wrap:wrap;align-items:center;margin:0 -0.2em 0 -0.2em}.pcr-app .pcr-interaction>*{margin:0 0.2em}.pcr-app .pcr-interaction input{letter-spacing:0.07em;font-size:0.75em;text-align:center;cursor:pointer;color:#75797e;background:#f1f3f4;border-radius:.15em;transition:all 0.15s;padding:0.45em 0.5em;margin-top:0.75em}.pcr-app .pcr-interaction input:hover{filter:brightness(0.975)}.pcr-app .pcr-interaction input:focus{box-shadow:0 0 0 1px rgba(255,255,255,0.85),0 0 0 3px rgba(66,133,244,0.75)}.pcr-app .pcr-interaction .pcr-result{color:#75797e;text-align:left;flex:1 1 8em;min-width:8em;transition:all 0.2s;border-radius:.15em;background:#f1f3f4;cursor:text}.pcr-app .pcr-interaction .pcr-result::-moz-selection{background:#4285f4;color:#fff}.pcr-app .pcr-interaction .pcr-result::selection{background:#4285f4;color:#fff}.pcr-app .pcr-interaction .pcr-type.active{color:#fff;background:#4285f4}.pcr-app .pcr-interaction .pcr-save,.pcr-app .pcr-interaction .pcr-cancel,.pcr-app .pcr-interaction .pcr-clear{color:#fff;width:auto}.pcr-app .pcr-interaction .pcr-save,.pcr-app .pcr-interaction .pcr-cancel,.pcr-app .pcr-interaction .pcr-clear{color:#fff}.pcr-app .pcr-interaction .pcr-save:hover,.pcr-app .pcr-interaction .pcr-cancel:hover,.pcr-app .pcr-interaction .pcr-clear:hover{filter:brightness(0.925)}.pcr-app .pcr-interaction .pcr-save{background:#4285f4}.pcr-app .pcr-interaction .pcr-clear,.pcr-app .pcr-interaction .pcr-cancel{background:#f44250}.pcr-app .pcr-interaction .pcr-clear:focus,.pcr-app .pcr-interaction .pcr-cancel:focus{box-shadow:0 0 0 1px rgba(255,255,255,0.85),0 0 0 3px rgba(244,66,80,0.75)}.pcr-app .pcr-selection .pcr-picker{position:absolute;height:18px;width:18px;border:2px solid #fff;border-radius:100%;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.pcr-app .pcr-selection .pcr-color-palette,.pcr-app .pcr-selection .pcr-color-chooser,.pcr-app .pcr-selection .pcr-color-opacity{position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:flex;flex-direction:column;cursor:grab;cursor:-webkit-grab}.pcr-app .pcr-selection .pcr-color-palette:active,.pcr-app .pcr-selection .pcr-color-chooser:active,.pcr-app .pcr-selection .pcr-color-opacity:active{cursor:grabbing;cursor:-webkit-grabbing}.pcr-app[data-theme=\'nano\']{width:14.25em;max-width:95vw}.pcr-app[data-theme=\'nano\'] .pcr-swatches{margin-top:.6em;padding:0 .6em}.pcr-app[data-theme=\'nano\'] .pcr-interaction{padding:0 .6em .6em .6em}.pcr-app[data-theme=\'nano\'] .pcr-selection{display:grid;grid-gap:.6em;grid-template-columns:1fr 4fr;grid-template-rows:5fr auto auto;align-items:center;height:10.5em;width:100%;align-self:flex-start}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-preview{grid-area:2 / 1 / 4 / 1;height:100%;width:100%;display:flex;flex-direction:row;justify-content:center;margin-left:.6em}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-preview .pcr-last-color{display:none}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-preview .pcr-current-color{position:relative;background:var(--pcr-color);width:2em;height:2em;border-radius:50em;overflow:hidden}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-preview .pcr-current-color::before{position:absolute;content:\'\';top:0;left:0;width:100%;height:100%;background:url(\'data:image/svg+xml;utf8, <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2 2"><path fill="white" d="M1,0H2V1H1V0ZM0,1H1V2H0V1Z"/><path fill="gray" d="M0,0H1V1H0V0ZM1,1H2V2H1V1Z"/></svg>\');background-size:.5em;border-radius:.15em;z-index:-1}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-palette{grid-area:1 / 1 / 2 / 3;width:100%;height:100%;z-index:1}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-palette .pcr-palette{border-radius:.15em;width:100%;height:100%}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-palette .pcr-palette::before{position:absolute;content:\'\';top:0;left:0;width:100%;height:100%;background:url(\'data:image/svg+xml;utf8, <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2 2"><path fill="white" d="M1,0H2V1H1V0ZM0,1H1V2H0V1Z"/><path fill="gray" d="M0,0H1V1H0V0ZM1,1H2V2H1V1Z"/></svg>\');background-size:.5em;border-radius:.15em;z-index:-1}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-chooser{grid-area:2 / 2 / 2 / 2}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-opacity{grid-area:3 / 2 / 3 / 2}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-chooser,.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-opacity{height:0.5em;margin:0 .6em}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-chooser .pcr-picker,.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-opacity .pcr-picker{top:50%;transform:translateY(-50%)}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-chooser .pcr-slider,.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-opacity .pcr-slider{flex-grow:1;border-radius:50em}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-chooser .pcr-slider{background:linear-gradient(to right, red, #ff0, lime, cyan, blue, #f0f, red)}.pcr-app[data-theme=\'nano\'] .pcr-selection .pcr-color-opacity .pcr-slider{background:linear-gradient(to right, transparent, black),url(\'data:image/svg+xml;utf8, <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2 2"><path fill="white" d="M1,0H2V1H1V0ZM0,1H1V2H0V1Z"/><path fill="gray" d="M0,0H1V1H0V0ZM1,1H2V2H1V1Z"/></svg>\');background-size:100%, 0.25em}\n\n',{});class Bo extends e.Modal{constructor(e,t,o){if(super(e),this.plugin=t,this.commandIndex=o,null!==o){const e=t.settings.customCommands[o];this.commandId=e.id,this.commandName=e.name,this.icon=e.icon||"",this.regexPattern=e.regexPattern||"",this.regexReplacement=e.regexReplacement||"",this.regexCaseInsensitive=e.regexCaseInsensitive||!1,this.regexGlobal=!1!==e.regexGlobal,this.regexMultiline=e.regexMultiline||!1,this.useCondition=e.useCondition||!1,this.conditionPattern=e.conditionPattern||""}else this.commandId="",this.commandName="",this.icon="",this.regexPattern="",this.regexReplacement="",this.regexCaseInsensitive=!1,this.regexGlobal=!0,this.regexMultiline=!1,this.useCondition=!1,this.conditionPattern=""}onOpen(){const{contentEl:t}=this;this.modalEl.addClass("custom-commands-modal"),t.empty(),t.createEl("h2",{text:null!==this.commandIndex?v("Edit regular expression command"):v("Add regular expression command")});const o=t.createDiv("basic-settings-container");new e.Setting(o).setName(v("Command ID")).setDesc(v('Unique identifier, no spaces, e.g.: "my-custom-format"')).addText(e=>(e.setValue(this.commandId),null!==this.commandIndex?(e.setDisabled(!0),e.inputEl.addClass("id-is-disabled")):e.onChange(e=>{this.commandId=e;const o=t.querySelector(".setting-item:nth-child(2) input");o instanceof HTMLInputElement&&(o.value=e,this.commandName=e)}),e)),new e.Setting(o).setName(v("Command Name")).setDesc(v("Displayed name in toolbar and menu")).addText(e=>e.setValue(this.commandName).onChange(e=>this.commandName=e));const n=t.createDiv("regex-settings");n.style.border="1px solid var(--background-modifier-border)",n.style.padding="10px",n.style.borderRadius="5px",n.style.marginBottom="10px";const i=n.createEl("details",{cls:"ai-help-container"});i.style.marginBottom="10px",i.style.borderRadius="5px",i.style.overflow="hidden";const a=i.createEl("summary",{text:v("How to use AI to get regular expressions?")});a.style.padding="8px 12px",a.style.backgroundColor="var(--background-secondary)",a.style.cursor="pointer",a.style.fontWeight="bold",a.style.borderRadius="4px",a.style.userSelect="none";const s=i.createDiv("ai-help-content");s.style.padding="6px",s.style.backgroundColor="var(--background-secondary-alt)",s.style.borderBottomLeftRadius="5px",s.style.borderBottomRightRadius="5px",s.style.marginTop="1px",s.setAttribute("contenteditable","false"),s.style.userSelect="text",s.innerHTML=`\n <p><strong>${v("AI question template:")}</strong><br>\n ${v("[Description]")}:\n ${v("I need to convert the url to a markdown format link")}\n <br>\n ${v("[Example]")}: \n ${v("For example, convert https://example.com to [https://example.com](https://example.com)")}\n <br>\n ${v("[Requirements]")}: \n ${v("Use js regular expression to implement, and output the parameters in the following format (the result does not need to be escaped with json)")}\n <br>\n ${v("[Output]")}:\n <br>\n "name": "[Descriptive Name]", <br>\n "pattern": "[Regex Pattern]", <br>\n "replacement": "[Replacement Pattern, if applicable]", <br>\n "flags": "[Regex Flags]" <br>\n </p>\n `,new e.Setting(n).setName(v("Matching pattern")).setDesc(v("Regex pattern to match")).addText(e=>this.regexPatternInput=e.setValue(this.regexPattern).onChange(e=>{this.regexPattern=e,this.updatePreview()})),new e.Setting(n).setName(v("Replacement pattern")).setDesc(v("Replacement pattern (use $1, $2, etc. to reference capture groups)")+v("Use \\n to represent line breaks")).addText(e=>this.regexReplacementInput=e.setValue(this.regexReplacement.replace(/\n/g,"\\n")).onChange(e=>{this.regexReplacement=e.replace(/\\n/g,"\n"),this.updatePreview()}));const r=n.createDiv("regex-options");r.style.display="flex",r.style.gap="8px",new e.Setting(r).setName(v("Ignore case")).setDesc(v("Match case-insensitive")).addToggle(e=>e.setValue(this.regexCaseInsensitive).onChange(e=>{this.regexCaseInsensitive=e,this.updatePreview()})),new e.Setting(r).setName(v("Global replace")).setDesc(v("Replace all matches")).addToggle(e=>e.setValue(this.regexGlobal).onChange(e=>{this.regexGlobal=e,this.updatePreview()})),new e.Setting(r).setName(v("Multiline mode")).setDesc(v("^ and $ match the start and end of each line")).addToggle(e=>this.regexMultilineToggle=e.setValue(this.regexMultiline).onChange(e=>{this.regexMultiline=e,this.updatePreview()}));const l=n.createDiv("condition-container");new e.Setting(l).setName(v("Use condition")).setDesc(v("Only apply custom command when text matches the condition")).addToggle(e=>this.useConditionToggle=e.setValue(this.useCondition).onChange(e=>{this.useCondition=e,c.style.display=e?"block":"none"}));const c=l.createDiv("condition-settings");c.style.display=this.useCondition?"block":"none",c.style.border="1px solid var(--background-modifier-border)",c.style.padding="10px",c.style.borderRadius="5px",c.style.marginBottom="15px",new e.Setting(c).setName(v("Condition pattern")).setDesc(v("Must exist regular expression or text")).addText(e=>this.conditionPatternInput=e.setValue(this.conditionPattern).onChange(e=>{this.conditionPattern=e}));const d=new e.Setting(n).setName(v("Icon")).setDesc(v("Command icon (click to select)"));if(this.iconDisplay=d.controlEl.createDiv("editingToolbarSettingsIcon"),this.icon)try{e.setIcon(this.iconDisplay,this.icon)}catch(e){this.iconDisplay.setText(this.icon)}d.addButton(t=>t.setButtonText(v("Choose icon")).onClick(()=>{const t={id:this.commandId,name:this.commandName,icon:this.icon};new w(this.plugin,t,!1,t=>{if(this.icon=t,this.iconDisplay.empty(),this.icon)try{e.setIcon(this.iconDisplay,this.icon)}catch(e){this.iconDisplay.setText(this.icon)}const o=d.controlEl.querySelector("input");o&&(o.value=this.icon)}).open()})),n.createSpan("regex-help");const u=n.createEl("details",{cls:"regex-examples-container"});u.style.marginTop="15px",u.style.borderRadius="5px",u.style.overflow="hidden";const m=u.createEl("summary",{text:v("Regular expression examples")});m.style.padding="8px 12px",m.style.backgroundColor="var(--background-secondary)",m.style.cursor="pointer",m.style.fontWeight="bold",m.style.borderRadius="4px",m.style.userSelect="none";const p=u.createDiv("examples-content");p.style.padding="10px",p.style.backgroundColor="var(--background-secondary-alt)",p.style.borderBottomLeftRadius="5px",p.style.borderBottomRightRadius="5px",p.style.marginTop="1px";const h=p.createEl("ul");h.style.paddingLeft="20px",h.style.margin="0";[{name:v("URL to Markdown link"),pattern:"(https?://\\S+)",replacement:"[$1]($1)"},{name:v("Convert MM/DD/YYYY to YYYY-MM-DD"),pattern:"(\\d{1,2})/(\\d{1,2})/(\\d{4})",replacement:"$3-$1-$2"},{name:v("Add bold to keywords"),pattern:"\\b(important|critical|urgent)\\b",replacement:"**$1**"},{name:v("Format phone number"),pattern:"(\\d{3})(\\d{3})(\\d{4})",replacement:"($1) $2-$3"},{name:v("Remove extra spaces"),pattern:"\\s{2,}",replacement:" "},{name:v("Convert HTML bold tags to Markdown format"),pattern:"<strong>(.*?)</strong>",replacement:"**$1**"},{name:v("Convert quoted text to quote block"),pattern:'"([^"]+)"',replacement:"> $1"},{name:v("Add uniform alias to Markdown links"),pattern:"\\[([^\\]]+)\\]\\(([^\\)]+)\\)",replacement:"[$1|alias]($2)"},{name:v("Delete empty lines (multiline mode)"),pattern:"^\\s*$\\n",replacement:"",toggleMultiline:!0},{name:v("Add list symbol to each line (multiline mode)"),pattern:"^(.+)$",replacement:"- $1",toggleMultiline:!0},{name:v("If the text contains important, set the text highlight (conditional format)"),pattern:"(.+)",replacement:"==$1==",useCondition:!0,conditionPattern:"important"}].forEach(e=>{const t=h.createEl("li");t.style.marginBottom="8px";const o=t.createEl("a",{text:e.name,href:"#"});o.style.color="var(--text-accent)",o.style.textDecoration="none",o.addEventListener("mouseenter",()=>{o.style.textDecoration="underline"}),o.addEventListener("mouseleave",()=>{o.style.textDecoration="none"}),o.addEventListener("click",t=>{t.preventDefault(),this.regexPattern=e.pattern,this.regexReplacement=e.replacement,this.regexPatternInput.setValue(e.pattern),this.regexReplacementInput.setValue(e.replacement),e.useCondition?(this.useCondition=!0,this.conditionPattern=e.conditionPattern||"",this.useConditionToggle.setValue(!0),this.conditionPatternInput.setValue(this.conditionPattern),c.style.display="block"):(this.useCondition=!1,this.useConditionToggle.setValue(!1),this.conditionPatternInput.setValue(""),c.style.display="none"),e.toggleMultiline?this.regexMultilineToggle.setValue(!0):this.regexMultilineToggle.setValue(!1),this.updatePreview(),u.removeAttribute("open")})});const g=t.createDiv("preview-container");g.style.marginTop="20px",g.style.marginBottom="20px",g.style.border="1px solid var(--background-modifier-border)",g.style.padding="10px",g.style.borderRadius="5px",g.createEl("label",{text:v("Preview")});const f=g.createDiv("preview-input-container");f.style.marginBottom="10px";const b=f.createEl("label",{text:v("Example text:")});b.style.display="block",b.style.marginBottom="5px",this.previewInput=f.createEl("textarea",{attr:{placeholder:v("Input example text to view the formatting effect of the command...")}}),this.previewInput.style.height="auto",this.previewInput.style.width="100%",this.previewInput.style.padding="8px",this.previewInput.style.borderRadius="4px",this.previewInput.style.border="1px solid var(--background-modifier-border)",this.previewInput.value="Sample text https://example.com important text 1234567890",this.previewInput.addEventListener("input",()=>{this.updatePreview()});const y=g.createDiv("preview-output-container"),C=y.createEl("label",{text:v("Result: ")});C.style.display="block",C.style.marginBottom="5px",this.previewOutput=y.createDiv("preview-output"),this.previewOutput.style.padding="8px",this.previewOutput.style.borderRadius="4px",this.previewOutput.style.border="1px solid var(--background-modifier-border)",this.previewOutput.style.backgroundColor="var(--background-secondary)",this.previewOutput.style.minHeight="3em",this.updatePreview(),new e.Setting(t).addButton(t=>t.setButtonText("保存").setCta().onClick(()=>{if(!this.commandId||!this.commandName)return void new e.Notice(v("Command ID and command name cannot be empty"));if(this.commandId.includes(" "))return void new e.Notice(v("Command ID cannot contain spaces"));if(!this.regexPattern)return void new e.Notice(v("Regex pattern cannot be empty"));const t=null===this.commandIndex?`custom-${this.commandId}`:this.commandId;if(null===this.commandIndex){if(this.plugin.settings.customCommands.findIndex(e=>e.id===t)>=0)return void new e.Notice(v("Command")+" "+this.commandId+" "+v("already exists"),8e3)}const o={id:t,name:this.commandName,icon:this.icon,useRegex:!0,regexPattern:this.regexPattern,regexReplacement:this.regexReplacement.replace(/\\n/g,"\n"),regexCaseInsensitive:this.regexCaseInsensitive,regexGlobal:this.regexGlobal,regexMultiline:this.regexMultiline,useCondition:this.useCondition,conditionPattern:this.conditionPattern,prefix:"",suffix:"",char:0,line:0,islinehead:!1};null!==this.commandIndex?this.plugin.settings.customCommands[this.commandIndex]=o:this.plugin.settings.customCommands.push(o),this.plugin.saveSettings().then(()=>{this.close(),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand")),this.plugin.reloadCustomCommands()},100)})})).addButton(e=>e.setButtonText(v("Cancel")).onClick(()=>this.close()))}onClose(){const{contentEl:e}=this;e.empty()}updatePreview(){const e=this.previewInput.value;let t=e;try{if(this.regexPattern){let o="";this.regexGlobal&&(o+="g"),this.regexCaseInsensitive&&(o+="i"),this.regexMultiline&&(o+="m");const n=new RegExp(this.regexPattern,o),i=this.regexReplacement.replace(/\\n/g,"\n");t=e.replace(n,i),this.showCompleteRegexCode(o)}this.previewOutput.empty(),t.split("\n").forEach((e,t,o)=>{this.previewOutput.createSpan({text:e}),t<o.length-1&&this.previewOutput.createEl("br")}),this.previewOutput.style.color="var(--text-normal)"}catch(e){this.previewOutput.setText(v("Error: ")+e.message),this.previewOutput.style.color="var(--text-error)";const t=this.previewOutput.parentElement?.querySelector(".regex-code-container");t&&t.remove()}}showCompleteRegexCode(e){const t=this.previewOutput.parentElement;if(!t)return;let o=t.querySelector(".regex-code-container");if(o){o.empty();const e=o.createEl("div",{text:v("Complete regular expression code (copy to AI for explanation)")});e.style.marginBottom="5px",e.style.fontWeight="bold"}else{o=t.createDiv("regex-code-container"),o.style.marginTop="15px",o.style.borderTop="1px solid var(--background-modifier-border)",o.style.paddingTop="10px";const e=o.createEl("div",{text:v("Complete regular expression code (copy to AI for explanation)")});e.style.marginBottom="5px",e.style.fontWeight="bold"}const n=o.createEl("pre");n.style.backgroundColor="var(--background-code)",n.style.padding="8px",n.style.borderRadius="4px",n.style.overflowX="auto",n.style.fontFamily="monospace",n.style.fontSize="var(--font-smaller)";let i=`//${v("Explain the syntax of JavaScript regular expressions")}\n`;i+=`const regex = /${this.escapeRegexForDisplay(this.regexPattern)}/${e};\n`,i+=`const result = text.replace(regex, "${this.escapeStringForDisplay(this.regexReplacement)}");\n`,this.useCondition&&this.conditionPattern&&(i+=`\n//${v("Conditional matching")}\n`,i+=`const condition = /${this.escapeRegexForDisplay(this.conditionPattern)}/;\n`,i+="if (condition.test(text)) {\n",i+=` //${v("Apply regular expression replacement")}\n`,i+=` const result = text.replace(regex, "${this.escapeStringForDisplay(this.regexReplacement)}");\n`,i+="}"),n.textContent=i;const a=o.createEl("button",{text:v("Copy code")});a.style.marginTop="5px",a.style.padding="4px 8px",a.style.borderRadius="4px",a.style.cursor="pointer",a.addEventListener("click",()=>{navigator.clipboard.writeText(i).then(()=>{a.textContent=v("Copied!"),setTimeout(()=>{a.textContent=v("Copy code")},2e3)}).catch(e=>{console.error("Failed to copy code: ",e)})})}escapeRegexForDisplay(e){return e.replace(/\\/g,"\\\\")}escapeStringForDisplay(e){return e.replace(/"/g,'\\"')}}class $o extends e.Modal{constructor(e,t,o){if(super(e),this.plugin=t,this.commandIndex=o,null!==o){const e=t.settings.customCommands[o];this.commandId=e.id,this.commandName=e.name,this.prefix=e.prefix,this.suffix=e.suffix,this.char=e.char,this.line=e.line,this.islinehead=e.islinehead,this.icon=e.icon||""}else this.commandId="",this.commandName="",this.prefix="",this.suffix="",this.char=0,this.line=0,this.islinehead=!1,this.icon=""}onOpen(){const{contentEl:t}=this;this.modalEl.addClass("custom-commands-modal"),t.empty(),t.createEl("h2",{text:null!==this.commandIndex?v("Edit Custom Command"):v("Add Custom Command")});const o=t.createDiv("switch-to-regex-container");o.style.marginBottom="20px",o.style.textAlign="center";const n=o.createEl("button",{text:v("Switch Regex Command Window")});n.addClass("mod-cta"),n.addEventListener("click",()=>{this.close(),new Bo(this.app,this.plugin,null).open()}),new e.Setting(t).setName(v("Command ID")).setDesc(v('Unique identifier, no spaces, e.g.: "my-custom-format"')).addText(e=>(this.commandIdInput=e,e.setValue(this.commandId),null!==this.commandIndex?(e.setDisabled(!0),e.inputEl.addClass("id-is-disabled")):e.onChange(e=>{this.commandId=e,this.commandNameInput&&(this.commandNameInput.setValue(e),this.commandName=e)}),e)),new e.Setting(t).setName(v("Command Name")).setDesc(v("Displayed name in toolbar and menu")).addText(e=>this.commandNameInput=e.setValue(this.commandName).onChange(e=>this.commandName=e));const i={"\n":"↵","\t":"⇥"},a=Object.fromEntries(Object.entries(i).map(([e,t])=>[t,e]));function s(e){let t=e;for(const[e,o]of Object.entries(i))t=t.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o);return t}function r(e){let t=e;for(const[e,o]of Object.entries(a))t=t.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o);return t}const l=Object.entries(i).map(([e,t])=>{let o=t;switch(e){case"\n":o+=" (New Line)";break;case"\t":o+=" (Tab)"}return{placeholder:t,label:o}});function c(e,t){t.setAttribute("title","点击可选择并复制文本");const o=e.controlEl.createDiv({cls:"special-char-buttons"});o.style.display="flex",o.style.flexWrap="wrap",o.style.gap="5px",o.style.marginTop="5px",l.forEach(({placeholder:e,label:t})=>{const n=o.createDiv({cls:"char-copy-container"});n.style.position="relative",n.style.display="inline-block";const i=n.createEl("button",{text:t});i.style.padding="2px 6px",i.style.fontSize="12px",i.style.minWidth="auto",i.style.border="1px solid var(--background-modifier-border)",i.style.cursor="pointer",i.setAttribute("data-char",e),i.addEventListener("click",t=>{t.preventDefault(),navigator.clipboard.writeText(e).then(()=>{const e=n.createDiv({cls:"copy-tooltip"});e.style.position="absolute",e.style.bottom="100%",e.style.left="50%",e.style.transform="translateX(-50%)",e.style.backgroundColor="var(--background-modifier-success)",e.style.color="white",e.style.padding="2px 6px",e.style.borderRadius="4px",e.style.fontSize="12px",e.style.pointerEvents="none",e.style.whiteSpace="nowrap",e.style.zIndex="100",e.textContent="已复制!",setTimeout(()=>{e.remove()},2e3)}).catch(e=>{console.error("无法复制文本: ",e)})}),i.addEventListener("mouseenter",()=>{i.style.backgroundColor="var(--interactive-accent)",i.style.color="var(--text-on-accent)"}),i.addEventListener("mouseleave",()=>{i.style.backgroundColor="",i.style.color=""})})}const d=new e.Setting(t).setName(v("Prefix")).setDesc(v("Add content before selected text")+v("Use ↵ to represent line breaks")).addText(e=>e.setValue(s(this.prefix)).onChange(e=>{this.prefix=r(e);const t=this.getMirrorText(e);t&&(this.suffix=r(t),this.suffixInput.setValue(t))}));c(d,d.controlEl.querySelector("input"));const u=new e.Setting(t).setName(v("Suffix")).setDesc(v("Add content after selected text")).addText(e=>{this.suffixInput=e,e.setValue(s(this.suffix)).onChange(e=>{this.suffix=r(e)})});c(u,u.controlEl.querySelector("input")),new e.Setting(t).setName(v("Cursor Position Offset")).setDesc(v("Default 0, format will keep the text selected")).addText(e=>e.setValue(this.char.toString()).onChange(e=>this.char=parseInt(e)||0)),new e.Setting(t).setName(v("Line Offset")).setDesc(v("Line offset of cursor after formatting")).addText(e=>e.setValue(this.line.toString()).onChange(e=>this.line=parseInt(e)||0)),new e.Setting(t).setName(v("Line Head Format")).setDesc(v("Whether to insert at the beginning of the next line")).addToggle(e=>e.setValue(this.islinehead).onChange(e=>this.islinehead=e));const m=new e.Setting(t).setName(v("Icon")).setDesc(v("Command icon (click to select)"));if(this.iconDisplay=m.controlEl.createDiv("editingToolbarSettingsIcon"),this.icon)try{e.setIcon(this.iconDisplay,this.icon)}catch(e){this.iconDisplay.setText(this.icon)}m.addButton(t=>t.setButtonText(v("Choose Icon")).onClick(()=>{const t={id:this.commandId,name:this.commandName,icon:this.icon};new w(this.plugin,t,!1,t=>{if(this.icon=t,this.iconDisplay.empty(),this.icon)try{e.setIcon(this.iconDisplay,this.icon)}catch(e){this.iconDisplay.setText(this.icon)}const o=m.controlEl.querySelector("input");o&&(o.value=this.icon)}).open()})),new e.Setting(t).addButton(t=>t.setButtonText(v("Save")).setCta().onClick(()=>{if(!this.commandId||!this.commandName)return void new e.Notice(v("Command ID and command name cannot be empty"));if(this.commandId.includes(" "))return void new e.Notice(v("Command ID cannot contain spaces"));const t=null===this.commandIndex?`custom-${this.commandId}`:this.commandId;if(null===this.commandIndex){if(this.plugin.settings.customCommands.findIndex(e=>e.id===t)>=0)return void new e.Notice(v("The command")+this.commandId+v("already exists"),8e3)}const o={id:t,name:this.commandName,prefix:this.prefix,suffix:this.suffix,char:this.char,line:this.line,islinehead:this.islinehead,icon:this.icon};if(null!==this.commandIndex){if(this.plugin.settings.customCommands[this.commandIndex].icon!==this.icon){const e=`editing-toolbar:${t}`;this.updateCommandIcon(this.plugin.settings.menuCommands,e),this.plugin.settings.enableMultipleConfig&&(this.updateCommandIcon(this.plugin.settings.followingCommands,e),this.updateCommandIcon(this.plugin.settings.topCommands,e),this.updateCommandIcon(this.plugin.settings.fixedCommands,e),this.plugin.settings.isLoadOnMobile&&this.updateCommandIcon(this.plugin.settings.mobileCommands,e))}this.plugin.settings.customCommands[this.commandIndex]=o}else this.plugin.settings.customCommands.push(o);this.plugin.saveSettings().then(()=>{this.close(),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand")),this.plugin.reloadCustomCommands()},100)})})).addButton(e=>e.setButtonText(v("Cancel")).onClick(()=>this.close())),setTimeout(()=>{this.commandIndex?this.commandIdInput.inputEl.focus():this.commandNameInput.inputEl.focus()},10)}updateCommandIcon(e,t){e&&e.forEach(e=>{e.id===t&&(e.icon=this.icon),e.SubmenuCommands&&this.updateCommandIcon(e.SubmenuCommands,t)})}onClose(){const{contentEl:e}=this;e.empty()}getMirrorText(e){const t={"**":"**","*":"*",__:"__",_:"_","~~":"~~","`":"`","```":"```",$:"$",$$:"$$","(":")","[":"]","{":"}","<":">","==":"==","*==":"==*","**==":"==**","***==":"==***"};if(!e)return"";if(e in t)return t[e];const o=e.match(/^<(\w+)([^>]*)>$/);return o?`</${o[1]}>`:""}}class _o extends e.Modal{constructor(e,t,o){super(e),this.deployOptions=[],this.plugin=t,this.command=o,this.deployOptions=[{id:"following",name:v("Following Style"),enabled:!0},{id:"top",name:v("Top Style"),enabled:!0},{id:"fixed",name:v("Fixed Style"),enabled:!0}],this.plugin.settings.isLoadOnMobile&&this.deployOptions.push({id:"mobile",name:v("Mobile Style"),enabled:!0})}onOpen(){const{contentEl:t}=this;t.empty(),t.createEl("h3",{text:v("Deploy command to configurations")}),t.createDiv("deploy-option");const o=t.createDiv("deploy-options");this.deployOptions.forEach(t=>{new e.Setting(o).setName(t.name).addToggle(e=>e.setValue(t.enabled).onChange(e=>{t.enabled=e})).settingEl.addClass("deploy-option")});const n=t.createDiv("deploy-buttons");new e.Setting(n).addButton(e=>e.setButtonText(v("Deploy")).setCta().onClick(()=>{this.deployCommand(),this.close()})).addButton(e=>e.setButtonText(v("Cancel")).onClick(()=>{this.close()}))}deployCommand(){const t={id:`editing-toolbar:${this.command.id}`,name:this.command.name,icon:this.command.icon||"obsidian-new"};this.plugin.settings.menuCommands.some(e=>e.id===t.id)||this.plugin.settings.menuCommands.push({...t});let o=0;this.deployOptions.forEach(e=>{if(e.enabled){let n;switch(e.id){case"mobile":n=this.plugin.settings.mobileCommands;break;case"following":n=this.plugin.settings.followingCommands;break;case"top":n=this.plugin.settings.topCommands;break;case"fixed":n=this.plugin.settings.fixedCommands}n&&!n.some(e=>e.id===t.id)&&(n.push({...t}),o++)}}),this.plugin.saveSettings().then(()=>{let t="";if(o>0){const e=this.deployOptions.filter(e=>e.enabled).map(e=>e.name).join(", ");t=v("Command deployed to: ")+e}else t=v("Command already exists in selected configurations");new e.Notice(t),dispatchEvent(new Event("editingToolbar-NewCommand")),this.plugin.reloadCustomCommands()})}}class zo extends e.Modal{constructor(e,t,o){super(e),this.plugin=t,this.mode=o,this.exportType="all",this.importMode="update"}onOpen(){const{contentEl:t}=this;if(t.addClass("editing-toolbar-import-export-modal"),t.createEl("h2",{text:"import"===this.mode?v("Import Configuration"):v("Export Configuration"),cls:"import-export-title"}),"export"===this.mode){new e.Setting(t).setName(v("Export Type")).setDesc(v("Choose what to export")).addDropdown(e=>{e.addOption("all",v("All Settings")).addOption("All commands",v("All Toolbar Commands")).addOption("custom",v("Custom Commands Only")),this.plugin.settings.enableMultipleConfig&&e.addOption("following",v("Following Style Only")).addOption("top",v("Top Style Only")).addOption("fixed",v("Fixed Style Only")).addOption("mobile",v("Mobile Style Only")),e.setValue(this.exportType).onChange(e=>{this.exportType=e,this.updateExportContent()})});const o=t.createDiv("export-container");o.style.border="1px solid var(--background-modifier-border)",o.style.padding="10px",o.style.borderRadius="5px",this.textArea=new e.TextAreaComponent(o),this.textArea.setValue("").setPlaceholder(v("Loading...")).then(e=>{e.inputEl.style.width="100%",e.inputEl.style.height="200px",e.inputEl.style.fontFamily="monospace",e.inputEl.style.fontSize="12px",e.inputEl.style.padding="8px",e.inputEl.style.border="1px solid var(--background-modifier-border)",e.inputEl.style.borderRadius="4px"}),this.updateExportContent();const n=t.createDiv("import-export-button-container");n.style.display="flex",n.style.justifyContent="flex-end",n.style.marginTop="16px";n.createEl("button",{text:v("Copy to Clipboard"),cls:"mod-cta"}).addEventListener("click",()=>{navigator.clipboard.writeText(this.textArea.getValue()).then(()=>{new e.Notice(v("Configuration copied to clipboard"))}).catch(t=>{console.error("Failed to copy: ",t),new e.Notice(v("Failed to copy configuration"))})})}else{new e.Setting(t).setName(v("Import Mode")).setDesc(v("Choose how to import the configuration")).addDropdown(e=>{e.addOption("update",v("Update Mode (Add new items and update existing ones)")).addOption("overwrite",v("Overwrite Mode (Replace settings with imported ones)")).setValue(this.importMode).onChange(e=>{this.importMode=e,this.importButton.setButtonText("overwrite"===this.importMode?v("Overwrite Import"):v("Update Import")),this.warningContent.setText("overwrite"===this.importMode?v("Warning: Overwrite mode will replace existing settings with imported ones."):v("Warning: Update mode will add new items and update existing ones."))})});const o=t.createDiv("import-container");o.style.border="1px solid var(--background-modifier-border)",o.style.padding="10px",o.style.borderRadius="5px",this.textArea=new e.TextAreaComponent(o),this.textArea.setValue("").setPlaceholder(v("Paste configuration here...")).then(e=>{e.inputEl.style.width="100%",e.inputEl.style.height="200px",e.inputEl.style.fontFamily="monospace",e.inputEl.style.fontSize="12px",e.inputEl.style.padding="8px",e.inputEl.style.border="1px solid var(--background-modifier-border)",e.inputEl.style.borderRadius="4px"});const n=t.createDiv("import-export-button-container");n.style.display="flex",n.style.justifyContent="flex-end",n.style.marginTop="16px",new e.Setting(n).addButton(e=>{this.importButton=e.setIcon("import").setButtonText(v("Import Configuration")).onClick(()=>{this.importConfiguration()})});const i=t.createDiv("import-export-warning");i.style.marginTop="16px",i.style.padding="8px 12px",i.style.backgroundColor="rgba(var(--color-red-rgb), 0.1)",i.style.borderRadius="4px",i.style.border="1px solid rgba(var(--color-red-rgb), 0.3)";const a=i.createEl("p",{text:v("Warning: Update mode will add new items and update existing ones."),cls:"warning-text"});a.style.margin="0",this.warningContent=a}}updateExportContent(){let e={_exportInfo:{version:this.plugin.manifest.version,exportType:this.exportType,exportTime:(new Date).toISOString(),pluginId:this.plugin.manifest.id}};switch(this.exportType){case"all":e={...e,menuCommands:this.plugin.settings.menuCommands||[],followingCommands:this.plugin.settings.followingCommands||[],topCommands:this.plugin.settings.topCommands||[],fixedCommands:this.plugin.settings.fixedCommands||[],mobileCommands:this.plugin.settings.mobileCommands||[],customCommands:this.plugin.settings.customCommands||[],enableMultipleConfig:this.plugin.settings.enableMultipleConfig,positionStyle:this.plugin.settings.positionStyle,aestheticStyle:this.plugin.settings.aestheticStyle,appendMethod:this.plugin.settings.appendMethod,autohide:this.plugin.settings.autohide,isLoadOnMobile:this.plugin.settings.isLoadOnMobile,cMenuNumRows:this.plugin.settings.cMenuNumRows,custom_bg1:this.plugin.settings.custom_bg1,custom_bg2:this.plugin.settings.custom_bg2,custom_bg3:this.plugin.settings.custom_bg3,custom_bg4:this.plugin.settings.custom_bg4,custom_bg5:this.plugin.settings.custom_bg5,custom_fc1:this.plugin.settings.custom_fc1,custom_fc2:this.plugin.settings.custom_fc2,custom_fc3:this.plugin.settings.custom_fc3,custom_fc4:this.plugin.settings.custom_fc4,custom_fc5:this.plugin.settings.custom_fc5,toolbarBackgroundColor:this.plugin.settings.toolbarBackgroundColor,toolbarIconColor:this.plugin.settings.toolbarIconColor,toolbarIconSize:this.plugin.settings.toolbarIconSize};break;case"All commands":e={...e,menuCommands:this.plugin.settings.menuCommands||[],followingCommands:this.plugin.settings.followingCommands||[],topCommands:this.plugin.settings.topCommands||[],fixedCommands:this.plugin.settings.fixedCommands||[],mobileCommands:this.plugin.settings.mobileCommands||[],enableMultipleConfig:this.plugin.settings.enableMultipleConfig};break;case"custom":e={...e,customCommands:this.plugin.settings.customCommands||[]};break;case"following":e={...e,followingCommands:this.plugin.settings.followingCommands||[]};break;case"top":e={...e,topCommands:this.plugin.settings.topCommands||[]};break;case"fixed":e={...e,fixedCommands:this.plugin.settings.fixedCommands||[]};break;case"mobile":e={...e,mobileCommands:this.plugin.settings.mobileCommands||[]}}this.validateExportContent(e),this.textArea.setValue(JSON.stringify(e,null,2))}validateExportContent(e){["menuCommands","followingCommands","topCommands","fixedCommands","mobileCommands","customCommands"].forEach(t=>{t in e&&!e[t]&&(e[t]=[])}),"enableMultipleConfig"in e&&void 0===e.enableMultipleConfig&&(e.enableMultipleConfig=!1),"autohide"in e&&void 0===e.autohide&&(e.autohide=!1),"Iscentered"in e&&void 0===e.Iscentered&&(e.Iscentered=!1),"isLoadOnMobile"in e&&void 0===e.isLoadOnMobile&&(e.isLoadOnMobile=!0),"positionStyle"in e&&!e.positionStyle&&(e.positionStyle="top"),"aestheticStyle"in e&&!e.aestheticStyle&&(e.aestheticStyle="default"),"appendMethod"in e&&!e.appendMethod&&(e.appendMethod="workspace"),"cMenuNumRows"in e&&void 0===e.cMenuNumRows&&(e.cMenuNumRows=1)}async importConfiguration(){try{const t=this.textArea.getValue();if(!t.trim())return void new e.Notice(v("Please paste configuration data first"));const o=JSON.parse(t);if(!o||"object"!=typeof o)return void new e.Notice(v("Invalid import data format"));const n="menuCommands"in o,i="customCommands"in o,a="followingCommands"in o,s="topCommands"in o,r="fixedCommands"in o,l="mobileCommands"in o,c="positionStyle"in o||"aestheticStyle"in o,d="enableMultipleConfig"in o,u=o.positionStyle,m=n&&Array.isArray(o.menuCommands)&&o.menuCommands.length>0,p=i&&Array.isArray(o.customCommands)&&o.customCommands.length>0,h=a&&Array.isArray(o.followingCommands)&&o.followingCommands.length>0,g=s&&Array.isArray(o.topCommands)&&o.topCommands.length>0,f=r&&Array.isArray(o.fixedCommands)&&o.fixedCommands.length>0,b=l&&Array.isArray(o.mobileCommands)&&o.mobileCommands.length>0,y=n&&(!Array.isArray(o.menuCommands)||0===o.menuCommands.length),C=i&&(!Array.isArray(o.customCommands)||0===o.customCommands.length),w=a&&(!Array.isArray(o.followingCommands)||0===o.followingCommands.length),x=s&&(!Array.isArray(o.topCommands)||0===o.topCommands.length),k=r&&(!Array.isArray(o.fixedCommands)||0===o.fixedCommands.length),S=l&&(!Array.isArray(o.mobileCommands)||0===o.mobileCommands.length);let T=v("This import will:")+"\n";if(c&&(T+="• "+v("Update general settings")+"\n"),m&&(T+="• "+v("Update Main Menu Commands")+" ("+o.menuCommands.length+" )\n"),p&&(T+="• "+v("Update Custom Commands")+" ("+o.customCommands.length+" )\n"),h&&(T+="• "+v("Update Following Style Commands")+" ("+o.followingCommands.length+" )\n"),g&&(T+="• "+v("Update Top Style Commands")+" ("+o.topCommands.length+" )\n"),f&&(T+="• "+v("Update Fixed Style Commands")+" ("+o.fixedCommands.length+" )\n"),b&&(T+="• "+v("Update Mobile Style Commands")+" ("+o.mobileCommands.length+" )\n"),"overwrite"===this.importMode&&(y&&(T+="• "+v("Clear all Main Menu Commands")+" ⚠️\n"),C&&(T+="• "+v("Clear all Custom Commands")+" ⚠️\n"),w&&(T+="• "+v("Clear all Following Style Commands")+" ⚠️\n"),x&&(T+="• "+v("Clear all Top Style Commands")+" ⚠️\n"),k&&(T+="• "+v("Clear all Fixed Style Commands")+" ⚠️\n"),S&&(T+="• "+v("Clear all Mobile Style Commands")+" ⚠️\n")),d){const e=o.enableMultipleConfig?v("Enable"):v("Disable");T+="• "+v("Set Multiple Config to:")+" "+e+"\n"}if(u&&(T+="• "+v("Set Position Style to:")+" "+this.getPositionStyleName(u)+"\n"),!(m||p||h||g||f||b||y||C||w||x||k||S||c||d))return void new e.Notice(v("No valid configuration found in import data"));"overwrite"===this.importMode?T+="\n"+v("⚠️ Overwrite mode will replace existing settings with imported ones."):T+="\n"+v(" Update mode will merge imported settings with existing ones."),No.show(this.app,{message:T+"\n"+v("Do you want to continue?"),onConfirm:async()=>{const t={positionStyle:this.plugin.settings.positionStyle,menuCommands:[...this.plugin.settings.menuCommands],customCommands:[...this.plugin.settings.customCommands],followingCommands:[...this.plugin.settings.followingCommands],topCommands:[...this.plugin.settings.topCommands],fixedCommands:[...this.plugin.settings.fixedCommands],mobileCommands:[...this.plugin.settings.mobileCommands]};try{"overwrite"===this.importMode?this.performOverwriteImport(o):this.performUpdateImport(o),this.fixImportedCommandIds(),await this.plugin.saveSettings(),this.plugin.reloadCustomCommands(),dispatchEvent(new Event("editingToolbar-NewCommand")),new e.Notice(v("Configuration imported successfully")),this.close()}catch(e){throw this.restoreBackup(t),e}}})}catch(t){console.error("Import error: ",t),new e.Notice(v("Error: ")+" "+t.message)}}performOverwriteImport(e){this.importGeneralSettings(e),e.menuCommands&&(this.plugin.settings.menuCommands=e.menuCommands),e.customCommands&&(this.plugin.settings.customCommands=e.customCommands),e.followingCommands&&(this.plugin.settings.followingCommands=e.followingCommands),e.topCommands&&(this.plugin.settings.topCommands=e.topCommands),e.fixedCommands&&(this.plugin.settings.fixedCommands=e.fixedCommands),e.mobileCommands&&(this.plugin.settings.mobileCommands=e.mobileCommands)}performUpdateImport(e){this.importGeneralSettings(e),e.menuCommands&&this.updateCommandArray(this.plugin.settings.menuCommands,e.menuCommands),e.customCommands&&this.updateCommandArray(this.plugin.settings.customCommands,e.customCommands),e.followingCommands&&this.updateCommandArray(this.plugin.settings.followingCommands,e.followingCommands),e.topCommands&&this.updateCommandArray(this.plugin.settings.topCommands,e.topCommands),e.fixedCommands&&this.updateCommandArray(this.plugin.settings.fixedCommands,e.fixedCommands),e.mobileCommands&&this.updateCommandArray(this.plugin.settings.mobileCommands,e.mobileCommands)}updateCommandArray(e,t){return e?(t.forEach(t=>{const o=e.findIndex(e=>e.id===t.id);o>=0?e[o]=t:e.push(t),t.SubmenuCommands&&e[o]?.SubmenuCommands&&this.updateCommandArray(e[o].SubmenuCommands,t.SubmenuCommands)}),e):t.slice()}importGeneralSettings(e){["positionStyle","aestheticStyle","appendMethod","autohide","Iscentered","isLoadOnMobile","cMenuNumRows","enableMultipleConfig","custom_bg1","custom_bg2","custom_bg3","custom_bg4","custom_bg5","custom_fc1","custom_fc2","custom_fc3","custom_fc4","custom_fc5","toolbarBackgroundColor","toolbarIconColor","toolbarIconSize"].forEach(t=>{void 0!==e[t]&&(this.plugin.settings[t]=e[t])})}fixImportedCommandIds(){const e={"editor:toggle-numbered-list":"editing-toolbar:toggle-numbered-list","editor:toggle-bullet-list":"editing-toolbar:toggle-bullet-list","editor:toggle-highlight":"editing-toolbar:toggle-highlight","toggle-highlight":"editing-toolbar:toggle-highlight","editing-toolbar:editor:toggle-bold":"editing-toolbar:toggle-bold","editing-toolbar:editor:toggle-italics":"editing-toolbar:toggle-italics","editing-toolbar:editor:toggle-strikethrough":"editing-toolbar:toggle-strikethrough","editing-toolbar:editor:toggle-inline-math":"editing-toolbar:toggle-inline-math","editing-toolbar:editor:insert-callout":"editing-toolbar:insert-callout","editing-toolbar:editor:insert-link":"editing-toolbar:insert-link","cMenuToolbar-Divider-Line":"editingToolbar-Divider-Line"},t=o=>{o&&Array.isArray(o)&&o.forEach(o=>{o.id&&e[o.id]&&(o.id=e[o.id]),o.SubmenuCommands&&Array.isArray(o.SubmenuCommands)&&t(o.SubmenuCommands)})};t(this.plugin.settings.menuCommands),t(this.plugin.settings.customCommands),t(this.plugin.settings.followingCommands),t(this.plugin.settings.topCommands),t(this.plugin.settings.fixedCommands),t(this.plugin.settings.mobileCommands)}restoreBackup(e){this.plugin.settings.positionStyle=e.positionStyle,this.plugin.settings.menuCommands=e.menuCommands,this.plugin.settings.customCommands=e.customCommands,this.plugin.settings.followingCommands=e.followingCommands,this.plugin.settings.topCommands=e.topCommands,this.plugin.settings.fixedCommands=e.fixedCommands,this.plugin.settings.mobileCommands=e.mobileCommands}onClose(){const{contentEl:e}=this;e.empty()}getPositionStyleName(e){switch(e){case"following":return v("Following Style");case"top":return v("Top Style");case"fixed":return v("Fixed Style");default:return e}}}const Uo=new Map;class Vo extends Error{constructor(e,t=8e3){super(e),this.name="AIUserNoticeError",this.noticeDuration=t}}function Ho(e){const t=e?.status;if("number"==typeof t)return t;const o=e?.response?.status;return"number"==typeof o?o:null}function Wo(e){if(e instanceof Error&&e.message.trim())return e.message.trim();if("string"==typeof e&&e.trim())return e.trim();const t=e?.response,o=t?.json?.error?.message||t?.json?.message||t?.text;return"string"==typeof o&&o.trim()?o.trim():v("Unknown connection error.")}function jo(t){if(!(t instanceof Vo))return!1;const o=Date.now();return o-(Uo.get(t.message)??0)<6e3||(Uo.set(t.message,o),new e.Notice(t.message,t.noticeDuration)),!0}const Ko="https://pkmer.cn/products/UserProfile/",Yo=`${Ko}#tab-ai-token`,Go="https://pkmer.net/en/products/ai-token";const Jo=[{id:"general",name:v("General"),icon:"gear"},{id:"appearance",name:v("Appearance"),icon:"brush"},{id:"customcommands",name:v("Custom Commands"),icon:"lucide-rectangle-ellipsis"},{id:"commands",name:v("Toolbar Commands"),icon:"lucide-command"},{id:"ai",name:v("AI"),icon:"lucide-sparkles"},{id:"importexport",name:v("Import/Export"),icon:"lucide-import"}];function Zo(e){const{el:t,containerEl:o,swatches:n,opacity:i,defaultColor:a}=e;return{el:t,container:o,theme:"nano",swatches:n,lockOpacity:!i,default:a,position:"left-middle",components:{preview:!0,hue:!0,opacity:!!i,interaction:{hex:!0,rgba:!1,hsla:!1,input:!0,cancel:!0,save:!0}}}}function Xo(e,t){if(!t||!Array.isArray(t))return-1;return t.findIndex(t=>t?.id===e)}class Qo extends e.PluginSettingTab{getLocalizedCommandName(e){return v(e)}constructor(e,t){super(e,t),this.pickrs=[],this.activeTab="general",this.cachedCustomOllamaModels=[],this.cachedCustomOllamaModelsBaseUrl="",this.cachedCustomOllamaModelsError="",this.aestheticStyleMap={default:"editingToolbarDefaultAesthetic",tiny:"editingToolbarTinyAesthetic",glass:"editingToolbarGlassAesthetic",custom:"editingToolbarCustomAesthetic",top:"top",following:"editingToolbarFlex",fixed:"fixed"},this.plugin=t,this.currentEditingConfig=this.plugin.settings.positionStyle,addEventListener("editingToolbar-NewCommand",()=>{se(this.plugin),Ie(e,this.plugin),this.display()})}async refreshCustomOllamaModels(){const t=this.plugin.settings.ai.customModel.baseUrl.trim();try{const o=await this.plugin.aiManager.listCustomOllamaModels();this.cachedCustomOllamaModels=o,this.cachedCustomOllamaModelsBaseUrl=t,this.cachedCustomOllamaModelsError="",0===o.length&&new e.Notice(v("No Ollama models found at this endpoint."))}catch(o){this.cachedCustomOllamaModels=[],this.cachedCustomOllamaModelsBaseUrl=t,this.cachedCustomOllamaModelsError=Wo(o),new e.Notice(`${v("Failed to load Ollama models:")} ${this.cachedCustomOllamaModelsError}`)}this.display()}display(){this.destroyPickrs();const{containerEl:t}=this;t.empty(),this.createHeader(t);const o=t.createEl("div",{cls:"editing-toolbar-tabs"});Jo.forEach(t=>{const n=o.createEl("div",{cls:"editing-toolbar-tab "+(this.activeTab===t.id?"active":"")});e.setIcon(n,t.icon),n.createEl("span",{text:t.name}),n.addEventListener("click",()=>{this.activeTab=t.id,this.display()})});const n=t.createEl("div",{cls:"editing-toolbar-content"});switch(this.activeTab){case"general":this.displayGeneralSettings(n);break;case"appearance":this.displayAppearanceSettings(n);break;case"customcommands":this.displayCustomCommandSettings(n);break;case"commands":this.displayCommandSettings(n);break;case"ai":this.displayAISettings(n);break;case"importexport":this.displayImportExportSettings(n)}}createDeleteButton(e,t,o=v("Delete")){let n,i=!1;e.setIcon("editingToolbarDelete").setTooltip(o).onClick(async()=>{i?(clearTimeout(n),e.setIcon("editingToolbarDelete").setTooltip(o),e.buttonEl.removeClass("mod-warning"),i=!1,await t()):(i=!0,e.setTooltip(v("Confirm Delete?")).setButtonText(v("Confirm Delete?")),e.buttonEl.addClass("mod-warning"),n=setTimeout(()=>{e.setIcon("editingToolbarDelete").setTooltip(o),e.buttonEl.removeClass("mod-warning"),i=!1},3500))})}displayGeneralSettings(t){const o=t.createDiv("generalSetting-container");o.style.padding="16px",o.style.borderRadius="8px",o.style.backgroundColor="var(--background-secondary)",o.style.marginBottom="20px",new e.Setting(o).setName(v("Editing Toolbar Append Method")).setDesc(v("Choose where Editing Toolbar will append upon regeneration.")).addDropdown(e=>{let t={};Y.map(e=>t[e]=e),e.addOptions(t),e.setValue(this.plugin.settings.appendMethod).onChange(e=>{this.plugin.settings.appendMethod=e,this.plugin.saveSettings()})}),new e.Setting(o).setName(v("Enable Multiple Configurations")).setDesc(v("Enable different command configurations for each position style (following, top, fixed).")).addToggle(e=>e.setValue(this.plugin.settings.enableMultipleConfig||!1).onChange(async e=>{this.plugin.settings.enableMultipleConfig=e,this.plugin.onPositionStyleChange(this.plugin.positionStyle),await this.plugin.saveSettings(),this.display()})),new e.Setting(o).setName(v("Top Toolbar")).setDesc(v("Enable the toolbar positioned at the top.")).addToggle(e=>{e.setValue(this.plugin.settings.enableTopToolbar||!1).onChange(async e=>{const t=this.plugin.settings,o=this.plugin.positionStyle;t.enableTopToolbar=e;let n=null;e?n="top":"top"===o&&(n=t.enableFollowingToolbar?"following":t.enableFixedToolbar?"fixed":null),n&&n!==o&&this.plugin.onPositionStyleChange(n),await this.plugin.saveSettings(),this.plugin.handleeditingToolbar(),this.display()})}),new e.Setting(o).setName(v("Following Toolbar")).setDesc(v("Enable the toolbar that appears upon text selection.")).addToggle(e=>{e.setValue(this.plugin.settings.enableFollowingToolbar||!1).onChange(async e=>{const t=this.plugin.settings,o=this.plugin.positionStyle;t.enableFollowingToolbar=e;let n=null;e?n="following":"following"===o&&(n=t.enableTopToolbar?"top":t.enableFixedToolbar?"fixed":null),n&&n!==o&&this.plugin.onPositionStyleChange(n),await this.plugin.saveSettings(),this.plugin.handleeditingToolbar(),this.display()})}),new e.Setting(o).setName(v("Fixed Toolbar")).setDesc(v("Enable the toolbar whose position may be fixed where you please.")).addToggle(e=>{e.setValue(this.plugin.settings.enableFixedToolbar||!1).onChange(async e=>{const t=this.plugin.settings,o=this.plugin.positionStyle;t.enableFixedToolbar=e;let n=null;e?n="fixed":"fixed"===o&&(n=t.enableTopToolbar?"top":t.enableFollowingToolbar?"following":null),n&&n!==o&&this.plugin.onPositionStyleChange(n),await this.plugin.saveSettings(),this.plugin.handleeditingToolbar(),this.display()})}),new e.Setting(o).setName(v("Mobile Enabled or Not")).setDesc(v("Whether to enable on mobile devices with device width less than 768px.")).addToggle(e=>e.setValue(this.plugin.settings?.isLoadOnMobile??!1).onChange(e=>{this.plugin.settings.isLoadOnMobile=e,this.plugin.saveSettings(),this.triggerRefresh()}));const n=t.createDiv("custom-paintbrush-container");n.style.padding="16px",n.style.borderRadius="8px",n.style.backgroundColor="var(--background-secondary)",n.style.marginBottom="20px",new e.Setting(n).setName(v("🎨 Set Custom Background")).setDesc(v("Click on the picker to adjust the color")).setClass("custom_bg").then(e=>{const t=e.controlEl.createDiv({cls:"pickr-container"});for(let e=0;e<5;e++){const o=t.createDiv({cls:"picker"}),n=Oo.create(Zo({isView:!1,el:o,containerEl:t,swatches:["#FFB78B8C","#CDF4698C","#A0CCF68C","#F0A7D88C","#ADEFEF8C"],opacity:!0,defaultColor:this.plugin.settings[`custom_bg${e+1}`]||"#000000"}));this.setupPickrEvents(n,`custom_bg${e+1}`,"background-color"),this.pickrs.push(n)}}),new e.Setting(n).setName(v("🖌️ Set Custom Font Color")).setDesc(v("Click on the picker to adjust the color")).setClass("custom_font").then(e=>{const t=e.controlEl.createDiv({cls:"pickr-container"});for(let e=0;e<5;e++){const o=t.createDiv({cls:"picker"}),n=Oo.create(Zo({isView:!1,el:o,containerEl:t,swatches:["#D83931","#DE7802","#245BDB","#6425D0","#646A73"],opacity:!0,defaultColor:this.plugin.settings[`custom_fc${e+1}`]||"#000000"}));this.setupPickrEvents(n,`custom_fc${e+1}`,"color"),this.pickrs.push(n)}})}displayAppearanceSettings(t){const o=t.createDiv("appearanceSetting-container");o.style.padding="16px",o.style.borderRadius="8px",o.style.backgroundColor="var(--background-secondary)",o.style.marginBottom="20px";const n=this.plugin.appearanceEditStyle||this.plugin.settings.positionStyle||"top";this.plugin.appearanceEditStyle=n,new e.Setting(o).setName(v("Toolbar Settings")).setDesc(v("Choose which toolbar style's appearance you want to edit.")).addDropdown(e=>{const t={};J.map(e=>t[e]=e),e.addOptions(t).setValue(n).onChange(async e=>{const t=e;this.plugin.appearanceEditStyle=t,this.plugin.settings.positionStyle=t,await this.plugin.saveSettings(),this.display()})}),"top"===n&&(new e.Setting(o).setName(v("Editing Toolbar Auto-hide")).setDesc(v("The toolbar is displayed when the mouse moves over it, otherwise it is automatically hidden")).addToggle(e=>e.setValue(this.plugin.settings?.autohide).onChange(e=>{this.plugin.settings.autohide=e,this.plugin.saveSettings(),this.triggerRefresh()})),new e.Setting(o).setName(v("Editing Toolbar Centred Display")).setDesc(v("Whether the toolbar is centred or full-width, the default is full-width.")).addToggle(e=>e.setValue(this.plugin.settings?.Iscentered).onChange(e=>{this.plugin.settings.Iscentered=e,this.plugin.saveSettings(),this.triggerRefresh()}))),"fixed"===n&&(new e.Setting(o).setName(v("Editing Toolbar Columns")).setDesc(v("Choose the number of columns per row to display on Editing Toolbar.")).addSlider(t=>{t.setLimits(1,32,1).setValue(this.plugin.settings.cMenuNumRows).onChange(e.debounce(async e=>{this.plugin.settings.cMenuNumRows=e,await this.plugin.saveSettings(),this.triggerRefresh()},100,!0)).setDynamicTooltip()}),new e.Setting(o).setName(v("Fixed Position Offset")).setDesc(v("Choose the offset of the Editing Toolbar in the fixed position.")).addButton(e=>e.setButtonText(v("Settings")).onClick(()=>{new T(this.app,this.plugin).open()}))),this.createColorSettings(t)}displayCommandSettings(t){const o=t.createDiv("commandSetting-container");if(o.style.padding="16px",o.style.borderRadius="8px",o.style.backgroundColor="var(--background-secondary)",o.style.marginBottom="20px",this.plugin.settings.enableMultipleConfig&&new e.Setting(o).setName(v("Current Configuration")).setDesc(v("Switch between different command configurations.")).addDropdown(e=>{e.addOption("top",v("Top Style")),e.addOption("fixed",v("Fixed Style")),e.addOption("following",v("Following Style")),this.plugin.settings.isLoadOnMobile&&e.addOption("mobile",v("Mobile Style")),e.setValue(this.currentEditingConfig),e.onChange(async e=>{this.currentEditingConfig=e,this.display()})}),this.plugin.settings.enableMultipleConfig){const o=this.currentEditingConfig;this.getCommandsArrayByType(o);const n=t.createDiv("command-buttons-container");n.style.display="flex",n.style.flexDirection="column",n.style.gap="10px",n.style.padding="16px",n.style.borderRadius="8px",n.style.backgroundColor="var(--background-secondary)";const i=new e.Setting(n).setName(v("Import From")).setDesc(v("Copy commands from another style configuration."));let a="Main menu";const s=new e.Setting(n);s.addDropdown(e=>{e.addOption("Main menu","Main Menu Commands"),"following"!==o&&this.plugin.settings.followingCommands&&e.addOption("following",v("Following Style")),"top"!==o&&this.plugin.settings.topCommands&&e.addOption("top",v("Top Style")),"fixed"!==o&&this.plugin.settings.fixedCommands&&e.addOption("fixed",v("Fixed Style")),"mobile"!==o&&this.plugin.settings.mobileCommands&&e.addOption("mobile",v("Mobile Style")),e.setValue(a).onChange(e=>{a=e})}),s.addExtraButton(e=>e.setIcon("arrow-right")),s.addButton(t=>t.setButtonText(this.currentEditingConfig+" "+v("Import")).setTooltip(v("Copy commands from selected style.")).onClick(async()=>{const t=this.getCommandsArrayByType(a);if(!t||0===t.length)return void new e.Notice("The selected style has no commands to import.");const n=`Import commands from "${a}" to "${this.currentEditingConfig}" `+v("configuration")+"?";No.show(this.app,{message:n,onConfirm:async()=>{switch(o){case"Main menu":this.plugin.settings.menuCommands=[...t];break;case"following":this.plugin.settings.followingCommands=[...t];break;case"top":this.plugin.settings.topCommands=[...t];break;case"fixed":this.plugin.settings.fixedCommands=[...t];break;case"mobile":this.plugin.settings.mobileCommands=[...t]}await this.plugin.saveSettings(),new e.Notice(`Commands imported successfully from "${a}" to "${this.currentEditingConfig}" `+v("configuration")),this.display()}})})),i.addButton(t=>t.setButtonText(v("Clear")+" "+`${this.currentEditingConfig}`).setTooltip(v("Remove all commands from this configuration.")).setWarning().onClick(async()=>{No.show(this.app,{message:v("Are you sure you want to clear all commands under the current style?"),onConfirm:async()=>{switch(o){case"following":this.plugin.settings.followingCommands=[];break;case"top":this.plugin.settings.topCommands=[];break;case"fixed":this.plugin.settings.fixedCommands=[];break;case"mobile":this.plugin.settings.mobileCommands=[]}await this.plugin.saveSettings(),new e.Notice("All commands have been removed."),this.display()}})}))}else{o.createDiv("command-buttons-container").createEl("button",{text:v("One-click Clear"),cls:"mod-warning"}).addEventListener("click",async()=>{No.show(this.app,{message:v("Are you sure you want to clear all commands under the current style?"),onConfirm:async()=>{this.plugin.settings.menuCommands=[],await this.plugin.saveSettings(),new e.Notice(v("All commands have been removed.")),this.display()}})})}const n=t.createDiv("command-lists-container");n.style.padding="16px",n.style.borderRadius="8px",n.addClass(`${this.currentEditingConfig}`),this.plugin.settings.enableMultipleConfig&&n.createEl("div",{cls:`position-style-info ${this.currentEditingConfig}`,text:v("Currently editing commands for")+` "${this.currentEditingConfig} Style" `+v("configuration")}),new e.Setting(n).setName(v("Editing Toolbar Commands")).setDesc(v("Add a command onto Editing Toolbar from Obsidian's commands library. To reorder the commands, drag and drop the command items. To delete them, use the delete buttom to the right of the command item. Editing Toolbar will not automaticaly refresh after reordering commands. Use the refresh button above.")).addButton(e=>{e.setIcon("plus").setTooltip(v("Add")).onClick(()=>{new k(this.plugin,this.currentEditingConfig).open(),this.triggerRefresh()})}),this.createCommandList(n)}displayCustomCommandSettings(t){t.empty();const o=t.createDiv("custom-commands-container");o.createEl("p",{text:v("Add, edit or delete custom format commands.")}),new e.Setting(o).setName(v("Use current line for regex commands")).setDesc(v("When no text is selected, regex commands will use the current line instead of clipboard content")).addToggle(e=>e.setValue(this.plugin.settings?.useCurrentLineForRegex??!1).onChange(async e=>{this.plugin.settings.useCurrentLineForRegex=e,await this.plugin.saveSettings()}));const n=o.createDiv("command-list-container");n.style.padding="16px",n.style.borderRadius="8px",n.style.backgroundColor="var(--background-secondary)",n.style.marginBottom="20px",n.style.marginTop="20px";const i=o.createDiv("add-command-button-container");i.style.padding="16px",i.style.borderRadius="8px",i.style.backgroundColor="var(--background-secondary)",i.style.marginBottom="20px",i.style.marginTop="20px",i.style.display="flex",i.style.gap="10px";const a=i.createEl("button",{text:v("Add Format Command")});a.addClass("mod-cta"),a.addEventListener("click",()=>{new $o(this.app,this.plugin,null).open()});const s=i.createEl("button",{text:v("Add Regex Command")});s.addClass("mod-cta"),s.addEventListener("click",()=>{new Bo(this.app,this.plugin,null).open()}),this.plugin.settings.customCommands.forEach((t,o)=>{const i=new e.Setting(n).setName(t.name),a=createFragment();let s=`${v("ID")}: ${t.id}`;t.useRegex?s+=`, ${v("Pattern")}: ${t.regexPattern}`:s+=`, ${v("Prefix")}: ${t.prefix}, ${v("Suffix")}: ${t.suffix}`,a.createSpan({text:s});const r=a.createSpan({cls:"command-type-badge"});if(t.useRegex?(r.addClass("regex"),r.setText(v("Regex"))):r.setText(v("Prefix/Suffix")),i.descEl.appendChild(a),i.addButton(o=>o.setButtonText(v("Add to Toolbar")).setTooltip(v("Add this command to the toolbar.")).setButtonText(v("Add to Toolbar")).setTooltip(v("Add this command to the toolbar.")).onClick(()=>{if(this.plugin.settings.enableMultipleConfig)new _o(this.app,this.plugin,t).open();else{if(this.plugin.settings.menuCommands.some(e=>e.id===`editing-toolbar:${t.id}`))return void new e.Notice(v("This command is already in the toolbar."));const o={id:`editing-toolbar:${t.id}`,name:t.name,icon:t.icon||"obsidian-new"};this.plugin.settings.menuCommands.push(o),this.plugin.saveSettings().then(()=>{new e.Notice(v("Command added to toolbar")),dispatchEvent(new Event("editingToolbar-NewCommand")),this.plugin.reloadCustomCommands()})}})).addExtraButton(e=>{e.setIcon("pencil").setTooltip(v("Edit")).onClick(()=>{t.useRegex?new Bo(this.app,this.plugin,o).open():new $o(this.app,this.plugin,o).open()})}).addButton(t=>this.createDeleteButton(t,async()=>{const t=`editing-toolbar:${this.plugin.settings.customCommands[o].id}`;this.removeCommandFromConfig(this.plugin.settings.menuCommands,t),this.plugin.settings.enableMultipleConfig&&(this.removeCommandFromConfig(this.plugin.settings.followingCommands,t),this.removeCommandFromConfig(this.plugin.settings.topCommands,t),this.removeCommandFromConfig(this.plugin.settings.fixedCommands,t),this.plugin.settings.isLoadOnMobile&&this.removeCommandFromConfig(this.plugin.settings.mobileCommands,t)),this.plugin.settings.customCommands.splice(o,1),await this.plugin.saveSettings(),this.plugin.reloadCustomCommands(),this.display(),new e.Notice(v("Command Deleted"))})),t.icon)try{const o=i.nameEl.createSpan({cls:"editingToolbarSettingsIcon"});o.style.marginRight="8px",ue(t.icon)?o.innerHTML=t.icon:e.setIcon(o,t.icon)}catch(e){console.error("Failed to set icon:",e)}})}triggerRefresh(){setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100)}createHeader(t){const o=t.createEl("div",{cls:"editing-toolbar-header"});o.createEl("div",{cls:"editing-toolbar-title-container"}).createEl("h1",{text:"Obsidian Editing Toolbar: "+this.plugin.manifest.version,cls:"editing-toolbar-title"});const n=o.createEl("div",{cls:"editing-toolbar-info"});new e.Setting(n).setClass("editing-toolbar-fix-button").addButton(e=>{e.setIcon("wrench").setTooltip(v("Fix")).onClick(()=>{new Do(this.app,this.plugin).open()})})}getAppearanceBucket(e){const t=this.plugin.settings;t.appearanceByStyle&&"object"==typeof t.appearanceByStyle||(t.appearanceByStyle={});const o=t.appearanceByStyle;return o[e]&&"object"==typeof o[e]||(o[e]={}),o[e]}createColorSettings(t){const o=this.plugin.appearanceEditStyle||this.plugin.settings.positionStyle||"top",n=this.getAppearanceBucket(o),i=t.createDiv("custom-toolbar-container");i.style.padding="16px",i.style.borderRadius="8px",i.style.backgroundColor="var(--background-secondary)",new e.Setting(i).setName(v("Toolbar Theme")).setDesc(v("Select a preset toolbar theme, automatically setting the background color, icon color, and size for the selected style.")).addDropdown(e=>{const t={};G.forEach(e=>{t[e]="custom"===e?v("Custom Theme"):e}),e.addOptions(t),e.selectEl.options[3].disabled=!0,e.addOption("light","┌ Light"),e.addOption("dark","├ Dark"),e.addOption("vibrant","├ Vibrant"),e.addOption("minimal","├ Minimal"),e.addOption("elegant","└ Elegant"),e.setValue(n.aestheticStyle??this.plugin.settings.aestheticStyle),e.onChange(async e=>{const o=this.plugin.appearanceEditStyle||this.plugin.settings.positionStyle||"top",n=this.getAppearanceBucket(o);switch(e in t?(n.aestheticStyle=e,n.toolbarIconSize=18):n.aestheticStyle="custom",e){case"light":n.toolbarBackgroundColor="#F5F8FA",n.toolbarIconColor="#4A5568",n.toolbarIconSize=18;break;case"dark":n.toolbarBackgroundColor="#2D3033",n.toolbarIconColor="#E2E8F0",n.toolbarIconSize=18;break;case"vibrant":n.toolbarBackgroundColor="#7E57C2",n.toolbarIconColor="#FFFFFF",n.toolbarIconSize=20;break;case"minimal":n.toolbarBackgroundColor="#F8F9FA",n.toolbarIconColor="#6B7280",n.toolbarIconSize=16;break;case"elegant":n.toolbarBackgroundColor="#1A2F28",n.toolbarIconColor="#D4AF37",n.toolbarIconSize=19}const i=n.toolbarBackgroundColor??this.plugin.settings.toolbarBackgroundColor,a=n.toolbarIconColor??this.plugin.settings.toolbarIconColor,s=n.toolbarIconSize??18;document.documentElement.style.setProperty("--editing-toolbar-background-color",i),document.documentElement.style.setProperty("--editing-toolbar-icon-color",a),document.documentElement.style.setProperty("--toolbar-icon-size",`${s}px`),this.plugin.toolbarIconSize=s,this.destroyPickrs(),this.display(),await this.plugin.saveSettings(),this.triggerRefresh()})}),new e.Setting(i).setName(v("Toolbar Background Color")).setDesc(v("Set the background color of the toolbar.")).setClass("toolbar_background").then(e=>{const t=e.controlEl.createDiv({cls:"pickr-container"}),o=t.createDiv({cls:"picker"}),i=Oo.create(Zo({isView:!1,el:o,containerEl:t,swatches:["#F5F8FA","#F4F1E8","#2D3033","#1A2F28","#2A1D3B"],opacity:!0,defaultColor:n.toolbarBackgroundColor??this.plugin.settings.toolbarBackgroundColor}));this.setupPickrEvents(i,"toolbarBackgroundColor","background-color"),this.pickrs.push(i)}),new e.Setting(i).setName(v("Toolbar Icon Color")).setDesc(v("Set the color of the toolbar icon.")).setClass("toolbar_icon").then(e=>{const t=e.controlEl.createDiv({cls:"pickr-container"}),o=t.createDiv({cls:"picker"}),n=Oo.create(Zo({isView:!1,el:o,containerEl:t,swatches:["#4A5568","#D4AF37","#2D3033","#6D5846","#4C2A55"],opacity:!1,defaultColor:this.plugin.settings.toolbarIconColor}));this.pickrs.push(n),this.setupPickrEvents(n,"toolbarIconColor","icon-color")}),new e.Setting(i).setName(v("Toolbar Icon Size")).setDesc(v("Set the size of the toolbar icon (px); default: 18px")).addSlider(e=>{const t=n.toolbarIconSize??this.plugin.settings.toolbarIconSize;e.setValue(t).setLimits(12,32,1).setDynamicTooltip().onChange(async e=>{const t=this.plugin.positionStyle,o=this.plugin.appearanceEditStyle||this.plugin.settings.positionStyle||"top",n=this.getAppearanceBucket(o);n.toolbarIconSize=e,n.aestheticStyle="custom",t===o&&(this.plugin.toolbarIconSize=e,document.documentElement.style.setProperty("--toolbar-icon-size",`${e}px`)),await this.plugin.saveSettings(),this.display(),this.triggerRefresh()})});const a=i.createDiv("toolbar-preview-container");a.addClass("toolbar-preview-section"),a.style.marginTop="20px";a.createEl("h3",{text:v("Toolbar Preview (With a hypothetical command configuration.)")}).style.marginBottom="10px";const s=a.createDiv();s.classList.add("preview-toolbar-wrapper"),s.classList.add(`preview-${o}`);const r=s.createDiv();r.classList.add("editing-toolbar-preview"),r.classList.add(`preview-${o}`),r.setAttribute("id","editingToolbarModalBar");const l=n.aestheticStyle??this.plugin.settings.aestheticStyle??"default";if(this.applyAestheticStyle(r,l,o),"fixed"===o){const e=this.plugin.settings.toolbarIconSize||18,t=this.plugin.settings.cMenuNumRows||6;r.style.display="grid",r.style.gridTemplateColumns=`repeat(${t}, ${e+10}px)`,r.style.gap=`${Math.max((e-18)/4,2)}px`,r.style.margin="0 auto"}[{id:"bold",name:"Bold",icon:"bold"},{id:"italics",name:"Italics",icon:"italic"},{id:"trikethrough",name:"Strikethrough",icon:"strikethrough"},{id:"code",name:"Code",icon:"code"},{id:"blockquote",name:"Blockquote",icon:"quote-glyph"},{id:"insert-link",name:"Link",icon:"link"},{id:"left-sidebar",name:"Left sidebar",icon:"lucide-panel-left"},{id:"editor:insert-embed",name:"Add embed",icon:"note-glyph"},{id:"editor:insert-link",name:"Insert markdown link",icon:"link-glyph"},{id:"editor:insert-tag",name:"Add tag",icon:"price-tag-glyph"},{id:"editor:insert-wikilink",name:"Add internal link",icon:"bracket-glyph"},{id:"editor:toggle-code",name:"Code",icon:"code-glyph"},{id:"editor:toggle-blockquote",name:"Blockquote",icon:"lucide-text-quote"},{id:"editor:toggle-checklist-status",name:"Checklist status",icon:"checkbox-glyph"},{id:"editor:toggle-comments",name:"Comment",icon:"percent-sign-glyph"},{id:"editor:insert-callout",name:"Insert Callout",icon:"lucide-quote"},{id:"editor:insert-mathblock",name:"MathBlock",icon:"lucide-sigma-square"},{id:"editor:insert-table",name:"Insert Table",icon:"lucide-table"}].forEach(t=>{const o=new e.ButtonComponent(r);o.setClass("editingToolbarCommandItem"),o.buttonEl.classList.add("preview-button"),o.setTooltip(v(t.name)),t.icon&&e.setIcon(o.buttonEl,t.icon)});const c="custom"===l,d=n.toolbarBackgroundColor??this.plugin.settings.toolbarBackgroundColor,u=n.toolbarIconColor??this.plugin.settings.toolbarIconColor,m=n.toolbarIconSize??this.plugin.settings.toolbarIconSize??18;c&&d?r.style.backgroundColor=d:r.style.removeProperty("background-color");r.querySelectorAll("svg").forEach(e=>{c&&u?e.style.color=u:e.style.removeProperty("color"),e.style.width=`${m}px`,e.style.height=`${m}px`})}createCommandList(t){let o=[];if(this.plugin.settings.enableMultipleConfig)switch(this.currentEditingConfig){case"mobile":o=this.plugin.settings.mobileCommands;break;case"following":o=this.plugin.settings.followingCommands;break;case"top":o=this.plugin.settings.topCommands;break;case"fixed":o=this.plugin.settings.fixedCommands;break;default:o=this.plugin.settings.menuCommands}else o=this.plugin.settings.menuCommands;const n=t.createEl("div",{cls:"editingToolbarSettingsTabsContainer"});let i="";co.create(n,{group:"item",animation:500,draggable:".setting-item",ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",dragoverBubble:!1,forceFallback:!0,fallbackOnBody:!0,swapThreshold:.7,fallbackClass:"sortable-fallback",easing:"cubic-bezier(1, 0, 0, 1)",delay:800,delayOnTouchOnly:!0,touchStartThreshold:5,filter:".setting-item-control button, .dropdown, .editingToolbarMenuTypeDropdown",preventOnFilter:!1,onChoose:function(e){e.item.classList.add("sortable-chosen-feedback")},onUnchoose:function(e){e.item.classList.remove("sortable-chosen-feedback")},onSort:e=>{if(e.from.className===e.to.className){const t=o,[n]=t.splice(e.oldIndex,1);if(t.splice(e.newIndex,0,n),this.plugin.settings.enableMultipleConfig)switch(this.currentEditingConfig){case"mobile":this.plugin.settings.mobileCommands=t;break;case"following":this.plugin.settings.followingCommands=t;break;case"top":this.plugin.settings.topCommands=t;break;case"fixed":this.plugin.settings.fixedCommands=t}else this.plugin.settings.menuCommands=t;this.plugin.saveSettings()}this.triggerRefresh()},onStart:function(e){i=e.item.className}});const s=o;s.forEach((t,r)=>{const l=new e.Setting(n);if("SubmenuCommands"in t){if(l.settingEl.setAttribute("data-id",t.id),l.setClass("editingToolbarCommandItem").setClass("editingToolbarCommandsubItem").setName(this.getLocalizedCommandName(t.name)).addButton(e=>{e.setClass("editingToolbarSettingsIcon").onClick(async()=>{new w(this.plugin,t,!1,null,this.currentEditingConfig).open()}),ue(t.icon)?e.buttonEl.innerHTML=t.icon:e.setIcon(t.icon)}).addButton(e=>{e.setIcon("pencil").setTooltip(v("Change Submenu Name")).setClass("editingToolbarSettingsButton").onClick(async()=>{new S(this.app,this.plugin,t,!1,this.currentEditingConfig).open()})}).addDropdown(o=>{o.addOption("submenu",v("Button Submenu")).addOption("dropdown",v("Dropdown Menu")).setValue(t.menuType||"submenu").onChange(async o=>{t.menuType=o,this.plugin.updateCurrentCommands(s,this.currentEditingConfig),await this.plugin.saveSettings(),this.triggerRefresh(),new e.Notice(v("Menu type changed to")+": "+v("dropdown"===o?"Dropdown Menu":"Button Submenu"))}),o.selectEl.addClass("editingToolbarMenuTypeDropdown")}).addButton(e=>this.createDeleteButton(e,async()=>{s.remove(t),this.plugin.updateCurrentCommands(s,this.currentEditingConfig),await this.plugin.saveSettings(),this.display(),this.triggerRefresh(),console.log(`%cCommand '${t.name}' was removed from editingToolbar`,"color: #989cab")})),"editingToolbar-plugin:change-font-color"==t.id)return;if("editingToolbar-plugin:change-background-color"==t.id)return;const n=l.settingEl.createEl("div",{cls:"editingToolbarSettingsTabsContainer_sub"});co.create(n,{group:{name:"item",pull:!0,put:function(){return!i.includes("editingToolbarCommandsubItem")}},draggable:".setting-item",animation:150,ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",dragoverBubble:!1,fallbackOnBody:!0,swapThreshold:.7,forceFallback:!0,delay:800,delayOnTouchOnly:!0,touchStartThreshold:5,fallbackClass:"sortable-fallback",easing:"cubic-bezier(1, 0, 0, 1)",onStart:function(){},onSort:e=>{if(e.from.className===e.to.className){const t=o,n=t[r]?.SubmenuCommands;if(n){const[o]=n.splice(e.oldIndex,1);n.splice(e.newIndex,0,o),this.plugin.updateCurrentCommands(t,this.currentEditingConfig),this.plugin.saveSettings()}}else if("editingToolbarSettingsTabsContainer"===e.to.className){const t=o,n=e.target.parentElement?.dataset?.id;if(!n)return void console.error("Cannot find parent dataset id");const i=Xo(n,t);if(-1===i||!t[i])return void console.error("Cannot find parent command:",n);const a=t[i].SubmenuCommands;if(!a||!Array.isArray(a)||e.oldIndex<0||e.oldIndex>=a.length)return void console.error("Invalid drag operation");const[s]=a.splice(e.oldIndex,1);t.splice(e.newIndex,0,s),this.plugin.updateCurrentCommands(t,this.currentEditingConfig),this.plugin.saveSettings()}else if("editingToolbarSettingsTabsContainer"===e.from.className){const t=o,n=e.target.parentElement?.dataset?.id;if(!n)return void console.error("Cannot find target dataset id");const i=Xo(n,t);if(-1===i||!t[i])return void console.error("Cannot find target command:",n);const a=t[i].SubmenuCommands;if(!a||!Array.isArray(a)||e.oldIndex<0||e.oldIndex>=t.length)return void console.error("Invalid drag operation");const[s]=t.splice(e.oldIndex,1);a.splice(e.newIndex,0,s),this.plugin.updateCurrentCommands(t,this.currentEditingConfig),this.plugin.saveSettings()}this.triggerRefresh()}}),t.SubmenuCommands.forEach(o=>{const i=new e.Setting(n);i.setClass("editingToolbarCommandItem").addButton(e=>{e.setClass("editingToolbarSettingsIcon").onClick(async()=>{new w(this.plugin,o,!0,null,this.currentEditingConfig).open()}),ue(o?.icon)?e.buttonEl.innerHTML=o.icon:e.setIcon(o.icon)}).setName(this.getLocalizedCommandName(o.name)).addButton(e=>{e.setIcon("pencil").setTooltip(v("Change Command Name")).setClass("editingToolbarSettingsButton").onClick(async()=>{new S(this.app,this.plugin,o,!0,this.currentEditingConfig).open()})}).addButton(e=>this.createDeleteButton(e,async()=>{t.SubmenuCommands.remove(o),await this.plugin.saveSettings(),this.display(),this.triggerRefresh(),console.log(`%cCommand '${t.name}' was removed from editingToolbar`,"color: #989cab")})),i.nameEl})}else l.addButton(e=>{e.setClass("editingToolbarSettingsIcon").onClick(async()=>{new w(this.plugin,t,!1,null,this.currentEditingConfig).open()}),ue(t.icon)?e.buttonEl.innerHTML=t.icon:e.setIcon(t.icon)}),"editingToolbar-Divider-Line"==t.id&&l.setClass("editingToolbar-Divider-Line"),l.setClass("editingToolbarCommandItem").setName(this.getLocalizedCommandName(t.name)).addButton(e=>{e.setIcon("pencil").setTooltip(v("Change Command Name")).setClass("editingToolbarSettingsButton").onClick(async()=>{new S(this.app,this.plugin,t,!1,this.currentEditingConfig).open()})}).addButton(e=>{e.setIcon("editingToolbarSub").setTooltip(v("Add Submenu")).setClass("editingToolbarSettingsButton").setClass("editingToolbarSettingsButtonaddsub").onClick(async()=>{const e={id:"SubmenuCommands-"+a(1),name:"submenu",icon:"remix-Filter3Line",SubmenuCommands:[]},t=o;t.splice(r+1,0,e),this.plugin.updateCurrentCommands(t,this.currentEditingConfig),await this.plugin.saveSettings(),this.display(),this.triggerRefresh(),console.log(`%cCommand '${e.id}' add `,"color: #989cab")})}).addButton(e=>{e.setIcon("vertical-split").setTooltip(v("Add Separator")).setClass("editingToolbarSettingsButton").setClass("editingToolbarSettingsButtonaddsub").onClick(async()=>{const e={id:"editingToolbar-Divider-Line",name:v("Vertical Split"),icon:"vertical-split"},t=o;t.splice(r+1,0,e),this.plugin.updateCurrentCommands(t,this.currentEditingConfig),await this.plugin.saveSettings(),this.display(),this.triggerRefresh()})}).addButton(e=>this.createDeleteButton(e,async()=>{s.remove(t),this.plugin.updateCurrentCommands(s,this.currentEditingConfig),await this.plugin.saveSettings(),this.display(),this.triggerRefresh(),console.log(`%cCommand '${t.name}' was removed from editingToolbar`,"color: #989cab")}))})}setupPickrEvents(e,t,o){e.on("save",e=>{const n=e.toHEXA().toString(),i=this.plugin.positionStyle,a=this.plugin.appearanceEditStyle||this.plugin.settings.positionStyle||i||"top";if("toolbarBackgroundColor"===t||"toolbarIconColor"===t){const e=this.getAppearanceBucket(a);e[t]=n,i===a&&document.documentElement.style.setProperty(`--editing-toolbar-${o}`,n),"custom"!==e.aestheticStyle&&(e.aestheticStyle="custom"),this.display(),this.triggerRefresh()}else this.plugin.settings[t]=n;this.plugin.saveSettings()})}destroyPickrs(){this.pickrs.forEach(e=>{e&&e.destroyAndRemove()}),this.pickrs=[]}hide(){this.destroyPickrs(),this.triggerRefresh()}removeCommandFromConfig(e,t){if(e)for(let o=e.length-1;o>=0;o--)e[o].id!==t?e[o].SubmenuCommands&&this.removeCommandFromConfig(e[o].SubmenuCommands,t):e.splice(o,1)}displayAISettings(t){const o=t.createDiv("editing-toolbar-ai-grid"),n=this.plugin.settings.ai.enabled,i=n&&this.plugin.settings.ai.enableInlineCompletion,a=i&&"auto"===this.plugin.settings.ai.completionTrigger,s=n&&this.plugin.settings.ai.enableCustomModel,r=this.plugin.settings.ai.pkmerModelRouting.mode,l=e=>{switch(e){case"04-fast":return v("Light model");case"03-agent":return v("Reasoning model");default:return e}},c=e=>(A.forEach(t=>{e.addOption(t.value,l(t.value))}),e),d=e=>{const t=e.collapsible?o.createEl("details",{cls:"editing-toolbar-ai-card editing-toolbar-ai-disclosure"}):o.createDiv("editing-toolbar-ai-card");e.collapsible&&e.open&&(t.open=!0);const n=(e.collapsible?t.createEl("summary",{cls:"editing-toolbar-ai-card-summary"}):t.createDiv("editing-toolbar-ai-card-summary editing-toolbar-ai-card-summary-static")).createDiv("editing-toolbar-ai-card-header"),i=n.createDiv("editing-toolbar-ai-card-copy");if(i.createDiv({cls:"editing-toolbar-ai-card-title",text:e.title}),i.createDiv({cls:"editing-toolbar-ai-card-desc",text:e.desc}),e.toggle){const{toggle:t}=e,o=n.createEl("div",{cls:"editing-toolbar-ai-card-toggle checkbox-container"});t.value&&o.addClass("is-enabled"),o.addEventListener("click",e=>{e.stopPropagation();const n=!o.hasClass("is-enabled");n?o.addClass("is-enabled"):o.removeClass("is-enabled"),t.onChange(n)})}else if(e.headerDropdown){const{headerDropdown:t}=e,o=n.createEl("select",{cls:"editing-toolbar-ai-card-header-select dropdown"});t.options.forEach(e=>{const n=o.createEl("option",{text:e.label});n.value=e.value,e.value===t.value&&(n.selected=!0)}),o.addEventListener("click",e=>e.stopPropagation()),o.addEventListener("change",e=>{t.onChange(e.target.value)})}else e.badge&&n.createDiv({cls:"editing-toolbar-ai-card-badge",text:e.badge});return t.createDiv("editing-toolbar-ai-card-body")};if(d({title:v("AI Editor"),desc:v("Enable AI editor features such as inline completion and selection rewrite."),toggle:{value:this.plugin.settings.ai.enabled,onChange:async e=>{e?await this.plugin.aiManager.requestEnableAIWithConsent("settings"):await this.plugin.aiManager.disableAI(),this.display()}}}),n){const t=d({title:v("PKMer AI"),desc:v("Log in to PKMer AI to get free AI features without manual model setup."),badge:this.plugin.settings.ai.pkmer.userInfo?v("Logged in"):v("Not logged in")}),o=document.createDocumentFragment();if(o.append(this.plugin.aiManager.getPKMerStatusText()),void 0!==this.plugin.settings.ai.pkmer.userInfo?.ai_quota?.quota){o.append(" ");const e=document.createElement("a");e.textContent=v("More Quota"),e.href=function(e=E()){return I(e)?Yo:Go}(),e.target="_blank",e.rel="noopener noreferrer",o.appendChild(e)}if(new e.Setting(t).setDesc(o).addButton(e=>{this.plugin.settings.ai.pkmer.userInfo?e.setButtonText(v("Logout")).onClick(async()=>{await this.plugin.aiManager.logoutFromPKMer(),this.display()}):e.setButtonText(v("Login")).setCta().onClick(async()=>{await this.plugin.aiManager.loginWithPKMer(),this.display()})}).addButton(e=>{this.plugin.settings.ai.pkmer.userInfo?e.setButtonText(v("Check Quota")).onClick(async()=>{await this.plugin.aiManager.refreshPKMerQuota(),this.display()}):e.buttonEl.style.display="none"}),!this.plugin.settings.ai.pkmer.userInfo){const e=t.createDiv({cls:"editing-toolbar-ai-note"});e.appendText(`${v("Need a PKMer AI account?")} `);const o=e.createEl("a",{text:v("Open PKMer AI")});o.href=function(e=E()){return I(e)?Ko:Go}(),o.target="_blank",o.rel="noopener noreferrer"}const n=t.createDiv({cls:"editing-toolbar-ai-note",text:v("Checking current AI route...")});this.plugin.aiManager.getProviderRouteStatusText().then(e=>{n.setText(e)});const u=d({title:v("Editor Features"),desc:v("Configure inline completion and rewrite after your AI provider is ready."),toggle:{value:this.plugin.settings.ai.enableInlineCompletion,onChange:async e=>{this.plugin.settings.ai.enableInlineCompletion=e,await this.plugin.saveSettings(),this.display()}}});i&&(new e.Setting(u).setName(v("Completion Mode")).setDesc(v("Choose whether completion is triggered manually or automatically after a short pause.")).addDropdown(e=>{e.addOption("manual",v("Manual")).addOption("auto",v("Auto")).setValue(this.plugin.settings.ai.completionTrigger).onChange(async e=>{this.plugin.settings.ai.completionTrigger=e,await this.plugin.saveSettings(),this.display()})}),"manual"===this.plugin.settings.ai.completionTrigger&&new e.Setting(u).setName(v("Manual Completion Shortcut")).setDesc(v("Default shortcut is Ctrl+J. You can customize it in Obsidian Hotkeys.")).addButton(e=>{e.setButtonText(v("Open Hotkey Settings")).onClick(()=>{this.app.setting.open(),this.app.setting.openTabById("hotkeys")})}),a&&new e.Setting(u).setName(v("Completion Delay (ms)")).setDesc(v("Delay before auto-triggering inline completion.")).addText(e=>{e.setValue(String(this.plugin.settings.ai.completionDelay)).onChange(async e=>{const t=Number.parseInt(e,10);!Number.isNaN(t)&&t>=0&&(this.plugin.settings.ai.completionDelay=t,await this.plugin.saveSettings())})}));const m=d({title:v("PKMer Model"),desc:v("Choose models by task."),headerDropdown:{options:[{value:"smart",label:v("Default")},{value:"manual",label:v("Manual")}],value:r,onChange:async e=>{this.plugin.settings.ai.pkmerModelRouting.mode=e,await this.plugin.saveSettings(),this.display()}},collapsible:!0,open:"manual"===r});if("smart"===r){const e=m.createDiv({cls:"editing-toolbar-ai-note"});e.createDiv({text:`${v("Completion")}: ${l(P(this.plugin.settings.ai,"completion"))}`}),e.createDiv({text:`${v("Rewrite")}: ${l(P(this.plugin.settings.ai,"rewrite"))}`}),e.createDiv({text:`${v("Reasoning")}: ${l(P(this.plugin.settings.ai,"reasoning"))}`}),e.createDiv({text:`${v("Structured")}: ${l(P(this.plugin.settings.ai,"artifact"))}`})}else new e.Setting(m).setName(v("Completion")).setDesc(v("Used for inline completion.")).addDropdown(e=>{c(e).setValue(this.plugin.settings.ai.pkmerModelRouting.completion).onChange(async e=>{this.plugin.settings.ai.pkmerModelRouting.completion=e,await this.plugin.saveSettings()})}),new e.Setting(m).setName(v("Rewrite")).setDesc(v("Used for normal rewrite.")).addDropdown(e=>{c(e).setValue(this.plugin.settings.ai.pkmerModelRouting.rewrite).onChange(async e=>{this.plugin.settings.ai.pkmerModelRouting.rewrite=e,await this.plugin.saveSettings()})}),new e.Setting(m).setName(v("Reasoning")).setDesc(v("Used for explain, summarize, and custom prompts.")).addDropdown(e=>{c(e).setValue(this.plugin.settings.ai.pkmerModelRouting.reasoning).onChange(async e=>{this.plugin.settings.ai.pkmerModelRouting.reasoning=e,await this.plugin.saveSettings()})}),new e.Setting(m).setName(v("Structured")).setDesc(v("Used for frontmatter and canvas.")).addDropdown(e=>{c(e).setValue(this.plugin.settings.ai.pkmerModelRouting.artifact).onChange(async e=>{this.plugin.settings.ai.pkmerModelRouting.artifact=e,await this.plugin.saveSettings()})});m.createDiv({cls:"editing-toolbar-ai-note",text:v("PKMer route only.")});const p=d({title:v("Custom Model (Optional)"),desc:v("Custom model is used automatically when PKMer AI is unavailable."),toggle:{value:this.plugin.settings.ai.enableCustomModel,onChange:async e=>{this.plugin.settings.ai.enableCustomModel=e,await this.plugin.saveSettings(),this.display()}}});if(s){const t=this.plugin.settings.ai.customModel.apiFormat??"openai-compatible",o="ollama"===t,n=this.plugin.settings.ai.customModel.baseUrl.trim(),i=o&&this.cachedCustomOllamaModelsBaseUrl===n?this.cachedCustomOllamaModels:[],a=o&&this.cachedCustomOllamaModelsBaseUrl===n?this.cachedCustomOllamaModelsError:"",s=this.plugin.aiManager.hasSecureStorage()?this.plugin.aiManager.hasCustomModelApiKey()?v("Stored securely in Obsidian secret storage."):v("Will be stored securely in Obsidian secret storage."):v("Current Obsidian version does not support secure secret storage."),r=o?`${v("Optional for Ollama. Leave empty unless your gateway requires authentication.")} ${s}`.trim():s;if(new e.Setting(p).setName(v("Custom API Format")).setDesc(v("Choose whether the custom model uses an OpenAI-compatible endpoint or the native Ollama API.")).addDropdown(e=>{e.addOption("openai-compatible",v("OpenAI-compatible")).addOption("ollama",v("Ollama")).setValue(t).onChange(async e=>{this.plugin.settings.ai.customModel.apiFormat=e,await this.plugin.saveSettings(),this.display()})}),new e.Setting(p).setName(v("Custom API Base URL")).setDesc(v(o?"Native Ollama endpoint. The root URL, /api, /api/chat, or /api/generate are all supported.":"OpenAI-compatible endpoint for your own provider.")).addText(e=>{e.setPlaceholder(o?"http://127.0.0.1:11434":"https://api.openai.com").setValue(this.plugin.settings.ai.customModel.baseUrl).onChange(async e=>{this.plugin.settings.ai.customModel.baseUrl=e.trim(),await this.plugin.saveSettings()})}),new e.Setting(p).setName(v("Custom Model Name")).setDesc(v("Model identifier used for inline completion and rewrite requests.")).addText(e=>{e.setPlaceholder(o?"qwen2.5:7b":"gpt-4o-mini").setValue(this.plugin.settings.ai.customModel.model).onChange(async e=>{this.plugin.settings.ai.customModel.model=e.trim(),await this.plugin.saveSettings()})}),o){const t=a?`${v("Choose a detected Ollama model to fill the model field.")} ${a}`.trim():v("Choose a detected Ollama model to fill the model field.");new e.Setting(p).setName(v("Detected Ollama Models")).setDesc(i.length>0?t:v("Fetch available models from your Ollama service.")).addDropdown(e=>{e.addOption("",v("Select a detected model")),i.forEach(t=>{e.addOption(t,t)});const t=this.plugin.settings.ai.customModel.model.trim();t&&!i.includes(t)&&e.addOption(t,t),e.setValue(i.includes(t)?t:""),e.onChange(async e=>{e&&(this.plugin.settings.ai.customModel.model=e,await this.plugin.saveSettings(),this.display())})}).addButton(e=>{e.setButtonText(v("Refresh")).onClick(async()=>{e.setDisabled(!0),e.setButtonText(v("Loading...")),await this.refreshCustomOllamaModels()})})}new e.Setting(p).setName(v("Custom API Key")).setDesc(r).addText(e=>{e.inputEl.type="password",e.setPlaceholder(this.plugin.aiManager.hasCustomModelApiKey()?v("Stored securely"):v(o?"Optional":"Enter API key")),e.setValue("").onChange(async e=>{e.trim()?this.plugin.aiManager.saveCustomModelApiKey(e):this.plugin.aiManager.clearCustomModelApiKey(),await this.plugin.saveSettings()})}).addButton(e=>{e.setButtonText(v("Clear")).onClick(async()=>{this.plugin.aiManager.clearCustomModelApiKey(),await this.plugin.saveSettings(),this.display()})}),new e.Setting(p).setName(v("Test Connection")).setDesc(v("Send a lightweight request to verify your custom model settings.")).addButton(e=>{e.setButtonText(v("Test Connection")).onClick(async()=>{e.setDisabled(!0),e.setButtonText(v("Testing..."));try{await this.plugin.aiManager.testCustomModelConnection()}finally{e.setDisabled(!1),e.setButtonText(v("Test Connection"))}})});const l=p.createEl("details",{cls:"editing-toolbar-ai-inline-disclosure"});l.createEl("summary",{cls:"editing-toolbar-ai-inline-summary",text:v("More Options")});const c=l.createDiv("editing-toolbar-ai-inline-body");new e.Setting(c).setName(v("Temperature")).setDesc(v("Lower values are more stable; higher values are more creative.")).addText(e=>{e.setValue(String(this.plugin.settings.ai.customModel.temperature)).onChange(async e=>{const t=Number.parseFloat(e);!Number.isNaN(t)&&t>=0&&(this.plugin.settings.ai.customModel.temperature=t,await this.plugin.saveSettings())})})}const h=d({title:v("Custom Prompt Templates"),desc:v("Manage quick-access templates for custom AI prompts"),collapsible:!0,open:!0}),g=h.createDiv({cls:"setting-item-description"});g.style.marginBottom="12px",g.style.padding="8px 12px",g.style.background="var(--background-secondary)",g.style.borderRadius="6px",g.style.fontSize="12px",g.innerHTML=`\n <strong>${v("Available Variables")}:</strong><br>\n <code>{{selection}}</code> - ${v("Selected text")} |\n <code>{{file:path}}</code> - ${v("Document path")} |\n <code>{{file:content}}</code> - ${v("Full document content")}<br>\n <code>{{date}}</code> - ${v("Date")} |\n <code>{{time}}</code> - ${v("Time")} |\n <code>{{datetime}}</code> - ${v("Date and time")} |\n <code>{{vault:name}}</code> - ${v("Vault name")}<br>\n <strong>${v("Linked note references")}:</strong> ${v("Use [[note name]] to reference the content of other notes.")}\n `;(this.plugin.settings.ai.customPromptTemplates||[]).forEach((t,o)=>{new e.Setting(h).setName(t.name).setDesc(t.prompt.length>80?t.prompt.substring(0,80)+"...":t.prompt).addButton(e=>{e.setButtonText(v("Edit")).onClick(()=>{this.openTemplateEditor(t,o)})}).addButton(e=>{e.setButtonText(v("Delete")).setWarning().onClick(async()=>{this.plugin.settings.ai.customPromptTemplates.splice(o,1),await this.plugin.saveSettings(),this.display()})})}),new e.Setting(h).addButton(e=>{e.setButtonText(v("Add Template")).setCta().onClick(()=>{this.openTemplateEditor(null,-1)})})}}openTemplateEditor(t,o){const n=new e.Modal(this.app);n.titleEl.setText(v(t?"Edit Template":"Add Template"));const{contentEl:i}=n;let a=t?.name||"",s=t?.prompt||"";new e.Setting(i).setName(v("Template Name")).addText(e=>{e.setPlaceholder(v("Enter template name")).setValue(a).onChange(e=>{a=e}),e.inputEl.style.width="100%"}),new e.Setting(i).setName(v("Prompt Content")).addTextArea(e=>{e.setPlaceholder(v("Enter prompt content")).setValue(s).onChange(e=>{s=e}),e.inputEl.style.width="100%",e.inputEl.style.minHeight="120px"}),new e.Setting(i).addButton(e=>{e.setButtonText(v("Cancel")).onClick(()=>{n.close()})}).addButton(i=>{i.setButtonText(v("Save")).setCta().onClick(async()=>{if(!a.trim()||!s.trim())return void new e.Notice(v("Template name and content cannot be empty"));if(o<0&&this.plugin.settings.ai.customPromptTemplates.length>=9)return void new e.Notice(v("Maximum 10 templates allowed"));const i={id:t?.id||`template-${Date.now()}`,name:a.trim(),prompt:s.trim(),icon:t?.icon||"lucide-sparkles"};o>=0?this.plugin.settings.ai.customPromptTemplates[o]=i:this.plugin.settings.ai.customPromptTemplates.push(i),await this.plugin.saveSettings(),n.close(),this.display()})}),n.open()}displayImportExportSettings(t){const o=t.createDiv("import-export-container");o.style.padding="16px",o.style.borderRadius="8px",o.style.backgroundColor="var(--background-secondary)",o.style.marginBottom="20px",new e.Setting(o).setName(v("Export Configuration")).setDesc(v("Export your toolbar configuration to share with others.")).addButton(e=>e.setButtonText(v("Export")).setCta().onClick(()=>{new zo(this.app,this.plugin,"export").open()})),new e.Setting(o).setName(v("Import Configuration")).setDesc(v("Import toolbar configuration from JSON.")).addButton(e=>e.setButtonText(v("Import")).setCta().onClick(()=>{new zo(this.app,this.plugin,"import").open()}));const n=t.createDiv("import-export-info");n.style.marginTop="20px",n.style.padding="16px",n.style.borderRadius="8px",n.style.backgroundColor="var(--background-secondary)",n.createEl("h3",{text:v("Usage Instructions"),cls:"import-export-heading"}).style.marginTop="0";const i=n.createEl("ul");i.style.paddingLeft="20px",i.createEl("li",{text:v("Export: Generate a JSON configuration that you can save or share.")}),i.createEl("li",{text:v("Import: Paste a previously exported JSON configuration.")});const a=t.createDiv("community-share-container");a.style.marginTop="20px",a.style.padding="16px",a.style.borderRadius="8px",a.style.backgroundColor="rgba(var(--color-green-rgb), 0.1)",a.style.border="1px solid rgba(var(--color-green-rgb), 0.3)",a.createEl("h3",{text:v("Join the Community"),cls:"community-heading"}).style.marginTop="0";a.createEl("p").innerHTML=v("Share your toolbar settings and styles in our")+' <a href="https://github.com/PKM-er/obsidian-editing-toolbar/discussions/categories/show-and-tell" target="_blank" rel="noopener noreferrer">Show and Tell</a> ',a.createEl("p",{text:v("Get inspired by what others have created or showcase your own customizations.")});const s=t.createDiv("import-export-warning");s.style.marginTop="20px",s.style.padding="16px",s.style.borderRadius="8px",s.style.backgroundColor="rgba(var(--color-red-rgb), 0.1)",s.style.border="1px solid rgba(var(--color-red-rgb), 0.3)",s.createEl("p",{text:v("Warning: Importing configuration will overwrite your current settings. Consider exporting your current configuration first as a backup."),cls:"warning-text"}).style.margin="0"}applyAestheticStyle(e,t,o){Object.values(this.aestheticStyleMap).forEach(t=>{e.removeClass(t)});const n=this.aestheticStyleMap[t]||this.aestheticStyleMap.default;e.addClass(n);const i=this.aestheticStyleMap[o]||this.aestheticStyleMap.top;e.addClass(i)}getCommandsArrayByType(e){switch(e){case"following":return this.plugin.settings.followingCommands;case"top":return this.plugin.settings.topCommands;case"fixed":return this.plugin.settings.fixedCommands;case"mobile":return this.plugin.settings.mobileCommands;default:return this.plugin.settings.menuCommands}}}const en={editingToolbar:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"><path d="M19 10H5c-1.103 0-2 .897-2 2v8c0 1.103.897 2 2 2h14c1.103 0 2-.897 2-2v-8c0-1.103-.897-2-2-2zM5 20v-8h14l.002 8H5zM5 6h14v2H5zm2-4h10v2H7z" fill="currentColor"/></svg>',editingToolbarSub:'<svg t="1661526346488" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="16880" ><path d="M597.333333 85.333333h-341.333333C187.733333 85.333333 128 140.8 128 213.333333v597.333334c0 72.533333 59.733333 128 128 128h426.666667c72.533333 0 128-55.466667 128-128V298.666667l-213.333334-213.333334z m170.666667 725.333334c0 46.933333-38.4 85.333333-85.333333 85.333333H256c-46.933333 0-85.333333-38.4-85.333333-85.333333V213.333333c0-46.933333 38.4-85.333333 85.333333-85.333333h298.666667v213.333333h213.333333v469.333334z m-320-234.666667h128c12.8 0 21.333333 8.533333 21.333333 21.333333s-8.533333 21.333333-21.333333 21.333334h-128v128c0 12.8-8.533333 21.333333-21.333333 21.333333s-21.333333-8.533333-21.333334-21.333333v-128h-128c-12.8 0-21.333333-8.533333-21.333333-21.333334s8.533333-21.333333 21.333333-21.333333h128v-128c0-12.8 8.533333-21.333333 21.333334-21.333333s21.333333 8.533333 21.333333 21.333333v128z" fill="#8a8a8a" p-id="16881"></path></svg>',editingToolbarAdd:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="white" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"><path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4z" fill="currentColor"/><path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10s10-4.486 10-10S17.514 2 12 2zm0 18c-4.411 0-8-3.589-8-8s3.589-8 8-8s8 3.589 8 8s-3.589 8-8 8z" fill="currentColor"/></svg>',editingToolbarDelete:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="white" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"><path d="M5 20a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8h2V6h-4V4a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2v2H3v2h2zM9 4h6v2H9zM8 8h9v12H7V8z" fill="var(--text-error)"/><path d="M9 10h2v8H9zm4 0h2v8h-2z" fill="var(--text-error)"/></svg>',editingToolbarReload:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke="white" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"><path d="M19 10H5c-1.103 0-2 .897-2 2v8c0 1.103.897 2 2 2h14c1.103 0 2-.897 2-2v-8c0-1.103-.897-2-2-2zM5 20v-8h14l.002 8H5zM5 6h14v2H5zm2-4h10v2H7z" fill="currentColor"/></svg>',"codeblock-glyph":'<svg xmlns="http://www.w3.org/2000/svg" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path fill="currentColor" d="M20 3H4c-1.103 0-2 .897-2 2v14c0 1.103.897 2 2 2h16c1.103 0 2-.897 2-2V5c0-1.103-.897-2-2-2zM4 19V7h16l.002 12H4z" fill="currentColor"/><path d="M9.293 9.293L5.586 13l3.707 3.707l1.414-1.414L8.414 13l2.293-2.293zm5.414 0l-1.414 1.414L15.586 13l-2.293 2.293l1.414 1.414L18.414 13z"/></svg>',"underline-glyph":'<svg xmlns="http://www.w3.org/2000/svg" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 1024 1024"><path fill="currentColor" d="M824 804H200c-4.4 0-8 3.4-8 7.6v60.8c0 4.2 3.6 7.6 8 7.6h624c4.4 0 8-3.4 8-7.6v-60.8c0-4.2-3.6-7.6-8-7.6zm-312-76c69.4 0 134.6-27.1 183.8-76.2C745 602.7 772 537.4 772 468V156c0-6.6-5.4-12-12-12h-60c-6.6 0-12 5.4-12 12v312c0 97-79 176-176 176s-176-79-176-176V156c0-6.6-5.4-12-12-12h-60c-6.6 0-12 5.4-12 12v312c0 69.4 27.1 134.6 76.2 183.8C377.3 701 442.6 728 512 728z"/></svg>',"superscript-glyph":'<svg xmlns="http://www.w3.org/2000/svg" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path fill="currentColor"d="M16 7.41L11.41 12L16 16.59L14.59 18L10 13.41L5.41 18L4 16.59L8.59 12L4 7.41L5.41 6L10 10.59L14.59 6L16 7.41M21.85 9h-4.88V8l.89-.82c.76-.64 1.32-1.18 1.7-1.63c.37-.44.56-.85.57-1.23a.884.884 0 0 0-.27-.7c-.18-.19-.47-.28-.86-.29c-.31.01-.58.07-.84.17l-.66.39l-.45-1.17c.27-.22.59-.39.98-.53S18.85 2 19.32 2c.78 0 1.38.2 1.78.61c.4.39.62.93.62 1.57c-.01.56-.19 1.08-.54 1.55c-.34.48-.76.93-1.27 1.36l-.64.52v.02h2.58V9z"/></svg>',"subscript-glyph":'<svg xmlns="http://www.w3.org/2000/svg" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path fill="currentColor" d="M16 7.41L11.41 12L16 16.59L14.59 18L10 13.41L5.41 18L4 16.59L8.59 12L4 7.41L5.41 6L10 10.59L14.59 6L16 7.41m5.85 13.62h-4.88v-1l.89-.8c.76-.65 1.32-1.19 1.7-1.63c.37-.44.56-.85.57-1.24a.898.898 0 0 0-.27-.7c-.18-.16-.47-.28-.86-.28c-.31 0-.58.06-.84.18l-.66.38l-.45-1.17c.27-.21.59-.39.98-.53s.82-.24 1.29-.24c.78.04 1.38.25 1.78.66c.4.41.62.93.62 1.57c-.01.56-.19 1.08-.54 1.55c-.34.47-.76.92-1.27 1.36l-.64.52v.02h2.58v1.35z"/></svg>',"bot-glyph":'<svg xmlns="http://www.w3.org/2000/svg" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path fill="currentColor" d="M21.928 11.607c-.202-.488-.635-.605-.928-.633V8c0-1.103-.897-2-2-2h-6V4.61c.305-.274.5-.668.5-1.11a1.5 1.5 0 0 0-3 0c0 .442.195.836.5 1.11V6H5c-1.103 0-2 .897-2 2v2.997l-.082.006A1 1 0 0 0 1.99 12v2a1 1 0 0 0 1 1H3v5c0 1.103.897 2 2 2h14c1.103 0 2-.897 2-2v-5a1 1 0 0 0 1-1v-1.938a1.006 1.006 0 0 0-.072-.455zM5 20V8h14l.001 3.996L19 12v2l.001.005l.001 5.995H5z" fill="currentColor"/><ellipse cx="8.5" cy="12" rx="1.5" ry="2" fill="currentColor"/><ellipse cx="15.5" cy="12" rx="1.5" ry="2" fill="currentColor"/><path d="M8 16h8v2H8z" fill="currentColor"/></svg>',"header-1":'<svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" fill="currentColor"><path fill="currentColor" d="M835.626667 349.397333A42.666667 42.666667 0 0 1 853.333333 384v426.666667a42.666667 42.666667 0 0 1-85.333333 0v-367.488l-71.850667 23.978666a42.666667 42.666667 0 0 1-26.965333-80.981333l128-42.666667a42.666667 42.666667 0 0 1 38.4 5.888zM128 170.666667a42.666667 42.666667 0 0 1 42.666667 42.666666v256h256V213.333333a42.666667 42.666667 0 1 1 85.333333 0v597.333334a42.666667 42.666667 0 1 1-85.333333 0v-256H170.666667v256a42.666667 42.666667 0 1 1-85.333334 0V213.333333a42.666667 42.666667 0 0 1 42.666667-42.666666z" p-id="1635"></path></svg>',"header-2":'<svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" fill="currentColor"><path d="M768 426.666667a85.333333 85.333333 0 0 0-85.333333 85.333333v21.333333a42.666667 42.666667 0 1 1-85.333334 0V512a170.666667 170.666667 0 0 1 170.666667-170.666667h7.338667a163.328 163.328 0 0 1 115.498666 278.869334L742.997333 768H896a42.666667 42.666667 0 1 1 0 85.333333h-256a42.666667 42.666667 0 0 1-30.165333-72.832l220.672-220.672A77.994667 77.994667 0 0 0 775.338667 426.666667H768zM128 170.666667a42.666667 42.666667 0 0 1 42.666667 42.666666v256h256V213.333333a42.666667 42.666667 0 1 1 85.333333 0v597.333334a42.666667 42.666667 0 1 1-85.333333 0v-256H170.666667v256a42.666667 42.666667 0 1 1-85.333334 0V213.333333a42.666667 42.666667 0 0 1 42.666667-42.666666z" p-id="1791"></path></svg>',"header-3":'<svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" fill="currentColor"><path d="M597.333333 384a42.666667 42.666667 0 0 1 42.666667-42.666667h256a42.666667 42.666667 0 0 1 30.165333 72.832l-105.941333 105.984A170.752 170.752 0 0 1 768 853.333333a170.666667 170.666667 0 0 1-160.938667-113.877333 42.666667 42.666667 0 0 1 80.469334-28.373333A85.333333 85.333333 0 1 0 768 597.333333h-42.666667a42.666667 42.666667 0 0 1-30.165333-72.832L793.002667 426.666667H640a42.666667 42.666667 0 0 1-42.666667-42.666667zM128 170.666667a42.666667 42.666667 0 0 1 42.666667 42.666666v256h256V213.333333a42.666667 42.666667 0 1 1 85.333333 0v597.333334a42.666667 42.666667 0 1 1-85.333333 0v-256H170.666667v256a42.666667 42.666667 0 1 1-85.333334 0V213.333333a42.666667 42.666667 0 0 1 42.666667-42.666666z" p-id="1949"></path></svg>',"header-4":'<svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" fill="currentColor"><path d="M780.714667 343.296a42.666667 42.666667 0 0 1 28.032 53.418667L719.36 682.666667H896a42.666667 42.666667 0 1 1 0 85.333333h-234.666667a42.666667 42.666667 0 0 1-40.704-55.381333l106.666667-341.333334a42.666667 42.666667 0 0 1 53.418667-27.989333z" p-id="2107"></path><path d="M853.333333 554.666667a42.666667 42.666667 0 0 1 42.666667 42.666666v213.333334a42.666667 42.666667 0 1 1-85.333333 0v-213.333334a42.666667 42.666667 0 0 1 42.666666-42.666666zM128 170.666667a42.666667 42.666667 0 0 1 42.666667 42.666666v256h256V213.333333a42.666667 42.666667 0 1 1 85.333333 0v597.333334a42.666667 42.666667 0 1 1-85.333333 0v-256H170.666667v256a42.666667 42.666667 0 1 1-85.333334 0V213.333333a42.666667 42.666667 0 0 1 42.666667-42.666666z" p-id="2108"></path></svg>',"header-5":'\n <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" fill="currentColor"><path d="M683.946667 373.674667A42.666667 42.666667 0 0 1 725.333333 341.333333h170.666667a42.666667 42.666667 0 1 1 0 85.333334h-137.301333l-22.016 88.234666A170.666667 170.666667 0 1 1 640 795.562667a42.666667 42.666667 0 1 1 64-56.448 85.333333 85.333333 0 1 0 0-112.896 42.666667 42.666667 0 0 1-73.386667-38.528l53.333334-214.016zM128 170.666667a42.666667 42.666667 0 0 1 42.666667 42.666666v256h256V213.333333a42.666667 42.666667 0 1 1 85.333333 0v597.333334a42.666667 42.666667 0 1 1-85.333333 0v-256H170.666667v256a42.666667 42.666667 0 1 1-85.333334 0V213.333333a42.666667 42.666667 0 0 1 42.666667-42.666666z" p-id="2264"></path></svg>',"header-6":'<svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" fill="currentColor"><path d="M831.274667 303.957333a42.666667 42.666667 0 0 1 16.725333 57.984l-83.498667 151.466667a170.453333 170.453333 0 0 1 88.746667 22.741333 169.557333 169.557333 0 0 1 62.506667 232.277334 171.093333 171.093333 0 0 1-232.96 62.165333 169.557333 169.557333 0 0 1-62.805334-231.850667l153.301334-278.016a42.666667 42.666667 0 0 1 57.984-16.768z m-20.48 306.176a85.76 85.76 0 0 0-116.736 31.018667 84.224 84.224 0 0 0 31.189333 115.456 85.76 85.76 0 0 0 116.736-31.018667 84.224 84.224 0 0 0-31.232-115.456zM128 170.666667a42.666667 42.666667 0 0 1 42.666667 42.666666v256h256V213.333333a42.666667 42.666667 0 1 1 85.333333 0v597.333334a42.666667 42.666667 0 1 1-85.333333 0v-256H170.666667v256a42.666667 42.666667 0 1 1-85.333334 0V213.333333a42.666667 42.666667 0 0 1 42.666667-42.666666z" p-id="2422"></path></svg>',"header-n":'<svg viewBox="0 0 24 24" ><path d="M2 3a1 1 0 0 0-1 1v16a1 1 0 1 0 2 0v-7h9v7a1 1 0 1 0 2 0V4a1 1 0 1 0-2 0v7H3V4a1 1 0 0 0-1-1Zm14 9a1 1 0 0 1 1.984-.177 4.099 4.099 0 0 1 1.757-.576 3.447 3.447 0 0 1 3.759 3.432V20a1 1 0 1 1-2 0v-5.32c0-.851-.73-1.519-1.578-1.442A2.114 2.114 0 0 0 18 15.344V20a1 1 0 1 1-2 0v-8Z" fill="currentColor"></path></svg>',obsidian:'<svg viewBox="0 0 100 100" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" class="logo-wireframe"><path d="M 30.91 17.52 L 34.43 35.7 M 61.44 14.41 L 62.61 0 M 34.43 35.7 L 37.57 90.47 M 81 26.39 L 61.44 14.41 L 34.43 35.7 L 65.35 100 M 62.61 0 L 30.91 17.52 L 18 45.45 L 37.57 90.47 L 65.35 100 L 70.44 89.8 L 81 26.39 L 62.61 0 Z"></path></svg>',"obsidian-new":'<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#A88BFA" d="m6.91927 14.5955c.64053-.1907 1.67255-.4839 2.85923-.5565-.71191-1.7968-.88376-3.3691-.74554-4.76905.15962-1.61678.72977-2.9662 1.28554-4.11442.1186-.24501.2326-.47313.3419-.69198.1549-.30984.3004-.60109.4365-.8953.2266-.48978.3948-.92231.4798-1.32416.0836-.39515.0841-.74806-.0148-1.08657-.099-.338982-.3093-.703864-.7093-1.1038132-.5222-.1353116-1.1017-.0165173-1.53613.3742922l-5.15591 4.638241c-.28758.25871-.47636.60929-.53406.99179l-.44455 2.94723c.69903.6179 2.42435 2.41414 3.47374 4.90644.09364.2224.1819.4505.26358.6838z"></path><path fill="#A88BFA" d="m2.97347 10.3512c-.02431.1037-.05852.205-.10221.3024l-2.724986 6.0735c-.279882.6238-.15095061 1.3552.325357 1.8457l4.288349 4.4163c2.1899-3.2306 1.87062-6.2699.87032-8.6457-.75846-1.8013-1.90801-3.2112-2.65683-3.9922z"></path><path fill="#A88BFA" d="m5.7507 23.5094c.07515.012.15135.0192.2281.0215.81383.0244 2.18251.0952 3.29249.2997.90551.1669 2.70051.6687 4.17761 1.1005 1.1271.3294 2.2886-.5707 2.4522-1.7336.1192-.8481.343-1.8075.7553-2.6869l-.0095.0033c-.6982-1.9471-1.5865-3.2044-2.5178-4.0073-.9284-.8004-1.928-1.1738-2.8932-1.3095-1.60474-.2257-3.07497.1961-4.00103.4682.55465 2.3107.38396 5.0295-1.48417 7.8441z"></path><path fill="#A88BFA" d="m17.3708 19.3102c.9267-1.3985 1.5868-2.4862 1.9352-3.0758.1742-.295.1427-.6648-.0638-.9383-.5377-.7126-1.5666-2.1607-2.1272-3.5015-.5764-1.3785-.6624-3.51876-.6673-4.56119-.0019-.39626-.1275-.78328-.3726-1.09465l-3.3311-4.23183c-.0117.19075-.0392.37998-.0788.56747-.1109.52394-.32 1.04552-.5585 1.56101-.1398.30214-.3014.62583-.4646.95284-.1086.21764-.218.4368-.3222.652-.5385 1.11265-1.0397 2.32011-1.1797 3.73901-.1299 1.31514.0478 2.84484.8484 4.67094.1333.0113.2675.0262.4023.0452 1.1488.1615 2.3546.6115 3.4647 1.5685.9541.8226 1.8163 2.0012 2.5152 3.6463z"></path></svg>'};class tn{constructor(e){this.plugin=e}init(){this.statusBarIcon=this.plugin.addStatusBarItem(),this.statusBarIcon.addClass("editingToolbar-statusbar-button"),e.setIcon(this.statusBarIcon,"editingToolbar"),this.registerClickEvent()}registerClickEvent(){this.plugin.registerDomEvent(this.statusBarIcon,"click",()=>{const e=this.statusBarIcon.parentElement.getBoundingClientRect(),t=this.statusBarIcon.getBoundingClientRect();this.showMenu(t,e)})}showMenu(t,o){const n=new e.Menu;n.addSections(["settings"]),this.addVisibilityToggle(n),this.addAestheticStyleToggle(n),n.addSections(["viewType"]),this.addViewTypeToggle(n),n.addSections(["controls"]),this.addToolbarControls(n);n.dom.addClass("editingToolbar-statusbar-menu"),n.showAtPosition({x:t.right+5,y:o.top-5})}addVisibilityToggle(t){t.addItem(t=>{t.setTitle(v("Hide & Show")),!e.requireApiVersion("0.15.0")||t.setSection("settings");const o=t.dom,n=new e.ToggleComponent(o).setValue(this.plugin.settings.cMenuVisibility).setDisabled(!0),i=async()=>{this.plugin.settings.cMenuVisibility=!this.plugin.settings.cMenuVisibility,n.setValue(this.plugin.settings.cMenuVisibility),1==this.plugin.settings.cMenuVisibility?setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100):p(this.plugin.settings.cMenuVisibility),se(this.plugin),await this.plugin.saveSettings()};t.onClick(e=>{e.preventDefault(),e.stopImmediatePropagation(),i()})}),t.addItem(t=>{t.setTitle(v("Toolbar Position")),!e.requireApiVersion("0.15.0")||t.setSection("settings"),t.setIcon("dock");const o=t.setSubmenu();o.addItem(t=>{t.setTitle(v("Top Toolbar"));const o=t.dom,n=new e.ToggleComponent(o).setValue(this.plugin.settings.enableTopToolbar||!1).setDisabled(!0);t.onClick(async e=>{e.preventDefault(),e.stopPropagation();const t=this.plugin.settings,o=this.plugin.positionStyle;t.enableTopToolbar=!t.enableTopToolbar,n.setValue(t.enableTopToolbar);let i=null;t.enableTopToolbar?i="top":"top"===o&&(i=t.enableFollowingToolbar?"following":t.enableFixedToolbar?"fixed":null),i&&i!==o&&this.plugin.onPositionStyleChange(i),await this.plugin.saveSettings(),this.plugin.handleeditingToolbar()})}),o.addItem(t=>{t.setTitle(v("Following Toolbar"));const o=t.dom,n=new e.ToggleComponent(o).setValue(this.plugin.settings.enableFollowingToolbar||!1).setDisabled(!0);t.onClick(async e=>{e.preventDefault(),e.stopPropagation();const t=this.plugin.settings,o=this.plugin.positionStyle;t.enableFollowingToolbar=!t.enableFollowingToolbar,n.setValue(t.enableFollowingToolbar);let i=null;t.enableFollowingToolbar?i="following":"following"===o&&(i=t.enableTopToolbar?"top":t.enableFixedToolbar?"fixed":null),i&&i!==o&&this.plugin.onPositionStyleChange(i),await this.plugin.saveSettings(),this.plugin.handleeditingToolbar()})}),o.addItem(t=>{t.setTitle(v("Fixed Toolbar"));const o=t.dom,n=new e.ToggleComponent(o).setValue(this.plugin.settings.enableFixedToolbar||!1).setDisabled(!0);t.onClick(async e=>{e.preventDefault(),e.stopPropagation();const t=this.plugin.settings,o=this.plugin.positionStyle;t.enableFixedToolbar=!t.enableFixedToolbar,n.setValue(t.enableFixedToolbar);let i=null;t.enableFixedToolbar?i="fixed":"fixed"===o&&(i=t.enableTopToolbar?"top":t.enableFollowingToolbar?"following":null),i&&i!==o&&this.plugin.onPositionStyleChange(i),await this.plugin.saveSettings(),this.plugin.handleeditingToolbar()})})})}addViewTypeToggle(t){const o=this.plugin.app.workspace.getActiveViewOfType(e.ItemView);if(!o)return;const n=o.getViewType();t.addItem(t=>{t.setTitle(v("Current View: ")+n),!e.requireApiVersion("0.15.0")||t.setSection("settings"),t.setIcon("layout-template");const i=t.setSubmenu(),a=X.isAllowedViewType(o);i.addItem(e=>{e.setTitle(v(a?"Disable toolbar for this view":"Enable toolbar for this view")),e.setIcon(a?"eye-off":"eye"),e.onClick(async()=>{this.plugin.settings.viewTypeSettings||(this.plugin.settings.viewTypeSettings={}),this.plugin.settings.viewTypeSettings[n]=!a,await this.plugin.saveSettings(),se(this.plugin),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100)})}),i.addItem(e=>{e.setTitle(v("Manage all view types")),e.setIcon("settings-2");const t=e.setSubmenu(),o=new Set(["markdown","canvas","thino_view","meld-encrypted-view",...Object.keys(this.plugin.settings.viewTypeSettings||{})]);Array.from(o).sort().forEach(e=>{const o=this.isViewTypeAllowed(e);t.addItem(t=>{t.setTitle(e),t.setIcon(o?"check":""),t.onClick(async()=>{this.plugin.settings.viewTypeSettings||(this.plugin.settings.viewTypeSettings={}),this.plugin.settings.viewTypeSettings[e]=!o,n===e&&(se(this.plugin),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100)),await this.plugin.saveSettings()})})})})})}isViewTypeAllowed(e){if(!this.plugin.settings.viewTypeSettings||void 0===this.plugin.settings.viewTypeSettings[e]){return["markdown","canvas","thino_view","meld-encrypted-view"].includes(e)}return this.plugin.settings.viewTypeSettings[e]}addToolbarControls(t){const o=[{icon:"plus",title:v("Add Command"),click:()=>new k(this.plugin).open()}];"fixed"===this.plugin.positionStyle&&o.push({icon:"file-sliders",title:v("Position Settings"),click:()=>new T(this.plugin.app,this.plugin).open()}),o.forEach(o=>{t.addItem(t=>{t.setIcon(o.icon),t.setTitle(o.title),t.onClick(o.click),e.requireApiVersion("0.15.0")&&t.setSection("controls")})})}addAestheticStyleToggle(t){t.addItem(t=>{t.setTitle(v("Appearance Style")),!e.requireApiVersion("0.15.0")||t.setSection("settings"),t.setIcon("cherry");const o=t.setSubmenu();G.forEach(e=>{o.addItem(t=>{t.setTitle(e),t.setIcon(this.plugin.settings.aestheticStyle===e?"check":""),t.onClick(async()=>{this.plugin.settings.aestheticStyle=e,await this.plugin.saveSettings(),se(this.plugin),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100)})})})})}}let on;class nn extends e.Modal{constructor(e){super(e.app),this.plugin=e,this.type="note",this.title="",this.content="",this.collapse="none",this.allCalloutOptions=[],this.builtInCalloutTypes=[{type:"note",aliases:[],icon:"lucide-pencil",label:"Note",color:"var(--callout-default)"},{type:"abstract",aliases:["summary","tldr"],icon:"lucide-clipboard-list",label:"Abstract",color:"var(--callout-summary)"},{type:"info",aliases:[],icon:"lucide-info",label:"Info",color:"var(--callout-info)"},{type:"todo",aliases:[],icon:"lucide-check-circle-2",label:"Todo",color:"var(--callout-todo)"},{type:"important",aliases:[],icon:"lucide-flame",label:"Important",color:"var(--callout-important)"},{type:"tip",aliases:["hint"],icon:"lucide-flame",label:"Tip",color:"var(--callout-tip)"},{type:"success",aliases:["check","done"],icon:"lucide-check",label:"Success",color:"var(--callout-success)"},{type:"question",aliases:["help","faq"],icon:"lucide-help-circle",label:"Question",color:"var(--callout-question)"},{type:"warning",aliases:["caution","attention"],icon:"lucide-alert-triangle",label:"Warning",color:"var(--callout-warning)"},{type:"failure",aliases:["fail","missing"],icon:"lucide-x",label:"Failure",color:"var(--callout-fail)"},{type:"danger",aliases:["error"],icon:"lucide-zap",label:"Danger",color:"var(--callout-error)"},{type:"bug",aliases:[],icon:"lucide-bug",label:"Bug",color:"var(--callout-bug)"},{type:"example",aliases:[],icon:"lucide-list",label:"Example",color:"var(--callout-example)"},{type:"quote",aliases:["cite"],icon:"lucide-quote",label:"Quote",color:"var(--callout-quote)"}],this.containerEl.addClass("insert-callout-modal"),this.prepareCalloutOptions();const t=this.plugin.commandsManager.getActiveEditor();if(t){const e=t.getSelection();e&&(this.content=e)}this.allCalloutOptions.find(e=>e.type===this.type)||(this.type=this.allCalloutOptions.length>0?this.allCalloutOptions[0].type:"note")}prepareCalloutOptions(){if(this.builtInCalloutTypes.forEach(e=>{this.allCalloutOptions.push({type:e.type,label:e.label,icon:e.icon,color:e.color,isAdmonition:!1}),e.aliases.forEach(t=>{this.allCalloutOptions.push({type:t,label:`${e.label} (${t})`,icon:e.icon,color:e.color,isAdmonition:!1})})}),this.plugin.admonitionDefinitions){const e=Object.values(this.plugin.admonitionDefinitions);e.length>0&&e.forEach(e=>{this.allCalloutOptions.some(t=>t.type===e.type)||this.allCalloutOptions.push({type:e.type,label:e.title||e.type.charAt(0).toUpperCase()+e.type.slice(1),icon:e.icon,color:`rgb(${e.color})`,isAdmonition:!0,sourcePlugin:"Admonition"})})}}onOpen(){this.display()}async display(){const{contentEl:t}=this;t.empty(),t.addEventListener("keydown",e=>{"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.insertButton&&this.insertButton.click())});const o=t.createDiv("callout-type-container");this.iconContainerEl=o.createDiv("callout-icon-container"),new e.Setting(o).setName(v("Callout Type")).addDropdown(e=>{const t=this.allCalloutOptions.filter(e=>!e.isAdmonition),o=this.allCalloutOptions.filter(e=>e.isAdmonition);if(t.length>0&&o.length>0){e.addOption("---separator---","---- Admonitions ----");const t=e.selectEl.options[e.selectEl.options.length-1];t&&(t.disabled=!0)}o.forEach(t=>{e.addOption(t.type,`${t.label} (Admonition)`)}),e.addOption("---separator---","---- Default ----"),t.forEach(t=>{e.addOption(t.type,t.label)}),this.allCalloutOptions.some(e=>e.type===this.type)||(this.type=this.allCalloutOptions.length>0?this.allCalloutOptions[0].type:"note"),e.setValue(this.type),e.onChange(t=>{"---separator---"!==t?(this.type=t,this.updateIconAndColor(this.iconContainerEl,t)):e.setValue(this.type)})}),this.updateIconAndColor(this.iconContainerEl,this.type),new e.Setting(t).setName(v("Title")).setDesc(v("Optional, leave blank for default title")).addText(e=>{e.setPlaceholder(v("Input title")).setValue(this.title).onChange(e=>{this.title=e})}),new e.Setting(t).setName(v("Collapse State")).addDropdown(e=>{e.addOption("none",v("Default")).addOption("open",v("Open")).addOption("closed",v("Closed")).setValue(this.collapse).onChange(e=>{this.collapse=e})}),new e.Setting(t).setName(v("Content")).addTextArea(e=>{e.setPlaceholder(v("Input content")).setValue(this.content).onChange(e=>{this.content=e}),e.inputEl.rows=5,e.inputEl.cols=40,this.contentTextArea=e.inputEl});const n=t.createDiv("shortcut-hint");n.setText(`${e.Platform.isMacOS?"⌘":"Ctrl"} + Enter ${v("to insert")}`),n.style.textAlign="right",n.style.fontSize="0.8em",n.style.opacity="0.7",n.style.marginTop="5px",new e.Setting(t).addButton(e=>(e.setButtonText(v("Insert")).setCta().onClick(()=>{this.insertCallout(),this.close()}),this.insertButton=e.buttonEl,e)).addButton(e=>(e.setButtonText(v("Cancel")).setTooltip(v("Cancel")).onClick(()=>this.close()),e)),setTimeout(()=>{this.contentTextArea&&this.contentTextArea.focus()},10)}updateIconAndColor(t,o){if(!t)return;const n=this.allCalloutOptions.find(e=>e.type===o);if(t.empty(),n)if(n.isAdmonition){const o=n.icon;if("custom"===o.type&&o.svg){t.innerHTML=o.svg;const e=t.querySelector("svg");e&&(e.style.fill=n.color,e.style.width="var(--icon-size)",e.style.height="var(--icon-size)")}else o.name.startsWith("lucide-")||"default"===o.type?(e.setIcon(t,o.name),t.style.setProperty("--callout-color",n.color)):(e.setIcon(t,"lucide-box"),t.style.setProperty("--callout-color",n.color))}else e.setIcon(t,n.icon),t.style.setProperty("--callout-color",n.color);else e.setIcon(t,"lucide-alert-circle"),t.style.removeProperty("--callout-color")}insertCallout(){const e=this.plugin.commandsManager.getActiveEditor();if(!e)return;let t=`> [!${this.type}]`;"none"!==this.collapse&&(t+=""+("open"===this.collapse?"+":"-")),this.title&&(t+=` ${this.title}`),t+=`\n> ${this.content.replace(/\n/g,"\n> ")}`;const o=e.getCursor(),n=e.getLine(o.line),i=0===o.ch;let a;if(e.getSelection()){!i&&n.trim().length>0&&(t="\n"+t);const o=e.getCursor("from");e.replaceSelection(t);const s=t.split("\n").length;a={line:o.line+s,ch:0}}else{!i&&n.trim().length>0&&(t="\n"+t),e.replaceRange(t,o);const s=t.split("\n").length;a={line:o.line+s,ch:0}}setTimeout(()=>{e.replaceRange("\n",a),e.setCursor({line:a.line+1,ch:0}),e.focus()},0)}}class an{static isValidUrl(e){try{return new URL(e),!0}catch(e){return!1}}static parseTitle(e,t){const o=[e.includes("mp.weixin.qq.com")?this.wxTitlePattern:null,this.htmlTitlePattern,/<title [^>]*>(.*?)<\/title>/i,/<meta name="title" content="([^<]*)" \/>/im].filter(Boolean);for(const e of o){const o=t.match(e);if(o&&"string"==typeof o[1])return o[1].trim()}throw new Error("Unable to parse the title tag")}static getFallbackTitle(e){const t=e.match(/[^/\\]+$/);return t?t[0].replace(/\.[^/.]+$/,"").replace(/[-_]/g," ").trim():e}static async fetchRemoteTitle(t){if(!this.isValidUrl(t)||!t.match(/^https?:\/\//))return this.getFallbackTitle(t);try{const o=await e.requestUrl({url:t,method:"GET",headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"},throw:!0});if(200!==o.status)throw new Error(`Status code ${o.status}`);const n=o.text,i=this.parseTitle(t,n);return!i||i.length>100?this.getFallbackTitle(t):i}catch(e){return console.error(`Failed to fetch title for ${t}:`,e),this.getFallbackTitle(t)}}}an.htmlTitlePattern=/<title>([^<]*)<\/title>/im,an.wxTitlePattern=/<meta property="og:title" content="([^<]*)" \/>/im;class sn extends e.Modal{constructor(e){super(e.app),this.plugin=e,this.linkText="",this.linkUrl="",this.linkAlias="",this.isEmbed=!1,this.insertNewLine=!1,this.imageWidth="",this.imageHeight="",this.prefixText="",this.suffixText="",this.selectedText="";const t=this.plugin.commandsManager.getActiveEditor();if(t){const e=t.getSelection()||"";e?this.handleSelectedText(t,e):this.handleCursorPosition(t)}else this.parseClipboard();this.updateHeader()}handleSelectedText(e,t){const o=this.tryExpandSelection(e,t);if(o){const t=this.formatTargetText(o);e.setSelection(o.from,o.to),this.selectedText=t,this.parseSelectedText(t)}else this.selectedText=t,this.parseSelectedText(t)}handleCursorPosition(e){const t=e.getCursor(),o=this.findLinkAtCursor(e,t);if(o){const t=this.formatTargetText(o);e.setSelection(o.from,o.to),this.selectedText=t,this.parseSelectedText(t)}else this.parseClipboard()}tryExpandSelection(e,t){const o=e.getCursor("from"),n=e.getLine(o.line),i=o.ch,a=e.getCursor("to").ch;return this.matchLinkInLine(n,i,a,o.line)}findLinkAtCursor(e,t){const o=e.getLine(t.line),n=t.ch;return this.matchLinkInLine(o,n,n,t.line)}matchLinkInLine(e,t,o,n){const i=/(!)?\[([^\]]+)\]\(([^\s)]+)(?:\s+["']([^"']*)["'])?\)/g;let a;for(;null!==(a=i.exec(e));){const e=!!a[1],i=a.index,s=a.index+a[0].length,r=a[2],l=a[3],c=a[4]||"";if(t<=s&&o>=i)return{isImage:e,text:r,url:l,title:c,from:{line:n,ch:i},to:{line:n,ch:s}}}const s=/(?:^|\s)([a-zA-Z][a-zA-Z\d+\-.]*:\/\/\S+|\S+\.[a-zA-Z]{2,}(?:\/\S*)?)/g;for(;null!==(a=s.exec(e));){const e=a[1],i=a.index+(a[0].startsWith(" ")?1:0),s=i+e.length;if(t<=s&&o>=i)return{isImage:/\.(jpg|jpeg|png|gif|webp|bmp)$/i.test(e),text:e,url:e,title:"",from:{line:n,ch:i},to:{line:n,ch:s}}}return null}formatTargetText(e){return e.isImage?`![${e.text}](${e.url}${e.title?` "${e.title}"`:""})`:e.title?`[${e.text}](${e.url} "${e.title}")`:`[${e.text}](${e.url})`}parseSelectedText(e){const t=e.match(/!\[.*?\]\(.*?\)/);if(t){const o=e.substring(0,t.index),n=e.substring(t.index+t[0].length),i=this.parseMarkdownImageLink(e);if(i)return this.linkText=i.title,this.linkUrl=i.url,this.linkAlias=i.quotedTitle||"",this.imageWidth=i.width||"",this.imageHeight=i.height||"",this.isEmbed=!0,this.prefixText=o,void(this.suffixText=n)}const o=e.match(/\[([^\]]+)\]\(([a-zA-Z]+:\/\/[^\s)]+)(?:\s+["']([^"']*)["'])?\)/);if(o){const t=o[0],n=e.substring(0,o.index),i=e.substring(o.index+t.length),a=this.parseMarkdownLink(t);a&&(this.linkText=a.text,this.linkUrl=a.url,this.linkAlias=a.title||"",this.isEmbed=!1),this.prefixText=n,this.suffixText=i}else{const t=this.parseMixedContent(e);t&&(this.linkText=t.title,this.linkUrl=t.url)}}parseMixedContent(e){let t;return(t=e.match(/^\[(.*?)\]\((.*?)\)$/))?{title:t[1].trim(),url:t[2].trim()}:(t=e.match(/<a[^>]+href=["']([^"']+)["'][^>]*>([^<]+)<\/a>/i))?{title:t[2].trim(),url:t[1].trim()}:(t=e.match(/^(.*?)\s*((?:https?:\/\/|www\.)\S+)$/i))&&t[1].trim()?{title:t[1].trim(),url:t[2].trim()}:this.isValidUrl(e.trim())?{title:this.extractTitleFromUrl(e.trim()),url:e.trim()}:{title:e.trim(),url:""}}extractTitleFromUrl(e){const t=e.match(/^([a-zA-Z]+):\/\/(.+)$/);if(t){const[,e,o]=t,n=o.split(/[/\\]/),i=n[n.length-1];return i?decodeURIComponent(i).trim():e.toUpperCase()}const o=e.match(/^\[\[(.*?)\]\]$/);if(o)return o[1];const n=e.match(/[^/\\]+$/);return n?n[0].replace(/\.[^/.]+$/,"").replace(/[-_]/g," ").trim():e}isValidUrl(e){if(!e||e.includes("\n")||/\s/.test(e))return!1;if(["obsidian://","zotero://","evernote://","notion://","bear://","things://","drafts://","x-devonthink-item://","file://","ftp://","ftps://","http://","https://","tel:","mailto:"].some(t=>e.startsWith(t)))return!0;if(e.match(/^\[\[.*?\]\]$/))return!0;if(e.match(/^[./\\]/)||e.match(/^[a-zA-Z]:\\/)||e.match(/^\/[^/]/)||e.match(/^[a-zA-Z]+:\/\//))return!0;try{return new URL(e),!0}catch(e){return!1}}parseMarkdownImageLink(e){const t=e.match(/!\[(.*?)(?:\|(\d+)(?:x(\d+))?)?\]\(\s*([^\s)]+)(?:\s+["']([^"']*)["'])?\s*\)/);if(t){const[,e,o,n,i,a]=t;if(this.isEmbed=!0,this.embedToggle){this.embedToggle.setValue(!0);const e=this.contentEl.querySelector(".image-size-setting");e&&(e.style.display="block")}return{title:e.trim(),url:i.trim(),width:o,height:n,quotedTitle:a?.trim()}}return null}parseMarkdownLink(e){const t=e.match(/\[([^\]]+)\]\(([a-zA-Z]+:\/\/[^\s)]+)(?:\s+["']([^"']*)["'])?\)/);if(t){const[,e,o,n]=t;return{text:e.trim(),url:o.trim(),title:n?.trim()}}return null}async parseClipboard(){try{const e=await this.readClipboard(),t=e["text/plain"];if(t){const e=this.parseMarkdownImageLink(t);if(e)return this.linkText=e.title,this.linkUrl=e.url,this.linkAlias=e.quotedTitle||"",(e.width||e.height)&&(this.isEmbed=!0,this.imageWidth=e.width||"",this.imageHeight=e.height||""),void this.updateUI();const o=this.parseMarkdownLink(t);if(o)return this.linkText=o.text,this.linkUrl=o.url,this.linkAlias=o.title||"",this.isEmbed=!1,void this.updateUI()}if(e["text/html"]){const t=this.parseHtmlContent(e["text/html"]);t&&(this.linkText=this.linkText||t.title,this.linkUrl=t.url)}else if(e["text/markdown"]){const t=this.parseMarkdownContent(e["text/markdown"]);t&&(this.linkText=this.linkText||t.title,this.linkUrl=t.url)}else if(e["text/plain"]){const t=this.parseMixedContent(e["text/plain"]);t&&(this.linkText=this.linkText||t.title,this.linkUrl=t.url)}this.updateUI()}catch(e){console.error("Failed to read clipboard:",e)}}async readClipboard(){const e={};try{const t=await navigator.clipboard.read();for(const o of t){const t=o.types;for(const n of t)if("text/html"===n||"text/plain"===n||"text/markdown"===n){const t=await o.getType(n);e[n]=await t.text()}}}catch(t){try{const t=await navigator.clipboard.readText();e["text/plain"]=t}catch(e){console.error("Failed to read clipboard:",e)}}return e}parseHtmlContent(e){const t=(new DOMParser).parseFromString(e,"text/html"),o=t.querySelector("a");if(o)return{title:o.textContent?.trim()||"",url:o.href};const n=t.body.textContent||"";return this.parseMixedContent(n)}parseMarkdownContent(e){const t=e.match(/\[([^\]]+)\]\(([^)]+)\)/);return t?{title:t[1].trim(),url:t[2].trim()}:this.parseMixedContent(e)}onOpen(){this.display()}updateHeader(){const e=this.getPreviewText();this.previewSetting&&(this.previewSetting.controlEl.querySelector("input").value=e)}getPreviewText(){const e=this.linkText||"",t=this.linkUrl;let o=this.isEmbed?"!":"";return o+=`[${e}`,this.isEmbed&&(this.imageWidth||this.imageHeight)&&(o+="|",this.imageWidth&&this.imageHeight?o+=`${this.imageWidth}x${this.imageHeight}`:this.imageWidth?o+=this.imageWidth:this.imageHeight&&(o+=`x${this.imageHeight}`)),o+=`](${t}`,this.linkAlias&&(o+=` "${this.linkAlias}"`),o+=")",o}async display(){const{contentEl:t}=this;t.empty(),t.addClass("insert-link-modal"),this.titleEl.textContent="",this.titleEl.addClass("insert-link-modal-title"),t.addEventListener("keydown",e=>{"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.insertButton&&this.insertButton.click())});new e.Setting(t).addButton(t=>{t.setIcon("lucide-globe").setTooltip(v("Fetch Remote Title")).onClick(async()=>{if(this.linkUrl){t.setDisabled(!0),t.setIcon("lucide-loader");const e=await this.fetchRemoteTitle(this.linkUrl);t.setIcon("lucide-globe"),t.setDisabled(!1),this.linkText=e,this.linkTextInput.setValue(e),this.updateHeader()}else new e.Notice(v("Please enter a URL first"))})}).setName(v("Link Text")).addText(e=>{this.linkTextInput=e,e.setPlaceholder(v("Link Text")).setValue(this.linkText).onChange(e=>{this.linkText=e,this.updateHeader()})});const o=new e.Setting(t).setName(v("Title")).addText(e=>{this.linkAliasInput=e,e.setPlaceholder(v("Link Title (optional)")).setValue(this.linkAlias).onChange(e=>{this.linkAlias=e,this.updateHeader()})}),n=new e.Setting(t).setName(v("Link URL")).setClass("link-url-setting").addText(e=>{this.linkUrlInput=e,e.setPlaceholder(v("Link URL")).setValue(this.linkUrl).onChange(e=>{this.linkUrl=e.trim(),this.validateUrl(this.linkUrl),this.updateHeader()})}).addButton(e=>{e.setIcon("lucide-clipboard").setTooltip(v("Paste and Parse")).onClick(async()=>{await this.parseClipboard(),this.updateHeader()})});this.urlErrorMsg=n.descEl.createDiv("url-error"),this.urlErrorMsg.style.color="var(--text-error)",this.urlErrorMsg.style.display="none";const i=new e.Setting(t).setName(v("Embed Content")).setDesc(v("If it is an image, turn on"));this.embedToggle=new e.ToggleComponent(i.controlEl),this.embedToggle.setValue(this.isEmbed).onChange(e=>{this.isEmbed=e;const n=t.querySelector(".image-size-setting");o.settingEl,n&&(n.style.display=e?"flex":"none"),this.updateHeader()});const a=new e.Setting(t).addButton(e=>{e.setIcon("lucide-maximize").setTooltip(v("Fit Editor Width")).onClick(()=>{const e=this.getImageDimensions();e&&(this.imageWidth=e.width.toString(),this.imageHeight=e.height?.toString(),a.components[1].setValue(this.imageWidth),this.imageHeight&&a.components[2].setValue(this.imageHeight),this.updateHeader())})});a.setClass("image-size-setting").setName(v("Image Size")).addText(e=>{e.inputEl.addClass("image-width-input"),e.setPlaceholder(v("Image Width")).setValue(this.imageWidth).onChange(t=>{this.imageWidth=t.replace(/[^\d]/g,""),e.setValue(this.imageWidth),this.updateHeader()})});const s=a.controlEl.createDiv("image-size-icon");e.setIcon(s,"lucide-x"),a.addText(e=>{e.inputEl.addClass("image-height-input"),e.setPlaceholder(v("Image Height")).setValue(this.imageHeight).onChange(t=>{this.imageHeight=t.replace(/[^\d]/g,""),e.setValue(this.imageHeight),this.updateHeader()})}),a.settingEl.style.display=this.isEmbed?"block":"none",new e.Setting(t).setName(v("Insert New Line")).setDesc(v("Insert a link on the next line")).addToggle(e=>{e.setValue(this.insertNewLine).onChange(e=>{this.insertNewLine=e,this.updateHeader()})}),this.previewSetting=new e.Setting(t).setClass("preview-setting").setTooltip(this.getPreviewText()).addText(e=>{e.setValue(this.getPreviewText()).inputEl.setAttribute("readonly","true")});const r=t.createDiv("shortcut-hint");r.setText(`${e.Platform.isMacOS?"⌘":"Ctrl"} + Enter ${v("to insert")}`),r.style.textAlign="right",r.style.fontSize="0.8em",r.style.opacity="0.7",r.style.marginTop="5px",new e.Setting(t).addButton(e=>{e.setButtonText(v("Insert")).setCta().onClick(()=>{this.insertLink(),this.close()}),this.insertButton=e.buttonEl}).addButton(e=>e.setButtonText(v("Cancel")).onClick(()=>{this.close()})),setTimeout(()=>{this.linkText||this.linkUrl?!this.linkText&&this.linkUrl?this.linkTextInput.inputEl.focus():this.linkText&&!this.linkUrl?this.linkUrlInput.inputEl.focus():this.linkAliasInput.inputEl.focus():this.linkTextInput.inputEl.focus()},10)}async fetchRemoteTitle(e){return an.fetchRemoteTitle(e)}getImageDimensions(){const t=this.app.workspace.getActiveViewOfType(e.MarkdownView);if(!t)return null;const o=t.contentEl.querySelector(".markdown-source-view .cm-content"),n=t.contentEl;if(!o||!n)return null;const i=o.offsetWidth,a=n.offsetHeight,s=Math.floor(a/2);if("preview"===t.getMode()||"source"===t.getMode()){const e=o.querySelectorAll("img");if(e.length>0){let t=null;if(this.linkUrl&&e.forEach(e=>{e.src===this.linkUrl&&e.complete&&e.naturalWidth>0&&(t=e)}),t){const e=t.naturalWidth,o=e/t.naturalHeight;let n=Math.min(e,Math.floor(.65*i)),a=Math.floor(n/o);return a>s&&(a=s,n=Math.floor(a*o)),{width:n,height:a}}}}const r=Math.floor(s*(4/3));return{width:Math.min(Math.floor(.65*i),r),height:null}}validateUrl(e){return e?this.isValidUrl(e)?(this.urlErrorMsg.style.display="none",!0):(this.urlErrorMsg.textContent=v("URL Format Error"),this.urlErrorMsg.style.display="block",!1):(this.urlErrorMsg.style.display="none",!0)}insertLink(){if(!this.validateUrl(this.linkUrl))return;const e=this.plugin.commandsManager.getActiveEditor();if(!e)return;let t=this.linkText||this.linkUrl;const o=this.linkUrl;let n,i=this.isEmbed?"!":"";i+=`[${t}`,this.isEmbed&&(this.imageWidth||this.imageHeight)&&(i+="|",this.imageWidth&&this.imageHeight?i+=`${this.imageWidth}x${this.imageHeight}`:this.imageWidth?i+=this.imageWidth:this.imageHeight&&(i+=`x${this.imageHeight}`)),i+=`](${o}`,this.linkAlias&&(i+=` "${this.linkAlias}"`),i+=")";if(e.somethingSelected()){const t=e.getCursor("from"),o=e.getCursor("to");if(this.insertNewLine)e.replaceRange("\n"+i,{line:o.line,ch:e.getLine(o.line).length}),n={line:o.line+1,ch:i.length};else{const a=this.prefixText+i+this.suffixText;e.replaceRange(a,{line:t.line,ch:t.ch},o),n={line:t.line,ch:this.prefixText.length+i.length}}}else{const t=e.getCursor(),o=e.getLine(t.line);if(this.insertNewLine){const a=t.line+1;e.replaceRange("\n",{line:t.line,ch:o.length}),e.setCursor({line:a,ch:0}),e.replaceRange(i,{line:a,ch:0}),n={line:a,ch:i.length}}else e.replaceRange(i,t),n={line:t.line,ch:t.ch+i.length}}setTimeout(()=>{n&&e.setCursor(n),e.focus()},0)}updateUI(){this.linkTextInput&&this.linkTextInput.setValue(this.linkText),this.linkUrlInput&&(this.linkUrlInput.setValue(this.linkUrl),this.validateUrl(this.linkUrl));const e=this.contentEl.querySelector(".image-width-input"),t=this.contentEl.querySelector(".image-height-input");e&&(e.value=this.imageWidth),t&&(t.value=this.imageHeight),this.linkAliasInput&&this.linkAliasInput.setValue(this.linkAlias);const o=this.contentEl.querySelector(".setting-item:nth-child(2)");o&&(o.style.display="flex"),this.updateHeader()}}class rn{static getPlainText(t){const o=t.getSelection();if(!o)return void new e.Notice(v("Please select text first"));let n=o.replace(/\[([^\[\]]*)\]\([^\(\)]+\)/gim,"$1").replace(/(^#+\s|(?<=^|\s*)#|^>|^\- \[( |x)\]|^\+ |<[^<>]+>|^1\. |^\-+$|^\*+$|==|\*+|~~|```|!*\[\[|\]\])/gm,"").replace(/^[ ]+|[ ]+$/gm,"").replace(/(\r\n|\n)+/gm,"\n");navigator.clipboard.writeText(n),new e.Notice(v("Plain text copied to clipboard"))}static insertBlankLines(e){const t=e.getValue();if(!t)return;const o=t.replace(/([^\n])\n([^\n])/g,"$1\n\n$2");e.setValue(o)}static processWhitespace(t,o={}){const n=t.getSelection();if(!n)return void new e.Notice(v("Please select text first"));let i=n;o.all?i=i.replace(/[ \u3000\t]+/g,""):(o.tabs&&(i=i.replace(/\t/g,"")),o.compress&&(i=i.replace(/[ \u3000]+/g," ")));let a=i.split(/\r?\n/);if(o.trim&&(a=a.map(e=>e.trim())),o.removeEmptyLines)a=a.filter(e=>e.length>0);else if(o.compactEmptyLines){const e=[];for(let t=0;t<a.length;t++)0===a[t].length&&t>0&&0===a[t-1].length||e.push(a[t]);a=e}i=a.join("\n"),o.removeEmptyLines&&(i=i.trim()),t.replaceSelection(i),new e.Notice(v("Whitespace cleaning completed"))}static splitLines(t){const o=t.getSelection();if(!o)return void new e.Notice(v("Please select text first"));const n=this.detectPattern(o);let i;if(n)i=o.split(n).map(e=>e.trim()).filter(e=>e.length>0),new e.Notice(v("List pattern detected, auto-split"));else{const t=this.detectSeparator(o);if(!t)return void new e.Notice(v("No obvious separator or list pattern detected"));i=this.smartSplit(o,t),new e.Notice(`${v("Merged with")} '${t}' ${v("Merge completed")}`)}t.replaceSelection(i.join("\n"))}static detectPattern(e){const t=/\s?\d+[\.、]\s?/g,o=/\s?[→=>]\s?/g;return(e.match(t)||[]).length>1?t:(e.match(o)||[]).length>1?o:null}static smartSplit(e,t){const o=[];let n="",i=null;const a={'"':'"',"'":"'","“":"”","":"","(":")","":"","《":"》","[":"]","[[":"]]"};for(let s=0;s<e.length;s++){const r=e[s];i?(n+=r,r===i&&(i=null)):a[r]?(i=a[r],n+=r):r===t?(o.push(n.trim()),n=""):n+=r}return n&&o.push(n.trim()),o.filter(e=>e.length>0)}static detectSeparator(e){let t=0,o=null;return["、","",",",";","","|","·"].forEach(n=>{const i=e.split(n).length-1;i>t&&(t=i,o=n)}),o}static async smartPaste(t){try{const e=await navigator.clipboard.readText();if(!e)return;let o=e.replace(/(\r\n|\n){3,}/g,"\n\n");o=o.replace(/[ \t]+$/gm,""),t.replaceSelection(o)}catch(t){new e.Notice(v("Paste failed"))}}static smartTypography(t){const o=t.getSelection();if(!o||0===o.trim().length)return void new e.Notice(v("Please select text first"));const n=(o.match(/[\u4e00-\u9fa5]/g)||[]).length/o.length>.1;let i=o;const a=[];[/`[^`]+`/g,/\$[^$]+\$/g,/https?:\/\/[^\s)]+/g,/!\[.*?\]\(.*?\)/g,/\[.*?\]\(.*?\)/g].forEach(e=>{i=i.replace(e,e=>(a.push(e),`__PROTECTED_${a.length-1}__`))}),n?(i=i.replace(/,/g,"").replace(/\.(?!\d)/g,"。").replace(/;/g,"").replace(/:/g,"").replace(/\?/g,"").replace(/!/g,"").replace(/\(/g,"").replace(/\)/g,"").replace(/"([^"]*)"/g,"“$1”").replace(/([\u4e00-\u9fa5])([a-zA-Z0-9])/g,"$1 $2").replace(/([a-zA-Z0-9])([\u4e00-\u9fa5])/g,"$1 $2"),new e.Notice(v("Detected Chinese context: converted to full-width symbols"))):(i=i.replace(//g,", ").replace(/。/g,". ").replace(//g,"; ").replace(//g,": ").replace(//g,"? ").replace(//g,"! ").replace(//g,"(").replace(//g,")").replace(/[""]/g,'"').replace(/ {2,}/g," "),new e.Notice(v("Detected code/English context: converted to half-width symbols"))),a.forEach((e,t)=>{i=i.replace(`__PROTECTED_${t}__`,e)}),t.replaceSelection(i)}static dedupe(t,o={}){const n=t.getSelection();if(!n)return void new e.Notice(v("Please select text to dedupe first"));const i=n.split(/\r?\n/),a=new Set,s=[];for(const e of i){const t=o.trimBeforeCompare?e.trim():e;""!==t?a.has(t)||(a.add(t),s.push(e)):o.includeEmpty?a.has("")||(a.add(""),s.push(e)):s.push(e)}o.sort&&s.sort((e,t)=>e.localeCompare(t,"zh-CN",{numeric:!0})),t.replaceSelection(s.join("\n")),new e.Notice(`${v("Deduplication completed, remaining")} ${s.length} ${v("lines")}`)}static addWrap(t,o="",n="",i=!0){const a=t.getSelection(),s=a&&""!==a.trim(),r=s?a:t.getValue();if(!r)return;const l=r.split("\n").map(e=>i&&0===e.trim().length?e:`${o}${e}${n}`).join("\n");s?t.replaceSelection(l):t.setValue(l),new e.Notice(v("Prefix/suffix added"))}static numberList(t,o=1,n=1,i=". ",a=""){const s=t.getSelection();if(!s)return void new e.Notice(v("Please select text to number first"));const r=s.split("\n");let l=o;const c=r.map(e=>{if(""===e.trim())return e;const t=e.replace(/^\s*\d+[\.\))、]?\s*/,""),o=`${a}${l}${i}${t}`;return l+=n,o}).join("\n");t.replaceSelection(c),new e.Notice(`${v("Numbering completed: starting from")} ${o}`)}static extractBetween(t,o,n){if(!o&&!n)return void new e.Notice(v("Please specify start or end string"));const i=t.getValue();if(i)try{const a=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=a(o),r=a(n),l=new RegExp(`${s}(.*?)${r}`,"g"),c=[];let d;for(;null!==(d=l.exec(i));)void 0!==d[1]&&c.push(d[1]);c.length>0?(t.setValue(c.join("\n")),new e.Notice(`${v("Extracted")} ${c.length} ${v("matches")}`)):new e.Notice(v("No matches found"))}catch(t){new e.Notice(v("Extraction failed"))}}static mergeLines(t,o){const n=t.getSelection();if(!n||""===n.trim())return void new e.Notice(v("Please select lines to merge first"));const i=n.split(/\r?\n/),a=""!==o.separator;let s="";for(let e=0;e<i.length;e++){let t=o.trimLines?i[e].trim():i[e];if(""!==t){if(""!==s&&!s.endsWith("\n"))if(a)s+=o.separator;else{const e=s.slice(-1),o=t.charAt(0);/[\u4e00-\u9fa5]/.test(e)&&/[\u4e00-\u9fa5]/.test(o)||(s+=" ")}s+=t}else o.preserveParagraphs&&!a&&(s+="\n\n")}s=s.replace(/[ ]{2,}/g," ").trim(),t.replaceSelection(s),new e.Notice(a?`${v("Merged with")} '${o.separator}'`:v("Merge completed"))}static convertListToTableMultiDim(e){const t=e.getSelection();if(!t||""===t.trim())return;const o=t.split(/\r?\n/),n=/^((\s*)(?:[-*+]|\d+\.)\s+)(.*)/;let i=0;const a=o.map(e=>e.match(n)).filter(e=>e&&e[2].length>0).map(e=>e[2].replace(/\t/g," ").length),s=a.length>0?Math.min(...a):4;o.forEach(e=>{const t=e.match(n);if(t){const e=Math.round(t[2].replace(/\t/g," ".repeat(s)).length/s);e>i&&(i=e)}});let r=[],l=[],c=[],d=!1;for(let e=0;e<o.length;e++){const t=o[e],a=t.match(n);if(a){d=!0;const e=a[3].trim(),t=Math.round((a[2]||"").replace(/\t/g," ".repeat(s)).length/s);1===i?0===t?(c.length>0&&l.push([...c]),c=[e,""]):c[1]=c[1]?c[1]+"<br>"+e:e:(void 0!==c[t]&&(l.push([...c]),c=c.slice(0,t)),c[t]=e)}else if(d){if(""!==t.trim()){const e=c.length-1;e>=0&&(c[e]+="<br>"+t.trim())}}else r.push(t)}c.length>0&&l.push(c);const u=1===i?l:this.applyVisualMerge(l);this.renderFinalResult(e,r,u,[],i+1)}static applyVisualMerge(e){let t=[];return e.map((e,o)=>{if(0===o)return t=[...e],e;const n=e.map((o,n)=>e.slice(0,n).every((e,o)=>e===t[o]||""===e)&&o===t[n]?"":o);return t=[...e],n})}static renderFinalResult(t,o,n,i,a){let s="| "+Array.from({length:a},(e,t)=>0===t?v("Item"):`${v("Content")} ${t}`).join(" | ")+" |\n"+("| "+Array.from({length:a},()=>"---").join(" | ")+" |\n")+n.map(e=>`| ${Array.from({length:a},(t,o)=>(e[o]||"").replace(/\|/g,"\\|")).join(" | ")} |`).join("\n"),r="";o.length>0&&(r+=o.join("\n").trimEnd()+"\n\n"),r+=s,i.length>0&&(r+="\n\n"+i.join("\n").trimStart());const l=t.getCursor("from");if(l.line>0&&0===o.length){""!==t.getLine(l.line-1).trim()&&(r="\n"+r)}t.replaceSelection(r),new e.Notice(v("Super conversion completed: context preserved and layout optimized"))}static convertTableToList(t){let o=t.getSelection();if(!o||!o.includes("|")){const e=t.getCursor("from"),n=t.lineCount();let i=e.line;for(;i>0;){if(!t.getLine(i-1).includes("|"))break;i--}let a=e.line;for(;a<n-1;){if(!t.getLine(a+1).includes("|"))break;a++}if(i<=a){const e=[];for(let o=i;o<=a;o++){const n=t.getLine(o);n.includes("|")&&e.push(n)}e.length>0&&(o=e.join("\n"),t.setSelection({line:i,ch:0},{line:a,ch:t.getLine(a).length}))}}if(!o||!o.includes("|"))return void new e.Notice(v("Please select a valid Markdown table"));const n=o.split(/\r?\n/),i=[];for(const e of n){if(e.match(/^\s*\|?[\s\-:|]+\|?\s*$/)||""===e.trim())continue;e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(e=>e.trim()).forEach((e,t)=>{if(""!==e&&e!==v("Item")&&!e.startsWith(v("Content"))){const o=" ".repeat(t);i.push(`${o}- ${e}`)}})}t.replaceSelection(i.join("\n")),new e.Notice(v("Table converted to multi-level list"))}}const ln={previewCharsPerSection:2e3,maxSections:50,verbatimThreshold:5e4};function cn(e,t={}){const o={...ln,...t};return e.length<=o.verbatimThreshold?e:function(e,t,o){const n=e.split(/(?=^#{1,6}\s+)/m).filter(e=>e.trim());if(n.length<=1)return dn(e,4*t);const i=n.slice(0,o),a=n.length>o,s=i.map(e=>{const o=e.trim().split("\n"),n=o[0],i=o.slice(1).join("\n").trim();return i.length<=t?e.trim():`${n}\n${dn(i,t)}`}).join("\n\n");if(a)return`${s}\n\n[... ${n.length-o} more sections omitted ...]`;return s}(e,o.previewCharsPerSection,o.maxSections)}function dn(e,t){if(e.length<=t)return e;const o=e.slice(0,t),n=/[.!?。!?]\s+/g;let i,a=-1;for(;null!==(i=n.exec(o));)i.index>.5*t&&(a=i.index+1);if(a>0)return o.slice(0,a)+" ...";const s=o.lastIndexOf("\n\n");if(s>.5*t)return o.slice(0,s)+"\n\n...";const r=o.lastIndexOf(" ");return r>.8*t?o.slice(0,r)+" ...":o+"..."}class un extends e.Modal{constructor(e,t,o,n,i={}){super(e),this.result={},this.inputElements=new Map,this.linkedNoteFieldStates=new Map,this.linkedContextByField=new Map,this.linkedContextSyncTokens=new Map,this.linkedContextWrapEl=null,this.linkedContextItemsEl=null,this.title=t,this.fields=o,this.onSubmit=n,this.options=i,o.forEach(e=>{this.result[e.key]=e.defaultValue||""})}onOpen(){const{contentEl:t}=this;if(t.empty(),this.inputElements.clear(),this.linkedNoteFieldStates.clear(),this.linkedContextByField.clear(),this.linkedContextSyncTokens.clear(),this.linkedContextWrapEl=null,this.linkedContextItemsEl=null,this.options.modalClassName&&this.modalEl.addClass(this.options.modalClassName),t.createEl("h2",{text:this.title}),this.fields.forEach(o=>{if(o.hideLabel)return void this.renderFullWidthField(t,o);const n=new e.Setting(t).setName(o.label);o.multiline?n.addTextArea(e=>{e.setPlaceholder(o.placeholder||"").setValue(o.defaultValue||"").onChange(e=>{this.result[o.key]=e}),this.inputElements.set(o.key,e.inputEl),e.inputEl.rows=5,e.inputEl.addClass("editing-toolbar-textarea-input"),this.attachLinkedNoteSupport(o,e.inputEl,e.inputEl.parentElement instanceof HTMLElement?e.inputEl.parentElement:n.controlEl),o===this.fields[0]&&setTimeout(()=>e.inputEl.focus(),10),e.inputEl.addEventListener("keydown",e=>{this.handleLinkedNoteKeydown(o.key,e)||"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.submit())})}):n.addText(e=>{e.setPlaceholder(o.placeholder||"").setValue(o.defaultValue||"").onChange(e=>{this.result[o.key]=e}),this.inputElements.set(o.key,e.inputEl),this.attachLinkedNoteSupport(o,e.inputEl,e.inputEl.parentElement instanceof HTMLElement?e.inputEl.parentElement:n.controlEl),o===this.fields[0]&&setTimeout(()=>e.inputEl.focus(),10),e.inputEl.addEventListener("keydown",e=>{this.handleLinkedNoteKeydown(o.key,e)||"Enter"===e.key&&(e.preventDefault(),this.submit())})})}),this.options.contextItems&&this.options.contextItems.length>0){const e=t.createDiv({cls:"editing-toolbar-text-input-context"});this.options.contextLabel&&e.createDiv({cls:"editing-toolbar-text-input-context-label",text:this.options.contextLabel}),this.options.contextItems.forEach(t=>{const o=e.createDiv({cls:"editing-toolbar-text-input-context-item"});o.createSpan({cls:"editing-toolbar-text-input-context-item-label",text:t.label});const n=o.createSpan({cls:"editing-toolbar-text-input-context-item-preview",text:t.preview});t.title&&(n.title=t.title)})}if(this.hasLinkedNoteSupport()&&(this.linkedContextWrapEl=t.createDiv({cls:"editing-toolbar-text-input-context"}),this.linkedContextWrapEl.style.display="none",this.linkedContextWrapEl.createDiv({cls:"editing-toolbar-text-input-context-label",text:this.options.linkedNotes?.contextLabel||v("Referenced notes")}),this.linkedContextItemsEl=this.linkedContextWrapEl.createDiv(),this.syncLinkedNoteContextsForEnabledFields()),this.options.suggestions&&this.options.suggestions.length>0){const e=t.createDiv({cls:"editing-toolbar-text-input-suggestions"});e.createDiv({cls:"editing-toolbar-text-input-suggestions-label",text:v("Suggestions")});const o=e.createDiv({cls:"editing-toolbar-text-input-suggestions-chips"});this.options.suggestions.forEach(e=>{const t=o.createEl("button",{cls:"mod-muted editing-toolbar-text-input-suggestion-chip",text:e.label});t.type="button",t.addEventListener("click",()=>{this.applySuggestion(e)})})}const o=[this.options.linkedNotes?.enabled?this.options.linkedNotes.hint||v("Type [[]] to reference document content."):"",this.options.footerHint||""].filter(e=>e.trim().length>0);if(o.length>0){t.createDiv({cls:"editing-toolbar-text-input-footer-hint"}).textContent=o.join(" ")}new e.Setting(t).addButton(e=>e.setButtonText(v("Confirm")).setCta().onClick(()=>{this.submit()})).addButton(e=>e.setButtonText(v("Cancel")).onClick(()=>{this.close()}))}renderFullWidthField(e,t){const o=e.createDiv({cls:"editing-toolbar-text-input-field-full"});if(t.multiline){const e=o.createEl("textarea",{cls:"editing-toolbar-textarea-input"});return e.placeholder=t.placeholder||"",e.value=t.defaultValue||"",e.rows=5,t.label&&e.setAttribute("aria-label",t.label),this.inputElements.set(t.key,e),this.attachLinkedNoteSupport(t,e,o),t===this.fields[0]&&setTimeout(()=>e.focus(),10),e.addEventListener("input",()=>{this.result[t.key]=e.value}),void e.addEventListener("keydown",e=>{this.handleLinkedNoteKeydown(t.key,e)||"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.submit())})}const n=o.createEl("input");n.type="text",n.placeholder=t.placeholder||"",n.value=t.defaultValue||"",t.label&&n.setAttribute("aria-label",t.label),this.inputElements.set(t.key,n),this.attachLinkedNoteSupport(t,n,o),t===this.fields[0]&&setTimeout(()=>n.focus(),10),n.addEventListener("input",()=>{this.result[t.key]=n.value}),n.addEventListener("keydown",e=>{this.handleLinkedNoteKeydown(t.key,e)||"Enter"===e.key&&(e.preventDefault(),this.submit())})}async submit(){await this.syncLinkedNoteContextsForEnabledFields();const e=this.buildSubmitMeta();await this.onSubmit(this.result,e),this.close()}applySuggestion(e){const t=e.fieldKey||this.fields[0]?.key;if(!t)return;const o=this.inputElements.get(t);if(!o)return;const n=this.result[t]||"",i=!1===e.replace&&n.trim().length>0?`${n.trim()}\n${e.value}`:e.value;if(this.result[t]=i,o.value=i,o.focus(),"number"==typeof o.selectionStart){const e=i.length;o.setSelectionRange(e,e)}this.isLinkedNoteField(t)&&this.syncLinkedNoteContextForField(t,i)}onClose(){const{contentEl:e}=this;e.empty(),this.inputElements.clear(),this.linkedNoteFieldStates.clear(),this.linkedContextByField.clear(),this.linkedContextSyncTokens.clear(),this.linkedContextWrapEl=null,this.linkedContextItemsEl=null,this.options.modalClassName&&this.modalEl.removeClass(this.options.modalClassName)}hasLinkedNoteSupport(){return!0===this.options.linkedNotes?.enabled}isLinkedNoteField(e){if(!this.hasLinkedNoteSupport())return!1;const t=this.options.linkedNotes?.fieldKeys;return t&&0!==t.length?t.includes(e):e===this.fields[0]?.key}attachLinkedNoteSupport(e,t,o){if(!this.isLinkedNoteField(e.key)||!o)return;o.addClass("editing-toolbar-text-input-linked-note-host");const n=o.createDiv({cls:"editing-toolbar-text-input-mention-dropdown"});n.style.display="none",this.linkedNoteFieldStates.set(e.key,{fieldKey:e.key,inputEl:t,hostEl:o,dropdownEl:n,linkStartPos:-1,selectedSuggestionIndex:0,suggestionFiles:[]}),t.addEventListener("input",()=>{const o="number"==typeof t.selectionStart?t.selectionStart:t.value.length,n=this.normalizeLinkTriggerInput(t.value,o);n.value===t.value&&n.cursorPos===o||(t.value=n.value,t.setSelectionRange(n.cursorPos,n.cursorPos),this.result[e.key]=n.value),this.updateLinkedNoteSuggestions(e.key),this.syncLinkedNoteContextForField(e.key,t.value)}),t.value.trim().length>0&&this.syncLinkedNoteContextForField(e.key,t.value)}handleLinkedNoteKeydown(e,t){const o=this.linkedNoteFieldStates.get(e);if(!o)return!1;if(!("none"!==o.dropdownEl.style.display&&o.suggestionFiles.length>0))return"Escape"===t.key&&(o.dropdownEl.style.display="none",o.linkStartPos=-1,o.suggestionFiles=[]),!1;if("ArrowDown"===t.key)return t.preventDefault(),o.selectedSuggestionIndex=(o.selectedSuggestionIndex+1)%o.suggestionFiles.length,this.renderLinkedNoteDropdown(o),!0;if("ArrowUp"===t.key)return t.preventDefault(),o.selectedSuggestionIndex=(o.selectedSuggestionIndex-1+o.suggestionFiles.length)%o.suggestionFiles.length,this.renderLinkedNoteDropdown(o),!0;if("Tab"===t.key||"Enter"===t.key&&!t.shiftKey&&!t.ctrlKey&&!t.metaKey){t.preventDefault();const e=o.suggestionFiles[o.selectedSuggestionIndex];return e&&this.selectLinkedNoteSuggestion(o,e),!0}return"Escape"===t.key&&(t.preventDefault(),o.dropdownEl.style.display="none",o.linkStartPos=-1,o.suggestionFiles=[],!0)}updateLinkedNoteSuggestions(e){const t=this.linkedNoteFieldStates.get(e);if(!t)return;const o="number"==typeof t.inputEl.selectionStart?t.inputEl.selectionStart:t.inputEl.value.length,n=t.inputEl.value.substring(0,o),i=n.match(/\[\[([^\]]*?)$/);if(!i)return t.dropdownEl.style.display="none",t.linkStartPos=-1,void(t.suggestionFiles=[]);t.linkStartPos=n.lastIndexOf("[[");const a=i[1].toLowerCase(),s=this.app.workspace.getActiveFile(),r=this.app.vault.getMarkdownFiles().filter(e=>e.basename.toLowerCase().includes(a)||e.path.toLowerCase().includes(a)).sort((e,t)=>s&&e.path===s.path?-1:s&&t.path===s.path?1:e.path.localeCompare(t.path)).slice(0,10);t.suggestionFiles=r,t.selectedSuggestionIndex=0,0!==r.length?this.renderLinkedNoteDropdown(t):t.dropdownEl.style.display="none"}renderLinkedNoteDropdown(e){e.dropdownEl.empty(),e.suggestionFiles.forEach((t,o)=>{const n=e.dropdownEl.createDiv({cls:"editing-toolbar-text-input-mention-item"});n.toggleClass("selected",o===e.selectedSuggestionIndex),n.createSpan({cls:"editing-toolbar-text-input-mention-icon",text:"📄"}),n.createSpan({cls:"editing-toolbar-text-input-mention-name",text:t.basename}),n.createSpan({cls:"editing-toolbar-text-input-mention-path",text:t.path}),n.addEventListener("mousedown",o=>{o.preventDefault(),this.selectLinkedNoteSuggestion(e,t)})}),e.dropdownEl.style.display="block";const t=e.dropdownEl.querySelectorAll(".editing-toolbar-text-input-mention-item")[e.selectedSuggestionIndex];t?.scrollIntoView({block:"nearest"})}async selectLinkedNoteSuggestion(e,t){const o="number"==typeof e.inputEl.selectionStart?e.inputEl.selectionStart:e.inputEl.value.length,n=this.app.workspace.getActiveFile()?.path??"",i=this.app.metadataCache.fileToLinktext(t,n,!0),a=e.inputEl.value.substring(0,e.linkStartPos),s=`${a}[[${i}]] ${e.inputEl.value.substring(o)}`;e.inputEl.value=s,this.result[e.fieldKey]=s,e.dropdownEl.style.display="none",e.suggestionFiles=[],e.linkStartPos=-1,e.inputEl.focus();const r=a.length+i.length+5;e.inputEl.setSelectionRange(r,r),await this.syncLinkedNoteContextForField(e.fieldKey,s)}normalizeLinkTriggerInput(e,t){let o=e,n=t;if(o.includes("【【")){const e=o.substring(0,n),t=o.substring(n),i=e.replace(/【【/g,"[[");o=i+t.replace(/【【/g,"[["),n-=e.length-i.length}const i=o.substring(0,n).match(/(?:\[|【){2,}$/);if(i&&i[0].includes("【")){const e=n-i[0].length;o=`${o.substring(0,e)}[[${o.substring(n)}`,n=e+2}return{value:o,cursorPos:n}}async syncLinkedNoteContextsForEnabledFields(){const e=[];this.fields.forEach(t=>{if(!this.isLinkedNoteField(t.key))return;const o=this.inputElements.get(t.key),n=o?.value??this.result[t.key]??"";e.push(this.syncLinkedNoteContextForField(t.key,n))}),await Promise.all(e)}async syncLinkedNoteContextForField(e,t){const o=(this.linkedContextSyncTokens.get(e)??0)+1;this.linkedContextSyncTokens.set(e,o);const n=await this.resolveLinkedContextItems(e,t);this.linkedContextSyncTokens.get(e)===o&&(this.linkedContextByField.set(e,n),this.renderLinkedContextItems())}async resolveLinkedContextItems(t,o){const n=this.app.workspace.getActiveFile()?.path??"",i=Array.from(o.matchAll(/\[\[([^\]]+)\]\]/g)),a=[],s=new Set;for(const o of i){const i=o[1]?.trim();if(!i)continue;const[r,l]=i.split("|"),c=e.parseLinktext((r||"").trim());if(!c.path)continue;const d=this.app.metadataCache.getFirstLinkpathDest(c.path,n);if(d&&!s.has(d.path)){s.add(d.path);try{const e=cn(await this.app.vault.cachedRead(d)),o=e.replace(/\s+/g," ").trim(),n=o.length>80?`${o.slice(0,80)}...`:o,s=l?.trim()||d.basename,r=e.length>140?`${e.slice(0,140)}...`:e;a.push({fieldKey:t,reference:`[[${i}]]`,label:`📄 ${s}`,preview:`${n} (${e.length.toLocaleString()} chars)`,title:r||d.path,content:e,filePath:d.path})}catch(e){console.error(`[TextInputModal] Failed to read linked file: ${i}`,e)}}}return a}renderLinkedContextItems(){if(!this.linkedContextWrapEl||!this.linkedContextItemsEl)return;this.linkedContextItemsEl.empty();const e=Array.from(this.linkedContextByField.values()).flat();0!==e.length?(this.linkedContextWrapEl.style.display="block",e.forEach(e=>{const t=this.linkedContextItemsEl?.createDiv({cls:"editing-toolbar-text-input-context-item"});t?.createSpan({cls:"editing-toolbar-text-input-context-item-label",text:e.label});const o=t?.createSpan({cls:"editing-toolbar-text-input-context-item-preview",text:e.preview});o&&e.title&&(o.title=e.title)})):this.linkedContextWrapEl.style.display="none"}buildSubmitMeta(){const e={},t={},o=[];return this.fields.forEach(n=>{const i=this.result[n.key]??"";e[n.key]=this.isLinkedNoteField(n.key)?this.stripWikiLinkSyntax(i):i;const a=[...this.linkedContextByField.get(n.key)??[]];t[n.key]=a,o.push(...a)}),{cleanedResult:e,linkedContextItems:o,linkedContextByField:t}}stripWikiLinkSyntax(e){return e.replace(/\[\[([^\]]+)\]\]/g,(e,t)=>{const[o,n]=String(t).split("|");return(n||o||"").trim()}).trim()}}class mn{formatAICommandName(...e){return[v("AI"),...e.map(e=>v(e))].join(" / ")}constructor(e){this.aiRewriteCommandIcons={improve:"lucide-wand-2","fix-grammar":"lucide-spell-check-2","make-shorter":"lucide-minimize-2","make-longer":"lucide-maximize-2",simplify:"lucide-align-left",professional:"lucide-briefcase",casual:"lucide-message-circle-more","translate-en":"lucide-languages","translate-zh":"lucide-languages","translate-ja":"lucide-languages","translate-de":"lucide-languages","translate-fr":"lucide-languages","translate-es":"lucide-languages",explain:"lucide-info",summarize:"lucide-file-text",continue:"lucide-pencil-line",custom:"lucide-message-square"},this.executeCommandWithoutBlur=async(e,t)=>{e&&(await t(),e.focus())},this.executeHistoryAction=e=>{if(this.executeCanvasHistoryAction(e))return;const t=this.getActiveEditor();if(t)return void this.executeCommandWithoutBlur(t,()=>"undo"===e?t?.undo():t?.redo());const o="undo"===e?["canvas:undo","editor:undo"]:["canvas:redo","editor:redo"];for(const e of o)try{if(this.plugin.app.commands.executeCommandById(e))return}catch{continue}},this._commandsMap={hrline:{char:5,line:1,prefix:"\n---",suffix:"\n",islinehead:!0},justify:{char:0,line:0,prefix:'<p align="justify">',suffix:"</p>",islinehead:!1},left:{char:0,line:0,prefix:'<p align="left">',suffix:"</p>",islinehead:!1},right:{char:0,line:0,prefix:'<p align="right">',suffix:"</p>",islinehead:!1},center:{char:0,line:0,prefix:"<center>",suffix:"</center>",islinehead:!1},underline:{char:0,line:0,prefix:"<u>",suffix:"</u>",islinehead:!1},superscript:{char:0,line:0,prefix:"<sup>",suffix:"</sup>",islinehead:!1},subscript:{char:0,line:0,prefix:"<sub>",suffix:"</sub>",islinehead:!1},codeblock:{char:4,line:0,prefix:"\n```\n",suffix:"\n```\n",islinehead:!1}},this.modCommands=[{id:"editor:insert-embed",name:"Insert Embed",icon:"note-glyph"},{id:"editor:insert-link",name:"Insert Link",icon:"link-glyph"},{id:"editor:insert-tag",name:"Insert Tag",icon:"price-tag-glyph"},{id:"editor:insert-wikilink",name:"Insert Internal link",icon:"bracket-glyph"},{id:"editor:toggle-code",name:"Insert Code",icon:"code-glyph"},{id:"editor:toggle-blockquote",name:"Insert Blockquote",icon:"lucide-text-quote"},{id:"editor:toggle-checklist-status",name:"Cycle List and Checklist",icon:"checkbox-glyph"},{id:"editor:toggle-comments",name:"Insert Comment",icon:"percent-sign-glyph"},{id:"editor:insert-callout",name:"Insert Callout",icon:"lucide-quote"},{id:"editor:insert-mathblock",name:"Insert MathBlock",icon:"lucide-sigma-square"},{id:"editor:insert-table",name:"Insert Table",icon:"lucide-table"},{id:"editor:swap-line-up",name:"Swap Line Up",icon:"lucide-corner-right-up"},{id:"editor:swap-line-down",name:"Swap Line Down",icon:"lucide-corner-right-down"},{id:"editor:attach-file",name:"Attach File",icon:"lucide-paperclip"},{id:"editor:clear-formatting",name:"Clear Formatting",icon:"lucide-eraser"}],this.applyCommand=(e,t)=>{const o=t.getSelection(),n=t.getCursor("from"),i=t.getCursor("to");let a=e.prefix;e.islinehead&&n.ch>0&&(a="\n"+a);const s=e.suffix,r={line:n.line-e.line,ch:n.ch-a.length};if(t.getRange(r,n)==a){const l={line:n.line+e.line,ch:i.ch+s.length};if(t.getRange(i,l)==s){t.replaceRange(o,r,l),t.setCursor(n.line-e.line,n.ch);const i={line:n.line,ch:n.ch-a.length},s={line:n.line,ch:i.ch+o.length};return void t.setSelection(i,s)}}if(t.replaceSelection(`${a}${o}${s}`),e.char>0)t.setCursor(n.line+e.line,n.ch+e.char+o.length);else{const e=n,i={line:e.line,ch:e.ch+a.length},s={line:e.line,ch:i.ch+o.length};t.setSelection(i,s)}},this.plugin=e}executeCanvasHistoryAction(e){const t=this.getActiveCanvasView();if("canvas"!==t?.getViewType?.())return!1;try{t.canvas?.wrapperEl?.focus?.({preventScroll:!0})}catch{}const o=[{owner:t.canvas,method:e,label:`canvas.${e}()`},{owner:t.canvas?.history,method:"undo"===e?"back":"forward",label:`canvas.history.${"undo"===e?"back":"forward"}()`}];for(const e of o){const t=e.owner?.[e.method];if("function"==typeof t)return t.call(e.owner),!0}return!1}getActiveCanvasView(){const e=this.plugin.app.workspace.activeLeaf?.view;if("canvas"===e?.getViewType?.())return e;const t=this.plugin.app.workspace.getLeavesOfType?.("canvas")??[];for(const e of t){const t=e?.view;if("canvas"===t?.getViewType?.())return t}return null}async applyRegexCommand(t,o){try{let n=t.getSelection(),i=t.getCursor("from"),a=t.getCursor("to");if(!n)if(this.plugin.settings.useCurrentLineForRegex){const o=i.line,s=t.getLine(o);if(!s||""===s.trim())return void new e.Notice(v("Current line is empty, please select text or move to a non-empty line"));n=s,i={line:o,ch:0},a={line:o,ch:s.length},t.setSelection(i,a)}else try{const o=await this.readClipboard();if(n=o["text/html"]?e.htmlToMarkdown(o["text/html"]):o["text/markdown"]||o["text/plain"],!n)return void new e.Notice(v("Please select text or copy text to clipboard first"));t.replaceRange(n,i,i);const a=t.offsetToPos(t.posToOffset(i)+n.length);t.setSelection(i,a)}catch(t){return console.error("读取剪贴板失败:",t),void new e.Notice(v("Please select text first"))}if(o.useCondition&&o.conditionPattern){if(!new RegExp(o.conditionPattern).test(n))return void new e.Notice(v("The selected text does not meet the condition requirements"))}let s="";!1!==o.regexGlobal&&(s+="g"),o.regexCaseInsensitive&&(s+="i"),o.regexMultiline&&(s+="m");const r=new RegExp(o.regexPattern,s),l=t.getCursor("from"),c=t.getCursor("to");t.transaction({changes:[{from:l,to:c,text:n.replace(r,o.regexReplacement)}]});const d=t.getSelection(),u=t.offsetToPos(t.posToOffset(l)),m=t.offsetToPos(t.posToOffset(l)+d.length);t.setSelection(u,m)}catch(t){console.error("正则表达式命令执行错误:",t),new e.Notice(v("Regex command execution error: ")+t.message)}}async readClipboard(){const e={};try{const t=await navigator.clipboard.read();for(const o of t){const t=o.types;for(const n of t)if("text/html"===n||"text/plain"===n||"text/markdown"===n){const t=await o.getType(n);e[n]=await t.text()}}}catch(t){try{const t=await navigator.clipboard.readText();e["text/plain"]=t}catch(e){console.error("读取剪贴板失败:",e)}}return e}getActiveEditor(){const e=this.plugin.app.workspace?.activeEditor;if(e&&e.editor)return e.editor;try{const e=this.plugin.app.workspace.activeLeaf?.view?.editor;if(e)return e}catch{}return null}registerCommands(){this.plugin.addCommand({id:"renumber-ordered-list",name:"Renumber Ordered List",editorCallback:e=>{e&&this.executeCommandWithoutBlur(e,()=>function(e){if(!e.getSelection()){const t=e.getCursor(),o=e.getLine(t.line);if(/^\s*\d+\.\s/.test(o)){const o=e.getLine(t.line).match(/^\s*/)?.[0].length||0,n=t.line-1,i=n>=0?e.getLine(n).trim():"";if(n<0||!/^\s*\d+\.\s/.test(i)||(i.match(/^\s*/)?.[0].length||0)<o){const{startLine:o,endLine:n}=function(e,t){let o=t,n=t;for(;o>0;){const t=e.getLine(o-1);if(!/^\s*\d+\.\s/.test(t.trim()))break;o--}for(;n<e.lineCount()-1;){const t=e.getLine(n+1);if(!/^\s*\d+\.\s/.test(t.trim()))break;n++}return{startLine:o,endLine:n}}(e,t.line);u(e,o,n)}else{const{startLine:o,endLine:n}=function(e,t){let o=t,n=t;const i=e.getLine(t).match(/^\s*/)?.[0].length||0;for(;n<e.lineCount()-1;){const t=e.getLine(n+1),o=t.match(/^\s*/)?.[0].length||0;if(!/^\s*\d+\.\s/.test(t.trim())||o<i)break;n++}return{startLine:o,endLine:n}}(e,t.line);u(e,o,n)}}return}const{lines:t,startLine:o}=function(e){const t=e.getSelection(),o=e.getCursor("from");return{lines:t.split("\n"),startLine:o.line}}(e);d(t,o,e)}(e))}}),this.plugin.addCommand({id:"hide-show-menu",name:"Hide/Show ",icon:"editingToolbar",callback:async()=>{this.plugin.settings.cMenuVisibility=!this.plugin.settings.cMenuVisibility,this.plugin.settings.cMenuVisibility?setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100):p(this.plugin.settings.cMenuVisibility),se(this.plugin),await this.plugin.saveSettings()}}),this.plugin.addCommand({id:"toggle-top-toolbar",name:"Toggle Top Toolbar",callback:async()=>{const e=this.plugin.settings,t=this.plugin.positionStyle;e.enableTopToolbar=!e.enableTopToolbar;let o=null;e.enableTopToolbar?o="top":"top"===t&&(o=e.enableFollowingToolbar?"following":e.enableFixedToolbar?"fixed":null),o&&o!==t&&this.plugin.onPositionStyleChange(o),await this.plugin.saveSettings(),this.plugin.handleeditingToolbar()}}),this.plugin.addCommand({id:"toggle-following-toolbar",name:"Toggle Following Toolbar",callback:async()=>{const e=this.plugin.settings,t=this.plugin.positionStyle;e.enableFollowingToolbar=!e.enableFollowingToolbar;let o=null;e.enableFollowingToolbar?o="following":"following"===t&&(o=e.enableTopToolbar?"top":e.enableFixedToolbar?"fixed":null),o&&o!==t&&this.plugin.onPositionStyleChange(o),await this.plugin.saveSettings(),this.plugin.handleeditingToolbar()}}),this.plugin.addCommand({id:"toggle-fixed-toolbar",name:"Toggle Fixed Toolbar",callback:async()=>{const e=this.plugin.settings,t=this.plugin.positionStyle;e.enableFixedToolbar=!e.enableFixedToolbar;let o=null;e.enableFixedToolbar?o="fixed":"fixed"===t&&(o=e.enableTopToolbar?"top":e.enableFollowingToolbar?"following":null),o&&o!==t&&this.plugin.onPositionStyleChange(o),await this.plugin.saveSettings(),this.plugin.handleeditingToolbar()}}),this.plugin.addCommand({id:"get-plain-text",name:"Get Plain Text",editorCallback:e=>{rn.getPlainText(e)}}),this.plugin.addCommand({id:"insert-blank-lines",name:"Insert Blank Lines",editorCallback:e=>{rn.insertBlankLines(e)}}),this.plugin.addCommand({id:"remove-blank-lines",name:"Remove Blank Lines",editorCallback:e=>rn.processWhitespace(e,{removeEmptyLines:!0})}),this.plugin.addCommand({id:"ai-login-pkmer",name:this.formatAICommandName("Account","Login to PKMer AI"),icon:"lucide-log-in",callback:async()=>{await this.plugin.aiManager.loginWithPKMer()}}),this.plugin.addCommand({id:"ai-logout-pkmer",name:this.formatAICommandName("Account","Logout from PKMer"),icon:"lucide-log-out",callback:async()=>{await this.plugin.aiManager.logoutFromPKMer()}}),this.plugin.addCommand({id:"ai-inline-completion",name:this.formatAICommandName("Complete","Quick Trigger"),icon:"lucide-sparkles",hotkeys:[{modifiers:["Mod"],key:"j"}],editorCallback:e=>{this.plugin.aiManager.triggerInlineCompletion(e)}});const t=(e,t,o,n)=>{this.plugin.addCommand({id:e,name:this.formatAICommandName("Rewrite",t),icon:n,editorCallback:e=>{this.plugin.aiManager.startRewrite(e,o)}})};t("ai-rewrite-improve","Improve Selection","improve","lucide-wand-2"),t("ai-rewrite-continue","Continue writing","continue","lucide-pencil-line"),O.forEach(e=>{const o=`ai-rewrite-${e.instruction}`;"improve"!==e.instruction&&"continue"!==e.instruction&&t(o,e.label,e.instruction,this.aiRewriteCommandIcons[e.instruction])}),this.plugin.addCommand({id:"ai-rewrite-custom",name:this.formatAICommandName("Rewrite","Custom Rewrite"),icon:"lucide-message-square",editorCallback:e=>{this.plugin.aiManager.openCustomRewrite(e)}}),this.plugin.addCommand({id:"ai-canvas-expand",name:this.formatAICommandName("Canvas","Expand Current Node"),icon:"lucide-waypoints",callback:()=>{this.plugin.aiManager.openCanvasNodeExpansionModal()}}),this.plugin.addCommand({id:"ai-canvas-global-prompt",name:this.formatAICommandName("Canvas","Global Prompt"),icon:"lucide-sparkles",callback:()=>{this.plugin.aiManager.openCanvasGlobalPromptModal()}}),ee.forEach(e=>{this.plugin.addCommand({id:`ai-toolbox-${e.id}`,name:this.formatAICommandName("Toolbox",e.label),icon:e.icon,editorCallback:t=>{this.plugin.aiManager.runToolboxAction(t,e.id)}})}),this.plugin.addCommand({id:"split-lines",name:"Split Lines",editorCallback:e=>{rn.splitLines(e)}}),this.plugin.addCommand({id:"smart-symbols",name:"Full Half Converter",editorCallback:e=>{rn.smartTypography(e)}}),this.plugin.addCommand({id:"dedupe-lines",name:"Dedupe Lines",editorCallback:e=>rn.dedupe(e,{trimBeforeCompare:!0})}),this.plugin.addCommand({id:"add-wrap",name:"Add Prefix/Suffix",editorCallback:e=>{new un(this.plugin.app,v("Add Prefix/Suffix"),[{key:"prefix",label:v("Prefix"),placeholder:v("Enter prefix"),defaultValue:""},{key:"suffix",label:v("Suffix"),placeholder:v("Enter suffix"),defaultValue:""}],t=>{const o=t;rn.addWrap(e,o.prefix,o.suffix,!0)}).open()}}),this.plugin.addCommand({id:"number-lines",name:"Number Lines (Custom)",editorCallback:e=>{new un(this.plugin.app,v("Number Lines Configuration"),[{key:"start",label:v("Start Number"),placeholder:"1",defaultValue:"1"},{key:"step",label:v("Step"),placeholder:"1",defaultValue:"1"},{key:"sep",label:v("Separator"),placeholder:". ",defaultValue:". "}],t=>{const o=parseInt(t.start)||1,n=parseInt(t.step)||1,i=t.sep||". ";rn.numberList(e,o,n,i,"")}).open()}}),this.plugin.addCommand({id:"remove-whitespace-trim",name:"Trim Line Ends",editorCallback:e=>{rn.processWhitespace(e,{trim:!0})}}),this.plugin.addCommand({id:"remove-whitespace-compress",name:"Shrink Extra Spaces",editorCallback:e=>{rn.processWhitespace(e,{compress:!0})}}),this.plugin.addCommand({id:"remove-whitespace-all",name:"Remove All Whitespace",editorCallback:e=>{rn.processWhitespace(e,{all:!0})}}),this.plugin.addCommand({id:"list-to-table",name:v("List to Table"),editorCallback:e=>{rn.convertListToTableMultiDim(e)}}),this.plugin.addCommand({id:"table-to-list",name:v("Table to List"),editorCallback:e=>rn.convertTableToList(e)}),this.plugin.addCommand({id:"extract-between",name:"Extract Between Strings",editorCallback:e=>{new un(this.plugin.app,v("Extract Between Strings"),[{key:"start",label:v("Start String"),placeholder:v("Enter start string"),defaultValue:"["},{key:"end",label:v("End String"),placeholder:v("Enter end string"),defaultValue:"]"}],t=>{const o=t;rn.extractBetween(e,o.start,o.end)}).open()}}),this.plugin.addCommand({id:"merge-lines",name:v("Merge Lines"),editorCallback:e=>{new un(this.plugin.app,v("Merge Lines Settings"),[{key:"sep",label:v("Separator (leave empty for smart spacing)"),placeholder:v("e.g., comma, pipe, arrow"),defaultValue:""}],t=>{rn.mergeLines(e,{separator:t.sep,preserveParagraphs:""===t.sep,trimLines:!0})}).open()}}),this.plugin.addCommand({id:"format-eraser",name:"Format Eraser",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>Te(this.plugin,e))},icon:"eraser"}),this.plugin.addCommand({id:"change-font-color",name:"Change Font Color",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>l(this.plugin.settings.cMenuFontColor??"#2DC26B",e))},icon:'<svg width="24" height="24" focusable="false" fill="currentColor"><g fill-rule="evenodd"><path id="change-font-color-icon" d="M3 18h18v3H3z" style="fill:#2DC26B"></path><path d="M8.7 16h-.8a.5.5 0 01-.5-.6l2.7-9c.1-.3.3-.4.5-.4h2.8c.2 0 .4.1.5.4l2.7 9a.5.5 0 01-.5.6h-.8a.5.5 0 01-.4-.4l-.7-2.2c0-.3-.3-.4-.5-.4h-3.4c-.2 0-.4.1-.5.4l-.7 2.2c0 .3-.2.4-.4.4zm2.6-7.6l-.6 2a.5.5 0 00.5.6h1.6a.5.5 0 00.5-.6l-.6-2c0-.3-.3-.4-.5-.4h-.4c-.2 0-.4.1-.5.4z"></path></g></svg>'}),this.plugin.addCommand({id:"change-background-color",name:"Change Background Color",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>c(this.plugin.settings.cMenuBackgroundColor??"#FA541C",e))},icon:'<svg width="18" height="24" viewBox="0 0 256 256" version="1.1" xmlns="http://www.w3.org/2000/svg"><g stroke="none" stroke-width="1" fill="currentColor" fill-rule="evenodd"><g ><g fill="currentColor"><g transform="translate(119.502295, 137.878331) rotate(-135.000000) translate(-119.502295, -137.878331) translate(48.002295, 31.757731)" ><path d="M100.946943,60.8084699 L43.7469427,60.8084699 C37.2852111,60.8084699 32.0469427,66.0467383 32.0469427,72.5084699 L32.0469427,118.70847 C32.0469427,125.170201 37.2852111,130.40847 43.7469427,130.40847 L100.946943,130.40847 C107.408674,130.40847 112.646943,125.170201 112.646943,118.70847 L112.646943,72.5084699 C112.646943,66.0467383 107.408674,60.8084699 100.946943,60.8084699 Z M93.646,79.808 L93.646,111.408 L51.046,111.408 L51.046,79.808 L93.646,79.808 Z" fill-rule="nonzero"></path><path d="M87.9366521,16.90916 L87.9194966,68.2000001 C87.9183543,69.4147389 86.9334998,70.399264 85.7187607,70.4 L56.9423078,70.4 C55.7272813,70.4 54.7423078,69.4150264 54.7423078,68.2 L54.7423078,39.4621057 C54.7423078,37.2523513 55.5736632,35.1234748 57.0711706,33.4985176 L76.4832996,12.4342613 C78.9534987,9.75382857 83.1289108,9.5834005 85.8093436,12.0535996 C87.1658473,13.303709 87.9372691,15.0644715 87.9366521,16.90916 Z" fill-rule="evenodd"></path><path d="M131.3,111.241199 L11.7,111.241199 C5.23826843,111.241199 0,116.479467 0,122.941199 L0,200.541199 C0,207.002931 5.23826843,212.241199 11.7,212.241199 L131.3,212.241199 C137.761732,212.241199 143,207.002931 143,200.541199 L143,122.941199 C143,116.479467 137.761732,111.241199 131.3,111.241199 Z M124,130.241 L124,193.241 L19,193.241 L19,130.241 L124,130.241 Z" fill-rule="nonzero"></path></g></g><path d="M51,218 L205,218 C211.075132,218 216,222.924868 216,229 C216,235.075132 211.075132,240 205,240 L51,240 C44.9248678,240 40,235.075132 40,229 C40,222.924868 44.9248678,218 51,218 Z" id="change-background-color-icon" style="fill:#FA541C"></path></g></g></svg>'}),this.plugin.addCommand({id:"indent-list",name:"Indent List",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.indentList())},icon:"indent-glyph"}),this.plugin.addCommand({id:"undent-list",name:"Unindent List",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.unindentList())},icon:"unindent-glyph"}),this.plugin.addCommand({id:"toggle-numbered-list",name:"Numbered List",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.toggleNumberList())},icon:"number-list-glyph"}),this.plugin.addCommand({id:"toggle-bullet-list",name:"Unordered List",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.toggleBulletList())},icon:"bullet-list-glyph"}),this.plugin.addCommand({id:"toggle-highlight",name:"Highlight",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.toggleMarkdownFormatting("highlight"))},icon:"highlight-glyph"}),this.plugin.addCommand({id:"toggle-bold",name:"Toggle Bold",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>{e.toggleMarkdownFormatting("bold")})},icon:"bold-glyph"}),this.plugin.addCommand({id:"toggle-italics",name:"Toggle Italics",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.toggleMarkdownFormatting("italic"))},icon:"italic-glyph"}),this.plugin.addCommand({id:"toggle-strikethrough",name:"Toggle Strikethrough",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.toggleMarkdownFormatting("strikethrough"))},icon:"strikethrough-glyph"}),this.plugin.addCommand({id:"toggle-inline-math",name:"Toggle Inline Math",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.toggleMarkdownFormatting("math"))},icon:"lucide-sigma"}),this.plugin.addCommand({id:"editor:cycle-list-checklist",name:"Cycle List and Checklist",icon:"lucide-check-square",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.toggleCheckList(!0))}}),this.plugin.addCommand({id:"editor-undo",name:"Undo Edit",callback:()=>{this.executeHistoryAction("undo")},icon:"undo-glyph"}),this.plugin.addCommand({id:"editor-redo",name:"Redo Edit",callback:()=>{this.executeHistoryAction("redo")},icon:"redo-glyph"}),this.plugin.addCommand({id:"editor-copy",name:"Copy",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,async()=>{try{await window.navigator.clipboard.writeText(e.getSelection()),this.plugin.app.commands.executeCommandById("editor:focus")}catch(e){console.error("Copy failed:",e)}})},icon:"lucide-copy"}),this.plugin.addCommand({id:"editor-paste",name:"Paste",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,async()=>{try{const t=await window.navigator.clipboard.readText();t&&e.replaceSelection(t),this.plugin.app.commands.executeCommandById("editor:focus")}catch(e){console.error("Paste failed:",e)}})},icon:"lucide-clipboard-type"}),this.plugin.addCommand({id:"editor-cut",name:"Cut",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,async()=>{try{await window.navigator.clipboard.writeText(e.getSelection()),e.replaceSelection(""),this.plugin.app.commands.executeCommandById("editor:focus")}catch(e){console.error("Cut failed:",e)}})},icon:"lucide-scissors"}),this.plugin.addCommand({id:"insert-callout",name:"Insert Callout(Modal)",icon:"lucide-quote",callback:()=>{new nn(this.plugin).open()}}),this.plugin.addCommand({id:"insert-link",name:"Insert Link(Modal)",icon:"lucide-link",callback:()=>{new sn(this.plugin).open()}}),this.plugin.addCommand({id:"fullscreen-focus",name:"Toggle Fullscreen Focus Mode",hotkeys:[{modifiers:["Mod","Shift"],key:"F11"}],callback:()=>function(t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.toggleFull=exports.isFull=exports.exitFull=exports.beFull=void 0;let o=document.documentElement,n=o.querySelector("head"),i=document.createElement("style"),a="requestFullscreen",s="exitFullscreen",r="fullscreenElement";"webkitRequestFullScreen"in o?(a="webkitRequestFullScreen",s="webkitExitFullscreen",r="webkitFullscreenElement"):"msRequestFullscreen"in o?(a="msRequestFullscreen",s="msExitFullscreen",r="msFullscreenElement"):"mozRequestFullScreen"in o?(a="mozRequestFullScreen",s="mozCancelFullScreen",r="mozFullScreenElement"):"requestFullscreen"in o||console.log("当前浏览器不支持Fullscreen API !");const l=t.workspace.getActiveViewOfType(e.MarkdownView);if(!l)return;let c,d=l.containerEl,u=document.body?.querySelector(".mod-vertical.mod-root .workspace-tab-container");function m(e){return e[a]()}function p(){return o.contains(i)&&(null==n||n.removeChild(i)),document[s]()}function h(e){return e===document[r]}c=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){if(h(u))try{document.body.removeChild(e),d.appendChild(e)}catch(e){console.log(e.message)}})})}),u.addEventListener("fullscreenchange",function(){h(u)||c.disconnect()}),h(u)?(c.disconnect(),p()):(m(u),c.observe(document.body,{childList:!0})),exports.beFull=m,exports.exitFull=p,exports.isFull=h,exports.toggleFull=function(e){return h(e)?(p(),!1):(m(e),!0)}}(app),icon:"fullscreen"}),this.plugin.addCommand({id:"workplace-fullscreen-focus",name:"Toggle Workplace Fullscreen Focus",callback:()=>function(t){on=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;let o=on;t.workspace.leftSplit.collapsed&&t.workspace.rightSplit.collapsed?(t.commands.executeCommandById("app:toggle-right-sidebar"),t.commands.executeCommandById("app:toggle-left-sidebar"),t.workspace.leftRibbon.show(),o.body.classList.contains("auto-hide-header")&&o.body.classList.remove("auto-hide-header")):(o.body.classList.contains("auto-hide-header")||o.body.classList.add("auto-hide-header"),t.workspace.leftRibbon.hide(),t.workspace.leftSplit.collapsed||t.commands.executeCommandById("app:toggle-left-sidebar"),t.workspace.rightSplit.collapsed||t.commands.executeCommandById("app:toggle-right-sidebar"))}(app),hotkeys:[{modifiers:["Mod"],key:"F11"}],icon:"remix-SplitCellsHorizontal"});for(let e=0;e<=6;e++)this.plugin.addCommand({id:`header${e}-text`,name:0===e?"Remove header level":`Header ${e}`,callback:()=>{const t=this.getActiveEditor();t&&this.executeCommandWithoutBlur(t,()=>r("#".repeat(e),t))},icon:0===e?"heading-glyph":`header-${e}`});Object.keys(this._commandsMap).forEach(e=>{this.plugin.addCommand({id:`${e}`,name:`Toggle ${e}`,icon:`${e}-glyph`,callback:()=>{const t=this.getActiveEditor();t&&this.executeCommandWithoutBlur(t,()=>{this.applyCommand(this._commandsMap[e],t)})}})}),this.modCommands.forEach(e=>{this.plugin.addCommand({id:`${e.id}`,name:`${e.name}`,icon:`${e.icon}`,callback:()=>{const t=this.getActiveEditor();t&&this.executeCommandWithoutBlur(t,async()=>{const o=t.getCursor("to");let n=this.getCharacterOffset(e.id);await this.plugin.app.commands.executeCommandById(`${e.id}`),0!=n&&t.setCursor(o.line,o.ch+n)})}})}),this.plugin.addCommand({id:"toggle-format-brush",name:"Toggle Format Brush",icon:"paintbrush",editorCallback:e=>{this.plugin.toggleFormatBrush()}}),this.registerCustomCommands();["toggle-bold","toggle-italics","toggle-strikethrough","toggle-highlight","toggle-code","toggle-blockquote","header0-text","header1-text","header2-text","header3-text","header4-text","header5-text","header6-text","toggle-numbered-list","toggle-bullet-list","format-eraser","indent-list","undent-list","change-font-color","change-background-color",...this.plugin.settings.customCommands.map(e=>`${e.id}`),...Object.keys(this._commandsMap)].forEach(e=>{const t=this.plugin.app.commands.commands[`editing-toolbar:${e}`];if(t&&t.callback){const o=t.callback;t.callback=()=>{o(),this.plugin.setLastExecutedCommand(`editing-toolbar:${e}`)}}})}getCharacterOffset(e){switch(e){case"editor:insert-tag":return 1;case"editor:insert-callout":return 11;default:return 0}}reloadCustomCommands(){this.plugin.settings.customCommands.forEach(e=>{const t=`${e.id}`;this.plugin.app.commands.commands[`editing-toolbar:${t}`]&&delete this.plugin.app.commands.commands[`editing-toolbar:${t}`]}),this.registerCustomCommands()}registerCustomCommands(){this.plugin.settings.customCommands.forEach(e=>{const t=`${e.id}`;this.plugin.addCommand({id:t,name:e.name,icon:e.icon,editorCallback:o=>{if(e.useRegex&&e.regexPattern)o&&this.executeCommandWithoutBlur(o,()=>{this.applyRegexCommand(o,e),this.plugin.setLastExecutedCommand(`editing-toolbar:${t}`)});else{const n={prefix:e.prefix,suffix:e.suffix,char:e.char,line:e.line,islinehead:e.islinehead};this._commandsMap[e.id]=n,o&&this.executeCommandWithoutBlur(o,()=>{this.applyCommand(n,o),this.plugin.setLastExecutedCommand(`editing-toolbar:${t}`)})}}})})}get commandsMap(){return this._commandsMap}}class pn extends e.Modal{constructor(e,t={}){super(e),this.resolver=null,this.settled=!1,this.options=t}openAndWait(){return new Promise(e=>{this.resolver=e,this.open()})}onOpen(){const{contentEl:t,modalEl:o}=this;o.addClass("editing-toolbar-ai-consent-modal"),t.empty(),t.addClass("editing-toolbar-ai-consent");const n=t.createDiv("editing-toolbar-ai-consent-hero");n.createEl("h2",{text:v("Enable AI Editor")}),n.createDiv({cls:"editing-toolbar-ai-consent-desc",text:v("Unlock inline completion, rewrite, frontmatter, and canvas generation right inside your toolbar.")}),n.createDiv({cls:"editing-toolbar-ai-consent-note",text:v("Sign in to PKMer AI for free managed AI, or use your own compatible model.")});const i=t.createDiv("editing-toolbar-ai-consent-section");i.createDiv({cls:"editing-toolbar-ai-consent-section-title",text:v("What you get")});const a=i.createDiv("editing-toolbar-ai-consent-list");this.createListItem(a,v("Inline completion while you write")),this.createListItem(a,v("Rewrite, summarize, and continue text in place")),this.createListItem(a,v("Generate frontmatter, lists, tables, and canvas drafts"));const s=t.createDiv("editing-toolbar-ai-consent-section");s.createDiv({cls:"editing-toolbar-ai-consent-section-title",text:v("Before you enable AI")});const r=s.createDiv("editing-toolbar-ai-consent-list");this.createListItem(r,v("The plugin itself does not intentionally store your note content.")),this.createListItem(r,v("AI requests are sent only to the provider you choose, such as PKMer AI or your custom model.")),this.createListItem(r,v("Those requests remain subject to the provider privacy policy, terms, and model rules.")),this.createListItem(r,v("You can turn AI off at any time in settings."));const l=t.createDiv("editing-toolbar-ai-consent-actions");new e.ButtonComponent(l).setButtonText(v("Not now")).onClick(()=>this.finish(!1)),new e.ButtonComponent(l).setButtonText(v("Agree & Enable AI")).setCta().onClick(()=>this.finish(!0))}onClose(){this.contentEl.empty(),this.resolve(!1)}createListItem(e,t){const o=e.createDiv("editing-toolbar-ai-consent-item");o.createSpan({cls:"editing-toolbar-ai-consent-dot"}),o.createSpan({cls:"editing-toolbar-ai-consent-text",text:t})}finish(e){this.resolve(e),this.close()}resolve(e){this.settled||(this.settled=!0,this.resolver?.(e),this.resolver=null)}}class hn{constructor(e,t){this.customChatCompletionsUrlCache=new Map,this.plugin=e,this.authService=t}async*complete(e,t){const o=await this.requestCompletion(e,t);yield*this.streamText(o,t)}async*rewrite(e,t){const o=await this.requestRewrite(e,t);yield*this.streamText(o,t)}hasCustomProviderConfigured(){return!!this.getCustomProviderValidation().provider}async testCustomProviderConnection(){const e=this.getCustomProviderValidation();if(!e.provider)throw new Error(`Missing custom model settings: ${e.missing.join(", ")}`);await this.requestChatCompletionResult([{role:"system",content:"Reply with OK only."},{role:"user",content:"ping"}],void 0,{maxTokens:1},e.provider)}async listCustomOllamaModels(){const t=this.getCustomProviderValidation().provider;if(!t||"custom"!==t.kind||"ollama"!==t.apiFormat)throw new Error("Ollama custom model settings are not enabled.");const o=this.buildOllamaTagsCandidateUrls(t.baseUrl);let n=null;for(let i=0;i<o.length;i+=1){const a=o[i];try{const o=await e.requestUrl({url:a,method:"GET",headers:this.buildRequestHeaders(t.apiKey)});if(o.status>=200&&o.status<300)return this.extractOllamaModelNames(o.json);throw this.createRequestResponseError(o,a)}catch(e){n=e;if(i<o.length-1&&this.isRetryableEndpointError(e))continue;await this.rethrowUserFacingRequestError(e,a)}}await this.rethrowUserFacingRequestError(n,o[0]??t.baseUrl)}async requestCompletion(e,t){const o=e.prefix.slice(-2e3),n=e.suffix.slice(0,800),i=e.context?`\n\nLocal cursor metadata:\n${e.context}`:"",a=await this.resolveProvider("completion");let s="";for(let e=0;e<3;e++){const r=await this.requestChatCompletionResult(this.buildCompletionMessages(o,n,i,s),t,{maxTokens:this.getCompletionTokenBudget(o,n,s,e),pkmerScene:"completion"},a),l=this.removeRepeatedPrefix(s,r.text);if(!l)break;if(s+=l,"length"!==r.finishReason)return s.trimEnd();if(this.looksSemanticallyComplete(s))return this.trimCompletionToBoundary(s)}return this.trimCompletionToBoundary(s)||s.trimEnd()}async requestRewrite(e,t){return this.requestChatCompletion(this.buildRewriteMessages(e),t,{pkmerScene:this.resolveRewriteScene(e)})}async requestChatCompletion(e,t,o={}){return(await this.requestChatCompletionResult(e,t,o)).text}async requestChatCompletionResult(e,t,o={},n){if(t?.aborted)throw new DOMException("Aborted","AbortError");const i=n??await this.resolveProvider(o.pkmerScene),{response:a}=await this.requestChatCompletionsWithFallback(i,e,t,o);if(t?.aborted)throw new DOMException("Aborted","AbortError");const s=a.json;return{text:this.extractText(s),finishReason:s?.choices?.[0]?.finish_reason??s?.done_reason??(s?.done?"stop":void 0)}}async requestChatCompletionsWithFallback(e,t,o,n={}){const i=this.getChatCompletionsCandidateUrls(e);let a=null;for(let s=0;s<i.length;s+=1){const r=i[s];try{const i=await this.executeChatCompletionsRequest(r,e,t,o,n);return"custom"===e.kind&&this.rememberCustomChatCompletionsUrl(e.baseUrl,e.apiFormat,r),{response:i,requestUrlValue:r}}catch(t){a=t;if("custom"===e.kind&&s<i.length-1&&this.isRetryableEndpointError(t))continue;await this.rethrowUserFacingRequestError(t,r)}}await this.rethrowUserFacingRequestError(a,i[0]??e.baseUrl)}async executeChatCompletionsRequest(t,o,n,i,a={}){const s=await e.requestUrl({url:t,method:"POST",headers:this.buildRequestHeaders(o.apiKey),body:JSON.stringify(this.buildRequestBody(t,o,n,a))});if(s.status>=200&&s.status<300)return s;throw this.createRequestResponseError(s,t)}buildRequestBody(e,t,o,n={}){return"custom"===t.kind&&"ollama"===t.apiFormat?this.buildOllamaRequestBody(e,t,o,n):{model:t.model,temperature:t.temperature,max_tokens:n.maxTokens,stream:!1,messages:o}}buildOllamaRequestBody(e,t,o,n={}){const i={};return Number.isFinite(t.temperature)&&(i.temperature=t.temperature),"number"==typeof n.maxTokens&&(i.num_predict=n.maxTokens),/\/api\/generate$/i.test(e)?{model:t.model,prompt:this.buildOllamaGeneratePrompt(o),stream:!1,options:Object.keys(i).length>0?i:void 0}:{model:t.model,stream:!1,messages:o,options:Object.keys(i).length>0?i:void 0}}buildOllamaGeneratePrompt(e){const t=e.filter(e=>"string"==typeof e.content&&e.content.trim().length>0).map(e=>`${e.role.toUpperCase()}:\n${e.content.trim()}`).join("\n\n");return t?`${t}\n\nASSISTANT:\n`:"ASSISTANT:\n"}async resolveProvider(e="rewrite"){const t=await this.getPKMerProvider(e);if(t)return t;const o=this.getCustomProviderValidation().provider;if(o)return o;throw new Error("No AI provider is configured. Please log in to PKMer or fill in custom model settings.")}async getPKMerProvider(e){const t=this.plugin.settings.ai;return await this.authService.verify()&&this.authService.aiToken?{kind:"pkmer",apiFormat:"openai-compatible",baseUrl:t.pkmerApiBaseUrl,apiKey:this.authService.aiToken,model:P(t,e),temperature:t.customModel.temperature}:null}getCustomProviderValidation(){if(!this.plugin.settings.ai.enableCustomModel)return{provider:null,missing:["disabled"]};const e=this.plugin.settings.ai.customModel,t=this.authService.customModelApiKey.trim(),o=e.apiFormat??"openai-compatible",n=[];return e.baseUrl.trim()||n.push("baseUrl"),e.model.trim()||n.push("model"),"ollama"===o||t||n.push("apiKey"),n.length>0?{provider:null,missing:n}:{provider:{kind:"custom",apiFormat:o,baseUrl:e.baseUrl.trim(),apiKey:t,model:e.model.trim(),temperature:e.temperature},missing:[]}}buildChatCompletionsUrl(e){return this.buildChatCompletionsCandidateUrls(e)[0]??e.trim().replace(/\/+$/,"")}getChatCompletionsCandidateUrls(e){if("custom"!==e.kind)return[this.buildChatCompletionsUrl(e.baseUrl)];const t=this.getCustomProviderCacheKey(e.baseUrl,e.apiFormat),o=this.customChatCompletionsUrlCache.get(t),n="ollama"===e.apiFormat?this.buildOllamaCandidateUrls(e.baseUrl):this.buildChatCompletionsCandidateUrls(e.baseUrl);return o?[o,...n.filter(e=>e!==o)]:n}buildChatCompletionsCandidateUrls(e){const t=this.normalizeProviderBaseUrl(e);if(!t)return[];if(/\/chat\/completions$/i.test(t))return[t];if(/\/v\d+$/i.test(t))return[`${t}/chat/completions`];const o=`${t}/chat/completions`,n=`${t}/v1/chat/completions`,i=`${t}/v3/chat/completions`;return this.hasPathSegment(t)?[o,n,i]:[n,o,i]}buildOllamaCandidateUrls(e){const t=this.normalizeProviderBaseUrl(e);return t?/\/api\/(chat|generate)$/i.test(t)?[t]:/\/api$/i.test(t)?[`${t}/chat`,`${t}/generate`]:[`${t}/api/chat`,`${t}/api/generate`]:[]}buildOllamaTagsCandidateUrls(e){const t=this.normalizeProviderBaseUrl(e);return t?/\/api\/tags$/i.test(t)?[t]:/\/api\/(chat|generate)$/i.test(t)?[t.replace(/\/(chat|generate)$/i,"/tags")]:/\/api$/i.test(t)?[`${t}/tags`]:[`${t}/api/tags`]:[]}buildRequestHeaders(e){const t={"Content-Type":"application/json"};return e.trim()&&(t.Authorization=`Bearer ${e}`),t}normalizeProviderBaseUrl(e){return e.trim().replace(/\/+$/,"")}hasPathSegment(e){try{const{pathname:t}=new URL(e),o=t.replace(/\/+$/,"");return o.length>0&&"/"!==o}catch{return!1}}getCustomProviderCacheKey(e,t){return`${t}:${this.normalizeProviderBaseUrl(e)}`}rememberCustomChatCompletionsUrl(e,t,o){this.customChatCompletionsUrlCache.set(this.getCustomProviderCacheKey(e,t),o)}isRetryableEndpointError(e){const t=Ho(e);if(404===t||405===t||410===t)return!0;if(400===t||422===t){const t=Wo(e).toLowerCase();return/not found|no route|unknown path|unknown endpoint|invalid url|invalid path|unsupported path|unsupported endpoint/.test(t)}return!1}createRequestResponseError(e,t){const o=e.json?.error?.message||e.json?.message||e.text||`Request failed with status ${e.status} (${t})`,n=new Error("string"==typeof o?o.trim():String(o));return n.status=e.status,n.response=e,n}extractOllamaModelNames(e){const t=(Array.isArray(e?.models)?e.models:[]).map(e=>"string"==typeof e?.name&&e.name.trim()?e.name.trim():"string"==typeof e?.model&&e.model.trim()?e.model.trim():"").filter(e=>!!e);return Array.from(new Set(t)).sort((e,t)=>e.localeCompare(t))}async rethrowUserFacingRequestError(e,t){if(await this.isPKMerQuotaError(e,t))throw new Vo(v("PKMer AI request failed because your quota is insufficient. Please get more quota in PKMer and try again."));throw e}async isPKMerQuotaError(e,t){if(!/pkmer\.cn/i.test(t))return!1;if(403!==Ho(e))return!1;const o=await this.authService.refreshQuota().catch(()=>null),n=o?.quota??o?.remainingQuota;if("number"==typeof n){if(Number((n/5e5).toFixed(2))<=1)return!0}const i=Wo(e).toLowerCase();return/quota|credit|balance|insufficient|额度|点数|余量不足|余额不足/.test(i)}buildCompletionMessages(e,t,o,n){return[{role:"system",content:"You are an inline writing assistant inside Obsidian. Continue the text exactly at the cursor using only the local context around the cursor. Return only the continuation text, with no explanations, no markdown fences, and no quotes. Produce one complete semantic unit that fits the local structure, such as one full sentence, one complete bullet item, one heading continuation, or one short paragraph. Never stop mid-word, mid-sentence, or mid-list-item."},{role:"user",content:`Continue the text at <CURSOR>. Use the local cursor context below, not the whole document.${n?"\n\nA draft continuation has already been generated. Continue exactly from where that draft ends. Do not repeat or paraphrase any previously generated text.":""}\n\nText before cursor:\n${`${e}${n}`}\n\n<CURSOR>\n\nText after cursor:\n${t}${o}`}]}resolveRewriteScene(e){return e.artifactKind?"artifact":"explain"===e.instruction||"summarize"===e.instruction||"custom"===e.instruction?"reasoning":"rewrite"}buildRewriteMessages(e){const t=this.buildRewriteInstruction(e.instruction,e.customPrompt),o=e.selectedText.trim().length>0,n=e.context?`\n\nLocal document context:\n${e.context}`:"",i=this.buildRewriteSystemPrompt(e.artifactKind),a=this.buildRewriteOutputRequirement(e.artifactKind);return[{role:"system",content:i},{role:"user",content:o?`Instruction:\n${t}\n\nTarget text:\n${e.selectedText}${n}\n\nRequirements:\n- Use the local context only to keep terminology, links, and structure consistent.\n- ${a}`:`Instruction:\n${t}\n\nTarget text:\n(none - use the local cursor context)${n}\n\nRequirements:\n- There is no explicit selection, so generate text that fits naturally at the cursor location.\n- ${a}`}]}buildRewriteSystemPrompt(e){return"canvas"===e?"You are an expert Obsidian Canvas generator. Generate production-ready JSON Canvas files that obey the JSON Canvas structure exactly. Return only valid JSON, never explanations, never markdown fences, and never partial structures. The output must be directly saveable as a .canvas file and open cleanly in Obsidian. Ensure nodes and edges are coherent, spatially organized, and semantically useful rather than generic placeholders.":"base"===e?"You are an expert Obsidian Bases generator. Generate production-ready .base YAML files that obey Obsidian Bases conventions. Return only valid YAML, never explanations, never markdown fences, and never partial structures. The output must be directly saveable as a .base file and open cleanly in Obsidian. Prefer practical fields, formulas, and views over placeholder content.":"frontmatter"===e?"You are an expert Obsidian note metadata assistant. Generate concise, practical YAML frontmatter for the current note. Return only one complete YAML frontmatter block wrapped by --- lines, never explanations, never markdown fences, and never partial YAML. Prefer real-world note properties that help filtering, browsing, and vault consistency. Follow existing folder conventions when they are provided in context.":"You are an editor assistant inside Obsidian. Rewrite, transform, or generate text according to the instruction. Preserve valid Obsidian Flavored Markdown whenever possible, including wikilinks, embeds, callouts, task lists, tables, properties, and inline formatting unless the instruction explicitly changes the format. Return only the final text, with no explanations, no markdown fences, and no surrounding quotes. Never stop mid-list-item, mid-table-row, mid-YAML block, or mid-JSON structure."}buildRewriteOutputRequirement(e){return"canvas"===e?"Return one complete JSON Canvas document with top-level nodes and edges arrays only. Make it visually useful, not minimal.":"base"===e?"Return one complete .base YAML document only. Make it practical and directly usable in Obsidian.":"frontmatter"===e?"Return one complete YAML frontmatter block only, wrapped in --- delimiters, ready to insert at the top of the note.":"Return only the final text ready to paste into the note."}getCompletionTokenBudget(e,t,o,n){if(n>0)return 96;const i=e.trimEnd(),a=t.trimStart(),s=i.split("\n").pop()??"";return/^\s*#{1,6}\s*$/.test(s)?48:/^\s*(?:[-*+] |\d+\. |> )?$/.test(s)?96:!a||o.includes("\n")?192:160}removeRepeatedPrefix(e,t){const o=t;if(!e)return t;if(!o.trim())return"";for(let t=Math.min(e.length,o.length,120);t>0;t--)if(e.slice(-t)===o.slice(0,t))return o.slice(t);return o}looksSemanticallyComplete(e){const t=e.trimEnd();if(!t)return!1;if(/[。!?.!?…'")】》]$/.test(t))return!0;const o=t.split("\n").pop()??"";return!!(/^\s*(?:[-*+] |\d+\. |> )/.test(o)&&o.trim().length>=8)}extractText(e){const t=e?.choices?.[0]?.message?.content??e?.choices?.[0]?.text??e?.message?.content??e?.response??"";return"string"==typeof t?t.trim():Array.isArray(t)?t.map(e=>"string"==typeof e?e:e?.text||e?.content||"").join("").trim():""}trimCompletionToBoundary(e){const t=e.trim();if(!t)return t;const o=Array.from(t.matchAll(/[。!?.!?;:\n]/g));if(o.length>0){const e=o[o.length-1],n=(e.index??-1)+e[0].length;if(n>=Math.max(12,Math.floor(.45*t.length)))return t.slice(0,n).trimEnd()}const n=t.lastIndexOf(" ");return n>=Math.max(12,Math.floor(.6*t.length))?t.slice(0,n).trimEnd():t}async*streamText(e,t){const o=e.split(/(\s+)/).filter(e=>e.length>0);for(const e of o){if(t?.aborted)throw new DOMException("Aborted","AbortError");yield e,await this.delay(18,t)}}delay(e,t){return new Promise((o,n)=>{if(t?.aborted)return void n(new DOMException("Aborted","AbortError"));const i=window.setTimeout(o,e);t?.addEventListener("abort",()=>{window.clearTimeout(i),n(new DOMException("Aborted","AbortError"))},{once:!0})})}buildRewriteInstruction(e,t){switch(e){case"improve":return"Improve clarity, fluency, and structure while keeping the original meaning.";case"fix-grammar":return"Fix spelling, grammar, and punctuation issues.";case"make-shorter":return"Make the text shorter and more concise.";case"make-longer":return"Expand the text with useful supporting detail.";case"simplify":return"Rewrite the text in simpler language.";case"professional":return"Rewrite the text in a professional tone.";case"casual":return"Rewrite the text in a casual tone.";case"translate-en":return"Translate the text into English.";case"translate-zh":return"Translate the text into Simplified Chinese.";case"translate-ja":return"Translate the text into Japanese.";case"translate-de":return"Translate the text into German.";case"translate-fr":return"Translate the text into French.";case"translate-es":return"Translate the text into Spanish.";case"explain":return"Explain the text in a clear, structured way.";case"summarize":return"Summarize the text while preserving the key points.";case"continue":return"Continue writing in a consistent tone and style.";case"custom":return t?.trim()||"Rewrite the selected text.";default:return"Rewrite the selected text."}}}const gn=new Set(["text","file","link","group"]),fn=new Set(["top","right","bottom","left"]),bn=new Set(["none","arrow"]);function yn(e){const t=vn(e.content);if(!t)throw new Error(v("AI generated content is empty."));return"canvas"===e.kind?function(e,t){let o;try{o=JSON.parse(e)}catch{throw new Error(v("AI returned invalid Canvas JSON."))}if(!o||"object"!=typeof o)throw new Error(v("AI returned invalid Canvas JSON."));const n=o,i=new Set,a=Array.isArray(n.nodes)?n.nodes:[],s=Array.isArray(n.edges)?n.edges:[];let r=a.map((e,o)=>function(e,t,o,n){if(!e||"object"!=typeof e)return null;const i=e,a=gn.has(i.type)?i.type:"text",s=Mn(i.id,t),r="string"==typeof i.color&&i.color.trim()?i.color.trim():void 0;if("group"===a)return{id:s,type:a,x:Nn(i.x,60*n-40),y:Nn(i.y,-60),width:Dn(i.width,680,240,2800),height:Dn(i.height,420,160,2200),label:"string"==typeof i.label?i.label.trim():Tn(o),color:r,background:"string"==typeof i.background?i.background:void 0,backgroundStyle:"string"==typeof i.backgroundStyle?i.backgroundStyle:void 0};if("file"===a&&"string"==typeof i.file&&i.file.trim())return{id:s,type:a,x:Nn(i.x,0),y:Nn(i.y,0),width:Dn(i.width,360,260,560),height:Dn(i.height,240,160,420),file:i.file.trim(),color:r};if("link"===a&&"string"==typeof i.url&&i.url.trim())return{id:s,type:a,x:Nn(i.x,0),y:Nn(i.y,0),width:Dn(i.width,320,240,520),height:Dn(i.height,180,120,320),url:i.url.trim(),color:r};const l=function(e,t,o){const n=[e.text,e.label,e.title,e.name,e.file,e.url];for(const e of n)if("string"==typeof e&&e.trim())return e.trim().replace(/\\n/g,"\n");const i=t.replace(/\r\n?/g,"\n").split("\n").map(e=>e.trim()).filter(Boolean);if(i[o])return i[o];return Sn(t)}(i,o,n),c=En(l);return{id:s,type:"text",x:Nn(i.x,0),y:Nn(i.y,0),width:Dn(i.width,c.width,220,620),height:Dn(i.height,c.height,90,420),text:l,color:r}}(e,i,t,o)).filter(e=>null!==e);0===r.length&&(r=[kn(i,t)]);let l=s.map(e=>function(e,t,o){if(!e||"object"!=typeof e)return null;const n=e,i="string"==typeof n.fromNode?n.fromNode.trim():"",a="string"==typeof n.toNode?n.toNode.trim():"";if(!o.has(i)||!o.has(a)||i===a)return null;return{id:Mn(n.id,t),fromNode:i,toNode:a,fromSide:An(n.fromSide,fn),toSide:An(n.toSide,fn),fromEnd:An(n.fromEnd,bn),toEnd:An(n.toEnd,bn)??"arrow",color:"string"==typeof n.color&&n.color.trim()?n.color.trim():void 0,label:"string"==typeof n.label&&n.label.trim()?n.label.trim():void 0}}(e,i,new Set(r.map(e=>e.id)))).filter(e=>null!==e);0===l.length&&r.filter(e=>"group"!==e.type).length>2&&(l=function(e,t){const o=e.filter(e=>"group"!==e.type);if(o.length<2)return[];const[n,...i]=o;return i.map(e=>({id:Mn(void 0,t),fromNode:n.id,toNode:e.id,toEnd:"arrow"}))}(r,i));const c=function(e,t,o){const n=e.nodes.filter(e=>"group"!==e.type),i=e.nodes.filter(e=>"group"===e.type),a=new Map,s=new Map;for(const e of n)a.set(e.id,new Set),s.set(e.id,0);for(const t of e.edges)a.has(t.fromNode)&&a.has(t.toNode)&&(a.get(t.fromNode)?.add(t.toNode),a.get(t.toNode)?.add(t.fromNode),s.set(t.fromNode,(s.get(t.fromNode)??0)+1),s.set(t.toNode,(s.get(t.toNode)??0)+1));const r=function(e,t,o){if(0===e.length)return null;const n=e.find(e=>(e.text||"").trim().startsWith("# "));if(n)return n;const i=Tn(o).toLowerCase(),a=e.find(e=>(e.text||"").toLowerCase().includes(i));if(a)return a;return[...e].sort((e,o)=>{const n=(t.get(o.id)??0)-(t.get(e.id)??0);return 0!==n?n:(o.text||"").length-(e.text||"").length})[0]}(n,s,t),l=function(e,t,o){if(0===e.length)return[];const n=new Map(e.map(e=>[e.id,e])),i=new Set,a=o?[o,...e.map(e=>e.id).filter(e=>e!==o)]:e.map(e=>e.id),s=[];for(const e of a){if(i.has(e)||!n.has(e))continue;const o=[{id:e,depth:0===s.length?0:s.length}];for(i.add(e);o.length>0;){const e=o.shift();s[e.depth]||(s[e.depth]=[]),s[e.depth].push(n.get(e.id));[...t.get(e.id)??[]].filter(e=>!i.has(e)).sort((e,t)=>(n.get(t)?.text||"").length-(n.get(e)?.text||"").length).forEach(t=>{i.add(t),o.push({id:t,depth:e.depth+1})})}}return s.filter(e=>e&&e.length>0)}(n,a,r?.id),c=420;l.forEach((e,t)=>{const o=e.reduce((e,t)=>e+t.height,0)+42*Math.max(0,e.length-1);let n=-Math.round(o/2);e.forEach(e=>{e.x=t*c,e.y=n,n+=e.height+42})}),1===n.length&&(n[0].x=0,n[0].y=0);const d=function(e,t,o,n){if(0===t.length)return e;const i=function(e){const t=Math.min(...e.map(e=>e.x)),o=Math.min(...e.map(e=>e.y)),n=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));return{x:t,y:o,width:n-t,height:i-o}}(t);if(0===e.length)return[{id:Mn(void 0,o),type:"group",x:i.x-70,y:i.y-70,width:i.width+140,height:i.height+140,label:Tn(n),color:"4"}];const[a,...s]=e;return a.x=i.x-70,a.y=i.y-70,a.width=i.width+140,a.height=i.height+140,a.label=a.label||Tn(n),s.forEach((e,t)=>{e.x=i.x-70+24*(t+1),e.y=i.y-70+24*(t+1),e.width=Math.max(240,i.width+90-18*(t+1)),e.height=Math.max(180,i.height+90-18*(t+1))}),e}(i,n,o,t);return{nodes:[...d,...n],edges:e.edges}}({nodes:r,edges:l},t,i);return`${JSON.stringify(c,null,2)}\n`}(t,e.sourceText):function(e,t){const o=e.replace(/\r\n?/g,"\n").replace(/\t/g," ").trim();if(!/^(filters|formulas|properties|summaries|views):/m.test(o))return`${function(e){const t=Tn(e);return["filters:"," and: []","properties:"," file.name:",' displayName: "Name"'," file.folder:",' displayName: "Folder"',"views:"," - type: table",` name: "${xn(t)}"`," order:"," - file.name"," - file.folder"].join("\n")}(t)}\n`;let n=o;/^views:/m.test(n)?/^\s*-\s+type:/m.test(n)||(n=n.replace(/^views:\s*$/m,`views:\n${function(e,t){const o=" ".repeat(t);return e.split("\n").map(e=>`${o}${e}`).join("\n")}(wn(),2)}`)):n=`${n}\n\n${["views:",...wn().split("\n")].join("\n")}`;/^\s+order:\s*$/m.test(n)||(n=n.replace(/(^\s*-\s+type:\s+[\w-]+\s*\n\s+name:\s+.+$)/m,"$1\n order:\n - file.name"));return`${n.trim()}\n`}(t,e.sourceText)}function Cn(e,t={}){const o=vn(e);if(!o)throw new Error(v("AI generated content is empty."));const n=o.replace(/^---\s*\n?/i,"").replace(/\n?---\s*$/i,"").trim();if(!n)throw new Error(v("AI generated content is empty."));const i=function(e,t){if(!t||0===Object.keys(t).length)return e;const o=e.replace(/\r\n?/g,"\n").split("\n"),n=new Set(o.map(e=>e.match(/^([A-Za-z0-9_-]+):(?:\s|$)/)?.[1]).filter(e=>!!e));return o.map(e=>{const o=e.match(/^([A-Za-z0-9_-]+):(.*)$/);if(!o)return e;const[,i,a]=o,s=t[i];return s&&s!==i?n.has(s)?e:`${s}:${a}`:e}).join("\n").trim()}(n,t);return`---\n${i}\n---\n\n`}function vn(e){return e.trim().replace(/^```(?:json|yaml|yml)?\s*/i,"").replace(/\s*```\s*$/i,"").trim()}function wn(){return["- type: table",' name: "Overview"'," order:"," - file.name"].join("\n")}function xn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function kn(e,t){const o=Sn(t),n=En(o);return{id:Mn(void 0,e),type:"text",x:0,y:0,width:n.width,height:n.height,text:o}}function Sn(e){const t=e.replace(/\r\n?/g,"\n").split("\n").map(e=>e.trim()).filter(Boolean).slice(0,6);if(0===t.length)return"# Canvas\n\n- Key point";const[o,...n]=t,i=n.slice(0,4).map(e=>`- ${e.replace(/^[-*+]\s+/,"")}`);return[`# ${In(o,48)}`,i.length?"":null,...i].filter(e=>null!==e).join("\n")}function Tn(e){return In(e.replace(/\r\n?/g,"\n").split("\n").map(e=>e.trim()).find(Boolean)||v("Untitled"),42)}function En(e){const t=e.split("\n"),o=t.reduce((e,t)=>Math.max(e,t.length),0);return{width:Math.min(520,Math.max(260,180+6*o)),height:Math.min(320,Math.max(110,70+28*t.length))}}function In(e,t){const o=e.trim();return o.length<=t?o:`${o.slice(0,Math.max(0,t-1)).trimEnd()}`}function An(e,t){if("string"!=typeof e)return;const o=e.trim();return t.has(o)?o:void 0}function Mn(e,t){if("string"==typeof e){const o=e.trim().toLowerCase();if(/^[0-9a-f]{16}$/.test(o)&&!t.has(o))return t.add(o),o}let o="";do{o=Pn()}while(t.has(o));return t.add(o),o}function Pn(){const e=new Uint8Array(8);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(256*Math.random());return Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}function Nn(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Dn(e,t,o,n){const i=Nn(e,t);return Math.max(o,Math.min(n,Math.round(i)))}function Ln(e){const t=e.app.workspace.activeLeaf?.view;return function(e){return!!e&&"canvas"===e.getViewType?.()&&"function"==typeof e.getViewData&&"function"==typeof e.setViewData}(t)?t:null}async function Fn(e,t={}){const o=Ln(e);if(!o)throw new Error(v("Canvas AI requires an active Canvas file."));const n=o.file??e.app.workspace.getActiveFile();if(!n||"canvas"!==n.extension)throw new Error(v("Canvas AI requires an active Canvas file."));const i=function(e){let t;try{t=JSON.parse(e)}catch{throw new Error(v("Failed to read the current canvas data."))}if(!t||"object"!=typeof t)throw new Error(v("Failed to read the current canvas data."));const o=t;return{nodes:Array.isArray(o.nodes)?o.nodes.map(e=>function(e){if(!e||"object"!=typeof e)return null;const t=e,o="string"==typeof t.id?t.id.trim():"",n=function(e){if("text"===e||"file"===e||"link"===e||"group"===e)return e;return null}(t.type);if(!o||!n)return null;return{id:o,type:n,x:vi(t.x,0),y:vi(t.y,0),width:vi(t.width,320),height:vi(t.height,180),text:"string"==typeof t.text?t.text:void 0,file:"string"==typeof t.file?t.file:void 0,url:"string"==typeof t.url?t.url:void 0,label:"string"==typeof t.label?t.label:void 0,color:"string"==typeof t.color?t.color:void 0,background:"string"==typeof t.background?t.background:void 0,backgroundStyle:"string"==typeof t.backgroundStyle?t.backgroundStyle:void 0}}(e)).filter(e=>null!==e):[],edges:Array.isArray(o.edges)?o.edges.map(e=>function(e){if(!e||"object"!=typeof e)return null;const t=e,o="string"==typeof t.id?t.id.trim():"",n="string"==typeof t.fromNode?t.fromNode.trim():"",i="string"==typeof t.toNode?t.toNode.trim():"";if(!o||!n||!i)return null;return{id:o,fromNode:n,toNode:i,fromSide:"string"==typeof t.fromSide?t.fromSide:void 0,toSide:"string"==typeof t.toSide?t.toSide:void 0,fromEnd:"string"==typeof t.fromEnd?t.fromEnd:void 0,toEnd:"string"==typeof t.toEnd?t.toEnd:void 0,color:"string"==typeof t.color?t.color:void 0,label:"string"==typeof t.label?t.label:void 0}}(e)).filter(e=>null!==e):[]}}(o.getViewData()),a=new Map(i.nodes.map(e=>[e.id,e])),s=function(e,t){const o=new Set(t.nodes.map(e=>e.id)),n=new Set,i=e,a=Ci(i.canvas);gi(a?.selection,n,o),gi(Ci(a?.selection)?.nodes,n,o),gi(Ci(a?.selection)?.items,n,o),gi(Ci(i.selection)?.nodes,n,o),gi(a?.selectedNodes,n,o),gi(i.selectedNodes,n,o);return[a?.nodes,a?.nodeMap,i.nodes,i.nodeMap].forEach(e=>{fi(e,e=>{const t=Ci(e),i=bi(t,o);if(!i)return;[t.selected,t.isSelected,Ci(t.nodeEl)?.classList,Ci(t.el)?.classList].some(e=>!0===e)&&n.add(i)})}),function(e,t){const o=e.containerEl;if(!o)return[];const n=[".canvas-node.is-selected",".canvas-node.mod-selected",".canvas-node.is-focused",".canvas-node.mod-focused"],i=new Set;return o.querySelectorAll(n.join(",")).forEach(e=>{let o=e;for(;o;){const e=yi(o,t);if(e){i.add(e);break}o=o.parentElement}}),[...i]}(e,o).forEach(e=>n.add(e)),[...n]}(o,i),r=function(e,t){for(const o of t){const t=e.get(o);if(t&&"group"!==t.type)return t}const o=[...e.values()].filter(e=>"group"!==e.type);if(1===o.length)return o[0];return null}(a,s);if(!r&&!1!==t.requireAnchor)throw new Error(v("Please select a canvas node first."));const l=await async function(e,t,o,n){if(0===o.length)return[];const i=new Map(t.nodes.map(e=>[e.id,e])),a=n?[n,...o.filter(e=>e!==n)]:o,s=[];for(const t of a){const o=i.get(t);if(o&&"group"!==o.type&&(s.push(await _n(e,o)),s.length>=6))break}return s}(e,i,s,r?.id??null),c=r?await async function(e,t,o){const n=new Map(t.nodes.map(e=>[e.id,e])),i=new Set;for(const e of t.edges)e.fromNode===o?i.add(e.toNode):e.toNode===o&&i.add(e.fromNode);const a=[...i].map(e=>n.get(e)).filter(e=>!!e&&"group"!==e.type).slice(0,10),s=[];for(const t of a)s.push(await _n(e,t));return s}(e,i,r.id):[],d=r?await _n(e,r):null,u=function(e,t,o,n,i,a){const s=t.nodes.filter(e=>"group"!==e.type),r=s.filter(e=>!o||e.id!==o.id&&!a.some(t=>t.id===e.id)).slice(0,10).map(e=>Wn({id:e.id,type:e.type,text:Un(e.text||e.label||e.file||e.url||""),node:e})),l=a.length>0?a.map((e,t)=>`${t+1}. ${Wn(e)}`).join("\n"):"(none)",c=i.length>0?i.map((e,t)=>`${t+1}. ${Wn(e)}`).join("\n"):"(none)",d=(o?t.edges.filter(e=>e.fromNode===o.id||e.toNode===o.id).slice(0,12):t.edges.slice(0,16)).map(e=>function(e,t){if(t&&(e.fromNode===t||e.toNode===t)){return`- ${e.fromNode===t?"outgoing":"incoming"} ${e.fromNode===t?e.toNode:e.fromNode}${e.label?` [${e.label}]`:""}`}return`- ${e.fromNode} -> ${e.toNode}${e.label?` [${e.label}]`:""}`}(e,o?.id)).join("\n")||"(none)";return[`canvas_file: ${e.path}`,"focus_mode: "+(o?"selected-node":"board-wide"),`selected_node_ids: ${n.join(", ")||"(none)"}`,`board_node_count: ${s.length}`,"selected_nodes:",c,"anchor_node:",o?Wn(o):"(none selected)",o?"anchor_connections:":"sample_board_connections:",d,"neighboring_nodes:",o?l:"(none)",o?"other_board_nodes:":"board_nodes:",r.length>0?r.join("\n"):"(none)"].join("\n\n")}(n,i,d,s,l,c);return{view:o,file:n,document:i,anchorNode:d,selectedNodeIds:s,selectedNodes:l,neighboringNodes:c,contextText:u}}async function On(e,t,o={}){const n=t.document.nodes.filter(e=>"group"!==e.type),i=t.selectedNodeIds.filter(e=>n.some(t=>t.id===e)),a=o.scopeMode??"auto",s=("selection"===a||"board"!==a)&&i.length>0,r=s?i:n.map(e=>e.id),l=function(e,t){const o=new Map(e.nodes.map(e=>[e.id,e])),n=new Set(t),i=new Map,a=new Map;t.forEach(e=>{i.set(e,[]),a.set(e,0)}),e.edges.forEach(e=>{n.has(e.fromNode)&&n.has(e.toNode)&&(i.get(e.fromNode)?.push(e.toNode),a.set(e.toNode,(a.get(e.toNode)??0)+1))}),i.forEach((e,t)=>{e.sort((e,t)=>Vn(o.get(e),o.get(t))),i.set(t,Array.from(new Set(e)))});const s=t.filter(e=>0===(a.get(e)??0)).sort((e,t)=>Vn(o.get(e),o.get(t))),r=t.slice().sort((e,t)=>Vn(o.get(e),o.get(t))),l=new Set,c=[],d=e=>{l.has(e)||(l.add(e),c.push(e),(i.get(e)??[]).forEach(e=>d(e)))};return(s.length>0?s:r).forEach(e=>d(e)),r.forEach(e=>d(e)),c}(t.document,r),c=l.map(e=>t.document.nodes.find(t=>t.id===e)).filter(e=>!!e),d=c.slice(0,48),u=new Set(d.map(e=>e.id)),m=[];for(const[o,n]of d.entries()){const i=await _n(e,n),a=t.document.edges.filter(e=>e.fromNode===n.id&&u.has(e.toNode)).map(e=>`- ${e.toNode}${e.label?` [${e.label}]`:""}`).slice(0,8),s=t.document.edges.filter(e=>e.toNode===n.id&&u.has(e.fromNode)).map(e=>`- ${e.fromNode}${e.label?` [${e.label}]`:""}`).slice(0,8);m.push([`node_index: ${o+1}`,Wn(i),`incoming_links:\n${s.join("\n")||"(none)"}`,`outgoing_links:\n${a.join("\n")||"(none)"}`].join("\n"))}const p=c.length-d.length,h=["document_scope: "+(s?"selected-nodes":"whole-canvas"),`document_node_count: ${c.length}`,"ordered_canvas_nodes:",m.join("\n\n")];return p>0&&h.push(`truncated_nodes: ${p}`),{scope:s?"selection":"board",nodeCount:c.length,text:h.join("\n\n")}}function Rn(e,t){const o=e.document.nodes.filter(e=>"group"!==e.type),n=function(e,t){const o=new Set(t.map(e=>e.id)),n=e.selectedNodeIds.filter(e=>o.has(e));return n.length>0?n:t.map(e=>e.id)}(e,o);if(0===n.length)return{addNodes:[],addEdges:[],layoutNodes:[],replaceExistingEdges:!1};const i=new Map(o.filter(e=>n.includes(e.id)).map(e=>[e.id,e])),a=new Set(n),s=e.document.edges.filter(e=>a.has(e.fromNode)&&a.has(e.toNode)&&e.fromNode!==e.toNode),r=function(e,t,o){const n=e.toLowerCase();if(/(mind\s*map|radial|中心主题|脑图|思维导图|发散)/i.test(n))return"mindmap";if(/(^|\b)(tree|hierarchy|org\s*chart)(\b|$)|树形|树状|层级|父子|组织结构/i.test(n))return"tree";if(/(dag|directed\s+acyclic|flow\s*chart|pipeline|dependency|依赖图|流程图|有向无环|拓扑)/i.test(n))return"dag";const i=Math.max(t.length,1),a=o.length/i,s=t.some(e=>o.filter(t=>t.toNode===e).length>1);if(s||a>1.15)return"dag";return"tree"}(t||e.contextText,n,s),l=new Map,c=new Map;n.forEach(e=>{l.set(e,[]),c.set(e,[])}),s.forEach(e=>{const t=l.get(e.fromNode);t&&!t.includes(e.toNode)&&t.push(e.toNode);const o=c.get(e.toNode);o&&!o.includes(e.fromNode)&&o.push(e.fromNode)}),l.forEach((e,t)=>{l.set(t,e.sort((e,t)=>Vn(i.get(e),i.get(t))))}),c.forEach((e,t)=>{c.set(t,e.sort((e,t)=>Vn(i.get(e),i.get(t))))});const d=function(e,t,o){const n=new Map;e.forEach(e=>{n.set(e,new Set)}),t.forEach(e=>{n.get(e.fromNode)?.add(e.toNode),n.get(e.toNode)?.add(e.fromNode)});const i=e.slice().sort((e,t)=>Vn(o.get(e),o.get(t))),a=new Set,s=[];return i.forEach(e=>{if(a.has(e))return;const t=[e],i=[];for(a.add(e);t.length>0;){const e=t.shift();e&&(i.push(e),n.get(e)?.forEach(e=>{a.has(e)||(a.add(e),t.push(e))}))}i.sort((e,t)=>Vn(o.get(e),o.get(t))),s.push(i)}),s.sort((e,t)=>Vn(o.get(e[0]),o.get(t[0])))}(n,s,i),u=[];let m=0;return d.forEach((t,o)=>{const n=function(e,t,o,n,i,a){const s=new Set(e),r=e.slice().sort((e,o)=>Vn(t.get(e),t.get(o))),l=r.filter(e=>(n.get(e)??[]).every(e=>!s.has(e))),c=(l.length>0?l:r.slice(0,1)).slice();if(a&&s.has(a)){const e=c.indexOf(a);e>=0?(c.splice(e,1),c.unshift(a)):0===l.length&&c.unshift(a)}const d=new Map;e.forEach(e=>{d.set(e,[])});const u=new Map,m=new Set,p=[],h=(e,n)=>{m.add(e),u.set(e,n);const i=(o.get(e)??[]).filter(e=>s.has(e)&&!m.has(e)).sort((e,o)=>Vn(t.get(e),t.get(o)));d.set(e,i),i.forEach(e=>h(e,n+1))};c.forEach(e=>{m.has(e)||(p.push(e),h(e,0))}),r.forEach(e=>{m.has(e)||(p.push(e),h(e,0))});const g=new Map,f=e=>{const t=g.get(e);if(void 0!==t)return t;const o=d.get(e)??[];if(0===o.length)return g.set(e,2),2;const n=o.reduce((e,t)=>e+f(t),0),i=Math.max(2,n+1*Math.max(0,o.length-1));return g.set(e,i),i},b=[],y=(e,t)=>{const o=f(e),n=t+Math.floor((o-1)/2),i=u.get(e)??0;b.push({nodeId:e,column:i,row:n});let a=t;(d.get(e)??[]).forEach(e=>{y(e,a),a+=f(e)+1})};let C=0;p.forEach((e,t)=>{y(e,C),C+=f(e),t<p.length-1&&(C+=2)});const v=Hn(b);return"mindmap"===i?function(e,t){if(!t||e.length<4)return e;const o=e.find(e=>e.nodeId===t);if(!o)return e;const n=e.filter(e=>e.column===o.column+1).sort((e,t)=>e.row-t.row||e.nodeId.localeCompare(t.nodeId));if(n.length<3)return e;const i=new Set(n.filter((e,t)=>t%2==1).map(e=>e.nodeId));if(0===i.size)return e;const a=new Map;return n.forEach(e=>{a.set(e.row,i.has(e.nodeId)?"left":"right")}),Hn(e.map(e=>{if(e.nodeId===t||e.column<=o.column)return e;const n=[...a.keys()].sort((t,o)=>Math.abs(t-e.row)-Math.abs(o-e.row))[0];return"right"===(a.get(n)??"right")?e:{...e,column:o.column-(e.column-o.column)}}))}(v,c[0]):v}(t,i,l,c,r,e.anchorNode?.id??null),a=n.reduce((e,t)=>Math.max(e,t.row),0);n.forEach(e=>{u.push({...e,row:e.row+m})}),o<d.length-1&&(m+=a+3+1)}),{addNodes:[],addEdges:[],layoutNodes:Hn(u),replaceExistingEdges:!1}}function qn(e){const t=Jn(e);let o;try{o=JSON.parse(t)}catch{throw new Error(v("Canvas AI returned invalid JSON."))}const n=Array.isArray(o)?o:null,i=n?n.map(e=>Kn(e)).filter(e=>null!==e).slice(0,8):function(e){const t=Ci(e);if(!t)return[];const o=[t.addNodes,t.nodes,t.items,t.children];for(const e of o)if(Array.isArray(e))return e;return[]}(o).map(e=>Kn(e)).filter(e=>null!==e).slice(0,8),a=n&&0===i.length?n.map(e=>Gn(e)).filter(e=>null!==e).slice(0,48):[],s=a.length>0?a:function(e){const t=Ci(e);if(!t)return[];const o=[t.layoutNodes,t.layout,t.positions];for(const e of o)if(Array.isArray(e))return e;return[]}(o).map(e=>Gn(e)).filter(e=>null!==e).slice(0,48),r=n&&0===i.length&&0===a.length?n.map(e=>Yn(e)).filter(e=>null!==e).slice(0,12):[],l=r.length>0?r:function(e){const t=Ci(e);if(!t)return[];const o=[t.addEdges,t.edges,t.links];for(const e of o)if(Array.isArray(e))return e;return[]}(o).map(e=>Yn(e)).filter(e=>null!==e).slice(0,12),c=function(e){const t=Ci(e);if(!t)return!1;return function(...e){for(const t of e){if("boolean"==typeof t)return t;if("number"==typeof t&&(0===t||1===t))return 1===t;if("string"==typeof t&&t.trim()){const e=t.trim().toLowerCase();if(["true","yes","1"].includes(e))return!0;if(["false","no","0"].includes(e))return!1}}return}(t.replaceExistingEdges,t.replaceEdges,t.resetEdges)??!1}(o);if(0===i.length&&0===l.length&&0===s.length)throw new Error(v("Canvas AI did not return any usable actions."));return{addNodes:i,addEdges:l,layoutNodes:s,replaceExistingEdges:c}}function Bn(e,t={}){const o=Jn(e);let n;try{n=JSON.parse(o)}catch{throw new Error(v("Canvas AI returned invalid JSON."))}const i=n&&"object"==typeof n?n:null,a=i&&Array.isArray(i.nodes)?i.nodes:[],s=new Set,r=a.map((e,t)=>function(e,t,o){if(!e||"object"!=typeof e)return null;const n=e,i=`n_${t+1}`,a=Xn(n.id,n.nodeId,n.key)||i,s=o.has(a)?i:a;if(o.has(s))return null;o.add(s);const r=Zn(Xn(n.title,n.name,n.label),40),l=Zn(Xn(n.content,n.summary,n.body,n.text),90),c=Qn(n.level,n.depth,n.layer)??0,d=Xn(n.type,n.kind).toLowerCase(),u="detail"===d?"detail":"concept"===d||c<=1?"concept":"detail";if(!r)return null;return{id:s,type:u,title:r,content:l,level:c,group:Zn(Xn(n.group,n.category,n.cluster,n.section),24)||void 0}}(e,t,s)).filter(e=>null!==e).slice(0,24);if(0===r.length)throw new Error(v("Canvas AI did not return any usable nodes."));const l=new Set(r.map(e=>e.id)),c=new Set(t.existingNodeIds??[]);return{nodes:r,edges:(i&&Array.isArray(i.edges)?i.edges:[]).map(e=>function(e,t){if(!e||"object"!=typeof e)return null;const o=e,n=Xn(o.from,o.source,o.parent,o.fromNode),i=Xn(o.to,o.target,o.child,o.toNode),a=Zn(Xn(o.relation,o.label,o.type),24);if(!(n&&i&&n!==i&&t.has(n)&&t.has(i)))return null;return{from:n,to:i,relation:a||void 0}}(e,l)).filter(e=>null!==e).slice(0,48),boardConnections:(i&&Array.isArray(i.boardConnections)?i.boardConnections:[]).map(e=>function(e,t,o){if(!e||"object"!=typeof e)return null;const n=e,i=Xn(n.nodeId,n.from,n.node,n.generatedNodeId),a=Xn(n.existingNodeId,n.toExisting,n.targetNodeId,n.existingId),s=Zn(Xn(n.relation,n.label,n.type),24);if(!(i&&a&&t.has(i)&&o.has(a)))return null;return{nodeId:i,existingNodeId:a,relation:s||void 0}}(e,l,c)).filter(e=>null!==e).slice(0,12)}}async function $n(e,t,o){const n={nodes:t.document.nodes.map(e=>({...e})),edges:t.document.edges.map(e=>({...e}))},i=new Set([...n.nodes.map(e=>e.id),...n.edges.map(e=>e.id)]),a=li(n),s=n.nodes.filter(e=>"group"!==e.type),r=new Map(s.map(e=>[e.id,e])),l=function(e,t){const o=new Map(e.map((e,t)=>[e.id,t])),n=Math.min(...e.map(e=>e.level)),i=e.filter(e=>e.level===n);if(1===i.length)return i[0].id;return i.slice().sort((e,n)=>{const i=ci(e.id,t),a=ci(n.id,t);return a!==i?a-i:(o.get(e.id)??0)-(o.get(n.id)??0)})[0]?.id??e[0].id}(o.nodes,o.edges),c=function(e,t,o){const n=new Map(e.map(e=>[e.id,e])),i=new Map(e.map((e,t)=>[e.id,t])),a=new Map;return a.set(o,null),e.forEach(s=>{if(s.id===o)return;const r=i.get(s.id)??0,l=new Set;t.forEach(e=>{if(e.to===s.id){const t=n.get(e.from);t&&t.level<s.level&&l.add(t.id)}if(e.from===s.id){const t=n.get(e.to);t&&t.level<s.level&&l.add(t.id)}});const c=[...l].sort((e,t)=>{const o=n.get(e),a=n.get(t);if(!o||!a)return 0;if(a.level!==o.level)return a.level-o.level;const s=Math.abs((i.get(e)??0)-r),l=Math.abs((i.get(t)??0)-r);return s!==l?s-l:(i.get(t)??0)-(i.get(e)??0)})[0];if(c)return void a.set(s.id,c);const d=e.slice(0,r).filter(e=>e.level<s.level).sort((e,t)=>t.level!==e.level?t.level-e.level:(i.get(t.id)??0)-(i.get(e.id)??0))[0]?.id??o;a.set(s.id,d)}),a}(o.nodes,o.edges,l),d=function(e,t){const o=new Map,n=new Map(e.map(e=>[e.id,e])),i=new Map(e.map((e,t)=>[e.id,t]));return e.forEach(e=>{o.set(e.id,[])}),t.forEach((e,t)=>{if(!e)return;const n=o.get(e)??[];n.push(t),o.set(e,n)}),o.forEach((e,t)=>{e.sort((e,t)=>{const o=n.get(e),a=n.get(t);return o&&a?o.level!==a.level?o.level-a.level:o.type!==a.type?"concept"===o.type?-1:1:(i.get(e)??0)-(i.get(t)??0):(i.get(e)??0)-(i.get(t)??0)}),o.set(t,e)}),o}(o.nodes,c),u=new Map,m=new Set;o.nodes.forEach(e=>{const t=ai({title:e.title,body:e.content,color:di(e)}),o=function(e){const t=e.split("\n"),o=t.reduce((e,t)=>Math.max(e,t.length),0),n=Math.min(460,Math.max(220,150+5*o)),i=Math.min(280,Math.max(104,64+24*t.length));return{width:n,height:i}}(t),n={id:ri(i),type:"text",x:0,y:0,width:o.width,height:o.height,text:t,color:di(e)};u.set(e.id,n),m.add(n.id)});const p=u.get(l);if(!p)throw new Error(v("Canvas AI did not return any usable nodes."));const h=function(e,t,o){const n=new Map;t.forEach(e=>{n.set(`${e.from}__${e.to}`,e.relation)});const i=[];return e.forEach(e=>{const t=o.get(e.id);if(!t)return;const a=n.get(`${t}__${e.id}`)??n.get(`${e.id}__${t}`)??void 0;i.push({from:t,to:e.id,relation:ui(a)})}),i}(o.nodes,o.edges,c),g=function(e,t,o,n){const i=new Map,a=new Map,s=[],r=e=>{const t=i.get(e);if(void 0!==t)return t;const n=o.get(e);if(!n)return i.set(e,0),0;const a=r(n)+1;return i.set(e,a),a},l=e=>{const t=a.get(e);if(void 0!==t)return t;const o=n.get(e)??[];if(0===o.length)return a.set(e,1),1;const i=Math.max(1,o.reduce((e,t)=>e+l(t),0)+1*Math.max(o.length-1,0));return a.set(e,i),i},c=(e,t)=>{const o=l(e);s.push({nodeId:e,column:r(e),row:t+Math.floor((o-1)/2)});let i=t;(n.get(e)??[]).forEach(e=>{c(e,i),i+=l(e)+1})};c(e,0);const d=new Set(s.map(e=>e.nodeId));let u=l(e)+1;return t.forEach(e=>{d.has(e.id)||(c(e.id,u),s.forEach(e=>{d.add(e.nodeId)}),u+=l(e.id)+1)}),Hn(s)}(l,o.nodes,c,d),f=g.map(e=>{const t=u.get(e.nodeId);return t?{...e,nodeId:t.id}:null}).filter(e=>null!==e);ti({nodes:[...u.values()],edges:[]},f,{columnGap:96,rowGap:64,baseX:0,baseY:0});const b=function(e,t,o){if(0===e.length)return o;const n=new Map;e.forEach(e=>{n.set(e.existingNodeId,(n.get(e.existingNodeId)??0)+1)});const i=[...n.entries()].sort((e,t)=>t[1]!==e[1]?t[1]-e[1]:e[0].localeCompare(t[0]))[0]?.[0];if(!i)return o;return t.get(i)??o}(o.boardConnections,r,a),y=ii(b),C="__canvas_board__"!==b.id,w=s.length>0,x=C?Math.round(b.x+b.width+180+p.width/2):w?Math.round(a.x+260):Math.round(220+p.width/2),k=C?Math.round(y.y):w?Math.round(a.y):Math.round(120+p.height/2),S=ii(p),T=x-S.x,E=k-S.y;u.forEach(e=>{e.x=Math.round(e.x+T),e.y=Math.round(e.y+E)}),function(e,t){if(0===t.length||0===e.size)return;const o=[...e.values()],n=t.map(e=>({x:e.x,y:e.y,width:e.width,height:e.height}));let i=0;for(;o.some(e=>si(e,n))&&i<16;)o.forEach(e=>{e.x+=180}),i+=1}(u,s);const I=function(e,t,o,n,i){const a=function(e,t,o,n){const i=new Map(e.map(e=>[e.id,e])),a=new Map,s=new Map,r=o.get(t)??[];r.forEach(e=>{const t=i.get(e);if(!t)return;const r=function(e,t){const o=[],n=[e];for(;n.length>0;){const e=n.pop();if(!e)continue;o.push(e);const i=t.get(e)??[];for(let e=i.length-1;e>=0;e-=1)n.push(i[e])}return o}(e,o).filter(e=>n.has(e));if(r.length<2)return;const l=t.group?.trim()||t.title.trim();if(!l)return;const c=a.get(l)??[];a.set(l,Array.from(new Set([...c,...r]))),s.set(l,mi(t))});const l=[...a.entries()].map(([e,t])=>({label:e,nodeIds:t,color:s.get(e)})).filter(e=>e.nodeIds.length>1);if(l.length>0)return l;const c=new Map;return e.forEach(e=>{if(e.id===t||!e.group?.trim())return;if(!n.get(e.id))return;const o=e.group.trim(),i=c.get(o)??[];i.push(e.id),c.set(o,i)}),[...c.entries()].map(([e,t])=>({label:e,nodeIds:t,color:mi(i.get(t[0])??null)})).filter(e=>e.nodeIds.length>1)}(e,t,o,n);return a.map(e=>{const t=function(e){const t=Math.min(...e.map(e=>e.x)),o=Math.min(...e.map(e=>e.y)),n=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));return{x:t,y:o,width:n-t,height:i-o}}(e.nodeIds.map(e=>n.get(e)).filter(e=>!!e));return{id:ri(i),type:"group",x:Math.round(t.x-48),y:Math.round(t.y-64),width:Math.max(260,Math.round(t.width+96)),height:Math.max(180,Math.round(t.height+112)),label:e.label,color:e.color}})}(o.nodes,l,d,u,i);I.forEach(e=>{n.nodes.push(e)}),u.forEach(e=>{n.nodes.push(e)});const A=[];h.forEach(e=>{const t=u.get(e.from),o=u.get(e.to);if(!t||!o||t.id===o.id)return;if(hi(n.edges,t.id,o.id,e.relation))return;const a={id:ri(i),fromNode:t.id,toNode:o.id,toEnd:"arrow",label:e.relation?.trim()||void 0};A.push(a),n.edges.push(a)}),o.boardConnections.forEach(e=>{const t=u.get(e.nodeId),o=r.get(e.existingNodeId);if(!t||!o||t.id===o.id)return;const a=ui(e.relation);if(hi(n.edges,t.id,o.id,a)||hi(n.edges,o.id,t.id,a))return;const s={id:ri(i),fromNode:o.id,toNode:t.id,toEnd:"arrow",label:a};A.push(s),n.edges.push(s)}),oi(n,m);const M=`${JSON.stringify(n,null,2)}\n`;try{t.view.setViewData(M,!1),await t.view.save(!1)}catch{await e.app.vault.modify(t.file,M)}return{addedNodeCount:u.size+I.length,addedEdgeCount:A.length,movedNodeCount:0}}async function _n(e,t){return{id:t.id,type:t.type,text:await zn(e,t),node:t}}async function zn(t,o){if("text"===o.type)return Un(o.text||"");if("file"===o.type){const n=o.file?.trim()||"",i=n?t.app.vault.getAbstractFileByPath(n):null;if(i instanceof e.TFile)try{const e=Un(await t.app.vault.cachedRead(i));return e?`[file] ${i.path}\n${e}`:`[file] ${i.path}`}catch{return`[file] ${n}`}return`[file] ${n||"(missing file path)"}`}if("link"===o.type){return[o.label?.trim(),o.url?.trim()].filter(Boolean).join("\n")}return(o.label||"").trim()}function Un(e){const t=e.trim();return t?cn(t,{previewCharsPerSection:600,maxSections:6,verbatimThreshold:2400}):""}function Vn(e,t){return e||t?e?t?e.x!==t.x?e.x-t.x:e.y!==t.y?e.y-t.y:e.id.localeCompare(t.id):-1:1:0}function Hn(e){return e.slice().sort((e,t)=>e.column!==t.column?e.column-t.column:e.row!==t.row?e.row-t.row:e.nodeId.localeCompare(t.nodeId))}function Wn(e){const t=`(${Math.round(e.node.x)}, ${Math.round(e.node.y)})`,o=`${Math.round(e.node.width)}x${Math.round(e.node.height)}`,n=e.text||"(empty)";return[`id: ${e.id}`,`type: ${e.type}`,`position: ${t}`,`size: ${o}`,"content:",n].join("\n")}function jn(e){if(!e||"object"!=typeof e)return null;const t=e,o=Xn(t.title,t.name,t.heading),n=Xn(t.body,t.summary,t.details,t.text),i=Xn(t.relation,t.edgeLabel,t.label),a=Xn(t.color);let s=o,r=n;if(!s&&r){const e=r.split("\n").map(e=>e.trim()).filter(Boolean);s=e[0]||"",r=e.slice(1).join("\n").trim()}return s?{title:s.trim(),body:r?.trim()||void 0,relation:i?.trim()||void 0,color:a?.trim()||void 0}:null}function Kn(e){const t=jn(e);if(!t)return null;const o=Ci(e),n=Xn(o?.connectTo,o?.targetNode,o?.targetId,o?.attachTo,o?.parentNode);return{...t,connectTo:n||void 0}}function Yn(e){const t=Ci(e);if(!t)return null;const o=Xn(t.fromNode,t.from,t.sourceNode,t.sourceId),n=Xn(t.toNode,t.to,t.targetNode,t.targetId),i=Xn(t.label,t.relation,t.edgeLabel);return o&&n?{fromNode:o,toNode:n,label:i||void 0}:null}function Gn(e){const t=Ci(e);if(!t)return null;const o=Ci(t.position)??Ci(t.layout),n=Xn(t.nodeId,t.id,t.node,t.targetNode,t.targetId,Ci(t.node)?.id),i=Qn(t.column,t.col,t.lane,t.columnIndex,t.xIndex,o?.column,o?.col,o?.lane,o?.columnIndex,o?.xIndex),a=Qn(t.row,t.index,t.order,t.rowIndex,t.yIndex,o?.row,o?.index,o?.order,o?.rowIndex,o?.yIndex);return n&&null!==i&&null!==a?{nodeId:n,column:i,row:a}:null}function Jn(e){return e.trim().replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,"").trim()}function Zn(e,t){const o=e.replace(/\s+/g," ").trim();return o?o.length>t?`${o.slice(0,Math.max(t-3,1)).trim()}...`:o:""}function Xn(...e){for(const t of e)if("string"==typeof t&&t.trim())return t.trim();return""}function Qn(...e){for(const t of e){if("number"==typeof t&&Number.isFinite(t))return Math.max(0,Math.round(t));if("string"==typeof t&&t.trim()){const e=Number(t);if(Number.isFinite(e))return Math.max(0,Math.round(e))}}return null}function ei(e,t,o,n){const i=e.nodes.filter(e=>"group"!==e.type).map(e=>({x:e.x,y:e.y,width:e.width,height:e.height})),a=o.map(e=>{const t=ai(e),o=function(e){const t=e.split("\n"),o=t.reduce((e,t)=>Math.max(e,t.length),0),n=Math.min(520,Math.max(280,180+6*o)),i=Math.min(340,Math.max(120,76+28*t.length));return{width:n,height:i}}(t);return{id:ri(n),type:"text",x:0,y:0,width:o.width,height:o.height,text:t,color:e.color}});let s=t.x+t.width+220;const r=a.reduce((e,t)=>e+t.height,0)+48*Math.max(0,a.length-1),l=Math.round(t.y+t.height/2-r/2);for(a.forEach((e,t)=>{const o=a.slice(0,t).reduce((e,t)=>e+t.height,0);e.x=s,e.y=Math.round(l+o+48*t)});a.some(e=>si(e,i));)s+=180,a.forEach(e=>{e.x=s});return a}function ti(e,t,o={}){if(0===t.length)return 0;const n=new Map(e.nodes.filter(e=>"group"!==e.type).map(e=>[e.id,e])),i=new Map;t.forEach(e=>{n.has(e.nodeId)&&i.set(e.nodeId,e)});const a=[...i.values()].map(e=>({layoutNode:e,node:n.get(e.nodeId)??null})).filter(e=>!!e.node);if(0===a.length)return 0;const s=o.columnGap??320,r=o.rowGap??96,l=o.baseX??Math.min(...a.map(e=>e.node.x)),c=o.baseY??Math.min(...a.map(e=>e.node.y)),d=[...new Set(a.map(e=>e.layoutNode.column))].sort((e,t)=>e-t),u=[...new Set(a.map(e=>e.layoutNode.row))].sort((e,t)=>e-t),m=new Map,p=new Map,h=new Map,g=new Map;d.forEach(e=>{h.set(e,Math.max(...a.filter(t=>t.layoutNode.column===e).map(e=>e.node.width)))}),u.forEach(e=>{g.set(e,Math.max(...a.filter(t=>t.layoutNode.row===e).map(e=>e.node.height)))});let f=l;d.forEach((e,t)=>{if(0===t)return void m.set(e,Math.round(f));const o=d[t-1];f+=(h.get(o)??0)+s*Math.max(e-o,1),m.set(e,Math.round(f))});let b=c;u.forEach((e,t)=>{if(0===t)return void p.set(e,Math.round(b));const o=u[t-1];b+=(g.get(o)??0)+r*Math.max(e-o,1),p.set(e,Math.round(b))});let y=0;return a.forEach(e=>{const t=m.get(e.layoutNode.column),o=p.get(e.layoutNode.row);void 0!==t&&void 0!==o&&(e.node.x===t&&e.node.y===o||(e.node.x=t,e.node.y=o,y+=1))}),y}function oi(e,t){const o=new Map(e.nodes.map(e=>[e.id,e]));e.edges.forEach(e=>{(t.has(e.fromNode)||t.has(e.toNode))&&ni(e,o)})}function ni(e,t){const o=t.get(e.fromNode),n=t.get(e.toNode);if(!o||!n)return;const i=function(e,t){const o=ii(e),n=ii(t),i=n.x-o.x,a=n.y-o.y,s=Math.abs(i)-(e.width+t.width)/2,r=Math.abs(a)-(e.height+t.height)/2;if(s>=r)return i>=0?{fromSide:"right",toSide:"left"}:{fromSide:"left",toSide:"right"};return a>=0?{fromSide:"bottom",toSide:"top"}:{fromSide:"top",toSide:"bottom"}}(o,n);e.fromSide=i.fromSide,e.toSide=i.toSide}function ii(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function ai(e){const t=e.title.trim(),o=e.body?.trim();return o?`# ${t}\n\n${o}`:`# ${t}`}function si(e,t){return t.some(t=>function(e,t){const o=24;return!(e.x+e.width+o<=t.x||t.x+t.width+o<=e.x||e.y+e.height+o<=t.y||t.y+t.height+o<=e.y)}(e,t))}function ri(e){let t="";do{const e=new Uint8Array(8);crypto.getRandomValues(e),t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}while(e.has(t));return e.add(t),t}function li(e){const t=e.nodes.filter(e=>"group"!==e.type);if(0===t.length)return{id:"__canvas_board__",type:"group",x:0,y:0,width:0,height:0};const o=Math.max(...t.map(e=>e.x+e.width)),n=Math.min(...t.map(e=>e.y)),i=Math.max(...t.map(e=>e.y+e.height));return{id:"__canvas_board__",type:"group",x:Math.round(o),y:Math.round((n+i)/2),width:0,height:0}}function ci(e,t){return t.reduce((t,o)=>o.from===e?t+2:o.to===e?t+1:t,0)}function di(e){return 0===e.level?"2":"concept"===e.type?"4":"detail"===e.type?"5":void 0}function ui(e){const t=e?.replace(/\s+/g," ").trim();if(!t)return;const o=t.toLowerCase();return["contains","include","includes","including","belongs to","relates to","related to"].includes(o)?void 0:["supports","support"].includes(o)?"支撑":["follows","follow","next","next step"].includes(o)?"后续":["causes","cause","leads to"].includes(o)?"导致":["contrasts","contrast","compares","compare"].includes(o)?"对比":t}function mi(e){return e?e.level<=1?"6":di(e)??"6":"6"}function pi(e,t,o){const n=(e||"").trim();return n&&"anchor"!==n.toLowerCase()&&"current"!==n.toLowerCase()?o.has(n)?n:null:t??null}function hi(e,t,o,n){return e.some(e=>e.fromNode===t&&e.toNode===o&&(e.label||"")===(n?.trim()||""))}function gi(e,t,o){fi(e,e=>{const n=bi(e,o);n&&t.add(n)})}function fi(e,t){e&&(Array.isArray(e)||e instanceof Set?e.forEach(t):e instanceof Map?e.forEach(e=>t(e)):"object"==typeof e&&t(e))}function bi(e,t){if("string"==typeof e&&t.has(e))return e;const o=Ci(e);if(!o)return null;const n=[o.id,Ci(o.node)?.id,Ci(o.data)?.id];for(const e of n)if("string"==typeof e&&t.has(e))return e;return null}function yi(e,t){const o=[e.dataset.nodeId,e.dataset.id,e.getAttribute("data-node-id"),e.getAttribute("data-id"),e.id];for(const e of o)if(e&&t.has(e))return e;for(const o of e.getAttributeNames()){const n=e.getAttribute(o);if(n&&t.has(n))return n}for(const o of Object.values(e.dataset))if(o&&t.has(o))return o;return null}function Ci(e){return e&&"object"==typeof e?e:null}function vi(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function wi(e){return 0===e.trim().length}function xi(e){const t=e.trimStart().match(/^(#{1,6})\s+(.+)$/);return t?{level:t[1].length,title:t[2].trim()}:null}function ki(e,t){let o=t;for(;o>1;){const t=e.state.doc.line(o-1).text;if(wi(t)||xi(t))break;o--}return o}function Si(e,t){let o=t;for(;o<e.state.doc.lines;){const t=e.state.doc.line(o+1).text;if(wi(t)||xi(t))break;o++}return o}function Ti(e,t,o){const n=[];for(let i=t;i<=o;i++)n.push(e.state.doc.line(i).text);return n.join("\n")}function Ei(e,t,o){let n=t;for(;n>=1&&n<=e.state.doc.lines;){const t=e.state.doc.line(n).text;if(!wi(t)){if(xi(t))return t;return Ti(e,ki(e,n),Si(e,n))}n+=o}return""}function Ii(e,t){const o=new Map;for(let n=1;n<=t;n++){const t=xi(e.state.doc.line(n).text);if(t){o.set(t.level,t.title);for(let e=t.level+1;e<=6;e++)o.delete(e)}}return Array.from(o.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}function Ai(e,t,o,n){const i=e.state.doc,a=i.length,s=Math.max(0,Math.min(t,a)),r=Math.max(0,Math.min(o,a)),l=s!==r,c=n?.preferBlockWhenCollapsed??!1;let d=s,u=r,m=l?e.state.sliceDoc(s,r):"",p=l?"selection":"cursor";if(!l&&c){const t=i.lineAt(s);if(!wi(t.text)){const o=ki(e,t.number),n=Si(e,t.number);d=i.line(o).from,u=i.line(n).to,m=e.state.sliceDoc(d,u),m.trim()?p="block":(d=s,u=r)}}const h="cursor"===p?s:d,g=i.lineAt(h),f=u>d?Math.max(d,u-1):d,b=i.lineAt(d).number,y=i.lineAt(f).number,C=ki(e,g.number),v=Si(e,g.number),w=Ti(e,C,v),x=Ii(e,g.number),k=Ei(e,b-1,-1),S=Ei(e,y+1,1),T="cursor"===p?i.line(C).from:Math.max(0,d-1200),E="cursor"===p?i.line(v).to:Math.min(a,u+900),I=e.state.sliceDoc(T,d),A=e.state.sliceDoc(u,E);return{from:d,to:u,selectedText:m,hasSelection:l,source:p,context:[`target_source: ${p}`,`target_lines: ${b}-${y}`,`heading_path: ${x.join(" > ")||"(root)"}`,"surrounding_block:",w,"text_before_target:",I,"text_after_target:",A,"previous_block:",k,"next_block:",S].join("\n")}}class Mi{constructor(e){this.cachedVerified=null,this.refreshPromise=null,this.callbackServer=null,this.pendingCodeVerifier=null,this.pendingState=null,this.pendingAuthorizationUrl=null,this.memAccessToken=null,this.memRefreshToken=null,this.memAiToken=null,this.memCustomModelApiKey=null,this.plugin=e}get secrets(){return this.plugin.app.secretStorage}get supportsSecretStorage(){return!!this.secrets&&"function"==typeof this.secrets.getSecret&&"function"==typeof this.secrets.setSecret}loadSecrets(){this.supportsSecretStorage&&(this.memAccessToken=this.secrets.getSecret(R)??null,this.memRefreshToken=this.secrets.getSecret(q)??null,this.memAiToken=this.secrets.getSecret(B)??null,this.memCustomModelApiKey=this.secrets.getSecret($)??null)}async syncLoginState(){if(this.memAccessToken&&!this.plugin.settings.ai.pkmer.userInfo){await this.verify()?(await this.fetchUserInfo(),this.cachedVerified=!0):this.clearSecrets()}}setAccessToken(e){this.memAccessToken=e,this.supportsSecretStorage&&this.secrets.setSecret(R,e)}setRefreshToken(e){this.memRefreshToken=e,this.supportsSecretStorage&&this.secrets.setSecret(q,e)}setAiToken(e){this.memAiToken=e,this.supportsSecretStorage&&this.secrets.setSecret(B,e)}clearSecrets(){this.memAccessToken=null,this.memRefreshToken=null,this.memAiToken=null,this.memCustomModelApiKey=null,this.supportsSecretStorage&&(this.secrets.setSecret(R,""),this.secrets.setSecret(q,""),this.secrets.setSecret(B,""),this.secrets.setSecret($,""))}get accessToken(){return this.memAccessToken??""}get aiToken(){return this.memAiToken??""}get customModelApiKey(){return this.memCustomModelApiKey??""}get hasSecureStorage(){return this.supportsSecretStorage}async migrateCustomModelApiKeyFromSettings(){const e=this.plugin.settings.ai.customModel.apiKey?.trim();e&&this.supportsSecretStorage&&(this.setCustomModelApiKey(e),this.plugin.settings.ai.customModel.apiKey="",await this.plugin.saveSettings())}setCustomModelApiKey(e){const t=e.trim();this.memCustomModelApiKey=t||null,this.supportsSecretStorage&&this.secrets.setSecret($,t)}clearCustomModelApiKey(){this.memCustomModelApiKey=null,this.supportsSecretStorage&&this.secrets.setSecret($,"")}async verify(){const e=this.plugin.settings.ai.pkmer;if(!this.memAccessToken)return this.cachedVerified=!1,!1;if(e.tokenExpiresAt&&Date.now()<e.tokenExpiresAt)return this.cachedVerified=!0,!0;if(this.memRefreshToken){const e=await this.refreshTokens();return this.cachedVerified=e,e}return this.cachedVerified=!1,!1}async verifyWithResult(){return{verified:await this.verify(),userInfo:this.plugin.settings.ai.pkmer.userInfo??null,expiresAt:this.plugin.settings.ai.pkmer.tokenExpiresAt??0}}async login(){if(!this.supportsSecretStorage)return void new e.Notice(v("Current Obsidian version does not support secure token storage."));if(this.hasPendingOAuthRequest())return this.pendingAuthorizationUrl&&window.open(this.pendingAuthorizationUrl),void new e.Notice(v("PKMer login is already in progress. Please continue in the opened browser window."));this.closeCallbackServer();const t=this.generateRandom(),o=this.generateRandom();this.pendingCodeVerifier=o,this.pendingState=t;const n=await this.computeCodeChallenge(o),i=new URLSearchParams({response_type:"code",client_id:V,redirect_uri:e.Platform.isMobile?j:W,scope:H,state:t,code_challenge:n,code_challenge_method:"S256"}),a=function(e,t=E()){if(I(t))return e;const o=new URL("https://pkmer.net/en/signin/");return o.searchParams.set("redirect",e),o.searchParams.set("app_name","Editing Toolbar"),o.searchParams.set("website","https://pkmer.net"),o.toString()}(`${_}?${i.toString()}`);if(this.pendingAuthorizationUrl=a,e.Platform.isMobile)return window.open(a),void setTimeout(()=>{this.isPendingStateMatch(t)&&this.clearPendingOAuthRequest()},3e5);const s=this.startCallbackServer();window.open(a);try{const t=await s;if(!t)return void new e.Notice(v("Login cancelled or timed out."));await this.exchangeCodeForTokens(t,W)?(await this.fetchUserInfo(),new e.Notice(v("Successfully logged in to PKMer!"))):new e.Notice(v("Failed to complete login. Please try again."))}catch(t){console.error("PKMer OAuth login error:",t),new e.Notice(v("Login failed. Please try again."))}finally{this.clearPendingOAuthRequest({closeServer:!0})}}async handleOAuthCallback(t,o){if(!this.isPendingStateMatch(o))return new e.Notice(v("OAuth state mismatch. Please try logging in again.")),this.clearPendingOAuthRequest(),!1;try{return await this.exchangeCodeForTokens(t,j)?(await this.fetchUserInfo(),new e.Notice(v("Successfully logged in to PKMer!")),!0):(new e.Notice(v("Failed to complete login. Please try again.")),!1)}catch(t){return console.error("PKMer OAuth callback error:",t),new e.Notice(v("Login failed. Please try again.")),!1}finally{this.clearPendingOAuthRequest()}}async logout(){this.clearSecrets(),this.plugin.settings.ai.pkmer={...this.plugin.settings.ai.pkmer,tokenExpiresAt:0,userInfo:null},this.cachedVerified=!1,await this.plugin.saveSettings(),new e.Notice(v("Logged out from PKMer."))}async refreshQuota(){return await this.verify()?(await this.fetchUserInfo(),this.plugin.settings.ai.pkmer.userInfo?.ai_quota??null):null}onunload(){this.closeCallbackServer()}async computeCodeChallenge(e){return function(e){const t=new Uint8Array(e);let o="";for(let e=0;e<t.length;e++)o+=String.fromCharCode(t[e]);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)))}startCallbackServer(){return new Promise(t=>{try{const o=window.require("node:http").createServer((e,o)=>{const n=new URL(e.url,`http://localhost:${K}`);if("/editing-toolbar/callback"!==n.pathname)return o.writeHead(404),void o.end();const i=n.searchParams.get("code"),a=n.searchParams.get("state");if(this.isPendingStateMatch(a))if(i)o.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),o.end("<html><body><h2>Login successful!</h2><p>You can close this window and return to Obsidian.</p><script>window.close()<\/script></body></html>"),t(i);else{const e=n.searchParams.get("error")||"unknown error";o.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),o.end(`<html><body><h2>Login failed: ${e}</h2></body></html>`),t(null)}else o.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),o.end("<html><body><h2>State mismatch.</h2><p>Another Obsidian window may have intercepted this callback.</p><p>Please close other Obsidian and try again.</p></body></html>"),t(null);setTimeout(()=>this.closeCallbackServer(),500)});o.on("error",o=>{console.error("Callback server error:",o),new e.Notice(`Failed to start login server: ${o.message}`),t(null)}),o.listen(K,"127.0.0.1"),this.callbackServer=o,setTimeout(()=>{this.callbackServer===o&&(this.closeCallbackServer(),t(null))},3e5)}catch(e){console.error("Failed to start callback server:",e),t(null)}})}closeCallbackServer(){if(this.callbackServer){try{this.callbackServer.close()}catch{}this.callbackServer=null}}hasPendingOAuthRequest(){return!!this.pendingState&&!!this.pendingCodeVerifier}isPendingStateMatch(e){return!!e&&!!this.pendingState&&e===this.pendingState}clearPendingOAuthRequest(e){this.pendingState=null,this.pendingCodeVerifier=null,this.pendingAuthorizationUrl=null,e?.closeServer&&this.closeCallbackServer()}async exchangeCodeForTokens(t,o){try{const n={grant_type:"authorization_code",code:t,redirect_uri:o,client_id:V};this.pendingCodeVerifier&&(n.code_verifier=this.pendingCodeVerifier);const i=(await e.requestUrl({url:z,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(n).toString()})).json;return!!i.access_token&&(this.setAccessToken(i.access_token),this.setRefreshToken(i.refresh_token||""),this.plugin.settings.ai.pkmer={...this.plugin.settings.ai.pkmer,tokenExpiresAt:Date.now()+1e3*(i.expires_in??3600)},await this.plugin.saveSettings(),this.cachedVerified=!0,!0)}catch(e){return console.error("Token exchange failed:",e),!1}}async refreshTokens(){if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=(async()=>{try{const t=(await e.requestUrl({url:z,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:this.memRefreshToken||"",client_id:V}).toString()})).json;return!!t.access_token&&(this.setAccessToken(t.access_token),t.refresh_token&&this.setRefreshToken(t.refresh_token),this.plugin.settings.ai.pkmer={...this.plugin.settings.ai.pkmer,tokenExpiresAt:Date.now()+1e3*(t.expires_in??3600)},await this.plugin.saveSettings(),!0)}catch(e){return console.error("Token refresh failed:",e),this.clearSecrets(),this.plugin.settings.ai.pkmer={...this.plugin.settings.ai.pkmer,tokenExpiresAt:0,userInfo:null},await this.plugin.saveSettings(),!1}})();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async fetchUserInfo(){try{const t=(await e.requestUrl({url:U,method:"GET",headers:{Authorization:`Bearer ${this.memAccessToken}`}})).json;t.ai_token&&this.setAiToken(t.ai_token),this.plugin.settings.ai.pkmer={...this.plugin.settings.ai.pkmer,userInfo:{sub:t.sub||t.id||"",name:t.name||t.preferred_username||t.username||void 0,email:t.email||void 0,avatar:t.picture||t.avatar||void 0,ai_quota:t.ai_quota||void 0,device_count:t.device_count??void 0,thino:t.thino??void 0,thinoWebExpir:t.thinoWebExpir??void 0,supporter:t.supporter??void 0}},await this.plugin.saveSettings()}catch(e){console.error("Failed to fetch user info:",e)}}generateRandom(){const e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}}const Pi=o.StateEffect.define(),Ni=o.StateEffect.define(),Di=o.StateField.define({create:()=>null,update(e,t){for(const e of t.effects)if(e.is(Pi))return e.value;return t.docChanged||e&&t.state.selection.main.head!==e.pos?null:e}});class Li extends n.WidgetType{constructor(e,t){super(),this.text=e,this.showHint=t}eq(e){return this.text===e.text&&this.showHint===e.showHint}toDOM(){const e=document.createElement("span");e.className="cm-ai-ghost-text",e.setAttribute("aria-label",v("AI suggestion"));const t=this.text.split("\n"),o=document.createElement("span");if(o.className="cm-ai-ghost-first-line",o.textContent=t[0],e.appendChild(o),this.showHint){const t=document.createElement("span");t.className="cm-ai-ghost-hint",t.textContent=v("Press Tab to accept"),e.appendChild(t)}if(t.length>1){const o=document.createElement("div");o.className="cm-ai-ghost-rest",o.textContent=t.slice(1).join("\n"),e.appendChild(o)}return e}updateDOM(e){const t=this.text.split("\n"),o=e.querySelector(".cm-ai-ghost-first-line"),n=e.querySelector(".cm-ai-ghost-hint"),i=e.querySelector(".cm-ai-ghost-rest");if(o&&(o.textContent=t[0]),this.showHint)if(n)n.textContent=v("Press Tab to accept"),n.style.display="inline-flex";else{const t=document.createElement("span");t.className="cm-ai-ghost-hint",t.textContent=v("Press Tab to accept"),o?.nextSibling?e.insertBefore(t,o.nextSibling):e.appendChild(t)}else n&&(n.style.display="none");if(t.length>1)if(i)i.textContent=t.slice(1).join("\n"),i.style.display="block";else{const o=document.createElement("div");o.className="cm-ai-ghost-rest",o.textContent=t.slice(1).join("\n"),e.appendChild(o)}else i&&(i.style.display="none");return!0}ignoreEvent(){return!0}}class Fi extends n.WidgetType{eq(){return!0}toDOM(){const e=document.createElement("span");e.className="cm-ai-loading cm-ai-loading-pill",e.setAttribute("aria-label",v("AI is generating"));const t=document.createElement("span");t.className="cm-ai-loading-visual";const o=document.createElement("span");o.className="cm-ai-loading-glow";const n=document.createElement("span");n.className="cm-ai-loading-spinner";const i=document.createElement("span");i.className="cm-ai-loading-label",i.textContent=v("AI thinking");const a=document.createElement("span");return a.className="cm-ai-loading-sheen",a.setAttribute("aria-hidden","true"),t.appendChild(o),t.appendChild(n),e.appendChild(t),e.appendChild(i),e.appendChild(a),e}ignoreEvent(){return!0}}function Oi(e,t){const o=e.state.field(Di);return!!o?.text&&(e.dispatch({changes:{from:o.pos,insert:o.text},selection:{anchor:o.pos+o.text.length},effects:Pi.of(null)}),t?.(),!0)}const Ri=n.keymap.of([{key:"Escape",run:e=>!!e.state.field(Di)&&(e.dispatch({effects:Pi.of(null)}),!0)}]);function qi(e,t,i,a){const s=function(e){return n.EditorView.decorations.compute([Di],t=>{const o=t.field(Di);return o?"loading"===o.status?n.Decoration.set([n.Decoration.widget({widget:new Fi,side:1}).range(o.pos)]):o.text?n.Decoration.set([n.Decoration.widget({widget:new Li(o.text,e?.()??!1),side:1}).range(o.pos)]):n.Decoration.none:n.Decoration.none})}(i),r=o.Prec.highest(n.keymap.of([{key:"Tab",run:e=>Oi(e,a)}])),l=n.ViewPlugin.fromClass(class{constructor(e){this.abortController=null,this.autoTriggerTimer=null,this.handleDocumentKeydown=e=>{if(e.defaultPrevented||"Tab"!==e.key||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||this.view.hasFocus||!this.view.dom.isConnected)return;const t=this.view.state.field(Di);if(!t?.text||"ready"!==t.status)return;const o=this.ownerDocument.activeElement;o&&!this.view.dom.contains(o)&&this.isTextInputElement(o)||(e.preventDefault(),e.stopPropagation(),Oi(this.view,a),this.view.focus())},this.view=e,this.ownerDocument=e.dom.ownerDocument,this.ownerDocument.addEventListener("keydown",this.handleDocumentKeydown,!0)}isTextInputElement(e){return!!e.closest("input, textarea, select, [contenteditable='true'], [contenteditable='']")}update(e){for(const t of e.transactions)for(const e of t.effects)e.is(Ni)&&this.scheduleCompletionStart(),e.is(Pi)&&null===e.value&&this.abortController?.abort();const o=t?.()??{trigger:"manual",delay:500};if("auto"===o.trigger&&e.docChanged){if(e.state.doc.length>=e.startState.doc.length){const t=e.state.selection.main.head,n=e.state.doc.lineAt(t);e.state.sliceDoc(n.from,t).trim().length>=2&&this.scheduleAutoTrigger(o.delay??500)}}}scheduleAutoTrigger(e){this.autoTriggerTimer&&clearTimeout(this.autoTriggerTimer),this.autoTriggerTimer=setTimeout(()=>{this.startCompletion()},e)}scheduleCompletionStart(){Promise.resolve().then(()=>{this.startCompletion()})}async startCompletion(){this.abortController?.abort(),this.abortController=new AbortController;const t=this.abortController.signal,o=e();if(!o)return;const n=this.view.state.selection.main.head,{prefix:i,suffix:a,context:s}=function(e,t){const o=e.state.doc.lineAt(t),n=ki(e,o.number),i=Si(e,o.number),a=e.state.doc.line(n).from,s=e.state.doc.line(i).to,r=e.state.sliceDoc(a,t),l=e.state.sliceDoc(t,s),c=e.state.sliceDoc(o.from,t),d=e.state.sliceDoc(t,o.to),u=Ei(e,n-1,-1),m=Ei(e,i+1,1),p=Ii(e,o.number),h=o.text.match(/^(\s*(?:[-*+] |\d+\. |>)?)/);return{prefix:r,suffix:l,context:[`cursor_line: ${o.number}`,`block_lines: ${n}-${i}`,`heading_path: ${p.join(" > ")||"(root)"}`,`line_prefix_pattern: ${(h?.[1]||"").replace(/\n/g,"")}`,"current_line_before_cursor:",c,"current_line_after_cursor:",d,"previous_block:",u,"next_block:",m].join("\n")}}(this.view,n);let r="";this.view.dispatch({effects:Pi.of({pos:n,text:"",status:"loading"})});try{for await(const e of o.complete({prefix:i,suffix:a,context:s},t)){if(t.aborted)return;if(r+=e,this.view.state.selection.main.head!==n)return void this.abortController.abort();this.view.dispatch({effects:Pi.of({pos:n,text:r,status:"ready"})})}r||this.view.dispatch({effects:Pi.of(null)})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;jo(e)||console.error("[AI Completion] Error:",e),this.view.dispatch({effects:Pi.of(null)})}}destroy(){this.ownerDocument.removeEventListener("keydown",this.handleDocumentKeydown,!0),this.abortController?.abort(),this.autoTriggerTimer&&clearTimeout(this.autoTriggerTimer)}});return[Di,s,r,Ri,l]}const Bi=o.StateEffect.define(),$i=o.StateEffect.define(),_i=o.StateEffect.define(),zi=o.StateEffect.define();function Ui(t){const o=t.toUpperCase();return e.Platform.isMacOS?{display:Hi(["Ctrl",o]),primaryKey:`Ctrl-${t.toLowerCase()}`}:{display:Hi(["Alt",o]),primaryKey:`Alt-${t.toLowerCase()}`}}const Vi={close:{...Ui("d"),fallbackKeys:["Escape"]},replace:{...Ui("r"),fallbackKeys:["Mod-Enter"]},insertBelow:{...Ui("i"),fallbackKeys:["Mod-Shift-Enter"]},copy:Ui("c"),retry:Ui("t")};function Hi(t){return t.map(t=>"Mod"===t?e.Platform.isMacOS?"⌘":"Ctrl":"Shift"===t?e.Platform.isMacOS?"⇧":"Shift":"Alt"===t?e.Platform.isMacOS?"⌥":"Alt":"Ctrl"===t?e.Platform.isMacOS?"⌃":"Ctrl":t).join("+")}function Wi(e,t,o=!1){const n=e.state.field(t,!1),i=n?.operation??null;return i?o&&"done"!==i.phase?null:i:null}function ji(e){return"base"===e?.params.artifactKind||"canvas"===e?.params.artifactKind}function Ki(e){return"frontmatter"===e?.params.artifactKind}function Yi(e,t){return!!Wi(e,t)&&(e.dispatch({effects:zi.of(void 0)}),e.focus(),!0)}async function Gi(t,o){const n=Wi(t,o,!0),i=n?.result;if(!i)return!1;try{return await navigator.clipboard.writeText(i),!0}catch(t){return console.error("[AI Rewrite] Failed to copy result:",t),new e.Notice(t instanceof Error&&t.message?t.message:v("Copy to Clipboard")),!1}}async function Ji(t,o,n,i){const a=Wi(t,o,!0);if(!a)return!1;if(ji(a))return async function(t,o,n,i){const a=Wi(t,o,!0);if(!a?.params.artifactKind)return!1;const s=n().createGeneratedArtifact;if(!s)return new e.Notice(v("AI file creation is unavailable.")),!0;try{const e=await s({kind:a.params.artifactKind,content:a.result,sourceText:a.params.originalText});if(t.dispatch({effects:zi.of(void 0)}),"embed"===i){const o=a.params.from===a.params.to?e.embedSyntax:`\n\n${e.embedSyntax}`,n=a.params.to;t.dispatch({changes:{from:n,insert:o},selection:{anchor:n+o.length}})}return t.focus(),!0}catch(t){const o=t instanceof Error&&t.message?t.message:v("Failed to create AI file.");return new e.Notice(o),console.error("[AI Artifact] Failed to create file:",t),!0}}(t,o,n,"replace"===i?"create":"embed");if(Ki(a))return function(t,o){const n=Wi(t,o,!0);if(!n)return!1;try{const e=Cn(n.result,n.params.preferredFrontmatterKeys);return t.dispatch({effects:zi.of(void 0)}),t.dispatch({changes:{from:n.params.from,to:n.params.to,insert:e},selection:{anchor:e.length}}),t.focus(),!0}catch(t){const o=t instanceof Error&&t.message?t.message:v("Failed to apply frontmatter.");return new e.Notice(o),!0}}(t,o);if("replace"===i){const{from:e,to:o}=a.params,n=a.result;return t.dispatch({effects:zi.of(void 0)}),t.dispatch({changes:{from:e,to:o,insert:n},selection:{anchor:e+n.length}}),t.focus(),!0}const{to:s}=a.params,r=a.result;return t.dispatch({effects:zi.of(void 0)}),t.dispatch({changes:{from:s,insert:`\n\n${r}`},selection:{anchor:s+r.length+2}}),t.focus(),!0}function Zi(e,t){const o=Wi(e,t,!0);return!!o&&(e.dispatch({effects:Bi.of(o.params)}),!0)}function Xi(e,t,o){e.replaceChildren();const n=document.createElement("span");if(n.className="cm-ai-btn-label",n.textContent=t,e.appendChild(n),o){const n=document.createElement("span");n.className="cm-ai-btn-shortcut",n.textContent=o,e.appendChild(n),e.title=`${t} (${o})`}else e.removeAttribute("title")}function Qi(e,t,o,n){const i=document.createElement("button");return i.className=`cm-ai-btn ${t}`,Xi(i,e,n),i.addEventListener("click",o),i}function ea(t,i){const a=()=>({createGeneratedArtifact:(i?.()??{}).createGeneratedArtifact}),s=o.StateField.define({create:()=>({operation:null,resultTooltip:null}),update(e,t){let o=e.operation;for(const e of t.effects)e.is(Bi)&&(o={phase:"streaming",params:e.value,result:""}),e.is($i)&&o&&(o={...o,result:e.value}),e.is(_i)&&o&&(o={...o,phase:"done"}),e.is(zi)&&(o=null);t.docChanged&&o&&(o={...o,params:{...o.params,from:t.changes.mapPos(o.params.from),to:t.changes.mapPos(o.params.to)}});let n=null;return o&&(n=e.resultTooltip&&e.resultTooltip.pos===o.params.from?e.resultTooltip:{pos:o.params.from,above:!1,create:e=>function(e,t,o){const n=document.createElement("div");n.className="cm-ai-result-panel",n.dataset.phase="streaming";let i=null;n.addEventListener("mousedown",e=>{e.target.closest(".cm-ai-result-content")||e.preventDefault()});const a=document.createElement("div");a.className="cm-ai-result-header-row";const s=document.createElement("div");s.className="cm-ai-result-header",s.textContent=v("AI is writing...");const r=document.createElement("button");r.type="button",r.className="cm-ai-result-close",r.textContent="×",r.setAttribute("aria-label",v("Close")),r.title=`${v("Close")} (${Vi.close.display} / Esc)`,r.addEventListener("click",()=>{d(),Yi(e,t)}),a.append(s,r),n.appendChild(a);const l=document.createElement("div");l.className="cm-ai-result-content",n.appendChild(l);const c=document.createElement("div");function d(){null!==i&&(window.clearTimeout(i),i=null),Xi(p,v("Copy to Clipboard"),Vi.copy.display)}c.className="cm-ai-result-actions",c.style.display="none";const u=Qi(v("Replace"),"cm-ai-btn-primary",()=>{Ji(e,t,o,"replace")},Vi.replace.display),m=Qi(v("Insert below"),"cm-ai-btn-secondary",()=>{Ji(e,t,o,"insert-below")},Vi.insertBelow.display),p=Qi(v("Copy to Clipboard"),"cm-ai-btn-secondary",()=>{Gi(e,t).then(e=>{e&&(null!==i&&window.clearTimeout(i),Xi(p,v("Copied!"),Vi.copy.display),i=window.setTimeout(()=>{i=null,Xi(p,v("Copy to Clipboard"),Vi.copy.display)},1500))})},Vi.copy.display),h=Qi(v("Try again"),"cm-ai-btn-secondary",()=>{d(),Zi(e,t)},Vi.retry.display);return c.append(u,m,p,h),n.appendChild(c),{dom:n,update(e){const o=e.state.field(t);if(!o.operation)return n.style.display="none",void(n.dataset.phase="idle");n.style.display="",n.dataset.phase=o.operation.phase,l.textContent=o.operation.result||"",ji(o.operation)?(s.textContent=v("AI file suggestion"),Xi(u,v("Create"),Vi.replace.display),Xi(m,v("Create & Embed"),Vi.insertBelow.display),m.style.display=""):Ki(o.operation)?(s.textContent=v("AI frontmatter suggestion"),Xi(u,o.operation.params.from===o.operation.params.to?v("Insert frontmatter"):v("Replace frontmatter"),Vi.replace.display),m.style.display="none"):(Xi(u,o.operation.params.from===o.operation.params.to?v("Insert at cursor"):v("Replace"),Vi.replace.display),Xi(m,v("Insert below"),Vi.insertBelow.display),m.style.display=""),"done"===o.operation.phase?("base"!==o.operation.params.artifactKind&&"canvas"!==o.operation.params.artifactKind&&"frontmatter"!==o.operation.params.artifactKind&&(s.textContent=v("AI suggestion")),p.style.display="",c.style.display="flex"):(d(),s.textContent=v("AI is writing..."),c.style.display="none")},destroy(){null!==i&&window.clearTimeout(i)}}}(e,s,a)}),{operation:o,resultTooltip:n}},provide:e=>n.showTooltip.from(e,e=>e.resultTooltip??null)}),r=n.ViewPlugin.fromClass(class{constructor(e){this.abortController=null,this.view=e}update(e){for(const t of e.transactions)for(const e of t.effects)e.is(Bi)&&this.startStreaming(e.value),e.is(zi)&&this.abortController?.abort()}async startStreaming(e){this.abortController?.abort(),this.abortController=new AbortController;const o=this.abortController.signal,n=t();if(!n)return;let i="";try{for await(const t of n.rewrite({selectedText:e.originalText,instruction:e.instruction,customPrompt:e.customPrompt,context:e.context,artifactKind:e.artifactKind},o)){if(o.aborted)return;i+=t,this.view.dispatch({effects:$i.of(i)})}this.view.dispatch({effects:_i.of(void 0)})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;jo(e)||console.error("[AI Rewrite] Error:",e),this.view.dispatch({effects:zi.of(void 0)})}}destroy(){this.abortController?.abort()}}),l=o.Prec.highest(n.keymap.of([{key:Vi.close.primaryKey,run:e=>Yi(e,s)},{key:"Escape",run:e=>Yi(e,s)},{key:Vi.replace.primaryKey,run:e=>!!Wi(e,s,!0)&&(Ji(e,s,a,"replace"),!0)},{key:"Mod-Enter",run:e=>!!Wi(e,s,!0)&&(Ji(e,s,a,"replace"),!0)},{key:Vi.insertBelow.primaryKey,run:e=>!!Wi(e,s,!0)&&(Ji(e,s,a,"insert-below"),!0)},{key:"Mod-Shift-Enter",run:e=>!!Wi(e,s,!0)&&(Ji(e,s,a,"insert-below"),!0)},{key:Vi.copy.primaryKey,run:t=>!!Wi(t,s,!0)&&(Gi(t,s).then(t=>{t&&new e.Notice(v("Copied!"))}),!0)},{key:"Mod-Shift-C",run:t=>!!Wi(t,s,!0)&&(Gi(t,s).then(t=>{t&&new e.Notice(v("Copied!"))}),!0)},{key:Vi.retry.primaryKey,run:e=>Zi(e,s)},{key:"Mod-Shift-R",run:e=>Zi(e,s)},{key:"Ctrl-Shift-Space",run:e=>{const{from:t,to:o}=e.state.selection.main;return t!==o&&(function(e,t,o){const{from:n,to:i}=e.state.selection.main;if(n===i)return;const a=Ai(e,n,i);e.dispatch({effects:Bi.of({from:a.from,to:a.to,originalText:a.selectedText,instruction:t,customPrompt:o,context:a.context})})}(e,"improve"),!0)}}]));return[s,r,l]}const ta=n.EditorView.baseTheme({".cm-ai-loading":{display:"inline-flex",alignItems:"center",gap:"7px",marginLeft:"8px",color:"var(--text-muted)",pointerEvents:"none",userSelect:"none",fontSize:"12px",whiteSpace:"nowrap",position:"relative"},".cm-ai-loading-visual":{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",width:"14px",height:"14px",flexShrink:"0",zIndex:"1"},".cm-ai-loading-spinner":{width:"8px",height:"8px",borderRadius:"999px",background:"linear-gradient(135deg, color-mix(in srgb, white 18%, var(--interactive-accent)), var(--interactive-accent))",boxShadow:"0 0 0 1px color-mix(in srgb, var(--interactive-accent) 22%, transparent), 0 0 12px color-mix(in srgb, var(--interactive-accent) 30%, transparent)",animation:"cm-ai-breathe 1.8s ease-in-out infinite",flexShrink:"0",position:"relative",zIndex:"1"},".cm-ai-loading-glow":{position:"absolute",inset:"-4px",borderRadius:"999px",background:"radial-gradient(circle, color-mix(in srgb, var(--interactive-accent) 38%, transparent) 0%, color-mix(in srgb, var(--interactive-accent) 18%, transparent) 45%, transparent 75%)",filter:"blur(0.5px)",opacity:"0.72",animation:"cm-ai-glow 1.8s ease-in-out infinite",pointerEvents:"none"},".cm-ai-loading-label":{letterSpacing:"0.02em",position:"relative",zIndex:"1",fontWeight:"500",animation:"cm-ai-label-breathe 1.8s ease-in-out infinite"},".cm-ai-loading-sheen":{position:"absolute",inset:"-1px",borderRadius:"999px",background:"linear-gradient(115deg, transparent 0%, transparent 34%, color-mix(in srgb, white 70%, transparent) 48%, transparent 62%, transparent 100%)",transform:"translateX(-140%)",opacity:"0",animation:"cm-ai-sheen 2.8s ease-in-out infinite",pointerEvents:"none",mixBlendMode:"screen"},".cm-ai-loading-pill":{gap:"7px",marginLeft:"8px",padding:"4px 10px 4px 8px",borderRadius:"999px",border:"1px solid color-mix(in srgb, var(--interactive-accent) 18%, var(--background-modifier-border))",background:"linear-gradient(135deg, color-mix(in srgb, var(--background-secondary) 92%, transparent), color-mix(in srgb, var(--background-secondary-alt) 82%, transparent))",color:"var(--text-faint)",opacity:"1",fontSize:"11px",lineHeight:"1.2",verticalAlign:"middle",backdropFilter:"blur(8px)",overflow:"hidden",isolation:"isolate",boxShadow:"0 6px 20px color-mix(in srgb, var(--interactive-accent) 8%, transparent), inset 0 1px 0 color-mix(in srgb, white 18%, transparent)",animation:"cm-ai-pill-breathe 2.2s ease-in-out infinite"},".cm-ai-loading-pill .cm-ai-loading-spinner":{opacity:"1"},".cm-ai-loading-pill .cm-ai-loading-label":{color:"var(--text-muted)"},"&dark .cm-ai-loading-pill":{background:"linear-gradient(135deg, color-mix(in srgb, var(--background-secondary-alt) 84%, transparent), color-mix(in srgb, var(--background-primary) 88%, transparent))",borderColor:"color-mix(in srgb, var(--interactive-accent) 24%, var(--background-modifier-border-hover))",boxShadow:"0 8px 26px color-mix(in srgb, black 26%, transparent), 0 0 0 1px color-mix(in srgb, var(--interactive-accent) 10%, transparent), inset 0 1px 0 rgba(255,255,255,0.04)"},".cm-ai-ghost-text":{color:"#999",fontStyle:"italic",pointerEvents:"none",userSelect:"none"},".cm-ai-ghost-hint":{display:"inline-flex",alignItems:"center",marginLeft:"10px",padding:"1px 6px",borderRadius:"999px",border:"1px solid color-mix(in srgb, var(--interactive-accent) 18%, var(--background-modifier-border))",background:"color-mix(in srgb, var(--interactive-accent) 8%, var(--background-secondary))",color:"var(--text-muted)",fontSize:"0.75em",fontStyle:"normal",letterSpacing:"0.01em"},".cm-ai-ghost-rest":{display:"block",whiteSpace:"pre-wrap"},"&dark .cm-ai-ghost-text":{color:"#666"},".cm-ai-result-panel.cm-tooltip":{background:"var(--background-primary)",backgroundColor:"var(--background-primary)",border:"1px solid var(--background-modifier-border)",borderRadius:"12px",boxShadow:"0 14px 40px rgba(0,0,0,0.16)",padding:"10px",minWidth:"320px",maxWidth:"520px",animation:"cm-ai-fade-in 0.15s ease-out"},".cm-ai-result-header":{fontWeight:"600",color:"var(--text-normal)"},".cm-ai-result-header-row":{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",marginBottom:"8px"},".cm-ai-result-close":{border:"none",background:"transparent",color:"var(--text-muted)",width:"28px",height:"28px",borderRadius:"999px",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"18px",lineHeight:"1",flexShrink:"0"},".cm-ai-result-close:hover":{background:"var(--background-modifier-hover)",color:"var(--text-normal)"},".cm-ai-result-content":{whiteSpace:"pre-wrap",lineHeight:"1.6",color:"var(--text-normal)",minHeight:"1.6em",maxHeight:"260px",overflowY:"auto",userSelect:"text",cursor:"text"},".cm-ai-result-actions":{display:"flex",gap:"8px",marginTop:"12px",flexWrap:"wrap"},".cm-ai-btn":{border:"none",borderRadius:"8px",padding:"6px 10px",cursor:"pointer",fontSize:"12px",display:"inline-flex",alignItems:"center",gap:"8px"},".cm-ai-btn-label":{lineHeight:"1.2"},".cm-ai-btn-shortcut":{fontSize:"11px",lineHeight:"1",opacity:"0.72",padding:"2px 6px",borderRadius:"999px",background:"color-mix(in srgb, var(--background-primary) 55%, transparent)"},".cm-ai-btn-primary":{background:"var(--interactive-accent)",color:"var(--text-on-accent)"},".cm-ai-btn-secondary":{background:"var(--background-secondary)",color:"var(--text-normal)"},".cm-ai-btn-danger":{background:"var(--background-modifier-error)",color:"var(--text-on-accent)"}});const oa="data-editing-toolbar-ai-busy",na="data-editing-toolbar-ai-busy-count";class ia{constructor(e){this.inlineCustomPromptEl=null,this.inlineCustomPromptTextarea=null,this.inlineCustomPromptEditor=null,this.inlineCustomPromptCleanup=[],this.vaultFrontmatterStatsCache=null,this.plugin=e,this.authService=new Mi(e),this.aiService=new hn(e,this.authService)}onload(){this.authService.loadSecrets(),this.authService.syncLoginState(),this.authService.migrateCustomModelApiKeyFromSettings();const e=this.plugin.registerObsidianProtocolHandler;"function"==typeof e&&e.call(this.plugin,"editing-toolbar-pkmer-auth",async e=>{e.code&&e.state&&await this.authService.handleOAuthCallback(e.code,e.state)}),this.plugin.registerEvent?.(this.plugin.app.metadataCache.on?.("changed",()=>{this.invalidateFrontmatterStatsCache()})),this.plugin.registerEvent?.(this.plugin.app.vault.on?.("create",()=>{this.invalidateFrontmatterStatsCache()})),this.plugin.registerEvent?.(this.plugin.app.vault.on?.("delete",()=>{this.invalidateFrontmatterStatsCache()})),this.plugin.registerEvent?.(this.plugin.app.vault.on?.("rename",()=>{this.invalidateFrontmatterStatsCache()}))}onunload(){this.closeInlineCustomPrompt(),this.authService.onunload()}async maybeShowAIOnboarding(){if(this.plugin.settings.ai.enabled||this.plugin.settings.ai.onboardingShown)return;this.plugin.settings.ai.onboardingShown=!0,await this.plugin.saveSettings();await this.openAIConsentModal("startup")&&(this.plugin.settings.ai.consentAccepted=!0,this.plugin.settings.ai.enabled=!0,await this.persistAIAvailabilityChange(),new e.Notice(v("AI editing is now enabled. The plugin does not intentionally store your note content, and requests follow your chosen provider policies."),6e3))}async requestEnableAIWithConsent(t){if(this.plugin.settings.ai.enabled)return!0;if(!this.plugin.settings.ai.consentAccepted){if(!await this.openAIConsentModal(t))return!1;this.plugin.settings.ai.consentAccepted=!0}return this.plugin.settings.ai.onboardingShown=!0,this.plugin.settings.ai.enabled=!0,await this.persistAIAvailabilityChange(),new e.Notice(v("AI editing is now enabled. The plugin does not intentionally store your note content, and requests follow your chosen provider policies."),6e3),!0}async disableAI(){this.plugin.settings.ai.enabled&&(this.plugin.settings.ai.enabled=!1,await this.persistAIAvailabilityChange())}async persistAIAvailabilityChange(){await this.plugin.saveSettings(),this.plugin.refreshAIAvailability()}async openAIConsentModal(e){return new pn(this.plugin.app,{source:e}).openAndWait()}createExtension(){return[qi((e={getService:()=>this.plugin.settings.ai.enabled?this.aiService:null,getCompletionConfig:()=>({trigger:this.plugin.settings.ai.enableInlineCompletion?this.plugin.settings.ai.completionTrigger:"manual",delay:this.plugin.settings.ai.completionDelay}),shouldShowInlineCompletionHint:()=>!this.plugin.settings.ai.inlineCompletionHintLearned,markInlineCompletionHintLearned:()=>{this.plugin.settings.ai.inlineCompletionHintLearned||(this.plugin.settings.ai.inlineCompletionHintLearned=!0,this.plugin.saveSettings())},getRewriteConfig:()=>({actions:O,minSelectionLength:this.plugin.settings.ai.rewriteMinSelectionLength,showToolbarOnSelection:!1,createGeneratedArtifact:e=>this.createGeneratedArtifact(e)})}).getService,e.getCompletionConfig,e.shouldShowInlineCompletionHint,e.markInlineCompletionHintLearned),ea(e.getService,e.getRewriteConfig),ta];var e}async loginWithPKMer(){await this.authService.login()}async logoutFromPKMer(){await this.authService.logout()}async refreshPKMerQuota(){const t=await this.authService.refreshQuota();t?new e.Notice(`${v("PKMer quota refreshed:")} ${Number((t.quota/5e5).toFixed(2))}`):new e.Notice(v("Unable to refresh PKMer quota."))}getPKMerStatusText(){const e=this.plugin.settings.ai.pkmer.userInfo;if(!e)return v("Not logged in");const t=[];return e.name&&t.push(e.name),e.email&&t.push(e.email),void 0!==e.ai_quota?.quota&&t.push(`${v("Quota")}: ${Number((e.ai_quota.quota/5e5).toFixed(2))}`),t.join(" / ")||v("Logged in")}hasSecureStorage(){return this.authService.hasSecureStorage}async getToolbarRouteState(){return await this.isPKMerAvailable()?"pkmer":this.aiService.hasCustomProviderConfigured()?"custom":"unavailable"}async getProviderRouteStatusText(){try{const e=await this.isPKMerAvailable(),t=this.aiService.hasCustomProviderConfigured();return e&&t?v("Current route: PKMer AI. If unavailable, it falls back to your custom model."):e?v("Current route: PKMer AI."):t?v("Current route: Custom model."):this.plugin.settings.ai.enableCustomModel?v("No provider available. Log in to PKMer or complete the custom model settings."):v("No provider available. Log in to PKMer to enable AI.")}catch(e){return console.error("[AI Settings] Failed to determine provider route:",e),v("Unable to determine current AI route.")}}hasCustomModelApiKey(){return!!this.authService.customModelApiKey}saveCustomModelApiKey(e){this.authService.setCustomModelApiKey(e)}clearCustomModelApiKey(){this.authService.clearCustomModelApiKey()}hasCustomModelReadyForTest(){return this.aiService.hasCustomProviderConfigured()}async testCustomModelConnection(){if(!this.hasCustomModelReadyForTest())return new e.Notice(v("Please fill in the required custom model settings first.")),!1;new e.Notice(v("Testing custom model connection..."));try{await this.aiService.testCustomProviderConnection();const t=this.plugin.settings.ai.customModel.model.trim();return new e.Notice(`${v("Custom model connection succeeded.")} ${t}`.trim()),!0}catch(t){const o=Wo(t);return new e.Notice(`${v("Custom model connection failed:")} ${o}`),!1}}async listCustomOllamaModels(){return this.aiService.listCustomOllamaModels()}triggerInlineCompletion(t){if(!this.plugin.settings.ai.enabled)return new e.Notice(v("AI features are disabled in settings.")),!1;if(!this.plugin.settings.ai.enableInlineCompletion)return new e.Notice(v("Inline completion is disabled in settings.")),!1;const o=this.getEditorView(t);return o?(o.dispatch({effects:Ni.of(void 0)}),!0):(new e.Notice(v("Current editor does not support AI inline completion.")),!1)}async startRewrite(t,o="improve",n,i){if(!this.plugin.settings.ai.enabled)return new e.Notice(v("AI features are disabled in settings.")),!1;const a=this.resolveEditor(t);if(!a)return new e.Notice(v("Please select text first")),!1;const s=this.getEditorView(a);if(!s)return new e.Notice(v("Current editor does not support AI rewrite.")),!1;const r=a.posToOffset(a.getCursor("from")),l=a.posToOffset(a.getCursor("to"));if("custom"!==o&&r===l)return new e.Notice("Please select text first"),!1;const c=Ai(s,r,l,{preferBlockWhenCollapsed:i?.preferBlockWhenCollapsed??"custom"===o}),d=i?.additionalContext?`${c.context}\n\n${i.additionalContext}`:c.context;return s.dispatch({effects:Bi.of({from:c.from,to:c.to,originalText:c.selectedText,instruction:o,customPrompt:n,context:d,artifactKind:i?.artifactKind})}),!0}async runToolboxAction(e,t){const o=function(e){switch(e){case"list":return[te,"Task:","Convert the source content into a clear Obsidian-friendly Markdown list.","Use ordered or unordered lists based on the content structure.","Preserve meaning, important emphasis, wikilinks, tags, task checkboxes, and inline Markdown when relevant.","Return only the final Markdown list."].join("\n\n");case"table":return[te,"Task:","Convert the source content into a valid Markdown table for Obsidian.","Choose concise and meaningful column headers.","Preserve important entities, wikilinks, tags, and inline formatting when possible.","Return only the final Markdown table."].join("\n\n");case"base":return[te,oe,"Task:","Convert the source content into one practical Obsidian .base file body.","Infer meaningful properties and views from the source content rather than emitting a placeholder schema.","If the content clearly describes entities or records, produce a table-first base with sensible order fields.","If multiple browsing modes make sense, include more than one view.","Return only YAML."].join("\n\n");case"frontmatter":return[te,"Obsidian frontmatter generation rules:","- Output YAML frontmatter only for the current note.","- Return a complete frontmatter block wrapped in leading and trailing --- lines.","- Prefer practical fields that users really filter or browse by, such as tags, aliases, status, category, type, project, area, source, created, updated, date, author, owner, rating, priority, due, and cssclasses when appropriate.","- If sibling notes in the same folder show recurring frontmatter conventions, follow those conventions closely in naming style and field shape.","- If context provides preferred_frontmatter_key_aliases, prefer those key names over lower-frequency aliases.","- Reuse existing frontmatter keys from the current note when they are still appropriate instead of inventing conflicting names.","- Keep the output concise and useful. Do not flood the note with speculative properties.","- Use YAML lists for tags/aliases when appropriate.","- Do not include explanations or markdown fences outside the YAML frontmatter block.","Task:","Generate frontmatter for the current note based on the note content, current frontmatter if any, and sibling-note frontmatter patterns from the same folder."].join("\n\n");case"canvas":return[te,ne,"Task:","Convert the source content into one useful Obsidian canvas.","Extract the main topic, key subtopics, supporting details, and relationships from the source.","Create a readable spatial structure rather than a shallow dump of text.","Prefer a center-out or left-to-right layout with 5-12 meaningful nodes when the source has enough content.","Use text nodes containing concise Markdown headings, bullets, and summaries.","Ensure the canvas feels visually organized when opened directly in Obsidian.","Return only JSON."].join("\n\n");default:return null}}(t);if(!o)return!1;if("frontmatter"===t)return this.startFrontmatterGeneration(e,o);const n=function(e){if("base"===e||"canvas"===e||"frontmatter"===e)return e}(t);return this.startRewrite(e,"custom",o,{artifactKind:n})}async openCanvasNodeExpansionModal(){if(!this.plugin.settings.ai.enabled)return new e.Notice(v("AI features are disabled in settings.")),!1;if("unavailable"===await this.getToolbarRouteState())return new e.Notice(await this.getProviderRouteStatusText()),!1;if(!Ln(this.plugin))return new e.Notice(v("Canvas AI requires an active Canvas file.")),!1;let t;try{t=await Fn(this.plugin)}catch(t){return new e.Notice(Wo(t)),!1}return new un(this.plugin.app,v("Expand current canvas node"),[{key:"instruction",label:v("Instruction"),placeholder:v("e.g. split into next steps, risks, dependencies"),defaultValue:"",multiline:!0,hideLabel:!0}],(e,t)=>{const o=this.resolveTextInputInstruction(e.instruction,t,"instruction"),n=this.buildLinkedNotesAdditionalContext(t,"instruction");this.expandCurrentCanvasNode(o,n)},{modalClassName:"editing-toolbar-text-input-modal-wide",contextLabel:t.selectedNodes.length>0?v("Selected nodes"):void 0,contextItems:this.buildCanvasSelectionContextItems(t),suggestions:this.getCanvasExpansionPromptSuggestions(),linkedNotes:{enabled:!0,fieldKeys:["instruction"],hint:v("Type [[]] to reference document content.")}}).open(),!0}async openCanvasGlobalPromptModal(){if(!this.plugin.settings.ai.enabled)return new e.Notice(v("AI features are disabled in settings.")),!1;if("unavailable"===await this.getToolbarRouteState())return new e.Notice(await this.getProviderRouteStatusText()),!1;if(!Ln(this.plugin))return new e.Notice(v("Canvas AI requires an active Canvas file.")),!1;let t;try{t=await Fn(this.plugin,{requireAnchor:!1})}catch(t){return new e.Notice(Wo(t)),!1}return new un(this.plugin.app,v("Canvas global prompt"),[{key:"instruction",label:v("Instruction"),placeholder:this.getCanvasGlobalPromptPlaceholder(t),defaultValue:"",multiline:!0,hideLabel:!0}],(e,t)=>{const o=this.resolveTextInputInstruction(e.instruction,t,"instruction"),n=this.buildLinkedNotesAdditionalContext(t,"instruction"),i=this.buildLinkedNotesPrimarySource(t,"instruction");this.runCanvasGlobalInstruction(o,n,i)},{modalClassName:"editing-toolbar-text-input-modal-wide",contextLabel:t.selectedNodes.length>0?v("Selected nodes"):void 0,contextItems:this.buildCanvasSelectionContextItems(t),suggestions:this.getCanvasGlobalPromptSuggestions(t),linkedNotes:{enabled:!0,fieldKeys:["instruction"],hint:v("Type [[]] to reference document content.")}}).open(),!0}async expandCurrentCanvasNode(t,o){if(!this.plugin.settings.ai.enabled)return new e.Notice(v("AI features are disabled in settings.")),!1;if("unavailable"===await this.getToolbarRouteState())return new e.Notice(await this.getProviderRouteStatusText()),!1;try{const n=await Fn(this.plugin);return await this.withCanvasToolbarBusyState(n.view,async()=>{new e.Notice(v("Canvas AI is expanding the current node..."));let i="";for await(const e of this.aiService.rewrite({selectedText:n.anchorNode.text,instruction:"custom",customPrompt:this.buildCanvasExpansionPrompt(t),context:this.mergeAIContext(n.contextText,o)}))i+=e;const a=function(e){const t=Jn(e);let o;try{o=JSON.parse(t)}catch{throw new Error(v("Canvas AI returned invalid JSON."))}const n=(Array.isArray(o)?o:Array.isArray(o?.nodes)?o.nodes:Array.isArray(o?.items)?o.items:Array.isArray(o?.children)?o.children:[]).map(e=>jn(e)).filter(e=>null!==e).slice(0,6);if(0===n.length)throw new Error(v("Canvas AI did not return any usable nodes."));return n}(i),s=await async function(e,t,o){if(!t.anchorNode)throw new Error(v("Please select a canvas node first."));const n={nodes:t.document.nodes.map(e=>({...e})),edges:t.document.edges.map(e=>({...e}))},i=new Set([...n.nodes.map(e=>e.id),...n.edges.map(e=>e.id)]),a=n.nodes.find(e=>e.id===t.anchorNode.id);if(!a)throw new Error(v("The focused canvas node no longer exists."));const s=ei(n,a,o,i);n.nodes.push(...s);const r=s.map((e,t)=>({id:ri(i),fromNode:a.id,toNode:e.id,fromSide:"right",toSide:"left",toEnd:"arrow",label:o[t]?.relation?.trim()||void 0}));n.edges.push(...r);const l=`${JSON.stringify(n,null,2)}\n`;try{t.view.setViewData(l,!1),await t.view.save(!1)}catch{await e.app.vault.modify(t.file,l)}return{addedNodeCount:s.length,addedEdgeCount:r.length,movedNodeCount:0}}(this.plugin,n,a);return new e.Notice(`${v("Canvas AI added")} ${s.addedNodeCount} ${v("nodes to the board.")}`),!0})}catch(t){const o=Wo(t);return new e.Notice(o),console.error("[Canvas AI] Failed to expand current node:",t),!1}}async runCanvasGlobalInstruction(t,o,n){if(!this.plugin.settings.ai.enabled)return new e.Notice(v("AI features are disabled in settings.")),!1;if("unavailable"===await this.getToolbarRouteState())return new e.Notice(await this.getProviderRouteStatusText()),!1;try{const i=await Fn(this.plugin,{requireAnchor:!1}),a=t?.trim();return a?await this.withCanvasToolbarBusyState(i.view,async()=>{const t=this.shouldTreatAsReferencedCanvasInstruction(a)?"reference-canvas":this.resolveCanvasGlobalInstructionMode(a);if("reference-canvas"===t){if(!n?.trim())return new e.Notice(v("Please reference at least one note with [[...]] before converting to canvas.")),!1;const t=await On(this.plugin,i,{scopeMode:"board"});new e.Notice(v("Canvas AI is structuring the referenced content..."));let o="";for await(const e of this.aiService.rewrite({selectedText:n,instruction:"custom",customPrompt:this.buildReferencedContentCanvasPrompt(a),context:t.text}))o+=e;const s=Bn(o,{existingNodeIds:i.document.nodes.filter(e=>"group"!==e.type).map(e=>e.id)}),r=await $n(this.plugin,i,s);return new e.Notice(`${v("Canvas AI updated the board:")} ${r.addedNodeCount} ${v("nodes")}, ${r.addedEdgeCount} ${v("links")}.`),!0}if("article"===t||"slides"===t)return this.generateCanvasDerivedMarkdown(i,a,t,o);const s="reorganize"===t,r=s?await On(this.plugin,i):null,l=s?Rn(i,a):null;let c;if(new e.Notice(v(s?"Canvas AI is reorganizing the board...":"Canvas AI is processing the board...")),s&&l)try{let e="";for await(const t of this.aiService.rewrite({selectedText:r?.text||i.anchorNode?.text||"Canvas board",instruction:"custom",customPrompt:this.buildCanvasReorganizationPrompt(a,r?.scope??"board",l),context:this.mergeAIContext(i.contextText,o)}))e+=t;c=function(e,t){const o=new Map;return t.layoutNodes.forEach(e=>{o.set(e.nodeId,e)}),e.layoutNodes.forEach(e=>{o.set(e.nodeId,e)}),{addNodes:[],addEdges:e.addEdges,layoutNodes:Hn([...o.values()]),replaceExistingEdges:e.addEdges.length>0&&e.replaceExistingEdges}}({...qn(e),addNodes:[]},l)}catch(e){console.warn("[Canvas AI] Falling back to deterministic reorganization plan:",e),c=l}else{let e="";for await(const t of this.aiService.rewrite({selectedText:r?.text||i.anchorNode?.text||"Canvas board",instruction:"custom",customPrompt:this.buildCanvasGlobalPrompt(a,!!i.anchorNode),context:this.mergeAIContext(i.contextText,o)}))e+=t;c=qn(e)}const d=await async function(e,t,o){const n={nodes:t.document.nodes.map(e=>({...e})),edges:t.document.edges.map(e=>({...e}))},i=new Set([...n.nodes.map(e=>e.id),...n.edges.map(e=>e.id)]),a=new Map(n.nodes.map(e=>[e.id,e])),s=t.anchorNode?n.nodes.find(e=>e.id===t.anchorNode?.id)??null:null,r=li(n),l=t.selectedNodeIds.filter(e=>{const t=a.get(e);return!!t&&"group"!==t.type}),c=new Set(l.length>0?l:n.nodes.filter(e=>"group"!==e.type).map(e=>e.id)),d=[],u=[],m=new Map,p="__canvas_board_scope__",h=ti(n,o.layoutNodes);o.replaceExistingEdges&&c.size>1&&(n.edges=n.edges.filter(e=>!c.has(e.fromNode)||!c.has(e.toNode))),o.addNodes.forEach(e=>{const t=pi(e.connectTo,s?.id??null,a)||p,o=m.get(t)??[];o.push(e),m.set(t,o)}),m.forEach((e,t)=>{const o=t===p,l=o?r:a.get(t)??s??r;ei(n,l,e,i).forEach((t,s)=>{if(d.push(t),n.nodes.push(t),a.set(t.id,t),o)return;const r=e[s]?.relation?.trim(),c={id:ri(i),fromNode:l.id,toNode:t.id,toEnd:"arrow",label:r||void 0};ni(c,a),u.push(c),n.edges.push(c)})}),o.addEdges.forEach(e=>{const t=pi(e.fromNode,s?.id??null,a),o=pi(e.toNode,s?.id??null,a);if(!t||!o||t===o)return;if(hi(n.edges,t,o,e.label))return;const r={id:ri(i),fromNode:t,toNode:o,toEnd:"arrow",label:e.label?.trim()||void 0};ni(r,a),u.push(r),n.edges.push(r)}),oi(n,new Set([...c,...d.map(e=>e.id)]));const g=`${JSON.stringify(n,null,2)}\n`;try{t.view.setViewData(g,!1),await t.view.save(!1)}catch{await e.app.vault.modify(t.file,g)}return{addedNodeCount:d.length,addedEdgeCount:u.length,movedNodeCount:h}}(this.plugin,i,c);return new e.Notice(s?`${v("Canvas AI reorganized the board:")} ${d.movedNodeCount} ${v("nodes moved")}, ${d.addedEdgeCount} ${v("links rebuilt")}.`:`${v("Canvas AI updated the board:")} ${d.addedNodeCount} ${v("nodes")}, ${d.addedEdgeCount} ${v("links")}.`),!0}):(new e.Notice(v("Please enter your canvas instruction.")),!1)}catch(t){const o=Wo(t);return new e.Notice(o),console.error("[Canvas AI] Failed to run global instruction:",t),!1}}buildCanvasExpansionPrompt(e){return["You are assisting inside an existing Obsidian Canvas.","Return JSON only. No explanations. No markdown fences.","Task:","- Expand the current focus node into useful neighboring text nodes for the same board.","- Follow the user instruction first.","- Avoid repeating ideas that already exist in the nearby canvas context.","- Prefer 2 to 5 concrete nodes unless the instruction clearly needs fewer.","- Keep every node concise, specific, and ready to place on the board.","- The app will create ids, coordinates, and edges locally, so do not output them.","Output schema:","{",' "nodes": ['," {",' "title": "Short node title",',' "body": "Short Obsidian-friendly Markdown body",',' "relation": "optional short edge label",',' "color": "optional canvas color id"'," }"," ]","}","Rules:","- Return exactly one JSON object with a nodes array.","- Do not return edges, ids, x, y, width, height, or commentary.","- title should be short and scannable.","- body should be brief and useful, usually bullets or one short paragraph.","- relation is optional and should be short if present.","",`User instruction:\n${e?.trim()||v("Expand the current node into the most useful next neighboring nodes.")}`].join("\n")}getCanvasGlobalPromptPlaceholder(e){return e.selectedNodes.length>0?v("e.g. tidy selected layout, connect selected nodes, add missing branches, convert [[a note]] to canvas"):v("e.g. reorganize the board, turn this canvas into an article, turn [[a note]] into canvas")}getCanvasGlobalPromptSuggestions(e){return e.selectedNodes.length>0?[{label:v("Convert to canvas"),value:v("Convert the referenced content into a structured canvas with one central topic, main branches, supporting details, and explicit relations."),replace:!1},{label:v("Tidy selected layout"),value:v("Reorganize the selected nodes into a clearer local hierarchy with tidy spacing and fewer edge crossings. Reuse current nodes instead of adding new ones.")},{label:v("Connect selected nodes"),value:v("Connect the selected nodes with the most meaningful relationships.")},{label:v("Add missing branches"),value:v("Add the missing branches around the selected nodes.")},{label:v("Clarify structure"),value:v("Clarify the structure around the selected nodes and remove ambiguity.")},{label:v("Generate next steps"),value:v("Generate the next actionable steps from the selected nodes.")},{label:v("Add risks and dependencies"),value:v("Add the risks, dependencies, and constraints related to the selected nodes.")}]:[{label:v("Convert to canvas"),value:v("Convert the referenced content into a structured canvas with one central topic, main branches, supporting details, and explicit relations."),replace:!1},{label:v("Organize canvas layout"),value:v("Reorganize this canvas into a clean hierarchy with tidy spacing, aligned sibling nodes, and fewer edge crossings. Reuse current nodes instead of adding new ones.")},{label:v("Reduce edge crossings"),value:v("Reorganize the canvas to reduce edge crossings, keep related nodes close, and make the reading path clearer. Reuse current nodes instead of adding new ones.")},{label:v("Canvas to article"),value:v("Convert this canvas into a polished Markdown article draft.")},{label:v("Canvas to slides"),value:v("Convert this canvas into Obsidian Slides Markdown.")},{label:v("Reorganize board"),value:v("Reorganize the existing canvas nodes into a clearer hierarchy and grouping. Reuse current nodes instead of adding new ones.")},{label:v("Connect board clusters"),value:v("Connect the related clusters across the whole canvas and add missing bridge nodes.")},{label:v("Summarize main narrative"),value:v("Identify the main narrative of this canvas and improve the section flow.")}]}getCanvasExpansionPromptSuggestions(){return[{label:v("Generate next steps"),value:v("Generate the next actionable steps from the current canvas node.")},{label:v("Add risks and dependencies"),value:v("Add the risks, dependencies, and constraints related to the current canvas node.")},{label:v("Add missing branches"),value:v("Add the missing branches around the current canvas node.")},{label:v("Clarify structure"),value:v("Clarify the structure around the current canvas node and remove ambiguity.")}]}getSelectedTextContextLabel(){return`📝 ${v("Selected text")}`}getSelectedTextPlaceholder(){return`[${this.getSelectedTextContextLabel()}]`}getSelectedTextPlaceholderVariants(){return Array.from(new Set([this.getSelectedTextPlaceholder(),"[📝 Selected text]","[📝 选中文本]"]))}getCurrentDocumentContextLabel(e){return`📋 ${e||v("Current document")}`}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}resolveCanvasGlobalInstructionMode(e){const t=this.normalizeCanvasInstructionText(e),o=[v("Convert to canvas"),v("Convert the referenced content into a structured canvas with one central topic, main branches, supporting details, and explicit relations.")].map(e=>this.normalizeCanvasInstructionText(e)),n=[v("Canvas to article"),v("Convert this canvas into a polished Markdown article draft.")].map(e=>this.normalizeCanvasInstructionText(e)),i=[v("Canvas to slides"),v("Convert this canvas into Obsidian Slides Markdown.")].map(e=>this.normalizeCanvasInstructionText(e)),a=[v("Organize canvas layout"),v("Reorganize this canvas into a clean hierarchy with tidy spacing, aligned sibling nodes, and fewer edge crossings. Reuse current nodes instead of adding new ones."),v("Reduce edge crossings"),v("Reorganize the canvas to reduce edge crossings, keep related nodes close, and make the reading path clearer. Reuse current nodes instead of adding new ones."),v("Tidy selected layout"),v("Reorganize the selected nodes into a clearer local hierarchy with tidy spacing and fewer edge crossings. Reuse current nodes instead of adding new ones."),v("Reorganize board"),v("Reorganize the whole canvas into a clearer hierarchy with better grouping."),v("Reorganize the existing canvas nodes into a clearer hierarchy and grouping. Reuse current nodes instead of adding new ones.")].map(e=>this.normalizeCanvasInstructionText(e));return o.some(e=>e&&t.includes(e))||/(?:turn|convert|transform|make|create|generate)\s+(?:the\s+)?(?:referenced\s+|linked\s+|source\s+)?(?:content|note|notes|document)?\s*(?:into|to)?\s*(?:a\s+)?(?:structured\s+)?(?:canvas|mindmap|mind map|concept map|knowledge map)|转为画板|转成画板|转成\s*canvas|转为\s*canvas|解构为画板|拆成画板|生成画板|知识图谱|概念图/i.test(t)?"reference-canvas":n.some(e=>e&&t.includes(e))?"article":i.some(e=>e&&t.includes(e))||/(^|\b)(slides?|slide deck|presentation|deck|reveal)(\b|$)|幻灯片|投影片|演示文稿/i.test(t)?"slides":/(^|\b)(article|document|essay|blog|post|writeup|manuscript)(\b|$)|文章|文稿|稿子|长文|博文|文档/i.test(t)?"article":a.some(e=>e&&t.includes(e))||/(^|\b)(organize|reorganize|rearrange|restructure|regroup|relayout|layout|tidy|tidy up|clean up|reduce crossings?|edge crossings?)(\b|$)|重组|重排|重整|重新布局|整理布局|整理画布|整理结构|梳理结构|减少交叉|避免交叉|连线交叉|层级|分组/i.test(t)?"reorganize":"board"}normalizeCanvasInstructionText(e){return e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ")}shouldTreatAsReferencedCanvasInstruction(e){const t=this.normalizeCanvasInstructionText(e),o=/\[\[|\]\]|引用|双链|参考文档|参考笔记|linked note|linked notes|referenced content|reference note|reference notes|source note|source notes/i.test(e),n=/canvas|mindmap|mind map|concept map|knowledge map|画板|知识图谱|概念图/i.test(t),i=/convert|turn|transform|make|create|generate|structured|structure|转为|转成|生成|解构|拆成|结构化/i.test(e);return o&&n&&i}buildCanvasGlobalPrompt(e,t){return["You are assisting inside an existing Obsidian Canvas.","Return JSON only. No explanations. No markdown fences.","You may add new nodes and/or connect existing nodes already on the board.","The local app will validate ids, coordinates, and edges.","Output schema:","{",' "addNodes": ['," {",' "title": "Short node title",',' "body": "Short Obsidian-friendly Markdown body",',t?' "connectTo": "anchor or existing node id",':' "connectTo": "existing node id (optional)",',' "relation": "optional short edge label",',' "color": "optional canvas color id"'," }"," ],",' "addEdges": ['," {",t?' "fromNode": "anchor or existing node id",':' "fromNode": "existing node id",',t?' "toNode": "anchor or existing node id",':' "toNode": "existing node id",',' "label": "optional short edge label"'," }"," ]","}","Rules:","- Use exact existing node ids when creating edges to existing nodes.","- Prefer concise, high-value updates that fit the current board.","- Do not output ids, x, y, width, or height for new nodes.","- If no new nodes are needed, return an empty addNodes array.","- If no new edges are needed, return an empty addEdges array.",t?"- You may use anchor/current to refer to the selected focus node.":"- No node is currently selected. Do not use anchor/current placeholders; use exact existing node ids or leave connectTo empty.","",`User instruction:\n${e}`].join("\n")}buildReferencedContentCanvasPrompt(e){return["Canvas quality reference:",ne.split("\n").filter(e=>["Prefer text nodes unless a file node or link node is clearly required by the source.","Text nodes should contain concise, structured Markdown-friendly text.","Layout should be readable: align to a loose grid, leave about 50-100px spacing between nodes, and avoid overlaps.","Coordinates can be negative, but prefer a clean left-to-right or center-out layout.","A good canvas usually has a clear central node and connected supporting nodes rather than isolated fragments.","Unless the source is tiny, create a meaningful structure with several nodes instead of only one or two.","Use edge labels only when they add real meaning."].some(t=>e.includes(t))).join("\n"),"Role:","You are a knowledge structure analyst working for an Obsidian Canvas workflow.","Input understanding:","- The selectedText contains the referenced note content that should be converted into new canvas nodes.","- The context contains the existing canvas nodes with exact node ids, summaries, and current links.","Task:","0. Read the existing canvas context first, so you understand what is already on the board.","1. Read the full source carefully and identify the core theme, major sections or arguments, supporting details, and conclusion when useful.","2. Compare the referenced source with the existing canvas nodes. If some generated nodes clearly belong to an existing node or extend it naturally, prepare explicit connections to those existing node ids.","3. Analyze the logical relationships between generated nodes, such as contains, supports, causes, contrasts, and follows.","4. Return one structured JSON object with nodes, edges, and boardConnections only.","Output schema:","{",' "nodes": ['," {",' "id": "n_1",',' "type": "concept",',' "title": "Short title",',' "content": "Key sentence summary within 30 Chinese characters when possible",',' "level": 0,',' "group": "optional thematic group label for branch clustering"'," }"," ],",' "edges": ['," {",' "from": "n_1",',' "to": "n_2",',' "relation": "optional short natural-language relation such as 前提 / 方法 / 结果 / 风险 / 示例"'," }"," ],",' "boardConnections": ['," {",' "nodeId": "n_2",',' "existingNodeId": "exact existing canvas node id from context",',' "relation": "optional short natural-language relation"'," }"," ]","}","Rules:","- Return valid JSON only. No explanations. No markdown fences.","- Create one clear central theme node at level 0 unless the source is too fragmentary.","- Use level 1 for main branches and level 2 for supporting details. Add deeper levels only when truly necessary.","- Keep titles short and scannable.","- Keep content concise and summary-like rather than copying long paragraphs.","- Prefer 5 to 14 nodes when the source has enough substance.","- Avoid duplicate nodes and isolated fragments.","- Prefer one clear parent-child backbone so the structure can be laid out cleanly as a hierarchy.","- Use explicit edges so the logical structure is recoverable, but avoid unnecessary cross-links.","- relation should be a short phrase that matches the topic content and the source language. Avoid generic fixed English labels like contains / supports / follows unless the source itself is English and that wording is genuinely natural.","- If an edge is only an obvious parent-child inclusion, relation may be omitted or left empty.","- Use group for thematic clustering when helpful. Nodes in the same branch or topic category can share the same group label so the app can create canvas groups automatically.","- Read the existing canvas nodes first. If a generated branch clearly belongs with an existing node, add a boardConnections item using that exact existing node id from the context.","- If there is no meaningful relation to the existing canvas, return an empty boardConnections array. The app will place the new cluster separately on one side.","- Only use exact existing canvas node ids that appear in the context. Never invent or guess ids.","- The local app will handle final canvas coordinates and apply a compact hierarchical layout. Focus on accurate levels, sibling grouping, and primary parent-child relations rather than coordinates.","",`User instruction:\n${e}`].join("\n\n")}buildCanvasReorganizationPrompt(e,t,o){const n=o?JSON.stringify({layoutNodes:o.layoutNodes,replaceExistingEdges:o.replaceExistingEdges,addEdges:o.addEdges},null,2):"";return["You are reorganizing an existing Obsidian Canvas.","Return JSON only. No explanations. No markdown fences.","Reuse existing canvas nodes only. Do not create new nodes.","The selectedText contains an ordered traversal of the relevant canvas nodes with exact node ids and current links.","selection"===t?"Reorganize only the selected canvas nodes.":"Reorganize the whole canvas.","Output schema:","{",' "layoutNodes": ['," {",' "nodeId": "existing node id",',' "column": 0,',' "row": 0'," }"," ],",' "replaceExistingEdges": true,',' "addEdges": ['," {",' "fromNode": "existing node id",',' "toNode": "existing node id",',' "label": "optional short edge label"'," }"," ]","}","Rules:","- Use only existing node ids from the provided canvas data.","- Do not return addNodes, titles, bodies, or new ids.","- Use layoutNodes to place the existing nodes into a clearer hierarchy or grouped structure.","- When you are rebuilding the relationship structure, set replaceExistingEdges to true.","- Choose a layout style that matches the instruction: mind map = central topic with balanced left/right branches; DAG/flow = left-to-right topological layers; tree = parent left, children right.","- Put parents before children in smaller columns and keep siblings vertically aligned by row.","- Reduce edge crossings and avoid routes that visually pass through node rectangles.","- Prefer edges that connect from right-to-left in left-to-right layouts, left-to-right for left branches of mind maps, and top-to-bottom only for vertical stacks.","- Keep related nodes close, but leave enough whitespace between rows and columns for readable connectors.","- If the current links already fit the new structure, you may keep replaceExistingEdges false and return layoutNodes only.",n?["","A deterministic local draft is provided below.","Use it as the baseline layout when it is already reasonable, and only override parts that clearly improve readability or reduce edge crossings.","If you rebuild edges, return only the improved edge set for the nodes in scope.","deterministic_local_draft:",n].join("\n"):"","",`User instruction:\n${e}`].join("\n")}buildCanvasArticlePrompt(e,t){return["You are converting an Obsidian Canvas into a coherent Markdown article.","Return Markdown only. No explanations. No markdown fences.","The selectedText contains an ordered traversal of the canvas nodes.","The traversal follows canvas structure, starting from root nodes and walking through connected children when possible.","selection"===t?"Focus on the selected canvas nodes as the primary source.":"Focus on the whole canvas as the primary source.","Requirements:","- Create a clear title and section hierarchy.","- Merge overlapping fragments into readable paragraphs or bullets.","- Preserve concrete facts, steps, and relationships from the canvas.","- Remove duplication, but do not invent unsupported claims.","- Keep the result Obsidian-friendly Markdown.","",`User instruction:\n${e}`].join("\n")}buildCanvasSlidesPrompt(e,t){return["You are converting an Obsidian Canvas into Markdown for Obsidian Slides.","Return Markdown only. No explanations. No markdown fences.","The selectedText contains an ordered traversal of the canvas nodes.","Use `---` as the slide separator so the result works with the core Slides plugin.","selection"===t?"Focus on the selected canvas nodes as the slide source.":"Focus on the whole canvas as the slide source.","Requirements:","- Start with a title slide.","- Create concise, presentation-ready slides with short headings and bullets.","- Prefer 6 to 12 slides unless the instruction clearly asks for another length.","- Combine related nodes into the same slide when that improves clarity.","- End with a summary or next-steps slide when helpful.","",`User instruction:\n${e}`].join("\n")}buildCanvasSelectionContextItems(e){return e.selectedNodes.map((t,o)=>{const n=(t.text.trim()||t.id).replace(/\s+/g," ").trim(),i=n.length>80?`${n.slice(0,80)}...`:n,a=t.text.length>140?`${t.text.slice(0,140)}...`:t.text;return{label:this.getCanvasContextNodeLabel(t,e.anchorNode?.id,o),preview:`${i} (${t.text.length.toLocaleString()} ${v("characters")})`,title:a||t.id}})}getCanvasContextNodeLabel(e,t,o=0){const n=e.text.split("\n").map(e=>e.replace(/^#+\s*/,"").trim()).find(Boolean),i=n&&n.length>28?`${n.slice(0,28)}...`:n,a=t&&e.id===t?v("Focused"):`${v("Selected")} ${o+1}`;return i?`${a} · ${i}`:`${a} · ${e.type}`}async generateCanvasDerivedMarkdown(t,o,n,i){try{const a=await On(this.plugin,t);new e.Notice(v("article"===n?"Canvas AI is drafting an article...":"Canvas AI is drafting slides..."));let s="";for await(const e of this.aiService.rewrite({selectedText:a.text,instruction:"custom",customPrompt:"article"===n?this.buildCanvasArticlePrompt(o,a.scope):this.buildCanvasSlidesPrompt(o,a.scope),context:this.mergeAIContext(t.contextText,i)}))s+=e;const r=this.normalizeCanvasGeneratedMarkdown(s);if(!r)throw new Error(v("Canvas AI did not return any usable Markdown."));const l=await this.createCanvasMarkdownFile(t,n,r),c=this.plugin.app.workspace.getLeaf(!0);return await c.openFile(l),new e.Notice(`${v("Created AI file:")} ${l.path}`),!0}catch(t){const o=Wo(t);return new e.Notice(o),console.error("[Canvas AI] Failed to generate derived markdown:",t),!1}}async withCanvasToolbarBusyState(e,t){const o=e.containerEl;if(!o)return t();const n=o.ownerDocument,i=n?.body??n?.documentElement??null;if(i){const e=Number.parseInt(i.getAttribute(na)??"0",10),t=Number.isFinite(e)?e+1:1;i.setAttribute(na,String(t)),i.setAttribute(oa,"true")}try{return await t()}finally{if(i){const e=Number.parseInt(i.getAttribute(na)??"1",10),t=Number.isFinite(e)?Math.max(e-1,0):0;t>0?i.setAttribute(na,String(t)):(i.removeAttribute(na),i.removeAttribute(oa))}}}normalizeCanvasGeneratedMarkdown(e){const t=e.trim();return t?t.replace(/^```(?:markdown|md)?\s*/i,"").replace(/\s*```$/i,"").trim().concat("\n"):""}async createCanvasMarkdownFile(e,t,o){const n=e.file.parent?.path&&"/"!==e.file.parent.path?e.file.parent.path:"",i=v("article"===t?"AI Article Draft":"AI Slides"),a=await this.getAvailableArtifactPath(n,`${e.file.basename} ${i}`,"md");return this.plugin.app.vault.create(a,o)}resolveTextInputInstruction(e,t,o="instruction"){const n=e?.trim()||"",i=t?.cleanedResult?.[o]?.trim()||"";if(0===(t?.linkedContextByField?.[o]??[]).length)return n;const a=n.replace(/\[\[[^\]]+\]\]/g,"").trim();return a||(i||n)}buildLinkedNotesAdditionalContext(e,t="instruction"){const o=e?.linkedContextByField?.[t]??[];if(0!==o.length)return o.map(e=>`<context source="Referenced note ${e.reference}">\n${e.content}\n</context>`).join("\n\n")}buildLinkedNotesPrimarySource(e,t="instruction"){const o=e?.linkedContextByField?.[t]??[];if(0!==o.length)return o.map((e,t)=>[`source_index: ${t+1}`,`source_reference: ${e.reference}`,`source_path: ${e.filePath}`,"source_content:",e.content].join("\n")).join("\n\n")}mergeAIContext(e,t){const o=t?.trim();if(!o)return e;const n=e.trim();return n?`${n}\n\n${o}`:o}async startFrontmatterGeneration(t,o){if(!this.plugin.settings.ai.enabled)return new e.Notice(v("AI features are disabled in settings.")),!1;const n=this.resolveEditor(t),i=this.getEditorView(n);if(!n||!i)return new e.Notice(v("Current editor does not support AI rewrite.")),!1;const a=n.getValue?.()??"",s=this.findFrontmatterRange(a),r=s?`${a.slice(0,s.from)}${a.slice(s.to)}`.trim():a.trim(),l=["current_note_scope: whole_note",s?"current_note_has_frontmatter: true":"current_note_has_frontmatter: false"],c=s?a.slice(s.from,s.to).trim():"";c&&l.push("current_note_frontmatter:",c);const d=this.buildFrontmatterStyleSummary();return d.context&&l.push(d.context),i.dispatch({effects:Bi.of({from:s?.from??0,to:s?.to??0,originalText:r,instruction:"custom",customPrompt:o,context:l.join("\n\n"),artifactKind:"frontmatter",preferredFrontmatterKeys:d.preferredAliases})}),!0}findFrontmatterRange(e){const t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return t&&0===t.index?{from:0,to:t[0].length}:null}buildFrontmatterStyleSummary(){const e=this.plugin.app.workspace.getActiveFile(),t=this.plugin.app.vault.getMarkdownFiles?.()??[];if(!e||0===t.length)return{context:"",preferredAliases:{}};const o=t.filter(t=>t?.path!==e.path&&t?.parent?.path===e.parent?.path).slice(0,48),n=this.collectFrontmatterStats(o,6),i=this.shouldFallbackToVaultFrontmatterStats(n),a=i?this.getVaultFrontmatterStats(t):this.createEmptyFrontmatterStats(),s=this.buildPreferredFrontmatterAliases(n.keyCounts,a.keyCounts),r=[];if(n.examples.length>0){const t=[...n.keyCounts.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>`- ${e} (${t})`).join("\n");r.push([`same_folder_path: ${e.parent?.path||""}`,"same_folder_frontmatter_common_keys:",t,"same_folder_frontmatter_examples:",...n.examples].join("\n"))}const l=i?[...a.keyCounts.entries()].sort((e,t)=>t[1]-e[1]).slice(0,14).map(([e,t])=>`- ${e} (${t})`).join("\n"):"";i&&l&&r.push(["vault_frontmatter_high_frequency_keys:",l].join("\n"));const c=Object.entries(s).map(([e,t])=>`- prefer ${t} over ${e}`);return c.length>0&&r.push(["preferred_frontmatter_key_aliases:",...c].join("\n")),{context:r.join("\n\n"),preferredAliases:s}}collectFrontmatterStats(e,t){const o=new Map,n=[];let i=0;for(const a of e){const e=this.plugin.app.metadataCache?.getFileCache?.(a),s=e?.frontmatter;if(!s||"object"!=typeof s)continue;const r=Object.entries(s).filter(([e])=>"position"!==e).slice(0,8);if(0!==r.length){if(i+=1,r.forEach(([e])=>{o.set(e,(o.get(e)??0)+1)}),t>0&&n.length<t){const e=r.map(([e,t])=>` ${e}: ${this.serializeFrontmatterValue(t)}`).join("\n");n.push(`${a.basename}:\n${e}`)}t>0&&n.length}}return{keyCounts:o,examples:n,fileCount:i}}createEmptyFrontmatterStats(){return{keyCounts:new Map,examples:[],fileCount:0}}getVaultFrontmatterStats(e){const t=Date.now(),o=this.vaultFrontmatterStatsCache;if(o&&o.expiresAt>t&&o.sourceFileCount===e.length)return o.stats;const n=this.collectFrontmatterStats(e,0);return this.vaultFrontmatterStatsCache={expiresAt:t+6e5,sourceFileCount:e.length,stats:n},n}invalidateFrontmatterStatsCache(){this.vaultFrontmatterStatsCache=null}shouldFallbackToVaultFrontmatterStats(e){const t=e.keyCounts.size,o=e.fileCount>=6,n=e.fileCount>=3&&t>=6,i=this.hasStrongSiblingAliasSignal(e.keyCounts);return!(o||n||i)}hasStrongSiblingAliasSignal(e){return[["tags","tag"],["aliases","alias"],["status","state"],["cssclasses","cssclass"]].some(t=>t.some(t=>(e.get(t)??0)>=2))}buildPreferredFrontmatterAliases(e,t){const o=[["tags","tag"],["aliases","alias"],["status","state"],["cssclasses","cssclass"]],n={};for(const i of o){const o=i.map(o=>({key:o,siblingCount:e.get(o)??0,vaultCount:t.get(o)??0})).sort((e,t)=>t.siblingCount!==e.siblingCount?t.siblingCount-e.siblingCount:t.vaultCount-e.vaultCount),a=o[0];!a||0===a.siblingCount&&0===a.vaultCount||o.slice(1).forEach(e=>{(e.siblingCount>0||e.vaultCount>0)&&(n[e.key]=a.key)})}return n}serializeFrontmatterValue(e){return Array.isArray(e)?`[${e.map(e=>this.serializeFrontmatterValue(e)).join(", ")}]`:e&&"object"==typeof e?JSON.stringify(e):"string"==typeof e?e:String(e)}async createGeneratedArtifact(t){const o=this.plugin.app.workspace.getActiveFile(),n=o?.parent?.path&&"/"!==o.parent.path?o.parent.path:"",i=(o?.basename||v("Untitled")).trim().replace(/[\\/:*?"<>|]/g," ").replace(/\s+/g," ").trim()||v("Untitled"),a="canvas"===t.kind?"canvas":"base",s="canvas"===t.kind?v("AI Canvas File"):v("AI Base File"),r=await this.getAvailableArtifactPath(n,`${i} ${s}`,a),l=yn(t);return await this.plugin.app.vault.create(r,l),new e.Notice(`${v("Created AI file:")} ${r}`),{path:r,embedSyntax:`![[${r}]]`}}async getAvailableArtifactPath(e,t,o){let n=0;for(;n<200;){const i=`${t}${0===n?"":` ${n+1}`}.${o}`,a=e?`${e}/${i}`:i;if(!this.plugin.app.vault.getAbstractFileByPath(a))return a;n+=1}throw new Error(v("Unable to allocate a file name for the generated artifact."))}openCustomRewrite(t){const o=this.resolveEditor(t),n=this.getEditorView(o);if(!o||!n)return new e.Notice(v("Current editor does not support AI rewrite.")),!1;const i=o.getSelection();return this.inlineCustomPromptEditor=o,this.renderInlineCustomPrompt(o,n,i),!0}closeInlineCustomPrompt(){this.inlineCustomPromptCleanup.forEach(e=>e()),this.inlineCustomPromptCleanup=[],this.inlineCustomPromptTextarea=null,this.inlineCustomPromptEditor=null,this.inlineCustomPromptEl&&(this.inlineCustomPromptEl.remove(),this.inlineCustomPromptEl=null)}renderInlineCustomPrompt(t,o,n){const i=o.dom.ownerDocument;if(!this.inlineCustomPromptEl){const a=i.createElement("div");a.className="editing-toolbar-ai-inline-prompt";const s=i.createElement("div");s.className="editing-toolbar-ai-inline-prompt-header";const r=i.createElement("div");r.className="editing-toolbar-ai-inline-prompt-drag-handle",r.style.cursor="grab";const l=i.createElement("div");l.className="editing-toolbar-ai-inline-prompt-title",l.textContent=v("AI Custom Rewrite");const c=i.createElement("button");c.type="button",c.className="editing-toolbar-ai-inline-prompt-close",c.title=v("Close"),c.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>',s.append(r,l,c);const d=i.createElement("button");d.type="button",d.className="editing-toolbar-ai-inline-prompt-settings",d.title=v("Manage Templates"),d.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M12 1v6m0 6v6M4.22 4.22l4.24 4.24m5.08 5.08l4.24 4.24M1 12h6m6 0h6M4.22 19.78l4.24-4.24m5.08-5.08l4.24-4.24"/></svg>';const u=i.createElement("div");u.className="editing-toolbar-ai-inline-prompt-input-wrapper";const m=i.createElement("textarea");m.className="editing-toolbar-ai-inline-prompt-input",m.placeholder=v("Describe what you want AI to do..."),m.rows=3,m.wrap="soft";const p=i.createElement("button");p.type="button",p.className="editing-toolbar-ai-inline-prompt-history-btn",p.title=v("History"),p.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/></svg>';const h=i.createElement("div");h.className="editing-toolbar-ai-inline-prompt-history-dropdown",h.style.display="none";const g=i.createElement("div");g.className="editing-toolbar-ai-inline-prompt-mention-dropdown",g.style.display="none";const f=i.createElement("button");f.type="button",f.className="editing-toolbar-ai-inline-prompt-send-btn",f.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>',f.title=v("Send"),u.append(m,p,h,g,f);const b=i.createElement("div");b.className="editing-toolbar-ai-inline-prompt-templates";const y=this.plugin.settings.ai.customPromptTemplates||[],C=e=>{const t=this.plugin.app.workspace.getActiveFile(),o=this.resolveEditor(),n=new Date,i=o?.getSelection()||"",a=o?.getValue()||"";if(e.includes("{{selection}}")&&i)if(x.some(e=>"selection"===e.type)){const e=x.find(e=>"selection"===e.type);e&&(e.content=i)}else x.push({type:"selection",content:i,label:this.getSelectedTextContextLabel()});if(e.includes("{{file:content}}")){const e=cn(a);if(x.some(e=>"doc"===e.type)){const o=x.find(e=>"doc"===e.type);o&&(o.content=e,o.label=this.getCurrentDocumentContextLabel(t?.basename))}else x.push({type:"doc",content:e,label:this.getCurrentDocumentContextLabel(t?.basename)})}return e.replace(/\{\{selection\}\}/g,i?this.getSelectedTextPlaceholder():"").replace(/\{\{file:path\}\}/g,t?.path||"").replace(/\{\{file:content\}\}/g,t?.basename?`[[${t.basename}]]`:"").replace(/\{\{date\}\}/g,n.toLocaleDateString()).replace(/\{\{time\}\}/g,n.toLocaleTimeString()).replace(/\{\{datetime\}\}/g,n.toLocaleString()).replace(/\{\{vault:name\}\}/g,this.plugin.app.vault.getName())};y.slice(0,9).forEach(e=>{const t=i.createElement("button");t.type="button",t.className="editing-toolbar-ai-inline-prompt-template-btn",t.textContent=e.name,t.title=e.prompt,t.addEventListener("click",async()=>{m.value=C(e.prompt),k(),L(),B(),m.focus(),await U()}),b.appendChild(t)});const w=i.createElement("div");w.className="editing-toolbar-ai-inline-prompt-context",w.style.display="none";const x=[];n&&x.push({type:"selection",content:n,label:this.getSelectedTextContextLabel()});const k=()=>{w.empty(),0!==x.length?(w.style.display="block",x.forEach((e,t)=>{const o=i.createElement("div");o.className="editing-toolbar-ai-inline-prompt-context-item";const n=i.createElement("span");n.className="editing-toolbar-ai-inline-prompt-context-label",n.textContent=e.label;const a=i.createElement("span");a.className="editing-toolbar-ai-inline-prompt-context-preview";const s=e.content.substring(0,50).replace(/\n/g," "),r=e.content.length>50?"...":"",l=`(${e.content.length.toLocaleString()} ${v("characters")})`;a.textContent=`${s}${r} ${l}`,a.title=e.content.length>100?e.content.substring(0,100)+"...":e.content;const c=i.createElement("button");c.type="button",c.className="editing-toolbar-ai-inline-prompt-context-remove",c.innerHTML='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>',c.addEventListener("click",()=>{if(x.splice(t,1),"selection"===e.type)this.getSelectedTextPlaceholderVariants().forEach(e=>{m.value=m.value.replace(e,"")});else if("note"===e.type||"doc"===e.type){const t=e.label.replace(/^📄 |^📋 /,"");m.value=m.value.replace(`[[${t}]]`,"")}k()}),o.append(n,a,c),w.appendChild(o)})):w.style.display="none"};k();const S=i.createElement("div");S.className="editing-toolbar-ai-inline-prompt-footer";const T=i.createElement("div");T.className="editing-toolbar-ai-inline-prompt-hint";const E=e.Platform.isMobileApp?v("Enter inserts a newline. Tap Send to submit."):v("Press Enter to send, Shift+Enter for newline, Esc to close.");T.textContent=E,S.appendChild(T),a.append(s,u,b,w,S),i.body.appendChild(a);let I=!1,A=0,M=0;const P=e=>{if(e.target!==r&&e.target!==l)return;I=!0;const t="touches"in e?e.touches[0].clientX:e.clientX,o="touches"in e?e.touches[0].clientY:e.clientY,n=a.getBoundingClientRect();A=t-n.left,M=o-n.top,a.style.cursor="grabbing",r.style.cursor="grabbing","touches"in e&&e.preventDefault()},N=e=>{if(!I)return;e.preventDefault();const t="touches"in e?e.touches[0].clientX:e.clientX,o="touches"in e?e.touches[0].clientY:e.clientY,n=t-A,i=o-M;a.style.left=`${n}px`,a.style.top=`${i}px`},D=()=>{I=!1,a.style.cursor="",r.style.cursor="grab"};r.addEventListener("mousedown",P),l.addEventListener("mousedown",P),r.addEventListener("touchstart",P,{passive:!1}),l.addEventListener("touchstart",P,{passive:!1}),i.addEventListener("mousemove",N),i.addEventListener("touchmove",N,{passive:!1}),i.addEventListener("mouseup",D),i.addEventListener("touchend",D);const L=()=>{m.style.height="auto";const e=Math.min(Math.max(m.scrollHeight,56),240);m.style.height=`${e}px`,m.scrollHeight>240?m.style.overflowY="auto":m.style.overflowY="hidden"},F=()=>{this.closeInlineCustomPrompt(),t.focus()},O=async()=>{let o=m.value.trim();if(!o)return;if("unavailable"===await this.getToolbarRouteState())return void new e.Notice(await this.getProviderRouteStatusText());const n=this.inlineCustomPromptEditor??t,i=n.getSelection().trim().length>0,a=/\[\[[^\]]+\]\]/.test(o),s=!i&&!a;let r=o.replace(/\[\[([^\]]+)\]\]/g,"$1");this.getSelectedTextPlaceholderVariants().forEach(e=>{const t=new RegExp(this.escapeRegExp(e),"g");r=r.replace(t,v("Selected text"))}),r=r.trim(),o&&this.addToHistory(o);const l=x.filter(e=>!!e.content.trim()&&(!i||"selection"!==e.type)),c=l.length>0?l.map(e=>`<context source="${e.label}">\n${e.content}\n</context>`).join("\n\n"):"";await this.startRewrite(n,"custom",r,{additionalContext:c,preferBlockWhenCollapsed:s})&&this.closeInlineCustomPrompt()},R=()=>{const e=this.plugin.settings.ai.customPromptHistory||[];if(h.empty(),0===e.length){const e=i.createElement("div");e.className="editing-toolbar-ai-inline-prompt-history-empty",e.textContent=v("No history"),h.appendChild(e)}else e.forEach((e,t)=>{const o=i.createElement("div");o.className="editing-toolbar-ai-inline-prompt-history-item",o.textContent=e.length>50?e.substring(0,50)+"...":e,o.title=e,o.addEventListener("click",async()=>{m.value=e,h.style.display="none",L(),B(),m.focus(),await U()}),h.appendChild(o)})};p.addEventListener("click",e=>{e.stopPropagation();const t="none"!==h.style.display;h.style.display=t?"none":"block",t||R()}),i.addEventListener("click",e=>{h.contains(e.target)||e.target===p||(h.style.display="none")});const q=()=>this.positionInlineCustomPrompt(t,o),B=()=>{f.disabled=0===m.value.trim().length};c.addEventListener("click",F),d.addEventListener("click",()=>{this.plugin.app.setting.open(),this.plugin.app.setting.openTabById("editing-toolbar"),setTimeout(()=>{const e=this.plugin.app.setting.activeTab?.containerEl?.querySelector(".editing-toolbar-tabs");if(e){const t=Array.from(e.children).find(e=>e.textContent?.includes("AI")||"ai"===e.getAttribute("data-tab"));t?.click()}},100),F()}),f.addEventListener("click",()=>{O()});let $=-1,_=0,z=[];const U=async()=>{const e=m.value,t=Array.from(e.matchAll(/\[\[([^\]]+)\]\]/g)),o=new Set(t.map(e=>e[1])),n=x.filter(e=>"note"===e.type);for(const e of n){const t=e.label.replace("📄 ","");if(!o.has(t)){const t=x.indexOf(e);t>-1&&x.splice(t,1)}}for(const e of o){if(x.some(t=>("note"===t.type||"doc"===t.type)&&(t.label.includes(e)||t.label.replace(/^📄 |^📋 /,"")===e)))continue;const t=this.plugin.app.metadataCache.getFirstLinkpathDest(e,"");if(t)try{const e=cn(await this.plugin.app.vault.cachedRead(t));x.push({type:"note",content:e,label:`📄 ${t.basename}`})}catch(t){console.error(`Failed to read linked file: ${e}`,t)}}k()},V=async e=>{const t=m.selectionStart,o=m.value.substring(0,$),n=m.value.substring(t);m.value=o+`[[${e.basename}]] `+n,g.style.display="none",m.focus();const i=$+e.basename.length+5;m.setSelectionRange(i,i),L(),B(),await U()},H=()=>{const e=m.selectionStart,t=m.value.substring(0,e),o=t.match(/\[\[([^\]]*?)$/);if(o){$=t.lastIndexOf("[[");const e=o[1].toLowerCase(),n=this.plugin.app.workspace.getActiveFile(),a=this.plugin.app.vault.getMarkdownFiles().filter(t=>t.basename.toLowerCase().includes(e)||t.path.toLowerCase().includes(e));a.sort((e,t)=>n&&e.path===n.path?-1:n&&t.path===n.path?1:0),z=a.slice(0,10),_=0,a.length>0?(g.empty(),a.forEach((e,t)=>{const o=i.createElement("div");o.className="editing-toolbar-ai-inline-prompt-mention-item",0===t&&o.classList.add("selected"),o.innerHTML=`<span class="editing-toolbar-ai-inline-prompt-mention-icon">📄</span>${e.basename} <span style="color: var(--text-faint); font-size: 10px;">${e.path}</span>`,o.addEventListener("click",()=>{V(e)}),g.appendChild(o)}),g.style.display="block"):g.style.display="none"}else g.style.display="none",$=-1,z=[]},W=()=>{const e=m.value,t=this.getSelectedTextPlaceholderVariants().some(t=>e.includes(t)),o=x.some(e=>"selection"===e.type);if(!t&&o){const e=x.findIndex(e=>"selection"===e.type);e>-1&&(x.splice(e,1),k())}},j=(e,t)=>{let o=e,n=t;if(o.includes("【【")){const e=o.substring(0,n),t=o.substring(n),i=e.replace(/【【/g,"[[");o=i+t.replace(/【【/g,"[["),n-=e.length-i.length}const i=o.substring(0,n).match(/(?:\[|【){2,}$/);if(i&&i[0].includes("【")){const e=n-i[0].length;o=`${o.substring(0,e)}[[${o.substring(n)}`,n=e+2}return{value:o,cursorPos:n}};m.addEventListener("input",e=>{const t=j(m.value,m.selectionStart);t.value===m.value&&t.cursorPos===m.selectionStart||(m.value=t.value,m.setSelectionRange(t.cursorPos,t.cursorPos)),L(),B(),H(),U(),W()}),m.addEventListener("keydown",t=>{const o="none"!==g.style.display&&z.length>0;if(o){if("ArrowDown"===t.key){t.preventDefault(),_=(_+1)%z.length;const e=g.querySelectorAll(".editing-toolbar-ai-inline-prompt-mention-item");return e.forEach((e,t)=>{e.classList.toggle("selected",t===_)}),void e[_]?.scrollIntoView({block:"nearest"})}if("ArrowUp"===t.key){t.preventDefault(),_=(_-1+z.length)%z.length;const e=g.querySelectorAll(".editing-toolbar-ai-inline-prompt-mention-item");return e.forEach((e,t)=>{e.classList.toggle("selected",t===_)}),void e[_]?.scrollIntoView({block:"nearest"})}if("Tab"===t.key)return t.preventDefault(),void(z[_]&&V(z[_]));if("Enter"===t.key&&!t.shiftKey&&!t.metaKey&&!t.ctrlKey)return t.preventDefault(),void(z[_]&&V(z[_]))}return"Escape"===t.key?(t.preventDefault(),void(o?g.style.display="none":F())):"Enter"===t.key&&(t.metaKey||t.ctrlKey)?(t.preventDefault(),void O()):void(e.Platform.isMobileApp||"Enter"!==t.key||t.shiftKey||(t.preventDefault(),O()))});const K=i.defaultView??window;K.addEventListener("resize",q),i.addEventListener("scroll",q,!0),this.inlineCustomPromptCleanup=[()=>K.removeEventListener("resize",q),()=>i.removeEventListener("scroll",q,!0),()=>r.removeEventListener("mousedown",P),()=>l.removeEventListener("mousedown",P),()=>r.removeEventListener("touchstart",P),()=>l.removeEventListener("touchstart",P),()=>i.removeEventListener("mousemove",N),()=>i.removeEventListener("touchmove",N),()=>i.removeEventListener("mouseup",D),()=>i.removeEventListener("touchend",D)],this.inlineCustomPromptEl=a,this.inlineCustomPromptTextarea=m,L(),B()}this.positionInlineCustomPrompt(t,o),this.inlineCustomPromptTextarea?.focus()}positionInlineCustomPrompt(e,t){if(!this.inlineCustomPromptEl)return;const o=t.dom.ownerDocument.defaultView??window,n=e.getCursor("to"),i=e.posToOffset(n),a=t.coordsAtPos(i);if(!a)return;const s=this.inlineCustomPromptEl.offsetWidth||320,r=this.inlineCustomPromptEl.offsetHeight||150,l=Math.max(12,Math.min(a.left,o.innerWidth-s-12)),c=Math.max(12,Math.min(a.bottom+10,o.innerHeight-r-12));this.inlineCustomPromptEl.style.left=`${l}px`,this.inlineCustomPromptEl.style.top=`${c}px`}resolveEditor(t){if(t)return t;try{return this.plugin.commandsManager?.getActiveEditor()??this.plugin.app.workspace.getActiveViewOfType(e.MarkdownView)?.editor??null}catch{return null}}getEditorView(e){const t=this.resolveEditor(e),o=t?.cm;return o&&o.state&&"function"==typeof o.dispatch?o:null}async isPKMerAvailable(){return await this.authService.verify()&&!!this.authService.aiToken}addToHistory(e){const t=this.plugin.settings.ai.customPromptHistory||[],o=t.indexOf(e);-1!==o&&t.splice(o,1),t.unshift(e),t.length>10&&t.splice(10),this.plugin.settings.ai.customPromptHistory=t,this.plugin.saveSettings()}}let aa;const sa=["top","following","fixed","mobile"],ra=["toolbarBackgroundColor","toolbarIconColor","toolbarIconSize","aestheticStyle"];function la(e,t){e.appearanceByStyle&&"object"==typeof e.appearanceByStyle||(e.appearanceByStyle={});const o=e.appearanceByStyle;sa.forEach(e=>{o[e]&&"object"==typeof o[e]||(o[e]={})}),t&&ra.forEach(t=>{const n=e[t];void 0!==n&&sa.forEach(e=>{const i=o[e];t in i||(i[t]=n)})})}class ca extends e.Plugin{constructor(){super(...arguments),this.appearanceEditStyle=null,this.admonitionDefinitions=null,this.lastExecutedCommand=null,this.formatBrushActive=!1,this.formatBrushNotice=null,this.lastCalloutType=null,this.lastExecutedCommandName=null,this.toolbarCache=new Map,this.popoverCache=new Map,this.handleCanvasNodeContextMenu=e=>{this.addEditorContextSubmenu(e,v("AI Tools"),"sparkles",this.buildCanvasNodeAIContextActions())},this.handleEditorContextMenu=(e,t,o)=>{this.addEditorContextSubmenu(e,v("Text Tools"),"whole-word",this.buildTextContextActions(t)),this.addEditorContextSubmenu(e,v("AI Tools"),"sparkles",this.buildAIContextActions(t))},this.handleeditingToolbar=()=>{if(this.formatBrushActive||aa.body.classList.remove("format-brush-cursor"),!this.settings.cMenuVisibility)return void["top","following","fixed"].forEach(e=>{const t=re(this.app,this,e);t&&(t.style.display="none")});const t=this.app.workspace.getActiveViewOfType(e.ItemView);if(!X.isAllowedViewType(t))return void["top","following","fixed"].forEach(e=>{const t=re(this.app,this,e);t&&(t.style.visibility="hidden")});const o=t?.getViewType(),n="markdown"===o,i=n&&X.isSourceMode(t);if(n&&!i)return void["top","following","fixed"].forEach(e=>{const t=re(this.app,this,e);t&&(t.style.visibility="hidden")});const a=[{key:"top",enabled:"function"==typeof this.isTopToolbarActive?this.isTopToolbarActive():this.settings.enableTopToolbar||!this.settings.enableFollowingToolbar&&!this.settings.enableFixedToolbar&&"top"===this.positionStyle},{key:"following",enabled:"function"==typeof this.isFollowingToolbarActive?this.isFollowingToolbarActive():this.settings.enableFollowingToolbar||!this.settings.enableTopToolbar&&!this.settings.enableFixedToolbar&&"following"===this.positionStyle},{key:"fixed",enabled:this.settings.enableFixedToolbar||!this.settings.enableTopToolbar&&!this.settings.enableFollowingToolbar&&"fixed"===this.positionStyle}];for(const{key:e,enabled:t}of a){const o=re(this.app,this,e);if(!t){o&&(o.style.visibility="hidden");continue}o||Ie(this.app,this,e);const n=re(this.app,this,e);n&&(n.style.visibility="following"===e?"hidden":"visible")}},this.handleeditingToolbar_layout=()=>{this.handleeditingToolbar()},this.handleeditingToolbar_resize=()=>{if(!this.settings.cMenuVisibility||!this.isTopToolbarActive())return!1;const t=app.workspace.getActiveViewOfType(e.ItemView);if(!X.isSourceMode(t))return!1;const o=this.app.workspace.activeLeaf.view.leaf.width??0;if(o<=0||this.Leaf_Width===o)return!1;if(this.Leaf_Width=o,this.settings.cMenuWidth&&o){if(o-this.settings.cMenuWidth<78&&o>this.settings.cMenuWidth)return;setTimeout(()=>{!function(t){ie=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;const o=ie,n=o.querySelectorAll(".editingToolbarModalBar"),i=o.querySelectorAll(".editingToolbarPopoverBar");n.forEach(e=>{e.firstChild&&e.removeChild(e.firstChild),e.remove()}),i.forEach(e=>{e.firstChild&&e.removeChild(e.firstChild),e.remove()}),t&&t.clearToolbarCache()}(this),Ie(app,this)},200)}return!0},this.handleKeyboardSelection=e=>{this.commandsManager.getActiveEditor(),["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown","ShiftLeft","ShiftRight"].includes(e.code)||e.shiftKey?this.handleTextSelection():!e.shiftKey&&this.isFollowingToolbarActive()&&this.hideToolbarIfNotSelected()}}initPerStyleAppearance(){const e=this.settings;if(!e)return;const t=!e.appearanceByStyle;la(e,t);const o=e.appearanceByStyle,n=()=>{const t=this.appearanceEditStyle||this.positionStyle||e.positionStyle||"top";return sa.includes(t)?t:"top"};ra.forEach(t=>{if(!(t in e))return;const i=e[t];Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const e=n(),a=o[e];return a&&Object.prototype.hasOwnProperty.call(a,t)?a[t]:i},set(o){const i=n();la(e,!1);e.appearanceByStyle[i][t]=o}})})}removeToolbarCommandById(e,t){if(Array.isArray(e))for(let o=e.length-1;o>=0;o--){const n=e[o];n&&"object"==typeof n&&(n.id!==t?Array.isArray(n.SubmenuCommands)&&this.removeToolbarCommandById(n.SubmenuCommands,t):e.splice(o,1))}}syncAIToolbarCommandVisibility(){[this.settings.menuCommands,this.settings.followingCommands,this.settings.topCommands,this.settings.fixedCommands,this.settings.mobileCommands].forEach(e=>{Array.isArray(e)&&(this.removeToolbarCommandById(e,Q),this.settings.ai.enabled&&e.unshift({id:Q,name:"AI Tools",icon:"lucide-sparkles"}))})}refreshAIAvailability(){this.syncAIToolbarCommandVisibility(),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100)}getPluginCommandId(e){return`${this.manifest.id}:${e}`}executePluginCommand(e){this.app.commands.executeCommandById(this.getPluginCommandId(e))}openPluginSettingsTab(e=this.manifest.id){this.app.setting.open(),this.app.setting.openTabById(e)}addEditorContextAction(e,t){e.addItem(e=>{e.setTitle(t.title),t.disabled?e.setDisabled(!0):e.onClick(()=>{t.callback?t.callback():t.commandId&&this.executePluginCommand(t.commandId)})})}addEditorContextSubmenu(t,o,n,i){i.length&&t.addItem(t=>{t.setTitle(o).setIcon(n),!e.requireApiVersion("0.15.0")||t.setSection("info");const a=t.setSubmenu();i.forEach(e=>this.addEditorContextAction(a,e))})}buildTextContextActions(e){const t=[],o=e.somethingSelected(),n=e.getCursor(),i=e.getLine(n.line),a=/^\d+\.\s/.test(i),s=i.includes("|");return o&&t.push({title:v("Split Lines"),commandId:"split-lines"},{title:v("Merge Lines"),commandId:"merge-lines"},{title:v("Full Half Converter"),commandId:"smart-symbols"},{title:v("Dedupe Lines"),commandId:"dedupe-lines"},{title:v("Add Prefix/Suffix"),commandId:"add-wrap"},{title:v("Number Lines (Custom)"),commandId:"number-lines"},{title:v("Trim Line Ends"),commandId:"remove-whitespace-trim"},{title:v("Shrink Extra Spaces"),commandId:"remove-whitespace-compress"},{title:v("Remove All Whitespace"),commandId:"remove-whitespace-all"},{title:v("Extract Between Strings"),commandId:"extract-between"},{title:v("List to Table"),commandId:"list-to-table"},{title:v("Table to List"),commandId:"table-to-list"}),o||t.push({title:v("Add Prefix/Suffix"),commandId:"add-wrap"},{title:v("Insert Blank Lines"),commandId:"insert-blank-lines"},{title:v("Extract Between Strings"),commandId:"extract-between"}),a&&t.push({title:v("Renumber List"),commandId:"renumber-ordered-list"}),!o&&s&&t.push({title:v("Table to List"),commandId:"table-to-list"}),t.length||t.push({title:v("Select text to see more tools"),disabled:!0}),t}buildAIContextActions(t){if(!this.settings.ai.enabled)return[{title:v("Enable AI Editor"),callback:()=>this.openPluginSettingsTab()}];const o=t.somethingSelected(),n=e.Platform.isMobileApp,i="canvas"===this.app.workspace.activeLeaf?.view?.getViewType?.(),a=[{title:v("Trigger AI Inline Completion"),commandId:"ai-inline-completion"}],s=[{title:v("AI Custom Rewrite"),commandId:"ai-rewrite-custom"},{title:v("Improve writing"),commandId:"ai-rewrite-improve"},{title:v("Fix spelling & grammar"),commandId:"ai-rewrite-fix-grammar"},{title:v("Summarize"),commandId:"ai-rewrite-summarize"},{title:v("Explain this"),commandId:"ai-rewrite-explain"},{title:v("Continue writing"),commandId:"ai-rewrite-continue"},{title:v("Convert to list"),commandId:"ai-toolbox-list"},{title:v("Convert to table"),commandId:"ai-toolbox-table"},{title:v("Generate frontmatter"),commandId:"ai-toolbox-frontmatter"},{title:v("Convert to canvas"),commandId:"ai-toolbox-canvas"}],r=i?[{title:v("Canvas global prompt"),commandId:"ai-canvas-global-prompt"},{title:v("Expand current canvas node"),commandId:"ai-canvas-expand"}]:[];return o||n?[...a,...s,...r]:[...a,{title:v("AI Custom Rewrite"),commandId:"ai-rewrite-custom"},{title:v("Continue writing"),commandId:"ai-rewrite-continue"},{title:v("Generate frontmatter"),commandId:"ai-toolbox-frontmatter"},{title:v("Convert to canvas"),commandId:"ai-toolbox-canvas"},...r]}buildCanvasNodeAIContextActions(){if(!this.settings.ai.enabled)return[{title:v("Enable AI Editor"),callback:()=>this.openPluginSettingsTab()}];const e=this.aiManager.getCanvasExpansionPromptSuggestions().map(e=>({title:e.label,callback:()=>{this.aiManager.expandCurrentCanvasNode(e.value)}}));return[{title:v("Expand current canvas node"),commandId:"ai-canvas-expand"},...e,{title:v("Canvas global prompt"),commandId:"ai-canvas-global-prompt"}]}async onload(){const t=this.manifest.version;console.log("editingToolbar v"+t+" loaded"),aa=e.requireApiVersion("0.15.0")?activeWindow.document:window.document,await this.loadSettings(),this.aiManager=new ia(this),this.aiManager.onload(),e.requireApiVersion("0.15.0")&&"function"==typeof this.registerEditorExtension&&this.registerEditorExtension(this.aiManager.createExtension()),this.initPerStyleAppearance(),this.settingTab=new Qo(this.app,this),this.addSettingTab(this.settingTab),this.commandsManager=new mn(this),this.commandsManager.registerCommands();const o=this.commandsManager.getActiveEditor();this.app.workspace.onLayoutReady(()=>{this.statusBar=new tn(this),this.statusBar.init(),setTimeout(()=>{this.settings.cMenuVisibility||this.handleeditingToolbar()},100),setTimeout(()=>{this.aiManager.maybeShowAIOnboarding()},1200)}),this.init_evt(aa,o),e.requireApiVersion("0.15.0")&&this.app.workspace.on("window-open",e=>{this.init_evt(e.doc,o),setTimeout(()=>{if(!this.settings.cMenuVisibility)return;this.isFollowingToolbarActive()&&Ie(this.app,this,"following",e.doc);(this.settings.enableFixedToolbar||!this.settings.enableTopToolbar&&!this.settings.enableFollowingToolbar&&"fixed"===this.positionStyle)&&Ie(this.app,this,"fixed",e.doc)},50)});const n=this.settings?.lastVersion||"0.0.0",i=e=>{const t=e.split(".").map(e=>parseInt(e));return{major:t[0]||0,minor:t[1]||0,patch:t[2]||0}},a=i(n);i(t);const s=new Do(this.app,this),r="0.0.0"===n;r&&s.fixCommandIds();!r&&(a.major<3||3===a.major&&a.minor<2||3===a.major&&2===a.minor&&a.patch<2)&&(this.settings.commandIdsFixed||(await s.fixCommandIds(),this.settings.commandIdsFixed=!0,await this.saveSettings()),setTimeout(()=>{s.open()},3e3)),this.settings.lastVersion=t,await this.saveSettings();app.plugins.enabledPlugins.has("obsidian-memos")&&this.registerEvent(this.app.workspace.on("thino-editor-created",this.handleeditingToolbar)),this.registerEvent(this.app.workspace.on("active-leaf-change",this.handleeditingToolbar)),this.registerEvent(this.app.workspace.on("layout-change",this.handleeditingToolbar_layout)),this.registerEvent(this.app.workspace.on("resize",this.handleeditingToolbar_resize)),1==this.settings.cMenuVisibility&&setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100),this.registerDomEvent(aa,"contextmenu",t=>{if(this.settings.isLoadOnMobile&&e.Platform.isMobile&&this.isFollowingToolbarActive()){const{target:e}=t;if(e instanceof HTMLElement){null!==e.closest(".cm-editor")&&t.preventDefault()}}}),this.app.workspace.onLayoutReady(async()=>{await this.tryGetAdmonitionTypes()}),this.registerEvent(this.app.workspace.on("editor-menu",this.handleEditorContextMenu)),this.registerEvent(this.app.workspace.on("canvas:node-menu",this.handleCanvasNodeContextMenu)),this.registerEvent(this.app.workspace.on("url-menu",(e,t,o)=>{e.addItem(e=>e.setTitle("Edit Link(Modal)").setSection("info").setIcon("link").onClick(()=>{new sn(this).open()}))})),Object.keys(en).forEach(t=>{e.addIcon(t,en[t])}),this.toolbarIconSize=this.settings.toolbarIconSize,this.positionStyle=this.settings.positionStyle,aa.documentElement.style.setProperty("--editing-toolbar-background-color",this.settings.toolbarBackgroundColor),aa.documentElement.style.setProperty("--editing-toolbar-icon-color",this.settings.toolbarIconColor),aa.documentElement.style.setProperty("--toolbar-icon-size",`${this.settings.toolbarIconSize}px`)}async tryGetAdmonitionTypes(e=0){const t=this.app.plugins?.getPlugin("obsidian-admonition");t&&this.processAdmonitionTypes(t)}processAdmonitionTypes(e){const t=e;t.admonitions&&"object"==typeof t.admonitions&&!Array.isArray(t.admonitions)&&Object.keys(t.admonitions).length>0?(Object.keys(t.admonitions),this.admonitionDefinitions=t.admonitions):(console.warn("未能从 admonitionPlugin.admonitions (作为对象) 获取类型。"),this.admonitionDefinitions=null)}isLoadMobile(){let t=window.innerWidth>0?window.innerWidth:screen.width,o=!!this.settings?.isLoadOnMobile&&this.settings.isLoadOnMobile;return!(e.Platform.isMobileApp&&!o&&t<=768)||(console.log("editing toolbar disable loading on mobile"),!1)}onunload(){this.aiManager?.onunload(),this.app.workspace.off("active-leaf-change",this.handleeditingToolbar),this.app.workspace.off("layout-change",this.handleeditingToolbar_layout),this.app.workspace.off("resize",this.handleeditingToolbar_resize),this.formatBrushNotice&&(this.formatBrushNotice.hide(),this.formatBrushNotice=null),this.quiteAllFormatBrushes(),se(this),console.log("editingToolbar unloaded")}isView(){const t=this.app.workspace.getActiveViewOfType(e.ItemView);return X.isAllowedViewType(t)}setIS_MORE_Button(e){this.IS_MORE_Button=e}setEN_BG_Format_Brush(e){this.EN_BG_Format_Brush=e}setEN_FontColor_Format_Brush(e){this.EN_FontColor_Format_Brush=e}setEN_Text_Format_Brush(e){this.EN_Text_Format_Brush=e}setTemp_Notice(e){this.Temp_Notice=e}async loadSettings(){const e=await this.loadData(),t=e?.ai,o=!!(t?.customModel?.baseUrl?.trim?.()||t?.customModel?.model?.trim?.()||t?.customModel?.apiKey?.trim?.()),n=Array.isArray(t?.customPromptTemplates)?t.customPromptTemplates.map(e=>({...e})):L(),i=Array.isArray(t?.customPromptHistory)?[...t.customPromptHistory]:[];if(this.settings=Object.assign({},Z,e),this.settings.ai={...Z.ai,...t||{},enableCustomModel:t?.enableCustomModel??o,pkmerModelRouting:{...Z.ai.pkmerModelRouting,...t?.pkmerModelRouting||{}},pkmer:{...Z.ai.pkmer,...t?.pkmer||{}},customModel:{...Z.ai.customModel,...t?.customModel||{}},customPromptHistory:i,customPromptTemplates:n},void 0===t?.consentAccepted&&!0===t?.enabled&&(this.settings.ai.consentAccepted=!0),void 0!==t&&void 0===t?.onboardingShown&&(this.settings.ai.onboardingShown=!0),void 0===t?.pkmerModelRouting&&t?.pkmerModel?.trim?.()){const e=t.pkmerModel.trim();this.settings.ai.pkmerModelRouting={mode:"manual",completion:e,rewrite:e,reasoning:e,artifact:e}}this.syncAIToolbarCommandVisibility();if(!this.settings.enableTopToolbar&&!this.settings.enableFollowingToolbar&&!this.settings.enableFixedToolbar&&this.settings.positionStyle){switch(this.settings.positionStyle){case"top":this.settings.enableTopToolbar=!0;break;case"following":this.settings.enableFollowingToolbar=!0;break;case"fixed":this.settings.enableFixedToolbar=!0}await this.saveSettings()}}getCurrentCommands(t){if(!this.settings.enableMultipleConfig)return this.settings.menuCommands;let o=t||this.positionStyle;if(this.settings.isLoadOnMobile&&e.Platform.isMobileApp)return this.settings.mobileCommands;switch(o){case"following":return this.settings.followingCommands;case"top":return this.settings.topCommands;case"fixed":return this.settings.fixedCommands;default:return this.settings.menuCommands}}updateCurrentCommands(t,o){if(!this.settings.enableMultipleConfig)return void(this.settings.menuCommands=t);let n=o;switch(n||(n=this.settings.isLoadOnMobile&&e.Platform.isMobileApp?"mobile":this.positionStyle),n){case"following":this.settings.followingCommands=t;break;case"top":this.settings.topCommands=t;break;case"fixed":this.settings.fixedCommands=t;break;case"mobile":this.settings.mobileCommands=t;break;default:this.settings.menuCommands=t}}async saveSettings(){this.syncAIToolbarCommandVisibility(),await this.saveData(this.settings)}setLastExecutedCommand(e){this.lastExecutedCommand=e;const t=this.app.commands.commands[e];if(t&&t.name)this.lastExecutedCommandName=t.name;else{const t=e.split(":");this.lastExecutedCommandName=t[t.length-1].replace(/-/g," ")}}toggleFormatBrush(){const t=this.commandsManager.getActiveEditor();let o=!1,n="";if(t)if(t.somethingSelected()){const e=t.getSelection();if(/^\*\*.*\*\*$/.test(e))this.lastExecutedCommand="editor:toggle-bold",this.lastExecutedCommandName="Bold",o=!0;else if(/^\*.*\*$/.test(e)||/^_.*_$/.test(e))this.lastExecutedCommand="editor:toggle-italics",this.lastExecutedCommandName="Italic",o=!0;else if(/^~~.*~~$/.test(e))this.lastExecutedCommand="editor:toggle-strikethrough",this.lastExecutedCommandName="Strikethrough",o=!0;else if(/^==.*==$/.test(e))this.lastExecutedCommand="editor:toggle-highlight",this.lastExecutedCommandName="Highlight",o=!0;else if(/^`.*`$/.test(e))this.lastExecutedCommand="editor:toggle-code",this.lastExecutedCommandName="Code",o=!0;else if(/^<font color=".*">.*<\/font>$/.test(e))this.lastExecutedCommand="editing-toolbar:change-font-color",this.lastExecutedCommandName="Font Color",o=!0;else if(/^<mark style="background:.*">.*<\/mark>$/.test(e))this.lastExecutedCommand="editing-toolbar:change-background-color",this.lastExecutedCommandName="Background Color",o=!0;else if(/^<u>([^<]+)<\/u>$/.test(e))this.lastExecutedCommand="editor:toggle-underline",this.lastExecutedCommandName="Underline",o=!0;else if(/^<center>([^<]+)<\/center>$/.test(e))this.lastExecutedCommand="editing-toolbar:center",this.lastExecutedCommandName="Center",o=!0;else if(/^<p align="left">(.*?)<\/p>$/.test(e))this.lastExecutedCommand="editing-toolbar:left",this.lastExecutedCommandName="Left Align",o=!0;else if(/^<p align="right">(.*?)<\/p>$/.test(e))this.lastExecutedCommand="editing-toolbar:right",this.lastExecutedCommandName="Right Align",o=!0;else if(/^<p align="justify">(.*?)<\/p>$/.test(e))this.lastExecutedCommand="editing-toolbar:justify",this.lastExecutedCommandName="Justify",o=!0;else if(/^<sup>(.*?)<\/sup>$/.test(e))this.lastExecutedCommand="editing-toolbar:superscript",this.lastExecutedCommandName="Superscript",o=!0;else if(/^<sub>(.*?)<\/sub>$/.test(e))this.lastExecutedCommand="editing-toolbar:subscript",this.lastExecutedCommandName="Subscript",o=!0;else if(/^> \[!(note|tip|warning|danger|info|success|question|quote)\]/i.test(e)){const t=e.match(/^> \[!(note|tip|warning|danger|info|success|question|quote)\]/i);t&&(this.lastExecutedCommand="editor:insert-callout",this.lastExecutedCommandName="Callout-"+t[1].toLowerCase(),o=!0,n=t[1].toLowerCase())}else/^# /.test(e)?(this.lastExecutedCommand="editor:set-heading-1",this.lastExecutedCommandName="Heading 1",o=!0):/^## /.test(e)?(this.lastExecutedCommand="editor:set-heading-2",this.lastExecutedCommandName="Heading 2",o=!0):/^### /.test(e)?(this.lastExecutedCommand="editor:set-heading-3",this.lastExecutedCommandName="Heading 3",o=!0):/^#### /.test(e)?(this.lastExecutedCommand="editor:set-heading-4",this.lastExecutedCommandName="Heading 4",o=!0):/^##### /.test(e)?(this.lastExecutedCommand="editor:set-heading-5",this.lastExecutedCommandName="Heading 5",o=!0):/^###### /.test(e)&&(this.lastExecutedCommand="editor:set-heading-6",this.lastExecutedCommandName="Heading 6",o=!0)}else{const e=t.getCursor(),n=t.getLine(e.line),i=e.ch,a=[],s=/<u>([^<]+)<\/u>/g;let r;for(;null!==(r=s.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editing-toolbar:toggle-underline",name:"Underline",distance:Math.min(i-e,t-i)})}const l=/<center>([^<]+)<\/center>/g;for(;null!==(r=l.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editing-toolbar:center",name:"Center",distance:Math.min(i-e,t-i)})}const c=/<p align="left">([^<]+)<\/p>/g;for(;null!==(r=c.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editing-toolbar:left",name:"Left Align",distance:Math.min(i-e,t-i)})}const d=/<p align="right">([^<]+)<\/p>/g;for(;null!==(r=d.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editing-toolbar:right",name:"Right Align",distance:Math.min(i-e,t-i)})}const u=/<p align="justify">([^<]+)<\/p>/g;for(;null!==(r=u.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editing-toolbar:justify",name:"Justify",distance:Math.min(i-e,t-i)})}const m=/<sup>([^<]+)<\/sup>/g;for(;null!==(r=m.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editing-toolbar:superscript",name:"Superscript",distance:Math.min(i-e,t-i)})}const p=/<sub>([^<]+)<\/sub>/g;for(;null!==(r=p.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editing-toolbar:subscript",name:"Subscript",distance:Math.min(i-e,t-i)})}const h=/\*\*([^*]+)\*\*/g;for(;null!==(r=h.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editor:toggle-bold",name:"Bold",distance:Math.min(i-e,t-i)})}const g=/~~([^~]+)~~/g;for(;null!==(r=g.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editor:toggle-strikethrough",name:"Strikethrough",distance:Math.min(i-e,t-i)})}const f=/==([^=]+)==/g;for(;null!==(r=f.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editor:toggle-highlight",name:"Highlight",distance:Math.min(i-e,t-i)})}const b=/`([^`]+)`/g;for(;null!==(r=b.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editor:toggle-code",name:"Code",distance:Math.min(i-e,t-i)})}const y=/<font color="([^"]+)">([^<]+)<\/font>/g;for(;null!==(r=y.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editing-toolbar:change-font-color",name:"Font Color",distance:Math.min(i-e,t-i)})}const C=/<span style="background:([^"]+)">([^<]+)<\/span>/g;for(;null!==(r=C.exec(n));){const e=r.index,t=r.index+r[0].length;i>e&&i<t&&a.push({command:"editing-toolbar:change-background-color",name:"Background Color",distance:Math.min(i-e,t-i)})}if(a.length>0){a.sort((e,t)=>e.distance-t.distance);const e=a[0];this.lastExecutedCommand=e.command,this.lastExecutedCommandName=e.name,o=!0}if(!o){const e=/(\*|_)([^*_]+)(\*|_)/g;for(;null!==(r=e.exec(n));)this.lastExecutedCommand="editor:toggle-italics",this.lastExecutedCommandName="Italic",o=!0}o||(/^# /.test(n)&&i>0?(this.lastExecutedCommand="editor:set-heading-1",this.lastExecutedCommandName="Heading 1",o=!0):/^## /.test(n)&&i>1?(this.lastExecutedCommand="editor:set-heading-2",this.lastExecutedCommandName="Heading 2",o=!0):/^### /.test(n)&&i>2?(this.lastExecutedCommand="editor:set-heading-3",this.lastExecutedCommandName="Heading 3",o=!0):/^#### /.test(n)&&i>3?(this.lastExecutedCommand="editor:set-heading-4",this.lastExecutedCommandName="Heading 4",o=!0):/^##### /.test(n)&&i>4?(this.lastExecutedCommand="editor:set-heading-5",this.lastExecutedCommandName="Heading 5",o=!0):/^###### /.test(n)&&i>5&&(this.lastExecutedCommand="editor:set-heading-6",this.lastExecutedCommandName="Heading 6",o=!0))}o||this.lastExecutedCommand?(this.formatBrushActive=!this.formatBrushActive,this.formatBrushActive?(aa.body.classList.add("format-brush-cursor"),this.EN_FontColor_Format_Brush=!1,this.EN_BG_Format_Brush=!1,this.EN_Text_Format_Brush=!1,this.lastCalloutType=n,this.formatBrushNotice&&this.formatBrushNotice.hide(),this.formatBrushNotice=new e.Notice(v("Format brush ON! Select text to apply【")+this.lastExecutedCommandName+v("】format"),0)):(aa.body.classList.remove("format-brush-cursor"),this.formatBrushNotice&&(this.formatBrushNotice.hide(),this.formatBrushNotice=null))):new e.Notice(v("Please execute a format command or select format text first, then enable the format brush"))}applyCalloutFormat(e,t,o){const n=`> [!${o}]\n> ${t.replace(/^> \[!(note|tip|warning|danger|info|success|question|quote)\] ?/i,"").trim().split("\n").map((e,t)=>e.replace(/^\s*>\s*/,"")).join("\n> ")}`;e.replaceSelection(n)}applyFormatBrush(t){if(!this.lastExecutedCommand||!this.formatBrushActive)return;const o=this.app.commands.commands[this.lastExecutedCommand];o&&o.callback&&o.callback(),o&&o.editorCallback&&o.editorCallback(t,this.app.workspace.getActiveViewOfType(e.MarkdownView))}quiteAllFormatBrushes(){this.EN_FontColor_Format_Brush=!1,this.EN_BG_Format_Brush=!1,this.EN_Text_Format_Brush=!1,aa.body.classList.remove("format-brush-cursor"),this.formatBrushActive&&(this.formatBrushActive=!1,this.formatBrushNotice&&(this.formatBrushNotice.hide(),this.formatBrushNotice=null)),this.Temp_Notice&&(this.Temp_Notice.hide(),this.Temp_Notice=null)}getCommandsManager(){return this.commandsManager}reloadCustomCommands(){this.commandsManager.reloadCustomCommands()}init_evt(t,o){this.resetFormatBrushStates();const n=e.debounce(()=>{this.handleTextSelection()},100);this.registerDomEvent(t,"mousedown",e=>{if(!this.isView()||!this.commandsManager.getActiveEditor())return;const o=Date.now();1===e.button&&this.registerDomEvent(t,"mouseup",e=>{Date.now()-o<300&&1===e.button&&this.handleMiddleClickToolbar(e)}),this.resetFormatBrushIfActive(t,e)}),e.Platform.isMobileApp?this.registerDomEvent(t,"selectionchange",()=>{n()}):this.registerDomEvent(t,"mouseup",e=>{1!==e.button&&n()}),this.registerDomEvent(t,"keyup",this.handleKeyboardSelection),this.registerScrollAndBlurEvents(t)}resetFormatBrushStates(){this.EN_FontColor_Format_Brush=!1,this.EN_BG_Format_Brush=!1,this.EN_Text_Format_Brush=!1,this.formatBrushActive=!1}getCachedToolbar(e){const t=this.toolbarCache.get(e);return t&&t.isConnected?t:(t&&this.toolbarCache.delete(e),null)}setCachedToolbar(e,t){this.toolbarCache.set(e,t)}getCachedPopover(e){const t=this.popoverCache.get(e);return t&&t.isConnected?t:(t&&this.popoverCache.delete(e),null)}setCachedPopover(e,t){this.popoverCache.set(e,t)}clearToolbarCache(e){e?(this.toolbarCache.delete(e),this.popoverCache.delete(e)):(this.toolbarCache.clear(),this.popoverCache.clear())}isTopToolbarActive(){return!!this.settings.enableTopToolbar||!this.settings.enableFollowingToolbar&&!this.settings.enableFixedToolbar&&"top"===this.positionStyle}isFollowingToolbarActive(){return!!this.settings.enableFollowingToolbar||!this.settings.enableTopToolbar&&!this.settings.enableFixedToolbar&&"following"===this.positionStyle}handleMiddleClickToolbar(e){const t=this.commandsManager.getActiveEditor();this.isFollowingToolbarActive()&&t?.hasFocus()&&this.showFollowingToolbar(t)}resetFormatBrushIfActive(e,t){if(2===t.button&&this.isFormatBrushActive()){const t=o=>{o.preventDefault(),o.stopPropagation(),e.removeEventListener("contextmenu",t,{capture:!0})};e.addEventListener("contextmenu",t,{capture:!0}),Se(this)}}isFormatBrushActive(){return this.EN_FontColor_Format_Brush||this.EN_BG_Format_Brush||this.EN_Text_Format_Brush||this.formatBrushActive}getToolbarHostDocument(t){return t?.cm?.dom?.ownerDocument||t?.cm?.contentDOM?.ownerDocument||this.app.workspace.activeLeaf?.view?.containerEl?.ownerDocument||(e.requireApiVersion("0.15.0")?activeWindow.document:window.document)}registerScrollAndBlurEvents(e){const t=this.throttle(()=>{this.isFollowingToolbarActive()&&this.hideToolbarIfNotSelected(e)},200);this.registerDomEvent(e,"wheel",t),this.registerDomEvent(e,"blur",()=>{this.hideToolbarIfNotSelected(e)})}hideToolbarIfNotSelected(e){const t=re(this.app,this,"following",e||this.getToolbarHostDocument(this.commandsManager.getActiveEditor()));t&&this.isFollowingToolbarActive()&&(t.style.visibility="hidden")}handleTextSelection(){if(!this.isView())return;const e=this.commandsManager.getActiveEditor();e?.hasFocus()&&(e.somethingSelected()?this.handleSelectedText(e):this.hideToolbarIfNotSelected(this.getToolbarHostDocument(e)))}handleSelectedText(e){this.EN_FontColor_Format_Brush?l(this.settings.cMenuFontColor,e):this.EN_BG_Format_Brush?c(this.settings.cMenuBackgroundColor,e):this.EN_Text_Format_Brush?Te(0,e):this.formatBrushActive&&this.lastCalloutType?this.applyCalloutFormat(e,e.getSelection(),this.lastCalloutType):this.formatBrushActive&&this.lastExecutedCommand?this.applyFormatBrush(e):this.isFollowingToolbarActive()&&this.showFollowingToolbar(e)}throttle(e,t=100){let o;return function(...n){const i=this;o||(e.apply(i,n),o=!0,setTimeout(()=>o=!1,t))}}showFollowingToolbar(e){if(!this.isFollowingToolbarActive())return;const t=this.getToolbarHostDocument(e),o=re(this.app,this,"following",t);o?(o.style.visibility="visible",o.classList.add("editingToolbarFlex"),o.classList.remove("editingToolbarGrid"),Ee(this.app,this.toolbarIconSize,this,e,!0,t)):Ee(this.app,this.toolbarIconSize,this,e,!0,t)}onPositionStyleChange(t){const o=this.appearanceEditStyle;if(this.appearanceEditStyle=null,this.positionStyle=t,this.settings.positionStyle=t,this.settings.enableMultipleConfig)switch(t){case"following":this.settings.followingCommands&&0!==this.settings.followingCommands.length||(this.settings.followingCommands=[...this.settings.menuCommands],this.saveSettings(),new e.Notice(v("Following style commands successfully initialized")));break;case"top":this.settings.topCommands&&0!==this.settings.topCommands.length||(this.settings.topCommands=[...this.settings.menuCommands],this.saveSettings(),new e.Notice(v("Top style commands successfully initialized")));break;case"fixed":this.settings.fixedCommands&&0!==this.settings.fixedCommands.length||(this.settings.fixedCommands=[...this.settings.menuCommands],this.saveSettings(),new e.Notice(v("Fixed style commands successfully initialized")));break;case"mobile":this.settings.mobileCommands&&0!==this.settings.mobileCommands.length||(this.settings.mobileCommands=[...this.settings.menuCommands],this.saveSettings(),new e.Notice(v("Mobile style commands successfully initialized")))}this.toolbarIconSize=this.settings.toolbarIconSize;const n=aa??document;n&&n.documentElement&&(n.documentElement.style.setProperty("--editing-toolbar-background-color",this.settings.toolbarBackgroundColor),n.documentElement.style.setProperty("--editing-toolbar-icon-color",this.settings.toolbarIconColor),n.documentElement.style.setProperty("--toolbar-icon-size",`${this.settings.toolbarIconSize}px`)),dispatchEvent(new Event("editingToolbar-NewCommand")),this.appearanceEditStyle=o}}module.exports=ca;
/* nosourcemap */