12 lines
567 KiB
JavaScript
12 lines
567 KiB
JavaScript
"use strict";var e=require("obsidian"),t=require("@codemirror/language"),o=require("@codemirror/state"),i=require("@codemirror/view");const n=["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,i){let n,a={index:-1,subindex:-1},s=i;return o?s.forEach((e,o)=>{if("SubmenuCommands"in e&&(n=e.SubmenuCommands.findIndex(e=>e.id==t.id),n>=0))return a={index:o,subindex:n},a}):(n=s.findIndex(e=>e.id==t.id),a={index:n,subindex:-1}),a}function r(e,t){let o,i=t.getLine(t.getCursor().line),n="";const a=/^(\>*(\[[!\w]+\])?\s*)#+\s/;let s;const r=i.match(a);r&&(s=r[0].trim()),e==s||""==e?o=i.replace(a,"$1"):(o=i.replace(/^\s*(#*|\>|\-|\d+\.)\s*/m,""),o=e+" "+o),n=""!=o?t.getRange(t.getCursor(),{line:t.getCursor().line,ch:i.length}):t.getRange(t.getCursor(),{line:t.getCursor().line,ch:0}),t.setLine(t.getCursor().line,o),t.setCursor({line:t.getCursor().line,ch:Number(o.length-n.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 i=/<font\s+color=["']?[^"'>]+["']?>(.*?)<\/font>/gms,n=i.test(o);if(a=o,new RegExp(`^<font\\s+color=["']?${e}["']?>(.+)<\\/font>$`,"ms").test(a.trim()))return;var a;const s=o.replace(i,(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=n?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 i=/<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 n;n=i?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=i?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(n),t.setSelections(a)}function d(o,i,n){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=n.posToOffset({line:i,ch:0});let d=-1;if(l.iterate({from:0,to:c,enter:e=>{"OrderedList"===e.name&&(d=e.to)}}),d>=0){const e=n.offsetToPos(d).line+1;e<i&&!/^\s*$/.test(n.getLine(e).trim())&&(n.replaceRange("\n",{line:e,ch:0},{line:e,ch:0}),i++)}let m=!0,u=[],p=-1;for(const e of o){const t=e.trim();if(/^\d+\.\s/.test(t)){const o=e.match(/^\s*/)?.[0].length||0,i=parseInt(t.match(/^\d+/)[0],10);if(u[o]=o!==p?1:(u[o]||1)+1,i!==u[o]){m=!1;break}p=o}}let h=[];const g=i-1,f=g>=0?n.getLine(g).trim():"";if(f&&!/^\s*$/.test(f)&&!f.includes("ㅤ")&&(h.push(""),h.push("ㅤ")),m)h.push(...o);else{let e={},t=-1;for(const i of o){const o=i.trim(),n=/^\d+\.\s/.test(o),a=i.match(/^\s*/)?.[0]||"";if(n){const i=a.length;e[i]=i!==t?1:(e[i]||1)+1,h.push(`${a}${e[i]}. ${o.replace(/^\d+\.\s/,"")}`),t=i}else h.push(i),t=-1}}n.replaceRange(h.join("\n"),{line:i,ch:0},{line:i+o.length-1,ch:n.getLine(i+o.length-1).length})}function m(e,t,o){const i=[];for(let n=t;n<=o;n++)i.push(e.getLine(n));d(i,t,e)}let u;const p=t=>{u=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;["top","following","fixed"].forEach(e=>{u.querySelectorAll(`.editingToolbarModalBar[data-toolbar-style="${e}"]`).forEach(e=>{t?(e.style.display="",e.style.visibility="visible"):e.style.display="none"})});const o=u.getElementById("editingToolbarModalBar");o&&(t?(o.style.display="",o.style.visibility="visible"):o.style.display="none")},h=t=>{u=e.requireApiVersion("0.15.0")?activeWindow.document:window.document,u.documentElement.style.setProperty("--toolbar-vertical-offset",`${t.verticalPosition}px`)},g=t=>{u=e.requireApiVersion("0.15.0")?activeWindow.document:window.document,u.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.","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","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.","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","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",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 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","If nothing is selected, AI will use the current block or cursor context.":"If nothing is selected, AI will use the current block or cursor context.",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.","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.":"工具栏在Obsidian中的追加的位置,只对固定和跟随模式有效。如果你遇到工具栏显示问题,可以选择body试试。请点击下面或者状态栏菜单中的刷新按钮生效。","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.x旧版本命令id,请点击【修复命令】进行兼容","⚠️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).":"启用每个位置样式的不同命令配置(following,top,fixed)","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":"URL转Markdown链接","Convert MM/DD/YYYY to YYYY-MM-DD":"将MM/DD/YYYY日期格式转换为YYYY-MM-DD","Add bold to keywords":"添加粗体到关键词","Format phone number":"格式化电话号码","Remove extra spaces":"删除多余空格","Convert HTML bold tags to Markdown format":"将HTML粗体标签转换为Markdown格式","Convert quoted text to quote block":"将引用的文本转换为引用块","Convert CSV to Markdown table row":"将CSV转换为Markdown表格行","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":"我需要将URL转换为Markdown格式链接","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)":"使用js正则表达式实现,并输出以下格式的参数(结果不需要用json转义)","[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":"设置工具栏图标大小(px)默认18px","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 关闭。","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 自定义改写",Send:"发送","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 获取更多额度后重试。","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:"指令","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 建议",Replace:"替换","Insert below":"插入到下方","Try again":"重试",Discard:"丢弃","AI List":"AI 列表","AI Table":"AI 表格","AI Base":"AI Base","AI Canvas":"AI Canvas","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":"插入到光标处","If nothing is selected, AI will use the current block or cursor context.":"如果未选中文本,AI 会自动使用当前段落或光标上下文。",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 无效。","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 w(e){return"string"!=typeof e||0===e.length?"":C&&C[e]||f[e]||e}class v extends e.FuzzySuggestModal{constructor(e,t,o=!1,i,n){super(e.app),this.customCallback=null,this.plugin=e,this.command=t,this.issub=o,this.customCallback=i||null,this.setPlaceholder(w("Choose an icon")),this.currentEditingConfig=n||""}capitalJoin(e){return e.split(" ").map(e=>e[0].toUpperCase()+e.substring(1)).join(" ")}getItems(){return n}getItemText(e){return this.capitalJoin(e.replace("feather-","").replace("remix-","").replace("bx-","").replace(/([A-Z])/g," $1").trim().replace(/-/gi," "))}renderSuggestion(t,o){const i=createSpan({cls:"editingToolbarIconPick"});o.appendChild(i),e.setIcon(i,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,i,n,a){super(e),this.customCallback=null,this.plugin=t,this.item=o,this.issub=i,this.customCallback=n||null,this.currentEditingConfig=a||"",this.containerEl.addClass("editingToolbar-Modal"),this.containerEl.addClass("customicon")}onOpen(){const{contentEl:e}=this;e.createEl("b",{text:w("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),i=s(this.plugin,this.item,this.issub,o);if(this.issub){let t=i.subindex;-1===t?this.plugin.settings.menuCommands[i.index].SubmenuCommands.push(this.item):this.plugin.settings.menuCommands[i.index].SubmenuCommands[t].icon=e}else{let e=i.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(w("Choose a command")),this.currentEditingConfig=t||""}getItems(){return app.commands.listCommands()}getItemText(e){return w(e.name)}async onChooseItem(t){const o=this.plugin.getCurrentCommands(this.currentEditingConfig);o.findIndex(e=>e.id==t.id)>-1?new e.Notice(w("The command")+w(t.name)+w("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 v(this.plugin,t,!1,null,this.currentEditingConfig).open()}}class T extends e.Modal{constructor(e,t,o,i,n){super(t.app),this.plugin=t,this.item=o,this.issub=i,this.currentEditingConfig=n||"",this.containerEl.addClass("editingToolbar-Modal"),this.containerEl.addClass("changename")}onOpen(){const{contentEl:t}=this;t.createEl("b",{text:w("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 i=o.subindex;-1===i?t[o.index].SubmenuCommands.push(this.item):t[o.index].SubmenuCommands[i].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 S 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:w("Drag the slider to move the position")});const o=t.createDiv({cls:"slider-container"}),i=o.createDiv({cls:"vertical-slider-container"});i.createEl("p",{text:w("Vertical Position")});const n=o.createDiv({cls:"horizontal-slider-container"});n.createEl("p",{text:w("Horizontal Position")});const a=o.createDiv({cls:"columns-slider-container"});a.createEl("p",{text:w("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),m=-Math.floor(r/2),u=new e.SliderComponent(i).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(n).setLimits(m,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:w("Reset"),cls:"reset-button"}).addEventListener("click",()=>{this.needSave=!0,u.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()}}const E=[{value:"04-fast",label:"04-fast"},{value:"03-agent",label:"03-agent"}],I={mode:"smart",completion:"04-fast",rewrite:"04-fast",reasoning:"03-agent",artifact:"03-agent"};function A(e,t){const o=e.pkmerModelRouting??I;if("smart"===o.mode)return I[t];const i=o[t]?.trim();return i||I[t]}const M=[{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"}],P="editing-toolbar-pkmer-access-token",D="editing-toolbar-pkmer-refresh-token",O="editing-toolbar-pkmer-ai-token",F="editing-toolbar-custom-model-api-key",q="https://api.pkmer.cn/api/v1/oauth/authorize",L="https://api.pkmer.cn/api/v1/oauth/token",N="https://api.pkmer.cn/api/v1/oauth/userinfo",R="pkmer_dd2a562c8653ca0112a050150d974ccd",B="openid profile email ai:token",_="http://localhost:10891/editing-toolbar/callback",$="obsidian://editing-toolbar-pkmer-auth",z=10891,U=["body","workspace"],V=["default","tiny","glass","custom"],H=["following","top","fixed"],W={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:{enabled:!1,consentAccepted:!1,onboardingShown:!1,providerMode:"pkmer-first",enableInlineCompletion:!0,completionTrigger:"manual",completionDelay:500,enableRewrite:!0,showRewriteToolbarOnSelection:!1,rewriteMinSelectionLength:1,pkmerApiBaseUrl:"https://newapi.pkmer.cn",pkmerModel:"04-fast",pkmerModelRouting:I,pkmer:{tokenExpiresAt:0,userInfo:null},enableCustomModel:!1,customModel:{apiFormat:"openai-compatible",baseUrl:"",apiKey:"",model:"",temperature:.2}}};class j{static isAllowedViewType(e,t){if(!e)return!1;const o=e.getViewType(),i=window.app?.plugins?.plugins?.["editing-toolbar"];if(i?.settings?.viewTypeSettings&&void 0!==i.settings.viewTypeSettings[o])return i.settings.viewTypeSettings[o];return(t||["markdown","canvas","thino_view","meld-encrypted-view"]).includes(o)}static isSourceMode(e){return!!e&&"source"===e.getMode?.()}}const K="editing-toolbar:ai-tools";const Y=[{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"}],G=["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"),Z=["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"),J=["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 X;const Q={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 ee(t){X=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}(),i=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()})};i(X),o&&o.forEach(e=>{e?.containerEl&&i(e.containerEl)}),t&&t.clearToolbarCache()}function te(t,o,i,n){const a=n||t.workspace.activeLeaf?.view?.containerEl?.ownerDocument||(e.requireApiVersion("0.15.0")?activeWindow.document:window.document);X=a;const s=i||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 oe=(e,t)=>t.reduce((e,t)=>e&&"undefined"!==e[t]?e[t]:void 0,e);function ie(e,t){return e&&void 0!==e[1][0]?t+e.flat(2).join("+").replace("Mod","Ctrl")+t:t+"–"+t}function ne(e,t,o=!0){let i=e.commands.findCommand(t),n=o?"*":"";if(i){let t=i.hotkeys?[[oe(i.hotkeys,[0,"modifiers"])],[oe(i.hotkeys,[0,"key"])]]:void 0,o=e.hotkeyManager.customKeys[i.id];var a=o?[[oe(o,[0,"modifiers"])],[oe(o,[0,"key"])]]:void 0;return a?ie(a,n):ie(t,"")}return"–"}function ae(e){return/<[^>]+>/g.test(e)}function se(t,o){return o?ae(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 re(e,t,o,i){const n=i.commandsManager.getActiveEditor(),a=n&&n.somethingSelected();0==t.cMenuVisibility?e.style.visibility="hidden":"following"===o?a||(e.style.visibility="hidden"):e.style.visibility="visible"}const le={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"},ce={"editing-toolbar:ai-inline-completion":"AI Complete","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"};function de(e,t){e.lastExecutedCommand=t,e.lastExecutedCommandName=w(ce[t]?ce[t]:"AI")}function me(e){const t=e.lastExecutedCommand;return t&&ce[t]?w(ce[t]):t?.startsWith("editing-toolbar:ai")&&e.lastExecutedCommandName?e.lastExecutedCommandName:w("AI")}function ue(t,o,i,n,a){if(i<=100)return!1;return t+o+6*Math.max(1,Math.round(t/Math.max(n,1)))+(n+12)+("following"===a?n+10:0)+(e.Platform.isMobileApp||"mobile"===a?14:0)>=Math.max(i-16,2*n)}function pe(t,o,i){X=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;const n=o.commandsManager.getActiveEditor();let a=te(t,o),s=a?.querySelector("#"+i);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=he(e),"x-color-picker-table"==i){o.settings.cMenuFontColor=e,l(e,n),X.querySelectorAll("#change-font-color-icon").forEach(t=>{t.style.fill=e})}else if("x-backgroundcolor-picker-table"==i){o.settings.cMenuBackgroundColor=e,c(e,n),X.querySelectorAll("#change-background-color-icon").forEach(t=>{t.style.fill=e})}o.saveSettings()}}}}}const he=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 i=Number(e[t]).toString(16);"0"===i&&(i+=i),1==i.length&&(i="0"+i),o+=i}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 ge(t,o,i){const n=t.workspace.getActiveViewOfType(e.ItemView);if(!j.isAllowedViewType(n))return;if(!o.IS_MORE_Button)return;const a=i.getAttribute("data-toolbar-style"),s=a?i.ownerDocument?.querySelector(`.editingToolbarPopoverBar[data-toolbar-style="${a}"]`):n.containerEl.querySelector("#editingToolbarPopoverBar");if(!s)return void o.setIS_MORE_Button(!1);let r=i.createEl("span");r.addClass("more-menu");let l=new e.ButtonComponent(r);return l.setClass("editingToolbarCommandItem").setTooltip(w("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 i=t.ownerDocument.defaultView??window,n=e.getBoundingClientRect(),a=Math.max(t.offsetWidth,t.scrollWidth),s=Math.max(t.offsetHeight,t.scrollHeight),r=Math.max(12,i.innerWidth-a-12);let l=n.right-a;a<=0&&(l=n.left),l=Math.min(Math.max(l,12),r);let c=n.bottom+8;s>0&&c+s>i.innerHeight-12&&(c=Math.max(12,n.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 fe(e){e.quiteAllFormatBrushes()}function be(e,t){let o=t.getSelection();if(!o||""===o.trim())return;if(o.match(/^>\s*\[\![\w\s]*\]/m)){let e=o.split("\n"),i=[],n=!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(n){let e=o.match(/^(>+)\s*/);if(e&&e[1].length>=a){let e=o.replace(new RegExp(`^>{${a}}\\s*`),"");i.push(e)}else n=!1,i.push(o)}else i.push(o);else a=r[1].length,s=!0,r[3].trim()&&i.push(r[3].trim()),n=!0}return void t.replaceSelection(i.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 ye(t,o,i,n,a=!1,s){const r=s||n?.cm?.dom?.ownerDocument||n?.cm?.contentDOM?.ownerDocument||t.workspace.activeLeaf?.view?.containerEl?.ownerDocument||(e.requireApiVersion("0.15.0")?activeWindow.document:window.document);let l=te(t,i,"following",r);const c=t.workspace.getActiveViewOfType(e.ItemView);if(!j.isAllowedViewType(c))return void(l&&(l.style.visibility="hidden"));if(!(i.settings.enableFollowingToolbar||!i.settings.enableTopToolbar&&!i.settings.enableFixedToolbar&&"following"===i.positionStyle))return;l||(Ce(t,i,"following",r),l=te(t,i,"following",r));const d=c?.getViewType(),m="markdown"===d;let u=30;if(u="tiny"===i.settings.aestheticStyle?30:o+14,m)if(j.isSourceMode(c)){if(l){const e=a||n.somethingSelected();l.style.visibility=e?"visible":"hidden","visible"===l.style.visibility&&(l.style.height=u+"px",l.addClass("editingToolbarFlex"),l.removeClass("editingToolbarGrid"),function(e,t){const o=t.containerEl.getBoundingClientRect(),i=e.offsetWidth,n=e.offsetHeight,a=12,s=e.ownerDocument.defaultView?.innerWidth??window.innerWidth,r=t.getCursor("from");t.getCursor("to");const l=t.coordsAtPos(r),c=X.getElementsByClassName("mod-left-split")[0]?.clientWidth??0,d=X.getElementsByClassName("side-dock-ribbon mod-left")[0]?.clientWidth??0,m=c+d;let u=l.left-m-28;u+i>s-m&&(u=s-m-i-a);u=Math.max(0,u);let p=function(e,t,o,i){const n=e.getCursor("from"),a=e.getCursor("to"),s=e.coordsAtPos(a),r=n.line===a.line;let l=t.top-i-10;if(r)l<=o.top&&(l=s.bottom+10);else{if(e.getCursor("head").ch==e.getCursor("from").ch)l=t.top-i-10,l<=o.top&&(l=o.top+2*i);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 i=e.posToOffset(o);t=e.cm.coordsAtPos?.(i)??e.coordsAtPos(i)}}return t})(e);l=t.bottom+10,l>=o.bottom-i&&(l=o.bottom-2*i)}}return l}(t,l,o,n);p=Math.max(0,p),e.style.left=`${u}px`,e.style.top=`${p}px`}(l,n))}}else l&&(l.style.visibility="hidden");else l&&(l.style.visibility="visible",l.style.height=u+"px",l.addClass("editingToolbarFlex"),l.removeClass("editingToolbarGrid"))}function Ce(t,o,i,n){const a=o.settings,s=n||t.workspace.activeLeaf?.view?.containerEl?.ownerDocument||(e.requireApiVersion("0.15.0")?activeWindow.document:window.document);if(X=s,!i){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=>{Ce(t,o,e,s)})}const r=i;if(!a.cMenuVisibility){const e=te(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",m="custom"===d?l.toolbarBackgroundColor??a.toolbarBackgroundColor:void 0,u="custom"===d?l.toolbarIconColor??a.toolbarIconColor:void 0,p={default:"editingToolbarDefaultAesthetic",tiny:"editingToolbarTinyAesthetic",glass:"editingToolbarGlassAesthetic",custom:"editingToolbarCustomAesthetic"};!function(){function i(e,t){Object.values(p).forEach(t=>{e.removeClass(t)});const o=p[t]||p.default;e.addClass(o)}const n=()=>{let n=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",i(h,d),i(g,d),m&&(h.style.setProperty("--editing-toolbar-background-color",m),g.style.setProperty("--editing-toolbar-background-color",m)),u&&(h.style.setProperty("--editing-toolbar-icon-color",u),g.style.setProperty("--editing-toolbar-icon-color",u)),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 i=t.workspace.activeLeaf.view.getViewType(),n=Q[i];if(n&&(o=e?.querySelector(n)),!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"===i?e?.querySelector(".view-content"):null;"canvas"===i&&a?(a.insertAdjacentElement("beforebegin",h),e?.querySelector("#editingToolbarPopoverBar")||a.insertAdjacentElement("beforebegin",g)):(e?.querySelector("#editingToolbarPopoverBar")||("excalidraw"==i?o.insertAdjacentElement("afterend",g):o.insertAdjacentElement("afterbegin",g)),"excalidraw"==i?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=>w(e),v=(e,t)=>{const o=C(e);return"–"===t?o:`${o}(${t})`};y.forEach((i,s)=>{let c;if("SubmenuCommands"in i){let d;ue(n,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"),ae(i.icon)?d.buttonEl.innerHTML=i.icon:d.setIcon(i.icon),n+=p+2;if("dropdown"===(i.menuType||"submenu")){d.setClass("editingToolbarDropdownButton");let n=ne(t,i.id);c=v(i.name,n),d.setTooltip(c),d.onClick(n=>{const s=new e.Menu;i.SubmenuCommands.forEach(e=>{"editingToolbar-Divider-Line"===e.id?(s.addSeparator(),s.addItem(t=>{t.setTitle(w(e.name)).setDisabled(!0),se(t,"")})):s.addItem(i=>{const n=ne(t,e.id,!1),s=w(e.name),l="–"!==n?`${s}`:s;if(i.setTitle(l).onClick(()=>{t.commands.executeCommandById(e.id);const i=o.commandsManager.getActiveEditor(),n=i&&i.somethingSelected();0==a.cMenuVisibility?h.style.visibility="hidden":"following"===r?n||(h.style.visibility="hidden"):h.style.visibility="visible"}),se(i,e.icon),"—"!==n){i.dom.createSpan({cls:"menu-item-hotkey"}).setText(n)}})}),s.dom.addClass("editing-toolbar-dropdown-menu"),s.showAtMouseEvent(n)})}else{let n=function(e){let t=createEl("div");return t.addClass(e),t}("subitem");n&&i.SubmenuCommands.forEach(i=>{let l=ne(t,i.id);c=v(i.name,l);let m=new e.ButtonComponent(n).setTooltip(c).setClass("menu-item").onClick(()=>{t.commands.executeCommandById(i.id);const e=o.commandsManager.getActiveEditor(),n=e&&e.somethingSelected();0==a.cMenuVisibility?h.style.visibility="hidden":"following"===r?n||(h.style.visibility="hidden"):h.style.visibility="visible"});s<a.cMenuNumRows&&"top"!==r&&m.buttonEl.setAttribute("aria-label-position","top"),"editingToolbar-Divider-Line"==i.id&&(m.setClass("editingToolbar-Divider-Line"),m.buttonEl.setAttribute("aria-label",C(i.name))),ae(i.icon)?m.buttonEl.innerHTML=i.icon:m.setIcon(i.icon),d.buttonEl.insertAdjacentElement("afterbegin",n)})}}else if(i.id==K){const c=function(e,t,o){if("fixed"===t)return o+6;const i=me(e),n=Math.min(Math.max(6.2*i.length,12),32);return Math.max(o+n+18,57)}(o,r,p),d=ue(n,c,l,p,r);d&&o.setIS_MORE_Button(!0);const m=b(d);let u=new e.ButtonComponent(m);u.setClass("editingToolbarCommandsubItem"+s).setClass("editingToolbarDropdownButton").setClass("editingToolbarCommandsubItem-ai").setTooltip(w("AI Tools")),s>=a.cMenuNumRows?u.setClass("editingToolbarSecond"):"top"!==r&&u.buttonEl.setAttribute("aria-label-position","top"),ae(i.icon)?u.buttonEl.innerHTML=i.icon:u.setIcon(i.icon);const g="fixed"===r;u.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=me(o),e.appendChild(f),u.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),u.buttonEl.appendChild(y),n+=c;const C=async i=>{v=Date.now()+240;const n="unavailable"!==await o.aiManager.getToolbarRouteState(),s=o.commandsManager.getActiveEditor(),l=ne(t,"editing-toolbar:ai-inline-completion",!1),c=l.includes("+")?l:"",d=new e.Menu,m=()=>{d.hide()},u=t=>{const i=async()=>{if(!n)return void new e.Notice(await o.aiManager.getProviderRouteStatusText());!1!==await t.action()&&(m(),t.commandIdForLabel&&(de(o,t.commandIdForLabel),f&&(f.textContent=me(o))),re(h,a,r,o))};d.addItem(e=>{if(e.setTitle(w(t.title)).setIcon(t.icon).onClick(i),t.hotkey){e.dom.createSpan({cls:"menu-item-hotkey"}).setText(t.hotkey)}})},p=(t,i,s)=>{d.addItem(l=>{l.setTitle(w(t)).setIcon(i);const c=l.setSubmenu();s.forEach(t=>{c.addItem(i=>{if(i.setTitle(w(t.title)).setIcon(t.icon).onClick(async()=>{if(!n)return void new e.Notice(await o.aiManager.getProviderRouteStatusText());!1!==await t.action()&&(m(),t.commandIdForLabel&&(de(o,t.commandIdForLabel),f&&(f.textContent=me(o))),re(h,a,r,o))}),t.hotkey){i.dom.createSpan({cls:"menu-item-hotkey"}).setText(t.hotkey)}})})})};u({title:"Trigger AI Inline Completion",icon:"lucide-sparkles",hotkey:c||void 0,commandIdForLabel:"editing-toolbar:ai-inline-completion",action:()=>o.aiManager.triggerInlineCompletion(s)});const g=new Map;M.forEach(e=>{const t=g.get(e.group)??[];t.push(e),g.set(e.group,t)});const b={Edit:"lucide-wand-sparkles",Tone:"lucide-messages-square",Translate:"lucide-languages",Generate:"lucide-bot"};g.forEach((e,t)=>{p(t,b[t]??"lucide-sparkles",e.map(e=>({title:e.label,icon:le[e.instruction],commandIdForLabel:`editing-toolbar:ai-tools:${e.instruction}`,action:async()=>{await o.aiManager.startRewrite(s,e.instruction)}})))}),u({title:"AI Custom Rewrite",icon:le.custom,commandIdForLabel:"editing-toolbar:ai-tools:custom",action:()=>o.aiManager.openCustomRewrite(s)}),p("AI Toolbox","lucide-boxes",Y.map(e=>({title:e.label,icon:e.icon,commandIdForLabel:`editing-toolbar:ai-toolbox:${e.id}`,action:async()=>o.aiManager.runToolboxAction(s,e.id)}))),d.dom.addClass("editing-toolbar-dropdown-menu"),d.dom.addClass("editing-toolbar-ai-dropdown-menu"),d.showAtMouseEvent(i)};let v=0;y.addEventListener("click",async e=>{e.preventDefault(),e.stopPropagation(),await C(e)}),u.buttonEl.addEventListener("click",async t=>{if(t.preventDefault(),t.stopPropagation(),Date.now()<v)return;const i=t.target;if(i?.closest(".editing-toolbar-ai-button-arrow"))return void await C(t);if(e.Platform.isMobileApp||"mobile"===r)return void await C(t);const n=o.commandsManager.getActiveEditor(),s=ce[o.lastExecutedCommand||""]?o.lastExecutedCommand:"editing-toolbar:ai-inline-completion",l=await async function(t,o,i){if("unavailable"===await t.aiManager.getToolbarRouteState())return new e.Notice(await t.aiManager.getProviderRouteStatusText()),!1;if("editing-toolbar:ai-inline-completion"===o)return t.aiManager.triggerInlineCompletion(i);if("editing-toolbar:ai-tools:custom"===o||"editing-toolbar:ai-rewrite-custom"===o)return t.aiManager.openCustomRewrite(i);if(o.startsWith("editing-toolbar:ai-toolbox:"))return t.aiManager.runToolboxAction(i,o.replace("editing-toolbar:ai-toolbox:",""));const n=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 n?t.aiManager.startRewrite(i,n):t.aiManager.triggerInlineCompletion(i)}(o,s,n);!1!==l&&f&&(f.textContent=me(o)),re(h,a,r,o)})}else if("editing-toolbar:change-font-color"==i.id){let s=new e.ButtonComponent(h);s.setClass("editingToolbarCommandsubItem-font-color").setTooltip(w("Font Colors")).onClick(()=>{t.commands.executeCommandById(i.id);const e=o.commandsManager.getActiveEditor(),n=e&&e.somethingSelected();0==a.cMenuVisibility?h.style.visibility="hidden":"following"===r?n||(h.style.visibility="hidden"):h.style.visibility="visible"}),ae(i.icon)?s.buttonEl.innerHTML=i.icon:s.setIcon(i.icon),n+=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),pe(t,o,"x-color-picker-table");let i=l.querySelector(".x-color-picker-wrapper");new e.ButtonComponent(i).setIcon("paintbrush").setTooltip(w("Format Brush")).onClick(()=>{fe(o),o.setEN_FontColor_Format_Brush(!0),o.Temp_Notice=new e.Notice(w("Font-Color formatting brush ON!"),0)}),new e.ButtonComponent(i).setIcon("palette").setTooltip(w("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[1];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"==i.id){let s=new e.ButtonComponent(h);s.setClass("editingToolbarCommandsubItem-font-color").setTooltip(w("Background Color")).onClick(()=>{t.commands.executeCommandById(i.id);const e=o.commandsManager.getActiveEditor(),n=e&&e.somethingSelected();0==a.cMenuVisibility?h.style.visibility="hidden":"following"===r?n||(h.style.visibility="hidden"):h.style.visibility="visible"}),ae(i.icon)?s.buttonEl.innerHTML=i.icon:s.setIcon(i.icon),n+=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),pe(t,o,"x-backgroundcolor-picker-table");let i=l.querySelector(".x-color-picker-wrapper");new e.ButtonComponent(i).setIcon("paintbrush").setTooltip(w("Format Brush")).onClick(()=>{fe(o),o.setEN_BG_Format_Brush(!0),o.Temp_Notice=new e.Notice(w("Font-Color formatting brush ON!"),0)}),new e.ButtonComponent(i).setIcon("palette").setTooltip(w("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[1];o?.click(),setTimeout(()=>{let e=t.setting.activeTab.containerEl.querySelector(".custom_bg");e&&e.addClass?.("toolbar-cta")},100)}},200)})}}else{let d;ue(n,p,l,p,r)?(o.setIS_MORE_Button(!0),d=new e.ButtonComponent(b(!0))):d=new e.ButtonComponent(h);let m=ne(t,i.id);c=v(i.name,m),d.setTooltip(c).onClick(()=>{t.commands.executeCommandById(i.id);const e=o.commandsManager.getActiveEditor(),n=e&&e.somethingSelected();0==a.cMenuVisibility?h.style.visibility="hidden":"following"===r?n||(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"==i.id&&d.setClass("editingToolbar-Divider-Line"),ae(i.icon)?d.buttonEl.innerHTML=i.icon:d.setIcon(i.icon),n+=p}}),ge(t,o,h),Math.abs(o.settings.cMenuWidth-Number(n))>n+4&&(o.settings.cMenuWidth=Number(n),setTimeout(()=>{o.saveSettings()},100))};if(!o.isLoadMobile())return;const l=t.workspace.getActiveViewOfType(e.ItemView);if(j.isAllowedViewType(l)){const i=te(t,o,r,s);if(i&&"top"!==r)return a.cMenuVisibility?"following"===r?(i.style.visibility="hidden",i.style.display=""):(i.style.visibility="visible",i.style.display=""):i.style.display="none",m&&i.style.setProperty("--editing-toolbar-background-color",m),u&&i.style.setProperty("--editing-toolbar-icon-color",u),void(c&&i.style.setProperty("--toolbar-icon-size",`${c}px`));if(n(),"top"!==r){const e=te(t,o,r,s);e&&o.setCachedToolbar(r,e)}g(o.settings),h(o.settings),function(t,o){X=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;const i=X.querySelectorAll("#change-font-color-icon"),n=X.querySelectorAll("#change-background-color-icon");i.length>0&&i.forEach(e=>{e.style.fill=t});n.length>0&&n.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 we(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 i=o.call(e,t||"default");if("object"!=typeof i)return i;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 ve(){return ve=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var i in o)({}).hasOwnProperty.call(o,i)&&(e[i]=o[i])}return e},ve.apply(null,arguments)}function xe(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),o.push.apply(o,i)}return o}function ke(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{};t%2?xe(Object(o),!0).forEach(function(t){we(e,t,o[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):xe(Object(o)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(o,t))})}return e}function Te(e){return Te="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},Te(e)}function Se(e){if("undefined"!=typeof window&&window.navigator)return!!navigator.userAgent.match(e)}var Ee=Se(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),Ie=Se(/Edge/i),Ae=Se(/firefox/i),Me=Se(/safari/i)&&!Se(/chrome/i)&&!Se(/android/i),Pe=Se(/iP(ad|od|hone)/i),De=Se(/chrome/i)&&Se(/android/i),Oe={capture:!1,passive:!1};function Fe(e,t,o){e.addEventListener(t,o,!Ee&&Oe)}function qe(e,t,o){e.removeEventListener(t,o,!Ee&&Oe)}function Le(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 Ne(e){return e.host&&e!==document&&e.host.nodeType&&e.host!==e?e.host:e.parentNode}function Re(e,t,o,i){if(e){o=o||document;do{if(null!=t&&(">"===t[0]?e.parentNode===o&&Le(e,t):Le(e,t))||i&&e===o)return e;if(e===o)break}while(e=Ne(e))}return null}var Be,_e=/\s+/g;function $e(e,t,o){if(e&&t)if(e.classList)e.classList[o?"add":"remove"](t);else{var i=(" "+e.className+" ").replace(_e," ").replace(" "+t+" "," ");e.className=(i+(o?" "+t:"")).replace(_e," ")}}function ze(e,t,o){var i=e&&e.style;if(i){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 i||-1!==t.indexOf("webkit")||(t="-webkit-"+t),i[t]=o+("string"==typeof o?"":"px")}}function Ue(e,t){var o="";if("string"==typeof e)o=e;else do{var i=ze(e,"transform");i&&"none"!==i&&(o=i+" "+o)}while(!t&&(e=e.parentNode));var n=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return n&&new n(o)}function Ve(e,t,o){if(e){var i=e.getElementsByTagName(t),n=0,a=i.length;if(o)for(;n<a;n++)o(i[n],n);return i}return[]}function He(){var e=document.scrollingElement;return e||document.documentElement}function We(e,t,o,i,n){if(e.getBoundingClientRect||e===window){var a,s,r,l,c,d,m;if(e!==window&&e.parentNode&&e!==He()?(s=(a=e.getBoundingClientRect()).top,r=a.left,l=a.bottom,c=a.right,d=a.height,m=a.width):(s=0,r=0,l=window.innerHeight,c=window.innerWidth,d=window.innerHeight,m=window.innerWidth),(t||o)&&e!==window&&(n=n||e.parentNode,!Ee))do{if(n&&n.getBoundingClientRect&&("none"!==ze(n,"transform")||o&&"static"!==ze(n,"position"))){var u=n.getBoundingClientRect();s-=u.top+parseInt(ze(n,"border-top-width")),r-=u.left+parseInt(ze(n,"border-left-width")),l=s+a.height,c=r+a.width;break}}while(n=n.parentNode);if(i&&e!==window){var p=Ue(n||e),h=p&&p.a,g=p&&p.d;p&&(l=(s/=g)+(d/=g),c=(r/=h)+(m/=h))}return{top:s,left:r,bottom:l,right:c,width:m,height:d}}}function je(e,t,o){for(var i=Je(e,!0),n=We(e)[t];i;){var a=We(i)[o];if(!("top"===o||"left"===o?n>=a:n<=a))return i;if(i===He())break;i=Je(i,!1)}return!1}function Ke(e,t,o,i){for(var n=0,a=0,s=e.children;a<s.length;){if("none"!==s[a].style.display&&s[a]!==to.ghost&&(i||s[a]!==to.dragged)&&Re(s[a],o.draggable,e,!1)){if(n===t)return s[a];n++}a++}return null}function Ye(e,t){for(var o=e.lastElementChild;o&&(o===to.ghost||"none"===ze(o,"display")||t&&!Le(o,t));)o=o.previousElementSibling;return o||null}function Ge(e,t){var o=0;if(!e||!e.parentNode)return-1;for(;e=e.previousElementSibling;)"TEMPLATE"===e.nodeName.toUpperCase()||e===to.clone||t&&!Le(e,t)||o++;return o}function Ze(e){var t=0,o=0,i=He();if(e)do{var n=Ue(e),a=n.a,s=n.d;t+=e.scrollLeft*a,o+=e.scrollTop*s}while(e!==i&&(e=e.parentNode));return[t,o]}function Je(e,t){if(!e||!e.getBoundingClientRect)return He();var o=e,i=!1;do{if(o.clientWidth<o.scrollWidth||o.clientHeight<o.scrollHeight){var n=ze(o);if(o.clientWidth<o.scrollWidth&&("auto"==n.overflowX||"scroll"==n.overflowX)||o.clientHeight<o.scrollHeight&&("auto"==n.overflowY||"scroll"==n.overflowY)){if(!o.getBoundingClientRect||o===document.body)return He();if(i||t)return o;i=!0}}}while(o=o.parentNode);return He()}function Xe(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 Qe(e,t){return function(){if(!Be){var o=arguments;1===o.length?e.call(this,o[0]):e.apply(this,o),Be=setTimeout(function(){Be=void 0},t)}}}function et(e,t,o){e.scrollLeft+=t,e.scrollTop+=o}function tt(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 ot(e,t,o){var i={};return Array.from(e.children).forEach(function(n){var a,s,r,l;if(Re(n,t.draggable,e,!1)&&!n.animated&&n!==o){var c=We(n);i.left=Math.min(null!==(a=i.left)&&void 0!==a?a:1/0,c.left),i.top=Math.min(null!==(s=i.top)&&void 0!==s?s:1/0,c.top),i.right=Math.max(null!==(r=i.right)&&void 0!==r?r:-1/0,c.right),i.bottom=Math.max(null!==(l=i.bottom)&&void 0!==l?l:-1/0,c.bottom)}}),i.width=i.right-i.left,i.height=i.bottom-i.top,i.x=i.left,i.y=i.top,i}var it="Sortable"+(new Date).getTime();function nt(){var e,t=[];return{captureAnimationState:function(){(t=[],this.options.animation)&&[].slice.call(this.el.children).forEach(function(e){if("none"!==ze(e,"display")&&e!==to.ghost){t.push({target:e,rect:We(e)});var o=ke({},t[t.length-1].rect);if(e.thisAnimationDuration){var i=Ue(e,!0);i&&(o.top-=i.f,o.left-=i.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 i in t)if(t.hasOwnProperty(i)&&t[i]===e[o][i])return Number(o);return-1}(t,{target:e}),1)},animateAll:function(o){var i=this;if(!this.options.animation)return clearTimeout(e),void("function"==typeof o&&o());var n=!1,a=0;t.forEach(function(e){var t=0,o=e.target,s=o.fromRect,r=We(o),l=o.prevFromRect,c=o.prevToRect,d=e.rect,m=Ue(o,!0);m&&(r.top-=m.f,r.left-=m.e),o.toRect=r,o.thisAnimationDuration&&Xe(l,r)&&!Xe(s,r)&&(d.top-r.top)/(d.left-r.left)===(s.top-r.top)/(s.left-r.left)&&(t=function(e,t,o,i){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))*i.animation}(d,l,c,i.options)),Xe(r,s)||(o.prevFromRect=s,o.prevToRect=r,t||(t=i.options.animation),i.animate(o,d,r,t)),t&&(n=!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),n?e=setTimeout(function(){"function"==typeof o&&o()},a):"function"==typeof o&&o(),t=[]},animate:function(e,t,o,i){if(i){ze(e,"transition",""),ze(e,"transform","");var n=Ue(this.el),a=n&&n.a,s=n&&n.d,r=(t.left-o.left)/(a||1),l=(t.top-o.top)/(s||1);e.animatingX=!!r,e.animatingY=!!l,ze(e,"transform","translate3d("+r+"px,"+l+"px,0)"),this.forRepaintDummy=function(e){return e.offsetWidth}(e),ze(e,"transition","transform "+i+"ms"+(this.options.easing?" "+this.options.easing:"")),ze(e,"transform","translate3d(0,0,0)"),"number"==typeof e.animated&&clearTimeout(e.animated),e.animated=setTimeout(function(){ze(e,"transition",""),ze(e,"transform",""),e.animated=!1,e.animatingX=!1,e.animatingY=!1},i)}}}}var at=[],st={initializeByDefault:!0},rt={mount:function(e){for(var t in st)st.hasOwnProperty(t)&&!(t in e)&&(e[t]=st[t]);at.forEach(function(t){if(t.pluginName===e.pluginName)throw"Sortable: Cannot mount plugin ".concat(e.pluginName," more than once")}),at.push(e)},pluginEvent:function(e,t,o){var i=this;this.eventCanceled=!1,o.cancel=function(){i.eventCanceled=!0};var n=e+"Global";at.forEach(function(i){t[i.pluginName]&&(t[i.pluginName][n]&&t[i.pluginName][n](ke({sortable:t},o)),t.options[i.pluginName]&&t[i.pluginName][e]&&t[i.pluginName][e](ke({sortable:t},o)))})},initializePlugins:function(e,t,o,i){for(var n in at.forEach(function(i){var n=i.pluginName;if(e.options[n]||i.initializeByDefault){var a=new i(e,t,e.options);a.sortable=e,a.options=e.options,e[n]=a,ve(o,a.defaults)}}),e.options)if(e.options.hasOwnProperty(n)){var a=this.modifyOption(e,n,e.options[n]);void 0!==a&&(e.options[n]=a)}},getEventProperties:function(e,t){var o={};return at.forEach(function(i){"function"==typeof i.eventProperties&&ve(o,i.eventProperties.call(t[i.pluginName],e))}),o},modifyOption:function(e,t,o){var i;return at.forEach(function(n){e[n.pluginName]&&n.optionListeners&&"function"==typeof n.optionListeners[t]&&(i=n.optionListeners[t].call(e[n.pluginName],o))}),i}};var lt=["evt"],ct=function(e,t){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=o.evt,n=function(e,t){if(null==e)return{};var o,i,n=function(e,t){if(null==e)return{};var o={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;o[i]=e[i]}return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)o=a[i],-1===t.indexOf(o)&&{}.propertyIsEnumerable.call(e,o)&&(n[o]=e[o])}return n}(o,lt);rt.pluginEvent.bind(to)(e,t,ke({dragEl:mt,parentEl:ut,ghostEl:pt,rootEl:ht,nextEl:gt,lastDownEl:ft,cloneEl:bt,cloneHidden:yt,dragStarted:Dt,putSortable:Tt,activeSortable:to.active,originalEvent:i,oldIndex:Ct,oldDraggableIndex:vt,newIndex:wt,newDraggableIndex:xt,hideGhostForTarget:Jt,unhideGhostForTarget:Xt,cloneNowHidden:function(){yt=!0},cloneNowShown:function(){yt=!1},dispatchSortableEvent:function(e){dt({sortable:t,name:e,originalEvent:i})}},n))};function dt(e){!function(e){var t=e.sortable,o=e.rootEl,i=e.name,n=e.targetEl,a=e.cloneEl,s=e.toEl,r=e.fromEl,l=e.oldIndex,c=e.newIndex,d=e.oldDraggableIndex,m=e.newDraggableIndex,u=e.originalEvent,p=e.putSortable,h=e.extraEventProperties;if(t=t||o&&o[it]){var g,f=t.options,b="on"+i.charAt(0).toUpperCase()+i.substr(1);!window.CustomEvent||Ee||Ie?(g=document.createEvent("Event")).initEvent(i,!0,!0):g=new CustomEvent(i,{bubbles:!0,cancelable:!0}),g.to=s||o,g.from=r||o,g.item=n||o,g.clone=a,g.oldIndex=l,g.newIndex=c,g.oldDraggableIndex=d,g.newDraggableIndex=m,g.originalEvent=u,g.pullMode=p?p.lastPutMode:void 0;var y=ke(ke({},h),rt.getEventProperties(i,t));for(var C in y)g[C]=y[C];o&&o.dispatchEvent(g),f[b]&&f[b].call(t,g)}}(ke({putSortable:Tt,cloneEl:bt,targetEl:mt,rootEl:ht,oldIndex:Ct,oldDraggableIndex:vt,newIndex:wt,newDraggableIndex:xt},e))}var mt,ut,pt,ht,gt,ft,bt,yt,Ct,wt,vt,xt,kt,Tt,St,Et,It,At,Mt,Pt,Dt,Ot,Ft,qt,Lt,Nt=!1,Rt=!1,Bt=[],_t=!1,$t=!1,zt=[],Ut=!1,Vt=[],Ht="undefined"!=typeof document,Wt=Pe,jt=Ie||Ee?"cssFloat":"float",Kt=Ht&&!De&&!Pe&&"draggable"in document.createElement("div"),Yt=function(){if(Ht){if(Ee)return!1;var e=document.createElement("x");return e.style.cssText="pointer-events:auto","auto"===e.style.pointerEvents}}(),Gt=function(e,t){var o=ze(e),i=parseInt(o.width)-parseInt(o.paddingLeft)-parseInt(o.paddingRight)-parseInt(o.borderLeftWidth)-parseInt(o.borderRightWidth),n=Ke(e,0,t),a=Ke(e,1,t),s=n&&ze(n),r=a&&ze(a),l=s&&parseInt(s.marginLeft)+parseInt(s.marginRight)+We(n).width,c=r&&parseInt(r.marginLeft)+parseInt(r.marginRight)+We(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(n&&s.float&&"none"!==s.float){var d="left"===s.float?"left":"right";return!a||"both"!==r.clear&&r.clear!==d?"horizontal":"vertical"}return n&&("block"===s.display||"flex"===s.display||"table"===s.display||"grid"===s.display||l>=i&&"none"===o[jt]||a&&"none"===o[jt]&&l+c>i)?"vertical":"horizontal"},Zt=function(e){function t(e,o){return function(i,n,a,s){var r=i.options.group.name&&n.options.group.name&&i.options.group.name===n.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(i,n,a,s),o)(i,n,a,s);var l=(o?i:n).options.group.name;return!0===e||"string"==typeof e&&e===l||e.join&&e.indexOf(l)>-1}}var o={},i=e.group;i&&"object"==Te(i)||(i={name:i}),o.name=i.name,o.checkPull=t(i.pull,!0),o.checkPut=t(i.put),o.revertClone=i.revertClone,e.group=o},Jt=function(){!Yt&&pt&&ze(pt,"display","none")},Xt=function(){!Yt&&pt&&ze(pt,"display","")};Ht&&!De&&document.addEventListener("click",function(e){if(Rt)return e.preventDefault(),e.stopPropagation&&e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),Rt=!1,!1},!0);var Qt=function(e){if(mt){e=e.touches?e.touches[0]:e;var t=(n=e.clientX,a=e.clientY,Bt.some(function(e){var t=e[it].options.emptyInsertThreshold;if(t&&!Ye(e)){var o=We(e),i=n>=o.left-t&&n<=o.right+t,r=a>=o.top-t&&a<=o.bottom+t;return i&&r?s=e:void 0}}),s);if(t){var o={};for(var i in e)e.hasOwnProperty(i)&&(o[i]=e[i]);o.target=o.rootEl=t,o.preventDefault=void 0,o.stopPropagation=void 0,t[it]._onDragOver(o)}}var n,a,s},eo=function(e){mt&&mt.parentNode[it]._isOutsideThisEl(e.target)};function to(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=ve({},t),e[it]=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 Gt(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!==to.supportPointer&&"PointerEvent"in window&&(!Me||Pe),emptyInsertThreshold:5};for(var i in rt.initializePlugins(this,e,o),o)!(i in t)&&(t[i]=o[i]);for(var n in Zt(t),this)"_"===n.charAt(0)&&"function"==typeof this[n]&&(this[n]=this[n].bind(this));this.nativeDraggable=!t.forceFallback&&Kt,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?Fe(e,"pointerdown",this._onTapStart):(Fe(e,"mousedown",this._onTapStart),Fe(e,"touchstart",this._onTapStart)),this.nativeDraggable&&(Fe(e,"dragover",this),Fe(e,"dragenter",this)),Bt.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),ve(this,nt())}function oo(e,t,o,i,n,a,s,r){var l,c,d=e[it],m=d.options.onMove;return!window.CustomEvent||Ee||Ie?(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=i,l.related=n||t,l.relatedRect=a||We(t),l.willInsertAfter=r,l.originalEvent=s,e.dispatchEvent(l),m&&(c=m.call(d,l,s)),c}function io(e){e.draggable=!1}function no(){Ut=!1}function ao(e){for(var t=e.tagName+e.className+e.src+e.href+e.textContent,o=t.length,i=0;o--;)i+=t.charCodeAt(o);return i.toString(36)}function so(e){return setTimeout(e,0)}function ro(e){return clearTimeout(e)}to.prototype={constructor:to,_isOutsideThisEl:function(e){this.el.contains(e)||e===this.el||(Ot=null)},_getDirection:function(e,t){return"function"==typeof this.options.direction?this.options.direction.call(this,e,t,mt):this.options.direction},_onTapStart:function(e){if(e.cancelable){var t=this,o=this.el,i=this.options,n=i.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=i.filter;if(function(e){Vt.length=0;var t=e.getElementsByTagName("input"),o=t.length;for(;o--;){var i=t[o];i.checked&&Vt.push(i)}}(o),!mt&&!(/mousedown|pointerdown/.test(a)&&0!==e.button||i.disabled)&&!l.isContentEditable&&(this.nativeDraggable||!Me||!r||"SELECT"!==r.tagName.toUpperCase())&&!((r=Re(r,i.draggable,o,!1))&&r.animated||ft===r)){if(Ct=Ge(r),vt=Ge(r,i.draggable),"function"==typeof c){if(c.call(this,e,r,this))return dt({sortable:t,rootEl:l,name:"filter",targetEl:r,toEl:o,fromEl:o}),ct("filter",t,{evt:e}),void(n&&e.preventDefault())}else if(c&&(c=c.split(",").some(function(i){if(i=Re(l,i.trim(),o,!1))return dt({sortable:t,rootEl:i,name:"filter",targetEl:r,fromEl:o,toEl:o}),ct("filter",t,{evt:e}),!0})))return void(n&&e.preventDefault());i.handle&&!Re(l,i.handle,o,!1)||this._prepareDragStart(e,s,r)}}},_prepareDragStart:function(e,t,o){var i,n=this,a=n.el,s=n.options,r=a.ownerDocument;if(o&&!mt&&o.parentNode===a){var l=We(o);if(ht=a,ut=(mt=o).parentNode,gt=mt.nextSibling,ft=o,kt=s.group,to.dragged=mt,St={target:mt,clientX:(t||e).clientX,clientY:(t||e).clientY},Mt=St.clientX-l.left,Pt=St.clientY-l.top,this._lastX=(t||e).clientX,this._lastY=(t||e).clientY,mt.style["will-change"]="all",i=function(){ct("delayEnded",n,{evt:e}),to.eventCanceled?n._onDrop():(n._disableDelayedDragEvents(),!Ae&&n.nativeDraggable&&(mt.draggable=!0),n._triggerDragStart(e,t),dt({sortable:n,name:"choose",originalEvent:e}),$e(mt,s.chosenClass,!0))},s.ignore.split(",").forEach(function(e){Ve(mt,e.trim(),io)}),Fe(r,"dragover",Qt),Fe(r,"mousemove",Qt),Fe(r,"touchmove",Qt),s.supportPointer?(Fe(r,"pointerup",n._onDrop),!this.nativeDraggable&&Fe(r,"pointercancel",n._onDrop)):(Fe(r,"mouseup",n._onDrop),Fe(r,"touchend",n._onDrop),Fe(r,"touchcancel",n._onDrop)),Ae&&this.nativeDraggable&&(this.options.touchStartThreshold=4,mt.draggable=!0),ct("delayStart",this,{evt:e}),!s.delay||s.delayOnTouchOnly&&!t||this.nativeDraggable&&(Ie||Ee))i();else{if(to.eventCanceled)return void this._onDrop();s.supportPointer?(Fe(r,"pointerup",n._disableDelayedDrag),Fe(r,"pointercancel",n._disableDelayedDrag)):(Fe(r,"mouseup",n._disableDelayedDrag),Fe(r,"touchend",n._disableDelayedDrag),Fe(r,"touchcancel",n._disableDelayedDrag)),Fe(r,"mousemove",n._delayedDragTouchMoveHandler),Fe(r,"touchmove",n._delayedDragTouchMoveHandler),s.supportPointer&&Fe(r,"pointermove",n._delayedDragTouchMoveHandler),n._dragStartTimer=setTimeout(i,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(){mt&&io(mt),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var e=this.el.ownerDocument;qe(e,"mouseup",this._disableDelayedDrag),qe(e,"touchend",this._disableDelayedDrag),qe(e,"touchcancel",this._disableDelayedDrag),qe(e,"pointerup",this._disableDelayedDrag),qe(e,"pointercancel",this._disableDelayedDrag),qe(e,"mousemove",this._delayedDragTouchMoveHandler),qe(e,"touchmove",this._delayedDragTouchMoveHandler),qe(e,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(e,t){t=t||"touch"==e.pointerType&&e,!this.nativeDraggable||t?this.options.supportPointer?Fe(document,"pointermove",this._onTouchMove):Fe(document,t?"touchmove":"mousemove",this._onTouchMove):(Fe(mt,"dragend",this),Fe(ht,"dragstart",this._onDragStart));try{document.selection?so(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch(e){}},_dragStarted:function(e,t){if(Nt=!1,ht&&mt){ct("dragStarted",this,{evt:t}),this.nativeDraggable&&Fe(document,"dragover",eo);var o=this.options;!e&&$e(mt,o.dragClass,!1),$e(mt,o.ghostClass,!0),to.active=this,e&&this._appendGhost(),dt({sortable:this,name:"start",originalEvent:t})}else this._nulling()},_emulateDragOver:function(){if(Et){this._lastX=Et.clientX,this._lastY=Et.clientY,Jt();for(var e=document.elementFromPoint(Et.clientX,Et.clientY),t=e;e&&e.shadowRoot&&(e=e.shadowRoot.elementFromPoint(Et.clientX,Et.clientY))!==t;)t=e;if(mt.parentNode[it]._isOutsideThisEl(e),t)do{if(t[it]){if(t[it]._onDragOver({clientX:Et.clientX,clientY:Et.clientY,target:e,rootEl:t})&&!this.options.dragoverBubble)break}e=t}while(t=Ne(t));Xt()}},_onTouchMove:function(e){if(St){var t=this.options,o=t.fallbackTolerance,i=t.fallbackOffset,n=e.touches?e.touches[0]:e,a=pt&&Ue(pt,!0),s=pt&&a&&a.a,r=pt&&a&&a.d,l=Wt&&Lt&&Ze(Lt),c=(n.clientX-St.clientX+i.x)/(s||1)+(l?l[0]-zt[0]:0)/(s||1),d=(n.clientY-St.clientY+i.y)/(r||1)+(l?l[1]-zt[1]:0)/(r||1);if(!to.active&&!Nt){if(o&&Math.max(Math.abs(n.clientX-this._lastX),Math.abs(n.clientY-this._lastY))<o)return;this._onDragStart(e,!0)}if(pt){a?(a.e+=c-(It||0),a.f+=d-(At||0)):a={a:1,b:0,c:0,d:1,e:c,f:d};var m="matrix(".concat(a.a,",").concat(a.b,",").concat(a.c,",").concat(a.d,",").concat(a.e,",").concat(a.f,")");ze(pt,"webkitTransform",m),ze(pt,"mozTransform",m),ze(pt,"msTransform",m),ze(pt,"transform",m),It=c,At=d,Et=n}e.cancelable&&e.preventDefault()}},_appendGhost:function(){if(!pt){var e=this.options.fallbackOnBody?document.body:ht,t=We(mt,!0,Wt,!0,e),o=this.options;if(Wt){for(Lt=e;"static"===ze(Lt,"position")&&"none"===ze(Lt,"transform")&&Lt!==document;)Lt=Lt.parentNode;Lt!==document.body&&Lt!==document.documentElement?(Lt===document&&(Lt=He()),t.top+=Lt.scrollTop,t.left+=Lt.scrollLeft):Lt=He(),zt=Ze(Lt)}$e(pt=mt.cloneNode(!0),o.ghostClass,!1),$e(pt,o.fallbackClass,!0),$e(pt,o.dragClass,!0),ze(pt,"transition",""),ze(pt,"transform",""),ze(pt,"box-sizing","border-box"),ze(pt,"margin",0),ze(pt,"top",t.top),ze(pt,"left",t.left),ze(pt,"width",t.width),ze(pt,"height",t.height),ze(pt,"opacity","0.8"),ze(pt,"position",Wt?"absolute":"fixed"),ze(pt,"zIndex","100000"),ze(pt,"pointerEvents","none"),to.ghost=pt,e.appendChild(pt),ze(pt,"transform-origin",Mt/parseInt(pt.style.width)*100+"% "+Pt/parseInt(pt.style.height)*100+"%")}},_onDragStart:function(e,t){var o=this,i=e.dataTransfer,n=o.options;ct("dragStart",this,{evt:e}),to.eventCanceled?this._onDrop():(ct("setupClone",this),to.eventCanceled||((bt=tt(mt)).removeAttribute("id"),bt.draggable=!1,bt.style["will-change"]="",this._hideClone(),$e(bt,this.options.chosenClass,!1),to.clone=bt),o.cloneId=so(function(){ct("clone",o),to.eventCanceled||(o.options.removeCloneOnHide||ht.insertBefore(bt,mt),o._hideClone(),dt({sortable:o,name:"clone"}))}),!t&&$e(mt,n.dragClass,!0),t?(Rt=!0,o._loopId=setInterval(o._emulateDragOver,50)):(qe(document,"mouseup",o._onDrop),qe(document,"touchend",o._onDrop),qe(document,"touchcancel",o._onDrop),i&&(i.effectAllowed="move",n.setData&&n.setData.call(o,i,mt)),Fe(document,"drop",o),ze(mt,"transform","translateZ(0)")),Nt=!0,o._dragStartId=so(o._dragStarted.bind(o,t,e)),Fe(document,"selectstart",o),Dt=!0,window.getSelection().removeAllRanges(),Me&&ze(document.body,"user-select","none"))},_onDragOver:function(e){var t,o,i,n,a=this.el,s=e.target,r=this.options,l=r.group,c=to.active,d=kt===l,m=r.sort,u=Tt||c,p=this,h=!1;if(!Ut){if(void 0!==e.preventDefault&&e.cancelable&&e.preventDefault(),s=Re(s,r.draggable,a,!0),M("dragOver"),to.eventCanceled)return h;if(mt.contains(e.target)||s.animated&&s.animatingX&&s.animatingY||p._ignoreWhileAnimating===s)return D(!1);if(Rt=!1,c&&!r.disabled&&(d?m||(i=ut!==ht):Tt===this||(this.lastPutMode=kt.checkPull(this,c,mt,e))&&l.checkPut(this,c,mt,e))){if(n="vertical"===this._getDirection(e,s),t=We(mt),M("dragOverValid"),to.eventCanceled)return h;if(i)return ut=ht,P(),this._hideClone(),M("revert"),to.eventCanceled||(gt?ht.insertBefore(mt,gt):ht.appendChild(mt)),D(!0);var g=Ye(a,r.draggable);if(!g||function(e,t,o){var i=We(Ye(o.el,o.options.draggable)),n=ot(o.el,o.options,pt),a=10;return t?e.clientX>n.right+a||e.clientY>i.bottom&&e.clientX>i.left:e.clientY>n.bottom+a||e.clientX>i.right&&e.clientY>i.top}(e,n,this)&&!g.animated){if(g===mt)return D(!1);if(g&&a===e.target&&(s=g),s&&(o=We(s)),!1!==oo(ht,a,mt,t,s,o,e,!!s))return P(),g&&g.nextSibling?a.insertBefore(mt,g.nextSibling):a.appendChild(mt),ut=a,O(),D(!0)}else if(g&&function(e,t,o){var i=We(Ke(o.el,0,o.options,!0)),n=ot(o.el,o.options,pt),a=10;return t?e.clientX<n.left-a||e.clientY<i.top&&e.clientX<i.right:e.clientY<n.top-a||e.clientY<i.bottom&&e.clientX<i.left}(e,n,this)){var f=Ke(a,0,r,!0);if(f===mt)return D(!1);if(o=We(s=f),!1!==oo(ht,a,mt,t,s,o,e,!1))return P(),a.insertBefore(mt,f),ut=a,O(),D(!0)}else if(s.parentNode===a){o=We(s);var b,y,C,w=mt.parentNode!==a,v=!function(e,t,o){var i=o?e.left:e.top,n=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 i===s||n===r||i+a/2===s+l/2}(mt.animated&&mt.toRect||t,s.animated&&s.toRect||o,n),x=n?"top":"left",k=je(s,"top","top")||je(mt,"top","top"),T=k?k.scrollTop:void 0;if(Ot!==s&&(y=o[x],_t=!1,$t=!v&&r.invertSwap||w),b=function(e,t,o,i,n,a,s,r){var l=i?e.clientY:e.clientX,c=i?o.height:o.width,d=i?o.top:o.left,m=i?o.bottom:o.right,u=!1;if(!s)if(r&&qt<c*n){if(!_t&&(1===Ft?l>d+c*a/2:l<m-c*a/2)&&(_t=!0),_t)u=!0;else if(1===Ft?l<d+qt:l>m-qt)return-Ft}else if(l>d+c*(1-n)/2&&l<m-c*(1-n)/2)return function(e){return Ge(mt)<Ge(e)?1:-1}(t);if((u=u||s)&&(l<d+c*a/2||l>m-c*a/2))return l>d+c/2?1:-1;return 0}(e,s,o,n,v?1:r.swapThreshold,null==r.invertedSwapThreshold?r.swapThreshold:r.invertedSwapThreshold,$t,Ot===s),0!==b){var S=Ge(mt);do{S-=b,C=ut.children[S]}while(C&&("none"===ze(C,"display")||C===pt))}if(0===b||C===s)return D(!1);Ot=s,Ft=b;var E=s.nextElementSibling,I=!1,A=oo(ht,a,mt,t,s,o,e,I=1===b);if(!1!==A)return 1!==A&&-1!==A||(I=1===A),Ut=!0,setTimeout(no,30),P(),I&&!E?a.appendChild(mt):s.parentNode.insertBefore(mt,I?E:s),k&&et(k,0,T-k.scrollTop),ut=mt.parentNode,void 0===y||$t||(qt=Math.abs(y-We(s)[x])),O(),D(!0)}if(a.contains(mt))return D(!1)}return!1}function M(r,l){ct(r,p,ke({evt:e,isOwner:d,axis:n?"vertical":"horizontal",revert:i,dragRect:t,targetRect:o,canSort:m,fromSortable:u,target:s,completed:D,onMove:function(o,i){return oo(ht,a,mt,t,o,We(o),e,i)},changed:O},l))}function P(){M("dragOverAnimationCapture"),p.captureAnimationState(),p!==u&&u.captureAnimationState()}function D(t){return M("dragOverCompleted",{insertion:t}),t&&(d?c._hideClone():c._showClone(p),p!==u&&($e(mt,Tt?Tt.options.ghostClass:c.options.ghostClass,!1),$e(mt,r.ghostClass,!0)),Tt!==p&&p!==to.active?Tt=p:p===to.active&&Tt&&(Tt=null),u===p&&(p._ignoreWhileAnimating=s),p.animateAll(function(){M("dragOverAnimationComplete"),p._ignoreWhileAnimating=null}),p!==u&&(u.animateAll(),u._ignoreWhileAnimating=null)),(s===mt&&!mt.animated||s===a&&!s.animated)&&(Ot=null),r.dragoverBubble||e.rootEl||s===document||(mt.parentNode[it]._isOutsideThisEl(e.target),!t&&Qt(e)),!r.dragoverBubble&&e.stopPropagation&&e.stopPropagation(),h=!0}function O(){wt=Ge(mt),xt=Ge(mt,r.draggable),dt({sortable:p,name:"change",toEl:a,newIndex:wt,newDraggableIndex:xt,originalEvent:e})}},_ignoreWhileAnimating:null,_offMoveEvents:function(){qe(document,"mousemove",this._onTouchMove),qe(document,"touchmove",this._onTouchMove),qe(document,"pointermove",this._onTouchMove),qe(document,"dragover",Qt),qe(document,"mousemove",Qt),qe(document,"touchmove",Qt)},_offUpEvents:function(){var e=this.el.ownerDocument;qe(e,"mouseup",this._onDrop),qe(e,"touchend",this._onDrop),qe(e,"pointerup",this._onDrop),qe(e,"pointercancel",this._onDrop),qe(e,"touchcancel",this._onDrop),qe(document,"selectstart",this)},_onDrop:function(e){var t=this.el,o=this.options;wt=Ge(mt),xt=Ge(mt,o.draggable),ct("drop",this,{evt:e}),ut=mt&&mt.parentNode,wt=Ge(mt),xt=Ge(mt,o.draggable),to.eventCanceled||(Nt=!1,$t=!1,_t=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),ro(this.cloneId),ro(this._dragStartId),this.nativeDraggable&&(qe(document,"drop",this),qe(t,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),Me&&ze(document.body,"user-select",""),ze(mt,"transform",""),e&&(Dt&&(e.cancelable&&e.preventDefault(),!o.dropBubble&&e.stopPropagation()),pt&&pt.parentNode&&pt.parentNode.removeChild(pt),(ht===ut||Tt&&"clone"!==Tt.lastPutMode)&&bt&&bt.parentNode&&bt.parentNode.removeChild(bt),mt&&(this.nativeDraggable&&qe(mt,"dragend",this),io(mt),mt.style["will-change"]="",Dt&&!Nt&&$e(mt,Tt?Tt.options.ghostClass:this.options.ghostClass,!1),$e(mt,this.options.chosenClass,!1),dt({sortable:this,name:"unchoose",toEl:ut,newIndex:null,newDraggableIndex:null,originalEvent:e}),ht!==ut?(wt>=0&&(dt({rootEl:ut,name:"add",toEl:ut,fromEl:ht,originalEvent:e}),dt({sortable:this,name:"remove",toEl:ut,originalEvent:e}),dt({rootEl:ut,name:"sort",toEl:ut,fromEl:ht,originalEvent:e}),dt({sortable:this,name:"sort",toEl:ut,originalEvent:e})),Tt&&Tt.save()):wt!==Ct&&wt>=0&&(dt({sortable:this,name:"update",toEl:ut,originalEvent:e}),dt({sortable:this,name:"sort",toEl:ut,originalEvent:e})),to.active&&(null!=wt&&-1!==wt||(wt=Ct,xt=vt),dt({sortable:this,name:"end",toEl:ut,originalEvent:e}),this.save())))),this._nulling()},_nulling:function(){ct("nulling",this),ht=mt=ut=pt=gt=bt=ft=yt=St=Et=Dt=wt=xt=Ct=vt=Ot=Ft=Tt=kt=to.dragged=to.ghost=to.clone=to.active=null;var e=this.el;Vt.forEach(function(t){e.contains(t)&&(t.checked=!0)}),Vt.length=It=At=0},handleEvent:function(e){switch(e.type){case"drop":case"dragend":this._onDrop(e);break;case"dragenter":case"dragover":mt&&(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,i=0,n=o.length,a=this.options;i<n;i++)Re(e=o[i],a.draggable,this.el,!1)&&t.push(e.getAttribute(a.dataIdAttr)||ao(e));return t},sort:function(e,t){var o={},i=this.el;this.toArray().forEach(function(e,t){var n=i.children[t];Re(n,this.options.draggable,i,!1)&&(o[e]=n)},this),t&&this.captureAnimationState(),e.forEach(function(e){o[e]&&(i.removeChild(o[e]),i.appendChild(o[e]))}),t&&this.animateAll()},save:function(){var e=this.options.store;e&&e.set&&e.set(this)},closest:function(e,t){return Re(e,t||this.options.draggable,this.el,!1)},option:function(e,t){var o=this.options;if(void 0===t)return o[e];var i=rt.modifyOption(this,e,t);o[e]=void 0!==i?i:t,"group"===e&&Zt(o)},destroy:function(){ct("destroy",this);var e=this.el;e[it]=null,qe(e,"mousedown",this._onTapStart),qe(e,"touchstart",this._onTapStart),qe(e,"pointerdown",this._onTapStart),this.nativeDraggable&&(qe(e,"dragover",this),qe(e,"dragenter",this)),Array.prototype.forEach.call(e.querySelectorAll("[draggable]"),function(e){e.removeAttribute("draggable")}),this._onDrop(),this._disableDelayedDragEvents(),Bt.splice(Bt.indexOf(this.el),1),this.el=e=null},_hideClone:function(){if(!yt){if(ct("hideClone",this),to.eventCanceled)return;ze(bt,"display","none"),this.options.removeCloneOnHide&&bt.parentNode&&bt.parentNode.removeChild(bt),yt=!0}},_showClone:function(e){if("clone"===e.lastPutMode){if(yt){if(ct("showClone",this),to.eventCanceled)return;mt.parentNode!=ht||this.options.group.revertClone?gt?ht.insertBefore(bt,gt):ht.appendChild(bt):ht.insertBefore(bt,mt),this.options.group.revertClone&&this.animate(mt,bt),ze(bt,"display",""),yt=!1}}else this._hideClone()}},Ht&&Fe(document,"touchmove",function(e){(to.active||Nt)&&e.cancelable&&e.preventDefault()}),to.utils={on:Fe,off:qe,css:ze,find:Ve,is:function(e,t){return!!Re(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:Qe,closest:Re,toggleClass:$e,clone:tt,index:Ge,nextTick:so,cancelNextTick:ro,detectDirection:Gt,getChild:Ke,expando:it},to.get=function(e){return e[it]},to.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&&(to.utils=ke(ke({},to.utils),e.utils)),rt.mount(e)})},to.create=function(e,t){return new to(e,t)},to.version="1.15.7";var lo,co,mo,uo,po,ho,go=[],fo=!1;function bo(){go.forEach(function(e){clearInterval(e.pid)}),go=[]}function yo(){clearInterval(ho)}var Co=Qe(function(e,t,o,i){if(t.scroll){var n,a=(e.touches?e.touches[0]:e).clientX,s=(e.touches?e.touches[0]:e).clientY,r=t.scrollSensitivity,l=t.scrollSpeed,c=He(),d=!1;co!==o&&(co=o,bo(),lo=t.scroll,n=t.scrollFn,!0===lo&&(lo=Je(o,!0)));var m=0,u=lo;do{var p=u,h=We(p),g=h.top,f=h.bottom,b=h.left,y=h.right,C=h.width,w=h.height,v=void 0,x=void 0,k=p.scrollWidth,T=p.scrollHeight,S=ze(p),E=p.scrollLeft,I=p.scrollTop;p===c?(v=C<k&&("auto"===S.overflowX||"scroll"===S.overflowX||"visible"===S.overflowX),x=w<T&&("auto"===S.overflowY||"scroll"===S.overflowY||"visible"===S.overflowY)):(v=C<k&&("auto"===S.overflowX||"scroll"===S.overflowX),x=w<T&&("auto"===S.overflowY||"scroll"===S.overflowY));var A=v&&(Math.abs(y-a)<=r&&E+C<k)-(Math.abs(b-a)<=r&&!!E),M=x&&(Math.abs(f-s)<=r&&I+w<T)-(Math.abs(g-s)<=r&&!!I);if(!go[m])for(var P=0;P<=m;P++)go[P]||(go[P]={});go[m].vx==A&&go[m].vy==M&&go[m].el===p||(go[m].el=p,go[m].vx=A,go[m].vy=M,clearInterval(go[m].pid),0==A&&0==M||(d=!0,go[m].pid=setInterval(function(){i&&0===this.layer&&to.active._onTouchMove(po);var t=go[this.layer].vy?go[this.layer].vy*l:0,o=go[this.layer].vx?go[this.layer].vx*l:0;"function"==typeof n&&"continue"!==n.call(to.dragged.parentNode[it],o,t,e,po,go[this.layer].el)||et(go[this.layer].el,o,t)}.bind({layer:m}),24))),m++}while(t.bubbleScroll&&u!==c&&(u=Je(u,!1)));fo=d}},30),wo=function(e){var t=e.originalEvent,o=e.putSortable,i=e.dragEl,n=e.activeSortable,a=e.dispatchSortableEvent,s=e.hideGhostForTarget,r=e.unhideGhostForTarget;if(t){var l=o||n;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:i,putSortable:o}))}};function vo(){}function xo(){}vo.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 i=Ke(this.sortable.el,this.startIndex,this.options);i?this.sortable.el.insertBefore(t,i):this.sortable.el.appendChild(t),this.sortable.animateAll(),o&&o.animateAll()},drop:wo},ve(vo,{pluginName:"revertOnSpill"}),xo.prototype={onSpill:function(e){var t=e.dragEl,o=e.putSortable||this.sortable;o.captureAnimationState(),t.parentNode&&t.parentNode.removeChild(t),o.animateAll()},drop:wo},ve(xo,{pluginName:"removeOnSpill"}),to.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?Fe(document,"dragover",this._handleAutoScroll):this.options.supportPointer?Fe(document,"pointermove",this._handleFallbackAutoScroll):t.touches?Fe(document,"touchmove",this._handleFallbackAutoScroll):Fe(document,"mousemove",this._handleFallbackAutoScroll)},dragOverCompleted:function(e){var t=e.originalEvent;this.options.dragOverBubble||t.rootEl||this._handleAutoScroll(t)},drop:function(){this.sortable.nativeDraggable?qe(document,"dragover",this._handleAutoScroll):(qe(document,"pointermove",this._handleFallbackAutoScroll),qe(document,"touchmove",this._handleFallbackAutoScroll),qe(document,"mousemove",this._handleFallbackAutoScroll)),yo(),bo(),clearTimeout(Be),Be=void 0},nulling:function(){po=co=lo=fo=ho=mo=uo=null,go.length=0},_handleFallbackAutoScroll:function(e){this._handleAutoScroll(e,!0)},_handleAutoScroll:function(e,t){var o=this,i=(e.touches?e.touches[0]:e).clientX,n=(e.touches?e.touches[0]:e).clientY,a=document.elementFromPoint(i,n);if(po=e,t||this.options.forceAutoScrollFallback||Ie||Ee||Me){Co(e,this.options,a,t);var s=Je(a,!0);!fo||ho&&i===mo&&n===uo||(ho&&yo(),ho=setInterval(function(){var a=Je(document.elementFromPoint(i,n),!0);a!==s&&(s=a,bo()),Co(e,o.options,a,t)},10),mo=i,uo=n)}else{if(!this.options.bubbleScroll||Je(a,!0)===He())return void bo();Co(e,this.options,Je(a,!1),!1)}}},ve(e,{pluginName:"scroll",initializeByDefault:!0})}),to.mount(xo,vo);class ko extends e.Modal{constructor(e,t){super(e),this.options={title:w("Confirm"),confirmText:w("Confirm"),cancelText:w("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 ko(e,t).open()}}class To 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="",i=[],n=!1;for(const t of e)if(t.startsWith("## ")&&!o)o=t.substring(3).trim(),n=!0,i.push(t);else{if(t.startsWith("## ")&&n)break;n&&i.push(t)}this.changelogContent=i.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 i=this.plugin.settings,n=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&&n(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=W.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};i.menuCommands&&(n(i.menuCommands),s(i.menuCommands)&&(o=!0),l(i.menuCommands)&&(o=!0)),i.enableMultipleConfig&&(i.followingCommands&&(n(i.followingCommands),s(i.followingCommands)&&(o=!0)),i.topCommands&&(n(i.topCommands),s(i.topCommands)&&(o=!0),l(i.topCommands)&&(o=!0)),i.fixedCommands&&(n(i.fixedCommands),s(i.fixedCommands)&&(o=!0)),i.mobileCommands&&(n(i.mobileCommands),s(i.mobileCommands)&&(o=!0))),o?(await this.plugin.saveSettings(),new e.Notice(w("Command IDs have been successfully repaired!")),dispatchEvent(new Event("editingToolbar-NewCommand"))):new e.Notice(w("No command IDs need to be repaired"))}catch(t){console.error("修复命令ID时出错:",t),new e.Notice(w("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={...W,lastVersion:t,customCommands:o},await this.plugin.saveSettings(),new e.Notice(w("Successfully restored default settings! (Custom commands preserved)")),this.reloadPlugin(this.plugin.manifest.id),this.close()}catch(t){console.error("恢复默认设置时出错:",t),new e.Notice(w("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} · ${w("Tips")}`}),t.createEl("p",{text:w("Notice:")});const o=t.createEl("ul");o.createEl("li",{text:w("⚠️This update is not compatible with 2.x version command ids, please click [Repair command] to be compatible")}),o.createEl("li",{text:w("⚠️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:w("Latest Changes")}),this.changelogContentEl=this.changelogContainer.createDiv({cls:"changelog-content"}),this.changelogContentEl.setText(w("Loading changelog...")),setTimeout(()=>{this.loadChangelog()},100),new e.Setting(t).setName(w("🔧Data repair")).setDesc(w("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(w("Repair command ID")).onClick(async()=>{await this.fixCommandIds()})),new e.Setting(t).setName(w("🔄Restore default settings")).setDesc(w("This will reset all your custom configurations, but custom commands will be preserved")).addButton(e=>e.setButtonText(w("Restore default")).onClick(async()=>{ko.show(this.app,{message:w("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(w("📋View full changelog")).setDesc(w("Open the complete changelog in your browser")).addButton(e=>e.setButtonText(w("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(w("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 So(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 Eo=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 i in o)e.o(o,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:o[i]})},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:()=>D});var o={};function i(e,t,o,i){let n=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,i,{capture:!1,...n});return Array.prototype.slice.call(arguments,1)}e.r(o),e.d(o,{adjustableInputNumbers:()=>d,createElementFromString:()=>s,createFromTemplate:()=>r,eventPath:()=>l,off:()=>a,on:()=>n,resolveElement:()=>c});const n=i.bind(null,"addEventListener"),a=i.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 i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=t(e,":obj"),a=t(e,":ref"),s=n?i[n]={}:i;a&&(i[a]=e);for(const i of Array.from(e.children)){const e=t(i,":arr"),n=o(i,e?{}:s);e&&(s[e]||(s[e]=[])).push(Object.keys(n).length?n:i)}return i};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,i)=>(e=e.querySelector(t),o<i.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 i=[.001,.01,.1][Number(o.shiftKey||2*o.ctrlKey)]*(o.deltaY<0?1:-1);let n=0,a=e.selectionStart;e.value=e.value.replace(/[\d.]+/g,(e,o)=>o<=a&&o+e.length>=a?(a=o,t(Number(e),i,n)):(n++,e)),e.focus(),e.setSelectionRange(a,a),o.preventDefault(),e.dispatchEvent(new Event("input"))}n(e,"focus",()=>n(window,"wheel",o,{passive:!1})),n(e,"blur",()=>a(window,"wheel",o))}const{min:m,max:u,floor:p,round:h}=Math;function g(e,t,o){t/=100,o/=100;const i=p(e=e/360*6),n=e-i,a=o*(1-t),s=o*(1-n*t),r=o*(1-(1-n)*t),l=i%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 i=g(e,t,o),n=i[0]/255,a=i[1]/255,s=i[2]/255,r=m(1-n,1-a,1-s);return[100*(1===r?0:(1-n-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 i=(2-(t/=100))*(o/=100)/2;return 0!==i&&(t=1===i?0:i<.5?t*o/(2*i):t*o/(2-2*i)),[e,100*t,100*i]}function C(e,t,o){const i=m(e/=255,t/=255,o/=255),n=u(e,t,o),a=n-i;let s,r;if(0===a)s=r=0;else{r=a/n;const i=((n-e)/6+a/2)/a,l=((n-t)/6+a/2)/a,c=((n-o)/6+a/2)/a;e===n?s=c-l:t===n?s=1/3+i-c:o===n&&(s=2/3+l-i),s<0?s+=1:s>1&&(s-=1)}return[360*s,100*r,100*n]}function w(e,t,o,i){return t/=100,o/=100,[...C(255*(1-m(1,(e/=100)*(1-(i/=100))+i)),255*(1-m(1,t*(1-i)+i)),255*(1-m(1,o*(1-i)+i)))]}function v(e,t,o){t/=100;const i=2*(t*=(o/=100)<.5?o:1-o)/(o+t)*100,n=100*(o+t);return[e,isNaN(i)?0:i,n]}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 i;e:for(const n in t){if(!(i=t[n].exec(e)))continue;const a=e=>!!i[2]==("number"==typeof e);switch(n){case"cmyk":{const[,e,t,a,s]=o(i);if(e>100||t>100||a>100||s>100)break e;return{values:w(e,t,a,s),type:n}}case"rgba":{const[,,,e,t,s,r]=o(i);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:n}}case"hexa":{let[,e]=i;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:n}}case"hsla":{const[,,,e,t,s,r]=o(i);if(e>360||t>100||s>100||r<0||r>1||!a(r))break e;return{values:[...v(e,t,s),r],a:r,type:n}}case"hsva":{const[,,,e,t,s,r]=o(i);if(e>360||t>100||s>100||r<0||r>1||!a(r))break e;return{values:[e,t,s,r],a:r,type:n}}}}return{values:null,type:null}}function T(){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:()=>T(t.h,t.s,t.v,t.a)};return t}const S=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:i,key:n}=e;if(document.activeElement===o.wrapper){const{lock:o}=t.options,a="ArrowUp"===n,s="ArrowRight"===n,r="ArrowDown"===n,l="ArrowLeft"===n;if("keydown"===i&&(a||s||r||l)){let i=0,n=0;"v"===o?i=a||s?1:-1:"h"===o?i=a||s?-1:1:(n=a?-1:r?1:0,i=l?-1:s?1:0),t.update(S(t.cache.x+.01*i),S(t.cache.y+.01*n)),e.preventDefault()}else n.startsWith("Arrow")&&(t.options.onstop(),e.preventDefault())}},_tapstart(e){n(document,["mouseup","touchend","touchcancel"],t._tapstop),n(document,["mousemove","touchmove"],t._tapmove),e.cancelable&&e.preventDefault(),t._tapmove(e)},_tapmove(e){const{options:o,cache:i}=t,{lock:n,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 i&&(l=i.x*r.width,c=i.y*r.height);"h"!==n&&(a.style.left=`calc(${l/r.width*100}% - ${a.offsetWidth/2}px)`),"v"!==n&&(a.style.top=`calc(${c/r.height*100}% - ${a.offsetHeight/2}px)`),t.cache={x:l/r.width,y:c/r.height};const d=S(l/r.width),m=S(c/r.height);switch(n){case"v":return o.onchange(d);case"h":return o.onchange(m);default:return o.onchange(d,m)}},_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:i,top:n,width:a,height:s}=t.options.wrapper.getBoundingClientRect();"h"===t.options.lock&&(o=e),t._tapmove({clientX:i+a*e,clientY:n+s*o})},destroy(){const{options:e,_tapstart:o,_keyboard:i}=t;a(document,["keydown","keyup"],i),a([e.wrapper,e.element],"mousedown",o),a([e.wrapper,e.element],"touchstart",o,{passive:!1})}},{options:o,_tapstart:i,_keyboard:s}=t;return n([o.wrapper,o.element],"mousedown",i),n([o.wrapper,o.element],"touchstart",i,{passive:!1}),n(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=n(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:i,margin:n,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(),m=t.getBoundingClientRect(),u={t:d.top-m.height-n,b:d.bottom+n,r:d.right+n,l:d.left-m.width-n},p={vs:d.left,vm:d.left+d.width/2+-m.width/2,ve:d.left+d.width-m.width,hs:d.top,hm:d.bottom-d.height/2-m.height/2,he:d.bottom-m.height},[h,g="middle"]=a.split("-"),f=r[h],b=s[g],{top:y,left:C,bottom:w,right:v}=i;for(const e of f){const o="t"===e||"b"===e,i=u[e],[n,a]=o?["top","left"]:["left","top"],[s,r]=o?[m.height,m.width]:[m.width,m.height],[l,c]=o?[w,v]:[v,w],[d,h]=o?[y,C]:[C,y];if(!(i<d||i+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-m[a]+"px",t.style[n]=i-m[n]+"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 D{constructor(e){P(this,"_initializingActive",!0),P(this,"_recalc",!0),P(this,"_nanopop",null),P(this,"_root",null),P(this,"_color",T()),P(this,"_lastColor",T()),P(this,"_swatchColors",[]),P(this,"_setupAnimationFrame",null),P(this,"_eventListener",{init:[],save:[],hide:[],show:[],clear:[],change:[],changestop:[],cancel:[],swatchselect:[]}),this.options=e=Object.assign({...D.DEFAULT_OPTIONS},e);const{swatches:t,components:o,theme:i,sliders:n,lockOpacity:a,padding:s}=e;["nano","monolith"].includes(i)&&!n&&(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:m,app:u}=this._root;this._nanopop=((e,t,o)=>{const i="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]:i;const{reference:t,popper:o}=Object.assign(i,e);if(!o||!t)throw new Error("Popper- or reference-element missing.");return M(t,o,i)}}})(m,u,{margin:s}),m.setAttribute("role","button"),m.setAttribute("aria-label",this._t("btn:toggle"));const p=this;this._setupAnimationFrame=requestAnimationFrame(function t(){if(!u.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:i,appClass:n,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 ${n||""}" data-theme="${a}" ${i?'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 `),m=d.interaction;return m.options.find(e=>!e.hidden&&!e.classList.add("active")),m.type=()=>m.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),[i,n]=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,i){if(!t.palette)return;const n=a(),{_root:s,options:r}=e,{lastColor:l,currentColor:c}=s.preview;e._recalc&&(n.s=100*o,n.v=100-100*i,n.v<0&&(n.v=0),e._updateOutput("slider"));const d=n.toRGBA().toString(0);this.element.style.background=d,this.wrapper.style.background=`\n linear-gradient(to top, rgba(0, 0, 0, ${n.a}), transparent),\n linear-gradient(to left, hsla(${n.h}, 100%, 50%, ${n.a}), rgba(255, 255, 255, ${n.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 m=n.toHEXA().toString();for(const{el:t,color:o}of e._swatchColors)t.classList[m===o.toHEXA().toString()?"add":"remove"]("pcr-active");c.style.setProperty("--pcr-color",d)}}),hue:E({lock:"v"===n?"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 i=a();e._recalc&&(i.h=360*o),this.element.style.backgroundColor=`hsl(${i.h}, 100%, 50%)`,s.palette.trigger()}}),opacity:E({lock:"v"===i?"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 i=a();e._recalc&&(i.a=Math.round(100*o)/100),this.element.style.background=`rgba(0, 0, 0, ${i.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=[n(e.interaction.clear,"click",()=>this._clearColor()),n([e.interaction.cancel,e.preview.lastColor],"click",()=>{this.setHSVA(...(this._lastColor||this._color).toHSVA(),!0),this._emit("cancel")}),n(e.interaction.save,"click",()=>{!this.applyColor()&&!t.showAlways&&this.hide()}),n(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()}),n(e.interaction.result,["focus","blur"],e=>{this._recalc="blur"===e.type,this._recalc&&this._updateOutput(null)}),n([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 i=t.closeWithKey;o.push(n(e.button,"click",()=>this.isOpen()?this.hide():this.show()),n(document,"keyup",e=>this.isOpen()&&(e.key===i||e.code===i)&&this.hide()),n(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,i)=>{const n=t[this.getColorRepresentation().toLowerCase()];if(n){const t=n[i],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 i=this;o.push(n(window,["scroll","resize"],()=>{i.isOpen()&&(t.closeOnScroll&&i.hide(),null===e?(e=setTimeout(()=>e=null,100),requestAnimationFrame(function t(){i._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:i}=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(i.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:i}=k(e),{lockOpacity:n}=this.options,a=void 0!==i&&1!==i;return t&&3===t.length&&(t[3]=void 0),{values:!t||n&&a?null:t,type:o}}_t(e){return this.options.i18n[e]||D.I18N_DEFAULTS[e]}_emit(e){for(var t=arguments.length,o=new Array(t>1?t-1:0),i=1;i<t;i++)o[i-1]=arguments[i];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]||[],i=o.indexOf(t);return~i&&o.splice(i,1),this}addSwatch(e){const{values:t}=this._parseLocalColor(e);if(t){const{_swatchColors:e,_root:o}=this,i=T(...t),a=s(`<button type="button" style="--pcr-color: ${i.toRGBA().toString(0)}" aria-label="${this._t("btn:swatch")}"/>`);return o.swatches.appendChild(a),e.push({el:a,color:i}),this._eventBindings.push(n(a,"click",()=>{this.setHSVA(...i.toHSVA(),!0),this._emit("swatchselect",i),this._emit("change",i,"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,i=this._color.toRGBA().toString(0);return t.lastColor.style.setProperty("--pcr-color",i),this.options.useAsButton||o.style.setProperty("--pcr-color",i),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,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,n=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||i<0||i>1)return!1;this._color=T(e,t,o,i);const{hue:s,opacity:r,palette:l}=this._components;return s.update(e/360),r.update(i),l.update(t/100,1-o/100),n||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:i}=this._parseLocalColor(e);if(o){const e=i.toUpperCase(),{options:n}=this._root.interaction,a=n.find(t=>t.getAttribute("data-type")===e);if(a&&!a.hidden)for(const e of n)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(D,"utils",o),P(D,"version","1.8.4"),P(D,"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(D,"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(D,"create",e=>new D(e)),t.default})()}),Io=So(Eo),Ao=[],Mo=[];!function(e,t){if(e&&"undefined"!=typeof document){var o,i=!0===t.prepend?"prepend":"append",n=!0===t.singleTag,a="string"==typeof t.container?document.querySelector(t.container):document.getElementsByTagName("head")[0];if(n){var s=Ao.indexOf(a);-1===s&&(s=Ao.push(a)-1,Mo[s]={}),o=Mo[s]&&Mo[s][i]?Mo[s][i]:Mo[s][i]=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),n=0;n<o.length;n++)e.setAttribute(o[n],t.attributes[o[n]]);var s="prepend"===i?"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 Po 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?w("Edit regular expression command"):w("Add regular expression command")});const o=t.createDiv("basic-settings-container");new e.Setting(o).setName(w("Command ID")).setDesc(w('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(w("Command Name")).setDesc(w("Displayed name in toolbar and menu")).addText(e=>e.setValue(this.commandName).onChange(e=>this.commandName=e));const i=t.createDiv("regex-settings");i.style.border="1px solid var(--background-modifier-border)",i.style.padding="10px",i.style.borderRadius="5px",i.style.marginBottom="10px";const n=i.createEl("details",{cls:"ai-help-container"});n.style.marginBottom="10px",n.style.borderRadius="5px",n.style.overflow="hidden";const a=n.createEl("summary",{text:w("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=n.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>${w("AI question template:")}</strong><br>\n ${w("[Description]")}:\n ${w("I need to convert the url to a markdown format link")}\n <br>\n ${w("[Example]")}: \n ${w("For example, convert https://example.com to [https://example.com](https://example.com)")}\n <br>\n ${w("[Requirements]")}: \n ${w("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 ${w("[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(i).setName(w("Matching pattern")).setDesc(w("Regex pattern to match")).addText(e=>this.regexPatternInput=e.setValue(this.regexPattern).onChange(e=>{this.regexPattern=e,this.updatePreview()})),new e.Setting(i).setName(w("Replacement pattern")).setDesc(w("Replacement pattern (use $1, $2, etc. to reference capture groups)")+w("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=i.createDiv("regex-options");r.style.display="flex",r.style.gap="8px",new e.Setting(r).setName(w("Ignore case")).setDesc(w("Match case-insensitive")).addToggle(e=>e.setValue(this.regexCaseInsensitive).onChange(e=>{this.regexCaseInsensitive=e,this.updatePreview()})),new e.Setting(r).setName(w("Global replace")).setDesc(w("Replace all matches")).addToggle(e=>e.setValue(this.regexGlobal).onChange(e=>{this.regexGlobal=e,this.updatePreview()})),new e.Setting(r).setName(w("Multiline mode")).setDesc(w("^ 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=i.createDiv("condition-container");new e.Setting(l).setName(w("Use condition")).setDesc(w("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(w("Condition pattern")).setDesc(w("Must exist regular expression or text")).addText(e=>this.conditionPatternInput=e.setValue(this.conditionPattern).onChange(e=>{this.conditionPattern=e}));const d=new e.Setting(i).setName(w("Icon")).setDesc(w("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(w("Choose icon")).onClick(()=>{const t={id:this.commandId,name:this.commandName,icon:this.icon};new v(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()})),i.createSpan("regex-help");const m=i.createEl("details",{cls:"regex-examples-container"});m.style.marginTop="15px",m.style.borderRadius="5px",m.style.overflow="hidden";const u=m.createEl("summary",{text:w("Regular expression examples")});u.style.padding="8px 12px",u.style.backgroundColor="var(--background-secondary)",u.style.cursor="pointer",u.style.fontWeight="bold",u.style.borderRadius="4px",u.style.userSelect="none";const p=m.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:w("URL to Markdown link"),pattern:"(https?://\\S+)",replacement:"[$1]($1)"},{name:w("Convert MM/DD/YYYY to YYYY-MM-DD"),pattern:"(\\d{1,2})/(\\d{1,2})/(\\d{4})",replacement:"$3-$1-$2"},{name:w("Add bold to keywords"),pattern:"\\b(important|critical|urgent)\\b",replacement:"**$1**"},{name:w("Format phone number"),pattern:"(\\d{3})(\\d{3})(\\d{4})",replacement:"($1) $2-$3"},{name:w("Remove extra spaces"),pattern:"\\s{2,}",replacement:" "},{name:w("Convert HTML bold tags to Markdown format"),pattern:"<strong>(.*?)</strong>",replacement:"**$1**"},{name:w("Convert quoted text to quote block"),pattern:'"([^"]+)"',replacement:"> $1"},{name:w("Add uniform alias to Markdown links"),pattern:"\\[([^\\]]+)\\]\\(([^\\)]+)\\)",replacement:"[$1|alias]($2)"},{name:w("Delete empty lines (multiline mode)"),pattern:"^\\s*$\\n",replacement:"",toggleMultiline:!0},{name:w("Add list symbol to each line (multiline mode)"),pattern:"^(.+)$",replacement:"- $1",toggleMultiline:!0},{name:w("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(),m.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:w("Preview")});const f=g.createDiv("preview-input-container");f.style.marginBottom="10px";const b=f.createEl("label",{text:w("Example text:")});b.style.display="block",b.style.marginBottom="5px",this.previewInput=f.createEl("textarea",{attr:{placeholder:w("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:w("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(w("Command ID and command name cannot be empty"));if(this.commandId.includes(" "))return void new e.Notice(w("Command ID cannot contain spaces"));if(!this.regexPattern)return void new e.Notice(w("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(w("Command")+" "+this.commandId+" "+w("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(w("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 i=new RegExp(this.regexPattern,o),n=this.regexReplacement.replace(/\\n/g,"\n");t=e.replace(i,n),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(w("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:w("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:w("Complete regular expression code (copy to AI for explanation)")});e.style.marginBottom="5px",e.style.fontWeight="bold"}const i=o.createEl("pre");i.style.backgroundColor="var(--background-code)",i.style.padding="8px",i.style.borderRadius="4px",i.style.overflowX="auto",i.style.fontFamily="monospace",i.style.fontSize="var(--font-smaller)";let n=`//${w("Explain the syntax of JavaScript regular expressions")}\n`;n+=`const regex = /${this.escapeRegexForDisplay(this.regexPattern)}/${e};\n`,n+=`const result = text.replace(regex, "${this.escapeStringForDisplay(this.regexReplacement)}");\n`,this.useCondition&&this.conditionPattern&&(n+=`\n//${w("Conditional matching")}\n`,n+=`const condition = /${this.escapeRegexForDisplay(this.conditionPattern)}/;\n`,n+="if (condition.test(text)) {\n",n+=` //${w("Apply regular expression replacement")}\n`,n+=` const result = text.replace(regex, "${this.escapeStringForDisplay(this.regexReplacement)}");\n`,n+="}"),i.textContent=n;const a=o.createEl("button",{text:w("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(n).then(()=>{a.textContent=w("Copied!"),setTimeout(()=>{a.textContent=w("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 Do 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?w("Edit Custom Command"):w("Add Custom Command")});const o=t.createDiv("switch-to-regex-container");o.style.marginBottom="20px",o.style.textAlign="center";const i=o.createEl("button",{text:w("Switch Regex Command Window")});i.addClass("mod-cta"),i.addEventListener("click",()=>{this.close(),new Po(this.app,this.plugin,null).open()}),new e.Setting(t).setName(w("Command ID")).setDesc(w('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(w("Command Name")).setDesc(w("Displayed name in toolbar and menu")).addText(e=>this.commandNameInput=e.setValue(this.commandName).onChange(e=>this.commandName=e));const n={"\n":"↵","\t":"⇥"},a=Object.fromEntries(Object.entries(n).map(([e,t])=>[t,e]));function s(e){let t=e;for(const[e,o]of Object.entries(n))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(n).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 i=o.createDiv({cls:"char-copy-container"});i.style.position="relative",i.style.display="inline-block";const n=i.createEl("button",{text:t});n.style.padding="2px 6px",n.style.fontSize="12px",n.style.minWidth="auto",n.style.border="1px solid var(--background-modifier-border)",n.style.cursor="pointer",n.setAttribute("data-char",e),n.addEventListener("click",t=>{t.preventDefault(),navigator.clipboard.writeText(e).then(()=>{const e=i.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)})}),n.addEventListener("mouseenter",()=>{n.style.backgroundColor="var(--interactive-accent)",n.style.color="var(--text-on-accent)"}),n.addEventListener("mouseleave",()=>{n.style.backgroundColor="",n.style.color=""})})}const d=new e.Setting(t).setName(w("Prefix")).setDesc(w("Add content before selected text")+w("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 m=new e.Setting(t).setName(w("Suffix")).setDesc(w("Add content after selected text")).addText(e=>{this.suffixInput=e,e.setValue(s(this.suffix)).onChange(e=>{this.suffix=r(e)})});c(m,m.controlEl.querySelector("input")),new e.Setting(t).setName(w("Cursor Position Offset")).setDesc(w("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(w("Line Offset")).setDesc(w("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(w("Line Head Format")).setDesc(w("Whether to insert at the beginning of the next line")).addToggle(e=>e.setValue(this.islinehead).onChange(e=>this.islinehead=e));const u=new e.Setting(t).setName(w("Icon")).setDesc(w("Command icon (click to select)"));if(this.iconDisplay=u.controlEl.createDiv("editingToolbarSettingsIcon"),this.icon)try{e.setIcon(this.iconDisplay,this.icon)}catch(e){this.iconDisplay.setText(this.icon)}u.addButton(t=>t.setButtonText(w("Choose Icon")).onClick(()=>{const t={id:this.commandId,name:this.commandName,icon:this.icon};new v(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=u.controlEl.querySelector("input");o&&(o.value=this.icon)}).open()})),new e.Setting(t).addButton(t=>t.setButtonText(w("Save")).setCta().onClick(()=>{if(!this.commandId||!this.commandName)return void new e.Notice(w("Command ID and command name cannot be empty"));if(this.commandId.includes(" "))return void new e.Notice(w("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(w("The command")+this.commandId+w("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(w("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 Oo extends e.Modal{constructor(e,t,o){super(e),this.deployOptions=[],this.plugin=t,this.command=o,this.deployOptions=[{id:"following",name:w("Following Style"),enabled:!0},{id:"top",name:w("Top Style"),enabled:!0},{id:"fixed",name:w("Fixed Style"),enabled:!0}],this.plugin.settings.isLoadOnMobile&&this.deployOptions.push({id:"mobile",name:w("Mobile Style"),enabled:!0})}onOpen(){const{contentEl:t}=this;t.empty(),t.createEl("h3",{text:w("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 i=t.createDiv("deploy-buttons");new e.Setting(i).addButton(e=>e.setButtonText(w("Deploy")).setCta().onClick(()=>{this.deployCommand(),this.close()})).addButton(e=>e.setButtonText(w("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 i;switch(e.id){case"mobile":i=this.plugin.settings.mobileCommands;break;case"following":i=this.plugin.settings.followingCommands;break;case"top":i=this.plugin.settings.topCommands;break;case"fixed":i=this.plugin.settings.fixedCommands}i&&!i.some(e=>e.id===t.id)&&(i.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=w("Command deployed to: ")+e}else t=w("Command already exists in selected configurations");new e.Notice(t),dispatchEvent(new Event("editingToolbar-NewCommand")),this.plugin.reloadCustomCommands()})}}class Fo 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?w("Import Configuration"):w("Export Configuration"),cls:"import-export-title"}),"export"===this.mode){new e.Setting(t).setName(w("Export Type")).setDesc(w("Choose what to export")).addDropdown(e=>{e.addOption("all",w("All Settings")).addOption("All commands",w("All Toolbar Commands")).addOption("custom",w("Custom Commands Only")),this.plugin.settings.enableMultipleConfig&&e.addOption("following",w("Following Style Only")).addOption("top",w("Top Style Only")).addOption("fixed",w("Fixed Style Only")).addOption("mobile",w("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(w("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 i=t.createDiv("import-export-button-container");i.style.display="flex",i.style.justifyContent="flex-end",i.style.marginTop="16px";i.createEl("button",{text:w("Copy to Clipboard"),cls:"mod-cta"}).addEventListener("click",()=>{navigator.clipboard.writeText(this.textArea.getValue()).then(()=>{new e.Notice(w("Configuration copied to clipboard"))}).catch(t=>{console.error("Failed to copy: ",t),new e.Notice(w("Failed to copy configuration"))})})}else{new e.Setting(t).setName(w("Import Mode")).setDesc(w("Choose how to import the configuration")).addDropdown(e=>{e.addOption("update",w("Update Mode (Add new items and update existing ones)")).addOption("overwrite",w("Overwrite Mode (Replace settings with imported ones)")).setValue(this.importMode).onChange(e=>{this.importMode=e,this.importButton.setButtonText("overwrite"===this.importMode?w("Overwrite Import"):w("Update Import")),this.warningContent.setText("overwrite"===this.importMode?w("Warning: Overwrite mode will replace existing settings with imported ones."):w("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(w("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 i=t.createDiv("import-export-button-container");i.style.display="flex",i.style.justifyContent="flex-end",i.style.marginTop="16px",new e.Setting(i).addButton(e=>{this.importButton=e.setIcon("import").setButtonText(w("Import Configuration")).onClick(()=>{this.importConfiguration()})});const n=t.createDiv("import-export-warning");n.style.marginTop="16px",n.style.padding="8px 12px",n.style.backgroundColor="rgba(var(--color-red-rgb), 0.1)",n.style.borderRadius="4px",n.style.border="1px solid rgba(var(--color-red-rgb), 0.3)";const a=n.createEl("p",{text:w("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(w("Please paste configuration data first"));const o=JSON.parse(t);if(!o||"object"!=typeof o)return void new e.Notice(w("Invalid import data format"));const i="menuCommands"in o,n="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,m=o.positionStyle,u=i&&Array.isArray(o.menuCommands)&&o.menuCommands.length>0,p=n&&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=i&&(!Array.isArray(o.menuCommands)||0===o.menuCommands.length),C=n&&(!Array.isArray(o.customCommands)||0===o.customCommands.length),v=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),T=l&&(!Array.isArray(o.mobileCommands)||0===o.mobileCommands.length);let S=w("This import will:")+"\n";if(c&&(S+="• "+w("Update general settings")+"\n"),u&&(S+="• "+w("Update Main Menu Commands")+" ("+o.menuCommands.length+" )\n"),p&&(S+="• "+w("Update Custom Commands")+" ("+o.customCommands.length+" )\n"),h&&(S+="• "+w("Update Following Style Commands")+" ("+o.followingCommands.length+" )\n"),g&&(S+="• "+w("Update Top Style Commands")+" ("+o.topCommands.length+" )\n"),f&&(S+="• "+w("Update Fixed Style Commands")+" ("+o.fixedCommands.length+" )\n"),b&&(S+="• "+w("Update Mobile Style Commands")+" ("+o.mobileCommands.length+" )\n"),"overwrite"===this.importMode&&(y&&(S+="• "+w("Clear all Main Menu Commands")+" ⚠️\n"),C&&(S+="• "+w("Clear all Custom Commands")+" ⚠️\n"),v&&(S+="• "+w("Clear all Following Style Commands")+" ⚠️\n"),x&&(S+="• "+w("Clear all Top Style Commands")+" ⚠️\n"),k&&(S+="• "+w("Clear all Fixed Style Commands")+" ⚠️\n"),T&&(S+="• "+w("Clear all Mobile Style Commands")+" ⚠️\n")),d){const e=o.enableMultipleConfig?w("Enable"):w("Disable");S+="• "+w("Set Multiple Config to:")+" "+e+"\n"}if(m&&(S+="• "+w("Set Position Style to:")+" "+this.getPositionStyleName(m)+"\n"),!(u||p||h||g||f||b||y||C||v||x||k||T||c||d))return void new e.Notice(w("No valid configuration found in import data"));"overwrite"===this.importMode?S+="\n"+w("⚠️ Overwrite mode will replace existing settings with imported ones."):S+="\n"+w("ℹ️ Update mode will merge imported settings with existing ones."),ko.show(this.app,{message:S+"\n"+w("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(w("Configuration imported successfully")),this.close()}catch(e){throw this.restoreBackup(t),e}}})}catch(t){console.error("Import error: ",t),new e.Notice(w("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 w("Following Style");case"top":return w("Top Style");case"fixed":return w("Fixed Style");default:return e}}}const qo=new Map;class Lo extends Error{constructor(e,t=8e3){super(e),this.name="AIUserNoticeError",this.noticeDuration=t}}function No(e){const t=e?.status;if("number"==typeof t)return t;const o=e?.response?.status;return"number"==typeof o?o:null}function Ro(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():w("Unknown connection error.")}function Bo(t){if(!(t instanceof Lo))return!1;const o=Date.now();return o-(qo.get(t.message)??0)<6e3||(qo.set(t.message,o),new e.Notice(t.message,t.noticeDuration)),!0}function _o(){return e.moment.locale()}function $o(e=_o()){const t=e.toLowerCase();return"zh"===t||t.startsWith("zh-")}function zo(e=_o()){return $o(e)}const Uo=[{id:"general",name:w("General"),icon:"gear"},{id:"appearance",name:w("Appearance"),icon:"brush"},{id:"customcommands",name:w("Custom Commands"),icon:"lucide-rectangle-ellipsis"},{id:"commands",name:w("Toolbar Commands"),icon:"lucide-command"},{id:"ai",name:w("AI"),icon:"lucide-sparkles"},{id:"importexport",name:w("Import/Export"),icon:"lucide-import"}];function Vo(e){const{el:t,containerEl:o,swatches:i,opacity:n,defaultColor:a}=e;return{el:t,container:o,theme:"nano",swatches:i,lockOpacity:!n,default:a,position:"left-middle",components:{preview:!0,hue:!0,opacity:!!n,interaction:{hex:!0,rgba:!1,hsla:!1,input:!0,cancel:!0,save:!0}}}}function Ho(e,t){let o;return t.forEach((t,i)=>{t.id===e&&(o=i)}),o}class Wo extends e.PluginSettingTab{getLocalizedCommandName(e){return w(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",()=>{ee(this.plugin),Ce(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(w("No Ollama models found at this endpoint."))}catch(o){this.cachedCustomOllamaModels=[],this.cachedCustomOllamaModelsBaseUrl=t,this.cachedCustomOllamaModelsError=Ro(o),new e.Notice(`${w("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"}),i=Uo.filter(e=>"ai"!==e.id||zo());"ai"!==this.activeTab||zo()||(this.activeTab="general"),i.forEach(t=>{const i=o.createEl("div",{cls:"editing-toolbar-tab "+(this.activeTab===t.id?"active":"")});e.setIcon(i,t.icon),i.createEl("span",{text:t.name}),i.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=w("Delete")){let i,n=!1;e.setIcon("editingToolbarDelete").setTooltip(o).onClick(async()=>{n?(clearTimeout(i),e.setIcon("editingToolbarDelete").setTooltip(o),e.buttonEl.removeClass("mod-warning"),n=!1,await t()):(n=!0,e.setTooltip(w("Confirm Delete?")).setButtonText(w("Confirm Delete?")),e.buttonEl.addClass("mod-warning"),i=setTimeout(()=>{e.setIcon("editingToolbarDelete").setTooltip(o),e.buttonEl.removeClass("mod-warning"),n=!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(w("Editing Toolbar Append Method")).setDesc(w("Choose where Editing Toolbar will append upon regeneration.")).addDropdown(e=>{let t={};U.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(w("Enable Multiple Configurations")).setDesc(w("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(w("Top Toolbar")).setDesc(w("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 i=null;e?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(),this.display()})}),new e.Setting(o).setName(w("Following Toolbar")).setDesc(w("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 i=null;e?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(),this.display()})}),new e.Setting(o).setName(w("Fixed Toolbar")).setDesc(w("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 i=null;e?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(),this.display()})}),new e.Setting(o).setName(w("Mobile Enabled or Not")).setDesc(w("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()}))}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 i=this.plugin.appearanceEditStyle||this.plugin.settings.positionStyle||"top";this.plugin.appearanceEditStyle=i,new e.Setting(o).setName(w("Toolbar Settings")).setDesc(w("Choose which toolbar style's appearance you want to edit.")).addDropdown(e=>{const t={};H.map(e=>t[e]=e),e.addOptions(t).setValue(i).onChange(async e=>{const t=e;this.plugin.appearanceEditStyle=t,this.plugin.settings.positionStyle=t,await this.plugin.saveSettings(),this.display()})}),"top"===i&&(new e.Setting(o).setName(w("Editing Toolbar Auto-hide")).setDesc(w("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(w("Editing Toolbar Centred Display")).setDesc(w("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"===i&&(new e.Setting(o).setName(w("Editing Toolbar Columns")).setDesc(w("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(w("Fixed Position Offset")).setDesc(w("Choose the offset of the Editing Toolbar in the fixed position.")).addButton(e=>e.setButtonText(w("Settings")).onClick(()=>{new S(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(w("Current Configuration")).setDesc(w("Switch between different command configurations.")).addDropdown(e=>{e.addOption("top",w("Top Style")),e.addOption("fixed",w("Fixed Style")),e.addOption("following",w("Following Style")),this.plugin.settings.isLoadOnMobile&&e.addOption("mobile",w("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 i=t.createDiv("command-buttons-container");i.style.display="flex",i.style.flexDirection="column",i.style.gap="10px",i.style.padding="16px",i.style.borderRadius="8px",i.style.backgroundColor="var(--background-secondary)";const n=new e.Setting(i).setName(w("Import From")).setDesc(w("Copy commands from another style configuration."));let a="Main menu";const s=new e.Setting(i);s.addDropdown(e=>{e.addOption("Main menu","Main Menu Commands"),"following"!==o&&this.plugin.settings.followingCommands&&e.addOption("following",w("Following Style")),"top"!==o&&this.plugin.settings.topCommands&&e.addOption("top",w("Top Style")),"fixed"!==o&&this.plugin.settings.fixedCommands&&e.addOption("fixed",w("Fixed Style")),"mobile"!==o&&this.plugin.settings.mobileCommands&&e.addOption("mobile",w("Mobile Style")),e.setValue(a).onChange(e=>{a=e})}),s.addExtraButton(e=>e.setIcon("arrow-right")),s.addButton(t=>t.setButtonText(this.currentEditingConfig+" "+w("Import")).setTooltip(w("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 i=`Import commands from "${a}" to "${this.currentEditingConfig}" `+w("configuration")+"?";ko.show(this.app,{message:i,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}" `+w("configuration")),this.display()}})})),n.addButton(t=>t.setButtonText(w("Clear")+" "+`${this.currentEditingConfig}`).setTooltip(w("Remove all commands from this configuration.")).setWarning().onClick(async()=>{ko.show(this.app,{message:w("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:w("One-click Clear"),cls:"mod-warning"}).addEventListener("click",async()=>{ko.show(this.app,{message:w("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(w("All commands have been removed.")),this.display()}})})}const i=t.createDiv("command-lists-container");i.style.padding="16px",i.style.borderRadius="8px",i.addClass(`${this.currentEditingConfig}`),this.plugin.settings.enableMultipleConfig&&i.createEl("div",{cls:`position-style-info ${this.currentEditingConfig}`,text:w("Currently editing commands for")+` "${this.currentEditingConfig} Style" `+w("configuration")}),new e.Setting(i).setName(w("Editing Toolbar Commands")).setDesc(w("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(w("Add")).onClick(()=>{new k(this.plugin,this.currentEditingConfig).open(),this.triggerRefresh()})}),this.createCommandList(i)}displayCustomCommandSettings(t){t.empty();const o=t.createDiv("custom-commands-container");o.createEl("p",{text:w("Add, edit or delete custom format commands.")}),new e.Setting(o).setName(w("Use current line for regex commands")).setDesc(w("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 i=o.createDiv("command-list-container");i.style.padding="16px",i.style.borderRadius="8px",i.style.backgroundColor="var(--background-secondary)",i.style.marginBottom="20px",i.style.marginTop="20px";const n=o.createDiv("add-command-button-container");n.style.padding="16px",n.style.borderRadius="8px",n.style.backgroundColor="var(--background-secondary)",n.style.marginBottom="20px",n.style.marginTop="20px",n.style.display="flex",n.style.gap="10px";const a=n.createEl("button",{text:w("Add Format Command")});a.addClass("mod-cta"),a.addEventListener("click",()=>{new Do(this.app,this.plugin,null).open()});const s=n.createEl("button",{text:w("Add Regex Command")});s.addClass("mod-cta"),s.addEventListener("click",()=>{new Po(this.app,this.plugin,null).open()}),this.plugin.settings.customCommands.forEach((t,o)=>{const n=new e.Setting(i).setName(t.name),a=createFragment();let s=`${w("ID")}: ${t.id}`;t.useRegex?s+=`, ${w("Pattern")}: ${t.regexPattern}`:s+=`, ${w("Prefix")}: ${t.prefix}, ${w("Suffix")}: ${t.suffix}`,a.createSpan({text:s});const r=a.createSpan({cls:"command-type-badge"});if(t.useRegex?(r.addClass("regex"),r.setText(w("Regex"))):r.setText(w("Prefix/Suffix")),n.descEl.appendChild(a),n.addButton(o=>o.setButtonText(w("Add to Toolbar")).setTooltip(w("Add this command to the toolbar.")).setButtonText(w("Add to Toolbar")).setTooltip(w("Add this command to the toolbar.")).onClick(()=>{if(this.plugin.settings.enableMultipleConfig)new Oo(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(w("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(w("Command added to toolbar")),dispatchEvent(new Event("editingToolbar-NewCommand")),this.plugin.reloadCustomCommands()})}})).addExtraButton(e=>{e.setIcon("pencil").setTooltip(w("Edit")).onClick(()=>{t.useRegex?new Po(this.app,this.plugin,o).open():new Do(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(w("Command Deleted"))})),t.icon)try{const o=n.nameEl.createSpan({cls:"editingToolbarSettingsIcon"});o.style.marginRight="8px",ae(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 i=o.createEl("div",{cls:"editing-toolbar-info"});new e.Setting(i).setClass("editing-toolbar-fix-button").addButton(e=>{e.setIcon("wrench").setTooltip(w("Fix")).onClick(()=>{new To(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",i=this.getAppearanceBucket(o),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(w("🎨 Set Custom Background")).setDesc(w("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"}),i=Io.create(Vo({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(i,`custom_bg${e+1}`,"background-color"),this.pickrs.push(i)}}),new e.Setting(n).setName(w("🖌️ Set Custom Font Color")).setDesc(w("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"}),i=Io.create(Vo({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(i,`custom_fc${e+1}`,"color"),this.pickrs.push(i)}});const a=t.createDiv("custom-toolbar-container");a.style.padding="16px",a.style.borderRadius="8px",a.style.backgroundColor="var(--background-secondary)",new e.Setting(a).setName(w("Toolbar Theme")).setDesc(w("Select a preset toolbar theme, automatically setting the background color, icon color, and size for the selected style.")).addDropdown(e=>{const t={};V.forEach(e=>{t[e]="custom"===e?w("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(i.aestheticStyle??this.plugin.settings.aestheticStyle),e.onChange(async e=>{const o=this.plugin.appearanceEditStyle||this.plugin.settings.positionStyle||"top",i=this.getAppearanceBucket(o);switch(e in t?(i.aestheticStyle=e,i.toolbarIconSize=18):i.aestheticStyle="custom",e){case"light":i.toolbarBackgroundColor="#F5F8FA",i.toolbarIconColor="#4A5568",i.toolbarIconSize=18;break;case"dark":i.toolbarBackgroundColor="#2D3033",i.toolbarIconColor="#E2E8F0",i.toolbarIconSize=18;break;case"vibrant":i.toolbarBackgroundColor="#7E57C2",i.toolbarIconColor="#FFFFFF",i.toolbarIconSize=20;break;case"minimal":i.toolbarBackgroundColor="#F8F9FA",i.toolbarIconColor="#6B7280",i.toolbarIconSize=16;break;case"elegant":i.toolbarBackgroundColor="#1A2F28",i.toolbarIconColor="#D4AF37",i.toolbarIconSize=19}const n=i.toolbarBackgroundColor??this.plugin.settings.toolbarBackgroundColor,a=i.toolbarIconColor??this.plugin.settings.toolbarIconColor,s=i.toolbarIconSize??18;document.documentElement.style.setProperty("--editing-toolbar-background-color",n),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(a).setName(w("Toolbar Background Color")).setDesc(w("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"}),n=Io.create(Vo({isView:!1,el:o,containerEl:t,swatches:["#F5F8FA","#F4F1E8","#2D3033","#1A2F28","#2A1D3B"],opacity:!0,defaultColor:i.toolbarBackgroundColor??this.plugin.settings.toolbarBackgroundColor}));this.setupPickrEvents(n,"toolbarBackgroundColor","background-color"),this.pickrs.push(n)}),new e.Setting(a).setName(w("Toolbar Icon Color")).setDesc(w("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"}),i=Io.create(Vo({isView:!1,el:o,containerEl:t,swatches:["#4A5568","#D4AF37","#2D3033","#6D5846","#4C2A55"],opacity:!1,defaultColor:this.plugin.settings.toolbarIconColor}));this.pickrs.push(i),this.setupPickrEvents(i,"toolbarIconColor","icon-color")}),new e.Setting(a).setName(w("Toolbar Icon Size")).setDesc(w("Set the size of the toolbar icon (px); default: 18px")).addSlider(e=>{const t=i.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",i=this.getAppearanceBucket(o);i.toolbarIconSize=e,i.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 s=a.createDiv("toolbar-preview-container");s.addClass("toolbar-preview-section"),s.style.marginTop="20px";s.createEl("h3",{text:w("Toolbar Preview (With a hypothetical command configuration.)")}).style.marginBottom="10px";const r=s.createDiv();r.classList.add("preview-toolbar-wrapper"),r.classList.add(`preview-${o}`);const l=r.createDiv();l.classList.add("editing-toolbar-preview"),l.classList.add(`preview-${o}`),l.setAttribute("id","editingToolbarModalBar");const c=i.aestheticStyle??this.plugin.settings.aestheticStyle??"default";if(this.applyAestheticStyle(l,c,o),"fixed"===o){const e=this.plugin.settings.toolbarIconSize||18,t=this.plugin.settings.cMenuNumRows||6;l.style.display="grid",l.style.gridTemplateColumns=`repeat(${t}, ${e+10}px)`,l.style.gap=`${Math.max((e-18)/4,2)}px`,l.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(l);o.setClass("editingToolbarCommandItem"),o.buttonEl.classList.add("preview-button"),o.setTooltip(w(t.name)),t.icon&&e.setIcon(o.buttonEl,t.icon)});const d="custom"===c,m=i.toolbarBackgroundColor??this.plugin.settings.toolbarBackgroundColor,u=i.toolbarIconColor??this.plugin.settings.toolbarIconColor,p=i.toolbarIconSize??this.plugin.settings.toolbarIconSize??18;d&&m?l.style.backgroundColor=m:l.style.removeProperty("background-color");l.querySelectorAll("svg").forEach(e=>{d&&u?e.style.color=u:e.style.removeProperty("color"),e.style.width=`${p}px`,e.style.height=`${p}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 i=t.createEl("div",{cls:"editingToolbarSettingsTabsContainer"});let n="";to.create(i,{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,[i]=t.splice(e.oldIndex,1);if(t.splice(e.newIndex,0,i),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){n=e.item.className}});const s=o;s.forEach((t,r)=>{const l=new e.Setting(i);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 v(this.plugin,t,!1,null,this.currentEditingConfig).open()}),ae(t.icon)?e.buttonEl.innerHTML=t.icon:e.setIcon(t.icon)}).addButton(e=>{e.setIcon("pencil").setTooltip(w("Change Submenu Name")).setClass("editingToolbarSettingsButton").onClick(async()=>{new T(this.app,this.plugin,t,!1,this.currentEditingConfig).open()})}).addDropdown(o=>{o.addOption("submenu",w("Button Submenu")).addOption("dropdown",w("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(w("Menu type changed to")+": "+w("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 i=l.settingEl.createEl("div",{cls:"editingToolbarSettingsTabsContainer_sub"});to.create(i,{group:{name:"item",pull:!0,put:function(){return!n.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,i=t[r]?.SubmenuCommands;if(i){const[o]=i.splice(e.oldIndex,1);i.splice(e.newIndex,0,o),this.plugin.updateCurrentCommands(t,this.currentEditingConfig),this.plugin.saveSettings()}}else if("editingToolbarSettingsTabsContainer"===e.to.className){const t=o;let i=Ho(e.target.parentElement.dataset.id,t);const n=t[i]?.SubmenuCommands;if(n){const[o]=n.splice(e.oldIndex,1);t.splice(e.newIndex,0,o),this.plugin.updateCurrentCommands(t,this.currentEditingConfig),this.plugin.saveSettings()}else console.error("Subresult is undefined.")}else if("editingToolbarSettingsTabsContainer"===e.from.className){const t=o,i=Ho(e.target.parentElement.dataset.id,t),n=t[i]?.SubmenuCommands;if(n){const[o]=t.splice(e.oldIndex,1);n.splice(e.newIndex,0,o),this.plugin.updateCurrentCommands(t,this.currentEditingConfig),this.plugin.saveSettings()}else console.error("Subresult is undefined.")}this.triggerRefresh()}}),t.SubmenuCommands.forEach(o=>{const n=new e.Setting(i);n.setClass("editingToolbarCommandItem").addButton(e=>{e.setClass("editingToolbarSettingsIcon").onClick(async()=>{new v(this.plugin,o,!0,null,this.currentEditingConfig).open()}),ae(o?.icon)?e.buttonEl.innerHTML=o.icon:e.setIcon(o.icon)}).setName(this.getLocalizedCommandName(o.name)).addButton(e=>{e.setIcon("pencil").setTooltip(w("Change Command Name")).setClass("editingToolbarSettingsButton").onClick(async()=>{new T(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")})),n.nameEl})}else l.addButton(e=>{e.setClass("editingToolbarSettingsIcon").onClick(async()=>{new v(this.plugin,t,!1,null,this.currentEditingConfig).open()}),ae(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(w("Change Command Name")).setClass("editingToolbarSettingsButton").onClick(async()=>{new T(this.app,this.plugin,t,!1,this.currentEditingConfig).open()})}).addButton(e=>{e.setIcon("editingToolbarSub").setTooltip(w("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(w("Add Separator")).setClass("editingToolbarSettingsButton").setClass("editingToolbarSettingsButtonaddsub").onClick(async()=>{const e={id:"editingToolbar-Divider-Line",name:w("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 i=e.toHEXA().toString(),n=this.plugin.positionStyle,a=this.plugin.appearanceEditStyle||this.plugin.settings.positionStyle||n||"top";if("toolbarBackgroundColor"===t||"toolbarIconColor"===t){const e=this.getAppearanceBucket(a);e[t]=i,n===a&&document.documentElement.style.setProperty(`--editing-toolbar-${o}`,i),"custom"!==e.aestheticStyle&&(e.aestheticStyle="custom"),this.display(),this.triggerRefresh()}else this.plugin.settings[t]=i;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){if(!zo())return void t.createDiv({cls:"editing-toolbar-ai-note",text:w("AI settings are currently available only in Simplified and Traditional Chinese.")});const o=t.createDiv("editing-toolbar-ai-grid"),i=this.plugin.settings.ai.enabled,n=i&&this.plugin.settings.ai.enableInlineCompletion,a=n&&"auto"===this.plugin.settings.ai.completionTrigger,s=i&&this.plugin.settings.ai.enableCustomModel,r=this.plugin.settings.ai.pkmerModelRouting.mode,l=e=>{switch(e){case"04-fast":return w("Light model");case"03-agent":return w("Reasoning model");default:return e}},c=e=>(E.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 i=(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"),n=i.createDiv("editing-toolbar-ai-card-copy");if(n.createDiv({cls:"editing-toolbar-ai-card-title",text:e.title}),n.createDiv({cls:"editing-toolbar-ai-card-desc",text:e.desc}),e.toggle){const{toggle:t}=e,o=i.createEl("div",{cls:"editing-toolbar-ai-card-toggle checkbox-container"});t.value&&o.addClass("is-enabled"),o.addEventListener("click",e=>{e.stopPropagation();const i=!o.hasClass("is-enabled");i?o.addClass("is-enabled"):o.removeClass("is-enabled"),t.onChange(i)})}else if(e.headerDropdown){const{headerDropdown:t}=e,o=i.createEl("select",{cls:"editing-toolbar-ai-card-header-select dropdown"});t.options.forEach(e=>{const i=o.createEl("option",{text:e.label});i.value=e.value,e.value===t.value&&(i.selected=!0)}),o.addEventListener("click",e=>e.stopPropagation()),o.addEventListener("change",e=>{t.onChange(e.target.value)})}else e.badge&&i.createDiv({cls:"editing-toolbar-ai-card-badge",text:e.badge});return t.createDiv("editing-toolbar-ai-card-body")};if(d({title:w("AI Editor"),desc:w("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()}}}),i){const t=d({title:w("PKMer AI"),desc:w("Log in to PKMer AI to get free AI features without manual model setup."),badge:this.plugin.settings.ai.pkmer.userInfo?w("Logged in"):w("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=w("More Quota"),e.href="https://pkmer.cn/products/UserProfile/#tab-ai-token",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(w("Logout")).onClick(async()=>{await this.plugin.aiManager.logoutFromPKMer(),this.display()}):e.setButtonText(w("Login")).setCta().onClick(async()=>{await this.plugin.aiManager.loginWithPKMer(),this.display()})}).addButton(e=>{this.plugin.settings.ai.pkmer.userInfo?e.setButtonText(w("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(`${w("Need a PKMer AI account?")} `);const o=e.createEl("a",{text:w("Open PKMer AI")});o.href="https://pkmer.cn/products/UserProfile/",o.target="_blank",o.rel="noopener noreferrer"}const i=t.createDiv({cls:"editing-toolbar-ai-note",text:w("Checking current AI route...")});this.plugin.aiManager.getProviderRouteStatusText().then(e=>{i.setText(e)});const m=d({title:w("Editor Features"),desc:w("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()}}});n&&(new e.Setting(m).setName(w("Completion Mode")).setDesc(w("Choose whether completion is triggered manually or automatically after a short pause.")).addDropdown(e=>{e.addOption("manual",w("Manual")).addOption("auto",w("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(m).setName(w("Manual Completion Shortcut")).setDesc(w("Default shortcut is Ctrl+J. You can customize it in Obsidian Hotkeys.")).addButton(e=>{e.setButtonText(w("Open Hotkey Settings")).onClick(()=>{this.app.setting.open(),this.app.setting.openTabById("hotkeys")})}),a&&new e.Setting(m).setName(w("Completion Delay (ms)")).setDesc(w("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 u=d({title:w("PKMer Model"),desc:w("Choose models by task."),headerDropdown:{options:[{value:"smart",label:w("Default")},{value:"manual",label:w("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=u.createDiv({cls:"editing-toolbar-ai-note"});e.createDiv({text:`${w("Completion")}: ${l(A(this.plugin.settings.ai,"completion"))}`}),e.createDiv({text:`${w("Rewrite")}: ${l(A(this.plugin.settings.ai,"rewrite"))}`}),e.createDiv({text:`${w("Reasoning")}: ${l(A(this.plugin.settings.ai,"reasoning"))}`}),e.createDiv({text:`${w("Structured")}: ${l(A(this.plugin.settings.ai,"artifact"))}`})}else new e.Setting(u).setName(w("Completion")).setDesc(w("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(u).setName(w("Rewrite")).setDesc(w("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(u).setName(w("Reasoning")).setDesc(w("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(u).setName(w("Structured")).setDesc(w("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()})});u.createDiv({cls:"editing-toolbar-ai-note",text:w("PKMer route only.")});const p=d({title:w("Custom Model (Optional)"),desc:w("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,i=this.plugin.settings.ai.customModel.baseUrl.trim(),n=o&&this.cachedCustomOllamaModelsBaseUrl===i?this.cachedCustomOllamaModels:[],a=o&&this.cachedCustomOllamaModelsBaseUrl===i?this.cachedCustomOllamaModelsError:"",s=this.plugin.aiManager.hasSecureStorage()?this.plugin.aiManager.hasCustomModelApiKey()?w("Stored securely in Obsidian secret storage."):w("Will be stored securely in Obsidian secret storage."):w("Current Obsidian version does not support secure secret storage."),r=o?`${w("Optional for Ollama. Leave empty unless your gateway requires authentication.")} ${s}`.trim():s;if(new e.Setting(p).setName(w("Custom API Format")).setDesc(w("Choose whether the custom model uses an OpenAI-compatible endpoint or the native Ollama API.")).addDropdown(e=>{e.addOption("openai-compatible",w("OpenAI-compatible")).addOption("ollama",w("Ollama")).setValue(t).onChange(async e=>{this.plugin.settings.ai.customModel.apiFormat=e,await this.plugin.saveSettings(),this.display()})}),new e.Setting(p).setName(w("Custom API Base URL")).setDesc(w(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(w("Custom Model Name")).setDesc(w("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?`${w("Choose a detected Ollama model to fill the model field.")} ${a}`.trim():w("Choose a detected Ollama model to fill the model field.");new e.Setting(p).setName(w("Detected Ollama Models")).setDesc(n.length>0?t:w("Fetch available models from your Ollama service.")).addDropdown(e=>{e.addOption("",w("Select a detected model")),n.forEach(t=>{e.addOption(t,t)});const t=this.plugin.settings.ai.customModel.model.trim();t&&!n.includes(t)&&e.addOption(t,t),e.setValue(n.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(w("Refresh")).onClick(async()=>{e.setDisabled(!0),e.setButtonText(w("Loading...")),await this.refreshCustomOllamaModels()})})}new e.Setting(p).setName(w("Custom API Key")).setDesc(r).addText(e=>{e.inputEl.type="password",e.setPlaceholder(this.plugin.aiManager.hasCustomModelApiKey()?w("Stored securely"):w(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(w("Clear")).onClick(async()=>{this.plugin.aiManager.clearCustomModelApiKey(),await this.plugin.saveSettings(),this.display()})}),new e.Setting(p).setName(w("Test Connection")).setDesc(w("Send a lightweight request to verify your custom model settings.")).addButton(e=>{e.setButtonText(w("Test Connection")).onClick(async()=>{e.setDisabled(!0),e.setButtonText(w("Testing..."));try{await this.plugin.aiManager.testCustomModelConnection()}finally{e.setDisabled(!1),e.setButtonText(w("Test Connection"))}})});const l=p.createEl("details",{cls:"editing-toolbar-ai-inline-disclosure"});l.createEl("summary",{cls:"editing-toolbar-ai-inline-summary",text:w("More Options")});const c=l.createDiv("editing-toolbar-ai-inline-body");new e.Setting(c).setName(w("Temperature")).setDesc(w("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())})})}}}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(w("Export Configuration")).setDesc(w("Export your toolbar configuration to share with others.")).addButton(e=>e.setButtonText(w("Export")).setCta().onClick(()=>{new Fo(this.app,this.plugin,"export").open()})),new e.Setting(o).setName(w("Import Configuration")).setDesc(w("Import toolbar configuration from JSON.")).addButton(e=>e.setButtonText(w("Import")).setCta().onClick(()=>{new Fo(this.app,this.plugin,"import").open()}));const i=t.createDiv("import-export-info");i.style.marginTop="20px",i.style.padding="16px",i.style.borderRadius="8px",i.style.backgroundColor="var(--background-secondary)",i.createEl("h3",{text:w("Usage Instructions"),cls:"import-export-heading"}).style.marginTop="0";const n=i.createEl("ul");n.style.paddingLeft="20px",n.createEl("li",{text:w("Export: Generate a JSON configuration that you can save or share.")}),n.createEl("li",{text:w("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:w("Join the Community"),cls:"community-heading"}).style.marginTop="0";a.createEl("p").innerHTML=w("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:w("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:w("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 i=this.aestheticStyleMap[t]||this.aestheticStyleMap.default;e.addClass(i);const n=this.aestheticStyleMap[o]||this.aestheticStyleMap.top;e.addClass(n)}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 jo={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 Ko{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 i=new e.Menu;i.addSections(["settings"]),this.addVisibilityToggle(i),this.addAestheticStyleToggle(i),i.addSections(["viewType"]),this.addViewTypeToggle(i),i.addSections(["controls"]),this.addToolbarControls(i);i.dom.addClass("editingToolbar-statusbar-menu"),i.showAtPosition({x:t.right+5,y:o.top-5})}addVisibilityToggle(t){t.addItem(t=>{t.setTitle(w("Hide & Show")),!e.requireApiVersion("0.15.0")||t.setSection("settings");const o=t.dom,i=new e.ToggleComponent(o).setValue(this.plugin.settings.cMenuVisibility).setDisabled(!0),n=async()=>{this.plugin.settings.cMenuVisibility=!this.plugin.settings.cMenuVisibility,i.setValue(this.plugin.settings.cMenuVisibility),1==this.plugin.settings.cMenuVisibility?setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100):p(this.plugin.settings.cMenuVisibility),ee(this.plugin),await this.plugin.saveSettings()};t.onClick(e=>{e.preventDefault(),e.stopImmediatePropagation(),n()})}),t.addItem(t=>{t.setTitle(w("Toolbar Position")),!e.requireApiVersion("0.15.0")||t.setSection("settings"),t.setIcon("dock");const o=t.setSubmenu();o.addItem(t=>{t.setTitle(w("Top Toolbar"));const o=t.dom,i=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,i.setValue(t.enableTopToolbar);let n=null;t.enableTopToolbar?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()})}),o.addItem(t=>{t.setTitle(w("Following Toolbar"));const o=t.dom,i=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,i.setValue(t.enableFollowingToolbar);let n=null;t.enableFollowingToolbar?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()})}),o.addItem(t=>{t.setTitle(w("Fixed Toolbar"));const o=t.dom,i=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,i.setValue(t.enableFixedToolbar);let n=null;t.enableFixedToolbar?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()})})})}addViewTypeToggle(t){const o=this.plugin.app.workspace.getActiveViewOfType(e.ItemView);if(!o)return;const i=o.getViewType();t.addItem(t=>{t.setTitle(w("Current View: ")+i),!e.requireApiVersion("0.15.0")||t.setSection("settings"),t.setIcon("layout-template");const n=t.setSubmenu(),a=j.isAllowedViewType(o);n.addItem(e=>{e.setTitle(w(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[i]=!a,await this.plugin.saveSettings(),ee(this.plugin),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100)})}),n.addItem(e=>{e.setTitle(w("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,i===e&&(ee(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:w("Add Command"),click:()=>new k(this.plugin).open()}];"fixed"===this.plugin.positionStyle&&o.push({icon:"file-sliders",title:w("Position Settings"),click:()=>new S(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(w("Appearance Style")),!e.requireApiVersion("0.15.0")||t.setSection("settings"),t.setIcon("cherry");const o=t.setSubmenu();V.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(),ee(this.plugin),setTimeout(()=>{dispatchEvent(new Event("editingToolbar-NewCommand"))},100)})})})})}}let Yo;class Go 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(w("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(w("Title")).setDesc(w("Optional, leave blank for default title")).addText(e=>{e.setPlaceholder(w("Input title")).setValue(this.title).onChange(e=>{this.title=e})}),new e.Setting(t).setName(w("Collapse State")).addDropdown(e=>{e.addOption("none",w("Default")).addOption("open",w("Open")).addOption("closed",w("Closed")).setValue(this.collapse).onChange(e=>{this.collapse=e})}),new e.Setting(t).setName(w("Content")).addTextArea(e=>{e.setPlaceholder(w("Input content")).setValue(this.content).onChange(e=>{this.content=e}),e.inputEl.rows=5,e.inputEl.cols=40,this.contentTextArea=e.inputEl});const i=t.createDiv("shortcut-hint");i.setText(`${e.Platform.isMacOS?"⌘":"Ctrl"} + Enter ${w("to insert")}`),i.style.textAlign="right",i.style.fontSize="0.8em",i.style.opacity="0.7",i.style.marginTop="5px",new e.Setting(t).addButton(e=>(e.setButtonText(w("Insert")).setCta().onClick(()=>{this.insertCallout(),this.close()}),this.insertButton=e.buttonEl,e)).addButton(e=>(e.setButtonText(w("Cancel")).setTooltip(w("Cancel")).onClick(()=>this.close()),e)),setTimeout(()=>{this.contentTextArea&&this.contentTextArea.focus()},10)}updateIconAndColor(t,o){if(!t)return;const i=this.allCalloutOptions.find(e=>e.type===o);if(t.empty(),i)if(i.isAdmonition){const o=i.icon;if("custom"===o.type&&o.svg){t.innerHTML=o.svg;const e=t.querySelector("svg");e&&(e.style.fill=i.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",i.color)):(e.setIcon(t,"lucide-box"),t.style.setProperty("--callout-color",i.color))}else e.setIcon(t,i.icon),t.style.setProperty("--callout-color",i.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(),i=e.getLine(o.line),n=0===o.ch;let a;if(e.getSelection()){!n&&i.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{!n&&i.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 Zo{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 i=o.text,n=this.parseTitle(t,i);return!n||n.length>100?this.getFallbackTitle(t):n}catch(e){return console.error(`Failed to fetch title for ${t}:`,e),this.getFallbackTitle(t)}}}Zo.htmlTitlePattern=/<title>([^<]*)<\/title>/im,Zo.wxTitlePattern=/<meta property="og:title" content="([^<]*)" \/>/im;class Jo 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"),i=e.getLine(o.line),n=o.ch,a=e.getCursor("to").ch;return this.matchLinkInLine(i,n,a,o.line)}findLinkAtCursor(e,t){const o=e.getLine(t.line),i=t.ch;return this.matchLinkInLine(o,i,i,t.line)}matchLinkInLine(e,t,o,i){const n=/(!)?\[([^\]]+)\]\(([^\s)]+)(?:\s+["']([^"']*)["'])?\)/g;let a;for(;null!==(a=n.exec(e));){const e=!!a[1],n=a.index,s=a.index+a[0].length,r=a[2],l=a[3],c=a[4]||"";if(t<=s&&o>=n)return{isImage:e,text:r,url:l,title:c,from:{line:i,ch:n},to:{line:i,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],n=a.index+(a[0].startsWith(" ")?1:0),s=n+e.length;if(t<=s&&o>=n)return{isImage:/\.(jpg|jpeg|png|gif|webp|bmp)$/i.test(e),text:e,url:e,title:"",from:{line:i,ch:n},to:{line:i,ch:s}}}return null}formatTargetText(e){return e.isImage?``: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),i=e.substring(t.index+t[0].length),n=this.parseMarkdownImageLink(e);if(n)return this.linkText=n.title,this.linkUrl=n.url,this.linkAlias=n.quotedTitle||"",this.imageWidth=n.width||"",this.imageHeight=n.height||"",this.isEmbed=!0,this.prefixText=o,void(this.suffixText=i)}const o=e.match(/\[([^\]]+)\]\(([a-zA-Z]+:\/\/[^\s)]+)(?:\s+["']([^"']*)["'])?\)/);if(o){const t=o[0],i=e.substring(0,o.index),n=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=i,this.suffixText=n}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,i=o.split(/[/\\]/),n=i[i.length-1];return n?decodeURIComponent(n).trim():e.toUpperCase()}const o=e.match(/^\[\[(.*?)\]\]$/);if(o)return o[1];const i=e.match(/[^/\\]+$/);return i?i[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,i,n,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:n.trim(),width:o,height:i,quotedTitle:a?.trim()}}return null}parseMarkdownLink(e){const t=e.match(/\[([^\]]+)\]\(([a-zA-Z]+:\/\/[^\s)]+)(?:\s+["']([^"']*)["'])?\)/);if(t){const[,e,o,i]=t;return{text:e.trim(),url:o.trim(),title:i?.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 i of t)if("text/html"===i||"text/plain"===i||"text/markdown"===i){const t=await o.getType(i);e[i]=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 i=t.body.textContent||"";return this.parseMixedContent(i)}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(w("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(w("Please enter a URL first"))})}).setName(w("Link Text")).addText(e=>{this.linkTextInput=e,e.setPlaceholder(w("Link Text")).setValue(this.linkText).onChange(e=>{this.linkText=e,this.updateHeader()})});const o=new e.Setting(t).setName(w("Title")).addText(e=>{this.linkAliasInput=e,e.setPlaceholder(w("Link Title (optional)")).setValue(this.linkAlias).onChange(e=>{this.linkAlias=e,this.updateHeader()})}),i=new e.Setting(t).setName(w("Link URL")).setClass("link-url-setting").addText(e=>{this.linkUrlInput=e,e.setPlaceholder(w("Link URL")).setValue(this.linkUrl).onChange(e=>{this.linkUrl=e.trim(),this.validateUrl(this.linkUrl),this.updateHeader()})}).addButton(e=>{e.setIcon("lucide-clipboard").setTooltip(w("Paste and Parse")).onClick(async()=>{await this.parseClipboard(),this.updateHeader()})});this.urlErrorMsg=i.descEl.createDiv("url-error"),this.urlErrorMsg.style.color="var(--text-error)",this.urlErrorMsg.style.display="none";const n=new e.Setting(t).setName(w("Embed Content")).setDesc(w("If it is an image, turn on"));this.embedToggle=new e.ToggleComponent(n.controlEl),this.embedToggle.setValue(this.isEmbed).onChange(e=>{this.isEmbed=e;const i=t.querySelector(".image-size-setting");o.settingEl,i&&(i.style.display=e?"flex":"none"),this.updateHeader()});const a=new e.Setting(t).addButton(e=>{e.setIcon("lucide-maximize").setTooltip(w("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(w("Image Size")).addText(e=>{e.inputEl.addClass("image-width-input"),e.setPlaceholder(w("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(w("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(w("Insert New Line")).setDesc(w("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 ${w("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(w("Insert")).setCta().onClick(()=>{this.insertLink(),this.close()}),this.insertButton=e.buttonEl}).addButton(e=>e.setButtonText(w("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 Zo.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"),i=t.contentEl;if(!o||!i)return null;const n=o.offsetWidth,a=i.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 i=Math.min(e,Math.floor(.65*n)),a=Math.floor(i/o);return a>s&&(a=s,i=Math.floor(a*o)),{width:i,height:a}}}}const r=Math.floor(s*(4/3));return{width:Math.min(Math.floor(.65*n),r),height:null}}validateUrl(e){return e?this.isValidUrl(e)?(this.urlErrorMsg.style.display="none",!0):(this.urlErrorMsg.textContent=w("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 i,n=this.isEmbed?"!":"";n+=`[${t}`,this.isEmbed&&(this.imageWidth||this.imageHeight)&&(n+="|",this.imageWidth&&this.imageHeight?n+=`${this.imageWidth}x${this.imageHeight}`:this.imageWidth?n+=this.imageWidth:this.imageHeight&&(n+=`x${this.imageHeight}`)),n+=`](${o}`,this.linkAlias&&(n+=` "${this.linkAlias}"`),n+=")";if(e.somethingSelected()){const t=e.getCursor("from"),o=e.getCursor("to");if(this.insertNewLine)e.replaceRange("\n"+n,{line:o.line,ch:e.getLine(o.line).length}),i={line:o.line+1,ch:n.length};else{const a=this.prefixText+n+this.suffixText;e.replaceRange(a,{line:t.line,ch:t.ch},o),i={line:t.line,ch:this.prefixText.length+n.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(n,{line:a,ch:0}),i={line:a,ch:n.length}}else e.replaceRange(n,t),i={line:t.line,ch:t.ch+n.length}}setTimeout(()=>{i&&e.setCursor(i),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 Xo{static getPlainText(t){const o=t.getSelection();if(!o)return void new e.Notice(w("Please select text first"));let i=o.replace(/\[([^\[\]]*)\]\([^\(\)]+\)/gim,"$1").replace(/(^#+\s|(?<=^|\s*)#|^>|^\- \[( |x)\]|^\+ |<[^<>]+>|^1\. |^\-+$|^\*+$|==|\*+|~~|```|!*\[\[|\]\])/gm,"").replace(/^[ ]+|[ ]+$/gm,"").replace(/(\r\n|\n)+/gm,"\n");navigator.clipboard.writeText(i),new e.Notice(w("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 i=t.getSelection();if(!i)return void new e.Notice(w("Please select text first"));let n=i;o.all?n=n.replace(/[ \u3000\t]+/g,""):(o.tabs&&(n=n.replace(/\t/g,"")),o.compress&&(n=n.replace(/[ \u3000]+/g," ")));let a=n.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}n=a.join("\n"),o.removeEmptyLines&&(n=n.trim()),t.replaceSelection(n),new e.Notice(w("Whitespace cleaning completed"))}static splitLines(t){const o=t.getSelection();if(!o)return void new e.Notice(w("Please select text first"));const i=this.detectPattern(o);let n;if(i)n=o.split(i).map(e=>e.trim()).filter(e=>e.length>0),new e.Notice(w("List pattern detected, auto-split"));else{const t=this.detectSeparator(o);if(!t)return void new e.Notice(w("No obvious separator or list pattern detected"));n=this.smartSplit(o,t),new e.Notice(`${w("Merged with")} '${t}' ${w("Merge completed")}`)}t.replaceSelection(n.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 i="",n=null;const a={'"':'"',"'":"'","“":"”","‘":"’","(":")","(":")","《":"》","[":"]","[[":"]]"};for(let s=0;s<e.length;s++){const r=e[s];n?(i+=r,r===n&&(n=null)):a[r]?(n=a[r],i+=r):r===t?(o.push(i.trim()),i=""):i+=r}return i&&o.push(i.trim()),o.filter(e=>e.length>0)}static detectSeparator(e){let t=0,o=null;return["、",",",",",";",";","|","·"].forEach(i=>{const n=e.split(i).length-1;n>t&&(t=n,o=i)}),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(w("Paste failed"))}}static smartTypography(t){const o=t.getSelection();if(!o||0===o.trim().length)return void new e.Notice(w("Please select text first"));const i=(o.match(/[\u4e00-\u9fa5]/g)||[]).length/o.length>.1;let n=o;const a=[];[/`[^`]+`/g,/\$[^$]+\$/g,/https?:\/\/[^\s)]+/g,/!\[.*?\]\(.*?\)/g,/\[.*?\]\(.*?\)/g].forEach(e=>{n=n.replace(e,e=>(a.push(e),`__PROTECTED_${a.length-1}__`))}),i?(n=n.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(w("Detected Chinese context: converted to full-width symbols"))):(n=n.replace(/,/g,", ").replace(/。/g,". ").replace(/;/g,"; ").replace(/:/g,": ").replace(/?/g,"? ").replace(/!/g,"! ").replace(/(/g,"(").replace(/)/g,")").replace(/[""]/g,'"').replace(/ {2,}/g," "),new e.Notice(w("Detected code/English context: converted to half-width symbols"))),a.forEach((e,t)=>{n=n.replace(`__PROTECTED_${t}__`,e)}),t.replaceSelection(n)}static dedupe(t,o={}){const i=t.getSelection();if(!i)return void new e.Notice(w("Please select text to dedupe first"));const n=i.split(/\r?\n/),a=new Set,s=[];for(const e of n){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(`${w("Deduplication completed, remaining")} ${s.length} ${w("lines")}`)}static addWrap(t,o="",i="",n=!0){const a=t.getSelection(),s=a&&""!==a.trim(),r=s?a:t.getValue();if(!r)return;const l=r.split("\n").map(e=>n&&0===e.trim().length?e:`${o}${e}${i}`).join("\n");s?t.replaceSelection(l):t.setValue(l),new e.Notice(w("Prefix/suffix added"))}static numberList(t,o=1,i=1,n=". ",a=""){const s=t.getSelection();if(!s)return void new e.Notice(w("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}${n}${t}`;return l+=i,o}).join("\n");t.replaceSelection(c),new e.Notice(`${w("Numbering completed: starting from")} ${o}`)}static extractBetween(t,o,i){if(!o&&!i)return void new e.Notice(w("Please specify start or end string"));const n=t.getValue();if(n)try{const a=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=a(o),r=a(i),l=new RegExp(`${s}(.*?)${r}`,"g"),c=[];let d;for(;null!==(d=l.exec(n));)void 0!==d[1]&&c.push(d[1]);c.length>0?(t.setValue(c.join("\n")),new e.Notice(`${w("Extracted")} ${c.length} ${w("matches")}`)):new e.Notice(w("No matches found"))}catch(t){new e.Notice(w("Extraction failed"))}}static mergeLines(t,o){const i=t.getSelection();if(!i||""===i.trim())return void new e.Notice(w("Please select lines to merge first"));const n=i.split(/\r?\n/),a=""!==o.separator;let s="";for(let e=0;e<n.length;e++){let t=o.trimLines?n[e].trim():n[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?`${w("Merged with")} '${o.separator}'`:w("Merge completed"))}static convertListToTableMultiDim(e){const t=e.getSelection();if(!t||""===t.trim())return;const o=t.split(/\r?\n/),i=/^((\s*)(?:[-*+]|\d+\.)\s+)(.*)/;let n=0;const a=o.map(e=>e.match(i)).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(i);if(t){const e=Math.round(t[2].replace(/\t/g," ".repeat(s)).length/s);e>n&&(n=e)}});let r=[],l=[],c=[],d=!1;for(let e=0;e<o.length;e++){const t=o[e],a=t.match(i);if(a){d=!0;const e=a[3].trim(),t=Math.round((a[2]||"").replace(/\t/g," ".repeat(s)).length/s);1===n?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 m=1===n?l:this.applyVisualMerge(l);this.renderFinalResult(e,r,m,[],n+1)}static applyVisualMerge(e){let t=[];return e.map((e,o)=>{if(0===o)return t=[...e],e;const i=e.map((o,i)=>e.slice(0,i).every((e,o)=>e===t[o]||""===e)&&o===t[i]?"":o);return t=[...e],i})}static renderFinalResult(t,o,i,n,a){let s="| "+Array.from({length:a},(e,t)=>0===t?w("Item"):`${w("Content")} ${t}`).join(" | ")+" |\n"+("| "+Array.from({length:a},()=>"---").join(" | ")+" |\n")+i.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,n.length>0&&(r+="\n\n"+n.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(w("Super conversion completed: context preserved and layout optimized"))}static convertTableToList(t){let o=t.getSelection();if(!o||!o.includes("|")){const e=t.getCursor("from"),i=t.lineCount();let n=e.line;for(;n>0;){if(!t.getLine(n-1).includes("|"))break;n--}let a=e.line;for(;a<i-1;){if(!t.getLine(a+1).includes("|"))break;a++}if(n<=a){const e=[];for(let o=n;o<=a;o++){const i=t.getLine(o);i.includes("|")&&e.push(i)}e.length>0&&(o=e.join("\n"),t.setSelection({line:n,ch:0},{line:a,ch:t.getLine(a).length}))}}if(!o||!o.includes("|"))return void new e.Notice(w("Please select a valid Markdown table"));const i=o.split(/\r?\n/),n=[];for(const e of i){if(e.match(/^\s*\|?[\s\-:|]+\|?\s*$/)||""===e.trim())continue;e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(e=>e.trim()).forEach((e,t)=>{if(""!==e&&e!==w("Item")&&!e.startsWith(w("Content"))){const o=" ".repeat(t);n.push(`${o}- ${e}`)}})}t.replaceSelection(n.join("\n")),new e.Notice(w("Table converted to multi-level list"))}}class Qo extends e.Modal{constructor(e,t,o,i){super(e),this.result={},this.title=t,this.fields=o,this.onSubmit=i,o.forEach(e=>{this.result[e.key]=e.defaultValue||""})}onOpen(){const{contentEl:t}=this;t.empty(),t.createEl("h2",{text:this.title}),this.fields.forEach(o=>{new e.Setting(t).setName(o.label).addText(e=>{e.setPlaceholder(o.placeholder||"").setValue(o.defaultValue||"").onChange(e=>{this.result[o.key]=e}),o===this.fields[0]&&setTimeout(()=>e.inputEl.focus(),10),e.inputEl.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),this.submit())})})}),new e.Setting(t).addButton(e=>e.setButtonText(w("Confirm")).setCta().onClick(()=>{this.submit()})).addButton(e=>e.setButtonText(w("Cancel")).onClick(()=>{this.close()}))}submit(){this.onSubmit(this.result),this.close()}onClose(){const{contentEl:e}=this;e.empty()}}class ei{formatAICommandName(...e){return[w("AI"),...e.map(e=>w(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._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(),i=t.getCursor("from"),n=t.getCursor("to");let a=e.prefix;e.islinehead&&i.ch>0&&(a="\n"+a);const s=e.suffix,r={line:i.line-e.line,ch:i.ch-a.length};if(t.getRange(r,i)==a){const l={line:i.line+e.line,ch:n.ch+s.length};if(t.getRange(n,l)==s){t.replaceRange(o,r,l),t.setCursor(i.line-e.line,i.ch);const n={line:i.line,ch:i.ch-a.length},s={line:i.line,ch:n.ch+o.length};return void t.setSelection(n,s)}}if(t.replaceSelection(`${a}${o}${s}`),e.char>0)t.setCursor(i.line+e.line,i.ch+e.char+o.length);else{const e=i,n={line:e.line,ch:e.ch+a.length},s={line:e.line,ch:n.ch+o.length};t.setSelection(n,s)}},this.plugin=e}async applyRegexCommand(t,o){try{let i=t.getSelection(),n=t.getCursor("from"),a=t.getCursor("to");if(!i)if(this.plugin.settings.useCurrentLineForRegex){const o=n.line,s=t.getLine(o);if(!s||""===s.trim())return void new e.Notice(w("Current line is empty, please select text or move to a non-empty line"));i=s,n={line:o,ch:0},a={line:o,ch:s.length},t.setSelection(n,a)}else try{const o=await this.readClipboard();if(i=o["text/html"]?e.htmlToMarkdown(o["text/html"]):o["text/markdown"]||o["text/plain"],!i)return void new e.Notice(w("Please select text or copy text to clipboard first"));t.replaceRange(i,n,n);const a=t.offsetToPos(t.posToOffset(n)+i.length);t.setSelection(n,a)}catch(t){return console.error("读取剪贴板失败:",t),void new e.Notice(w("Please select text first"))}if(o.useCondition&&o.conditionPattern){if(!new RegExp(o.conditionPattern).test(i))return void new e.Notice(w("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:i.replace(r,o.regexReplacement)}]});const d=t.getSelection(),m=t.offsetToPos(t.posToOffset(l)),u=t.offsetToPos(t.posToOffset(l)+d.length);t.setSelection(m,u)}catch(t){console.error("正则表达式命令执行错误:",t),new e.Notice(w("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 i of t)if("text/html"===i||"text/plain"===i||"text/markdown"===i){const t=await o.getType(i);e[i]=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,i=t.line-1,n=i>=0?e.getLine(i).trim():"";if(i<0||!/^\s*\d+\.\s/.test(n)||(n.match(/^\s*/)?.[0].length||0)<o){const{startLine:o,endLine:i}=function(e,t){let o=t,i=t;for(;o>0;){const t=e.getLine(o-1);if(!/^\s*\d+\.\s/.test(t.trim()))break;o--}for(;i<e.lineCount()-1;){const t=e.getLine(i+1);if(!/^\s*\d+\.\s/.test(t.trim()))break;i++}return{startLine:o,endLine:i}}(e,t.line);m(e,o,i)}else{const{startLine:o,endLine:i}=function(e,t){let o=t,i=t;const n=e.getLine(t).match(/^\s*/)?.[0].length||0;for(;i<e.lineCount()-1;){const t=e.getLine(i+1),o=t.match(/^\s*/)?.[0].length||0;if(!/^\s*\d+\.\s/.test(t.trim())||o<n)break;i++}return{startLine:o,endLine:i}}(e,t.line);m(e,o,i)}}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),ee(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=>{Xo.getPlainText(e)}}),this.plugin.addCommand({id:"insert-blank-lines",name:"Insert Blank Lines",editorCallback:e=>{Xo.insertBlankLines(e)}}),this.plugin.addCommand({id:"remove-blank-lines",name:"Remove Blank Lines",editorCallback:e=>Xo.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,i)=>{this.plugin.addCommand({id:e,name:this.formatAICommandName("Rewrite",t),icon:i,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"),M.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)}}),Y.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=>{Xo.splitLines(e)}}),this.plugin.addCommand({id:"smart-symbols",name:"Full Half Converter",editorCallback:e=>{Xo.smartTypography(e)}}),this.plugin.addCommand({id:"dedupe-lines",name:"Dedupe Lines",editorCallback:e=>Xo.dedupe(e,{trimBeforeCompare:!0})}),this.plugin.addCommand({id:"add-wrap",name:"Add Prefix/Suffix",editorCallback:e=>{new Qo(this.plugin.app,w("Add Prefix/Suffix"),[{key:"prefix",label:w("Prefix"),placeholder:w("Enter prefix"),defaultValue:""},{key:"suffix",label:w("Suffix"),placeholder:w("Enter suffix"),defaultValue:""}],t=>{const o=t;Xo.addWrap(e,o.prefix,o.suffix,!0)}).open()}}),this.plugin.addCommand({id:"number-lines",name:"Number Lines (Custom)",editorCallback:e=>{new Qo(this.plugin.app,w("Number Lines Configuration"),[{key:"start",label:w("Start Number"),placeholder:"1",defaultValue:"1"},{key:"step",label:w("Step"),placeholder:"1",defaultValue:"1"},{key:"sep",label:w("Separator"),placeholder:". ",defaultValue:". "}],t=>{const o=parseInt(t.start)||1,i=parseInt(t.step)||1,n=t.sep||". ";Xo.numberList(e,o,i,n,"")}).open()}}),this.plugin.addCommand({id:"remove-whitespace-trim",name:"Trim Line Ends",editorCallback:e=>{Xo.processWhitespace(e,{trim:!0})}}),this.plugin.addCommand({id:"remove-whitespace-compress",name:"Shrink Extra Spaces",editorCallback:e=>{Xo.processWhitespace(e,{compress:!0})}}),this.plugin.addCommand({id:"remove-whitespace-all",name:"Remove All Whitespace",editorCallback:e=>{Xo.processWhitespace(e,{all:!0})}}),this.plugin.addCommand({id:"list-to-table",name:w("List to Table"),editorCallback:e=>{Xo.convertListToTableMultiDim(e)}}),this.plugin.addCommand({id:"table-to-list",name:w("Table to List"),editorCallback:e=>Xo.convertTableToList(e)}),this.plugin.addCommand({id:"extract-between",name:"Extract Between Strings",editorCallback:e=>{new Qo(this.plugin.app,w("Extract Between Strings"),[{key:"start",label:w("Start String"),placeholder:w("Enter start string"),defaultValue:"["},{key:"end",label:w("End String"),placeholder:w("Enter end string"),defaultValue:"]"}],t=>{const o=t;Xo.extractBetween(e,o.start,o.end)}).open()}}),this.plugin.addCommand({id:"merge-lines",name:w("Merge Lines"),editorCallback:e=>{new Qo(this.plugin.app,w("Merge Lines Settings"),[{key:"sep",label:w("Separator (leave empty for smart spacing)"),placeholder:w("e.g., comma, pipe, arrow"),defaultValue:""}],t=>{Xo.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,()=>be(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:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.undo())},icon:"undo-glyph"}),this.plugin.addCommand({id:"editor-redo",name:"Redo Edit",callback:()=>{const e=this.getActiveEditor();e&&this.executeCommandWithoutBlur(e,()=>e?.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 Go(this.plugin).open()}}),this.plugin.addCommand({id:"insert-link",name:"Insert Link(Modal)",icon:"lucide-link",callback:()=>{new Jo(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,i=o.querySelector("head"),n=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,m=document.body?.querySelector(".mod-vertical.mod-root .workspace-tab-container");function u(e){return e[a]()}function p(){return o.contains(n)&&(null==i||i.removeChild(n)),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(m))try{document.body.removeChild(e),d.appendChild(e)}catch(e){console.log(e.message)}})})}),m.addEventListener("fullscreenchange",function(){h(m)||c.disconnect()}),h(m)?(c.disconnect(),p()):(u(m),c.observe(document.body,{childList:!0})),exports.beFull=u,exports.exitFull=p,exports.isFull=h,exports.toggleFull=function(e){return h(e)?(p(),!1):(u(e),!0)}}(app),icon:"fullscreen"}),this.plugin.addCommand({id:"workplace-fullscreen-focus",name:"Toggle Workplace Fullscreen Focus",callback:()=>function(t){Yo=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;let o=Yo;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 i=this.getCharacterOffset(e.id);await this.plugin.app.commands.executeCommandById(`${e.id}`),0!=i&&t.setCursor(o.line,o.ch+i)})}})}),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 i={prefix:e.prefix,suffix:e.suffix,char:e.char,line:e.line,islinehead:e.islinehead};this._commandsMap[e.id]=i,o&&this.executeCommandWithoutBlur(o,()=>{this.applyCommand(i,o),this.plugin.setLastExecutedCommand(`editing-toolbar:${t}`)})}}})})}get commandsMap(){return this._commandsMap}}class ti 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 i=t.createDiv("editing-toolbar-ai-consent-hero");i.createEl("h2",{text:w("Enable AI Editor")}),i.createDiv({cls:"editing-toolbar-ai-consent-desc",text:w("Unlock inline completion, rewrite, frontmatter, and canvas generation right inside your toolbar.")}),i.createDiv({cls:"editing-toolbar-ai-consent-note",text:w("Sign in to PKMer AI for free managed AI, or use your own compatible model.")});const n=t.createDiv("editing-toolbar-ai-consent-section");n.createDiv({cls:"editing-toolbar-ai-consent-section-title",text:w("What you get")});const a=n.createDiv("editing-toolbar-ai-consent-list");this.createListItem(a,w("Inline completion while you write")),this.createListItem(a,w("Rewrite, summarize, and continue text in place")),this.createListItem(a,w("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:w("Before you enable AI")});const r=s.createDiv("editing-toolbar-ai-consent-list");this.createListItem(r,w("The plugin itself does not intentionally store your note content.")),this.createListItem(r,w("AI requests are sent only to the provider you choose, such as PKMer AI or your custom model.")),this.createListItem(r,w("Those requests remain subject to the provider privacy policy, terms, and model rules.")),this.createListItem(r,w("You can turn AI off at any time in settings."));const l=t.createDiv("editing-toolbar-ai-consent-actions");new e.ButtonComponent(l).setButtonText(w("Not now")).onClick(()=>this.finish(!1)),new e.ButtonComponent(l).setButtonText(w("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 oi{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 i=null;for(let n=0;n<o.length;n+=1){const a=o[n];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){i=e;if(n<o.length-1&&this.isRetryableEndpointError(e))continue;await this.rethrowUserFacingRequestError(e,a)}}await this.rethrowUserFacingRequestError(i,o[0]??t.baseUrl)}async requestCompletion(e,t){const o=e.prefix.slice(-2e3),i=e.suffix.slice(0,800),n=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,i,n,s),t,{maxTokens:this.getCompletionTokenBudget(o,i,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={},i){if(t?.aborted)throw new DOMException("Aborted","AbortError");const n=i??await this.resolveProvider(o.pkmerScene),{response:a}=await this.requestChatCompletionsWithFallback(n,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,i={}){const n=this.getChatCompletionsCandidateUrls(e);let a=null;for(let s=0;s<n.length;s+=1){const r=n[s];try{const n=await this.executeChatCompletionsRequest(r,e,t,o,i);return"custom"===e.kind&&this.rememberCustomChatCompletionsUrl(e.baseUrl,e.apiFormat,r),{response:n,requestUrlValue:r}}catch(t){a=t;if("custom"===e.kind&&s<n.length-1&&this.isRetryableEndpointError(t))continue;await this.rethrowUserFacingRequestError(t,r)}}await this.rethrowUserFacingRequestError(a,n[0]??e.baseUrl)}async executeChatCompletionsRequest(t,o,i,n,a={}){const s=await e.requestUrl({url:t,method:"POST",headers:this.buildRequestHeaders(o.apiKey),body:JSON.stringify(this.buildRequestBody(t,o,i,a))});if(s.status>=200&&s.status<300)return s;throw this.createRequestResponseError(s,t)}buildRequestBody(e,t,o,i={}){return"custom"===t.kind&&"ollama"===t.apiFormat?this.buildOllamaRequestBody(e,t,o,i):{model:t.model,temperature:t.temperature,max_tokens:i.maxTokens,stream:!1,messages:o}}buildOllamaRequestBody(e,t,o,i={}){const n={};return Number.isFinite(t.temperature)&&(n.temperature=t.temperature),"number"==typeof i.maxTokens&&(n.num_predict=i.maxTokens),/\/api\/generate$/i.test(e)?{model:t.model,prompt:this.buildOllamaGeneratePrompt(o),stream:!1,options:Object.keys(n).length>0?n:void 0}:{model:t.model,stream:!1,messages:o,options:Object.keys(n).length>0?n: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:A(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",i=[];return e.baseUrl.trim()||i.push("baseUrl"),e.model.trim()||i.push("model"),"ollama"===o||t||i.push("apiKey"),i.length>0?{provider:null,missing:i}:{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),i="ollama"===e.apiFormat?this.buildOllamaCandidateUrls(e.baseUrl):this.buildChatCompletionsCandidateUrls(e.baseUrl);return o?[o,...i.filter(e=>e!==o)]:i}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`,i=`${t}/v1/chat/completions`,n=`${t}/v3/chat/completions`;return this.hasPathSegment(t)?[o,i,n]:[i,o,n]}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=No(e);if(404===t||405===t||410===t)return!0;if(400===t||422===t){const t=Ro(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})`,i=new Error("string"==typeof o?o.trim():String(o));return i.status=e.status,i.response=e,i}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 Lo(w("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!==No(e))return!1;const o=await this.authService.refreshQuota().catch(()=>null),i=o?.quota??o?.remainingQuota;if("number"==typeof i){if(Number((i/5e5).toFixed(2))<=1)return!0}const n=Ro(e).toLowerCase();return/quota|credit|balance|insufficient|额度|点数|余量不足|余额不足/.test(n)}buildCompletionMessages(e,t,o,i){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.${i?"\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}${i}`}\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,i=e.context?`\n\nLocal document context:\n${e.context}`:"",n=this.buildRewriteSystemPrompt(e.artifactKind),a=this.buildRewriteOutputRequirement(e.artifactKind);return[{role:"system",content:n},{role:"user",content:o?`Instruction:\n${t}\n\nTarget text:\n${e.selectedText}${i}\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)${i}\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,i){if(i>0)return 96;const n=e.trimEnd(),a=t.trimStart(),s=n.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],i=(e.index??-1)+e[0].length;if(i>=Math.max(12,Math.floor(.45*t.length)))return t.slice(0,i).trimEnd()}const i=t.lastIndexOf(" ");return i>=Math.max(12,Math.floor(.6*t.length))?t.slice(0,i).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,i)=>{if(t?.aborted)return void i(new DOMException("Aborted","AbortError"));const n=window.setTimeout(o,e);t?.addEventListener("abort",()=>{window.clearTimeout(n),i(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 ii=new Set(["text","file","link","group"]),ni=new Set(["top","right","bottom","left"]),ai=new Set(["none","arrow"]);function si(e){const t=li(e.content);if(!t)throw new Error(w("AI generated content is empty."));return"canvas"===e.kind?function(e,t){let o;try{o=JSON.parse(e)}catch{throw new Error(w("AI returned invalid Canvas JSON."))}if(!o||"object"!=typeof o)throw new Error(w("AI returned invalid Canvas JSON."));const i=o,n=new Set,a=Array.isArray(i.nodes)?i.nodes:[],s=Array.isArray(i.edges)?i.edges:[];let r=a.map((e,o)=>function(e,t,o,i){if(!e||"object"!=typeof e)return null;const n=e,a=ii.has(n.type)?n.type:"text",s=bi(n.id,t),r="string"==typeof n.color&&n.color.trim()?n.color.trim():void 0;if("group"===a)return{id:s,type:a,x:Ci(n.x,60*i-40),y:Ci(n.y,-60),width:wi(n.width,680,240,2800),height:wi(n.height,420,160,2200),label:"string"==typeof n.label?n.label.trim():pi(o),color:r,background:"string"==typeof n.background?n.background:void 0,backgroundStyle:"string"==typeof n.backgroundStyle?n.backgroundStyle:void 0};if("file"===a&&"string"==typeof n.file&&n.file.trim())return{id:s,type:a,x:Ci(n.x,0),y:Ci(n.y,0),width:wi(n.width,360,260,560),height:wi(n.height,240,160,420),file:n.file.trim(),color:r};if("link"===a&&"string"==typeof n.url&&n.url.trim())return{id:s,type:a,x:Ci(n.x,0),y:Ci(n.y,0),width:wi(n.width,320,240,520),height:wi(n.height,180,120,320),url:n.url.trim(),color:r};const l=function(e,t,o){const i=[e.text,e.label,e.title,e.name,e.file,e.url];for(const e of i)if("string"==typeof e&&e.trim())return e.trim().replace(/\\n/g,"\n");const n=t.replace(/\r\n?/g,"\n").split("\n").map(e=>e.trim()).filter(Boolean);if(n[o])return n[o];return ui(t)}(n,o,i),c=hi(l);return{id:s,type:"text",x:Ci(n.x,0),y:Ci(n.y,0),width:wi(n.width,c.width,220,620),height:wi(n.height,c.height,90,420),text:l,color:r}}(e,n,t,o)).filter(e=>null!==e);0===r.length&&(r=[mi(n,t)]);let l=s.map(e=>function(e,t,o){if(!e||"object"!=typeof e)return null;const i=e,n="string"==typeof i.fromNode?i.fromNode.trim():"",a="string"==typeof i.toNode?i.toNode.trim():"";if(!o.has(n)||!o.has(a)||n===a)return null;return{id:bi(i.id,t),fromNode:n,toNode:a,fromSide:fi(i.fromSide,ni),toSide:fi(i.toSide,ni),fromEnd:fi(i.fromEnd,ai),toEnd:fi(i.toEnd,ai)??"arrow",color:"string"==typeof i.color&&i.color.trim()?i.color.trim():void 0,label:"string"==typeof i.label&&i.label.trim()?i.label.trim():void 0}}(e,n,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[i,...n]=o;return n.map(e=>({id:bi(void 0,t),fromNode:i.id,toNode:e.id,toEnd:"arrow"}))}(r,n));const c=function(e,t,o){const i=e.nodes.filter(e=>"group"!==e.type),n=e.nodes.filter(e=>"group"===e.type),a=new Map,s=new Map;for(const e of i)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 i=e.find(e=>(e.text||"").trim().startsWith("# "));if(i)return i;const n=pi(o).toLowerCase(),a=e.find(e=>(e.text||"").toLowerCase().includes(n));if(a)return a;return[...e].sort((e,o)=>{const i=(t.get(o.id)??0)-(t.get(e.id)??0);return 0!==i?i:(o.text||"").length-(e.text||"").length})[0]}(i,s,t),l=function(e,t,o){if(0===e.length)return[];const i=new Map(e.map(e=>[e.id,e])),n=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(n.has(e)||!i.has(e))continue;const o=[{id:e,depth:0===s.length?0:s.length}];for(n.add(e);o.length>0;){const e=o.shift();s[e.depth]||(s[e.depth]=[]),s[e.depth].push(i.get(e.id));[...t.get(e.id)??[]].filter(e=>!n.has(e)).sort((e,t)=>(i.get(t)?.text||"").length-(i.get(e)?.text||"").length).forEach(t=>{n.add(t),o.push({id:t,depth:e.depth+1})})}}return s.filter(e=>e&&e.length>0)}(i,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 i=-Math.round(o/2);e.forEach(e=>{e.x=t*c,e.y=i,i+=e.height+42})}),1===i.length&&(i[0].x=0,i[0].y=0);const d=function(e,t,o,i){if(0===t.length)return e;const n=function(e){const t=Math.min(...e.map(e=>e.x)),o=Math.min(...e.map(e=>e.y)),i=Math.max(...e.map(e=>e.x+e.width)),n=Math.max(...e.map(e=>e.y+e.height));return{x:t,y:o,width:i-t,height:n-o}}(t);if(0===e.length)return[{id:bi(void 0,o),type:"group",x:n.x-70,y:n.y-70,width:n.width+140,height:n.height+140,label:pi(i),color:"4"}];const[a,...s]=e;return a.x=n.x-70,a.y=n.y-70,a.width=n.width+140,a.height=n.height+140,a.label=a.label||pi(i),s.forEach((e,t)=>{e.x=n.x-70+24*(t+1),e.y=n.y-70+24*(t+1),e.width=Math.max(240,n.width+90-18*(t+1)),e.height=Math.max(180,n.height+90-18*(t+1))}),e}(n,i,o,t);return{nodes:[...d,...i],edges:e.edges}}({nodes:r,edges:l},t,n);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=pi(e);return["filters:"," and: []","properties:"," file.name:",' displayName: "Name"'," file.folder:",' displayName: "Folder"',"views:"," - type: table",` name: "${di(t)}"`," order:"," - file.name"," - file.folder"].join("\n")}(t)}\n`;let i=o;/^views:/m.test(i)?/^\s*-\s+type:/m.test(i)||(i=i.replace(/^views:\s*$/m,`views:\n${function(e,t){const o=" ".repeat(t);return e.split("\n").map(e=>`${o}${e}`).join("\n")}(ci(),2)}`)):i=`${i}\n\n${["views:",...ci().split("\n")].join("\n")}`;/^\s+order:\s*$/m.test(i)||(i=i.replace(/(^\s*-\s+type:\s+[\w-]+\s*\n\s+name:\s+.+$)/m,"$1\n order:\n - file.name"));return`${i.trim()}\n`}(t,e.sourceText)}function ri(e,t={}){const o=li(e);if(!o)throw new Error(w("AI generated content is empty."));const i=o.replace(/^---\s*\n?/i,"").replace(/\n?---\s*$/i,"").trim();if(!i)throw new Error(w("AI generated content is empty."));const n=function(e,t){if(!t||0===Object.keys(t).length)return e;const o=e.replace(/\r\n?/g,"\n").split("\n"),i=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[,n,a]=o,s=t[n];return s&&s!==n?i.has(s)?e:`${s}:${a}`:e}).join("\n").trim()}(i,t);return`---\n${n}\n---\n\n`}function li(e){return e.trim().replace(/^```(?:json|yaml|yml)?\s*/i,"").replace(/\s*```\s*$/i,"").trim()}function ci(){return["- type: table",' name: "Overview"'," order:"," - file.name"].join("\n")}function di(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function mi(e,t){const o=ui(t),i=hi(o);return{id:bi(void 0,e),type:"text",x:0,y:0,width:i.width,height:i.height,text:o}}function ui(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,...i]=t,n=i.slice(0,4).map(e=>`- ${e.replace(/^[-*+]\s+/,"")}`);return[`# ${gi(o,48)}`,n.length?"":null,...n].filter(e=>null!==e).join("\n")}function pi(e){return gi(e.replace(/\r\n?/g,"\n").split("\n").map(e=>e.trim()).find(Boolean)||w("Untitled"),42)}function hi(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 gi(e,t){const o=e.trim();return o.length<=t?o:`${o.slice(0,Math.max(0,t-1)).trimEnd()}…`}function fi(e,t){if("string"!=typeof e)return;const o=e.trim();return t.has(o)?o:void 0}function bi(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=yi()}while(t.has(o));return t.add(o),o}function yi(){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 Ci(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function wi(e,t,o,i){const n=Ci(e,t);return Math.max(o,Math.min(i,Math.round(n)))}function vi(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(vi(t)||xi(t))break;o--}return o}function Ti(e,t){let o=t;for(;o<e.state.doc.lines;){const t=e.state.doc.line(o+1).text;if(vi(t)||xi(t))break;o++}return o}function Si(e,t,o){const i=[];for(let n=t;n<=o;n++)i.push(e.state.doc.line(n).text);return i.join("\n")}function Ei(e,t,o){let i=t;for(;i>=1&&i<=e.state.doc.lines;){const t=e.state.doc.line(i).text;if(!vi(t)){if(xi(t))return t;return Si(e,ki(e,i),Ti(e,i))}i+=o}return""}function Ii(e,t){const o=new Map;for(let i=1;i<=t;i++){const t=xi(e.state.doc.line(i).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,i){const n=e.state.doc,a=n.length,s=Math.max(0,Math.min(t,a)),r=Math.max(0,Math.min(o,a)),l=s!==r,c=i?.preferBlockWhenCollapsed??!1;let d=s,m=r,u=l?e.state.sliceDoc(s,r):"",p=l?"selection":"cursor";if(!l&&c){const t=n.lineAt(s);if(!vi(t.text)){const o=ki(e,t.number),i=Ti(e,t.number);d=n.line(o).from,m=n.line(i).to,u=e.state.sliceDoc(d,m),u.trim()?p="block":(d=s,m=r)}}const h="cursor"===p?s:d,g=n.lineAt(h),f=m>d?Math.max(d,m-1):d,b=n.lineAt(d).number,y=n.lineAt(f).number,C=ki(e,g.number),w=Ti(e,g.number),v=Si(e,C,w),x=Ii(e,g.number),k=Ei(e,b-1,-1),T=Ei(e,y+1,1),S="cursor"===p?n.line(C).from:Math.max(0,d-1200),E="cursor"===p?n.line(w).to:Math.min(a,m+900),I=e.state.sliceDoc(S,d),A=e.state.sliceDoc(m,E);return{from:d,to:m,selectedText:u,hasSelection:l,source:p,context:[`target_source: ${p}`,`target_lines: ${b}-${y}`,`heading_path: ${x.join(" > ")||"(root)"}`,"surrounding_block:",v,"text_before_target:",I,"text_after_target:",A,"previous_block:",k,"next_block:",T].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(P)??null,this.memRefreshToken=this.secrets.getSecret(D)??null,this.memAiToken=this.secrets.getSecret(O)??null,this.memCustomModelApiKey=this.secrets.getSecret(F)??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(P,e)}setRefreshToken(e){this.memRefreshToken=e,this.supportsSecretStorage&&this.secrets.setSecret(D,e)}setAiToken(e){this.memAiToken=e,this.supportsSecretStorage&&this.secrets.setSecret(O,e)}clearSecrets(){this.memAccessToken=null,this.memRefreshToken=null,this.memAiToken=null,this.memCustomModelApiKey=null,this.supportsSecretStorage&&(this.secrets.setSecret(P,""),this.secrets.setSecret(D,""),this.secrets.setSecret(O,""),this.secrets.setSecret(F,""))}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(F,t)}clearCustomModelApiKey(){this.memCustomModelApiKey=null,this.supportsSecretStorage&&this.secrets.setSecret(F,"")}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(w("Current Obsidian version does not support secure token storage."));if(this.hasPendingOAuthRequest())return this.pendingAuthorizationUrl&&window.open(this.pendingAuthorizationUrl),void new e.Notice(w("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 i=await this.computeCodeChallenge(o),n=new URLSearchParams({response_type:"code",client_id:R,redirect_uri:e.Platform.isMobile?$:_,scope:B,state:t,code_challenge:i,code_challenge_method:"S256"}),a=function(e,t=_o()){if($o(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()}(`${q}?${n.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(w("Login cancelled or timed out."));await this.exchangeCodeForTokens(t,_)?(await this.fetchUserInfo(),new e.Notice(w("Successfully logged in to PKMer!"))):new e.Notice(w("Failed to complete login. Please try again."))}catch(t){console.error("PKMer OAuth login error:",t),new e.Notice(w("Login failed. Please try again."))}finally{this.clearPendingOAuthRequest({closeServer:!0})}}async handleOAuthCallback(t,o){if(!this.isPendingStateMatch(o))return new e.Notice(w("OAuth state mismatch. Please try logging in again.")),this.clearPendingOAuthRequest(),!1;try{return await this.exchangeCodeForTokens(t,$)?(await this.fetchUserInfo(),new e.Notice(w("Successfully logged in to PKMer!")),!0):(new e.Notice(w("Failed to complete login. Please try again.")),!1)}catch(t){return console.error("PKMer OAuth callback error:",t),new e.Notice(w("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(w("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 i=new URL(e.url,`http://localhost:${z}`);if("/editing-toolbar/callback"!==i.pathname)return o.writeHead(404),void o.end();const n=i.searchParams.get("code"),a=i.searchParams.get("state");if(this.isPendingStateMatch(a))if(n)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(n);else{const e=i.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(z,"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 i={grant_type:"authorization_code",code:t,redirect_uri:o,client_id:R};this.pendingCodeVerifier&&(i.code_verifier=this.pendingCodeVerifier);const n=(await e.requestUrl({url:L,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(i).toString()})).json;return!!n.access_token&&(this.setAccessToken(n.access_token),this.setRefreshToken(n.refresh_token||""),this.plugin.settings.ai.pkmer={...this.plugin.settings.ai.pkmer,tokenExpiresAt:Date.now()+1e3*(n.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:L,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:this.memRefreshToken||"",client_id:R}).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:N,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(),Di=o.StateEffect.define(),Oi=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 Fi extends i.WidgetType{constructor(e){super(),this.text=e}eq(e){return this.text===e.text}toDOM(){const e=document.createElement("span");e.className="cm-ai-ghost-text",e.setAttribute("aria-label",w("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),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"),i=e.querySelector(".cm-ai-ghost-rest");if(o&&(o.textContent=t[0]),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 qi extends i.WidgetType{eq(){return!0}toDOM(){const e=document.createElement("span");e.className="cm-ai-loading",e.setAttribute("aria-label",w("AI is generating"));const t=document.createElement("span");t.className="cm-ai-loading-spinner";const o=document.createElement("span");return o.className="cm-ai-loading-label",o.textContent=w("AI thinking"),e.appendChild(t),e.appendChild(o),e}ignoreEvent(){return!0}}const Li=i.EditorView.decorations.compute([Oi],e=>{const t=e.field(Oi);return t?"loading"===t.status?i.Decoration.set([i.Decoration.widget({widget:new qi,side:1}).range(t.pos)]):t.text?i.Decoration.set([i.Decoration.widget({widget:new Fi(t.text),side:1}).range(t.pos)]):i.Decoration.none:i.Decoration.none}),Ni=o.Prec.highest(i.keymap.of([{key:"Tab",run:e=>{const t=e.state.field(Oi);return!!t?.text&&(e.dispatch({changes:{from:t.pos,insert:t.text},selection:{anchor:t.pos+t.text.length},effects:Pi.of(null)}),!0)}}])),Ri=i.keymap.of([{key:"Escape",run:e=>!!e.state.field(Oi)&&(e.dispatch({effects:Pi.of(null)}),!0)}]);function Bi(e,t){const o=i.ViewPlugin.fromClass(class{constructor(e){this.abortController=null,this.autoTriggerTimer=null,this.view=e}update(e){for(const t of e.transactions)for(const e of t.effects)e.is(Di)&&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,i=e.state.doc.lineAt(t);e.state.sliceDoc(i.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 i=this.view.state.selection.main.head,{prefix:n,suffix:a,context:s}=function(e,t){const o=e.state.doc.lineAt(t),i=ki(e,o.number),n=Ti(e,o.number),a=e.state.doc.line(i).from,s=e.state.doc.line(n).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),m=Ei(e,i-1,-1),u=Ei(e,n+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: ${i}-${n}`,`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:",m,"next_block:",u].join("\n")}}(this.view,i);let r="";this.view.dispatch({effects:Pi.of({pos:i,text:"",status:"loading"})});try{for await(const e of o.complete({prefix:n,suffix:a,context:s},t)){if(t.aborted)return;if(r+=e,this.view.state.selection.main.head!==i)return void this.abortController.abort();this.view.dispatch({effects:Pi.of({pos:i,text:r,status:"ready"})})}r||this.view.dispatch({effects:Pi.of(null)})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;Bo(e)||console.error("[AI Completion] Error:",e),this.view.dispatch({effects:Pi.of(null)})}}destroy(){this.abortController?.abort(),this.autoTriggerTimer&&clearTimeout(this.autoTriggerTimer)}});return[Oi,Li,Ni,Ri,o]}const _i=o.StateEffect.define(),$i=o.StateEffect.define(),zi=o.StateEffect.define(),Ui=o.StateEffect.define();function Vi(e,t,o){const i=document.createElement("button");return i.className=`cm-ai-btn ${t}`,i.textContent=e,i.addEventListener("click",o),i}function Hi(t,n){const a=()=>({createGeneratedArtifact:(n?.()??{}).createGeneratedArtifact}),s=o.StateField.define({create:()=>({operation:null,resultTooltip:null}),update(t,o){let i=t.operation;for(const e of o.effects)e.is(_i)&&(i={phase:"streaming",params:e.value,result:""}),e.is($i)&&i&&(i={...i,result:e.value}),e.is(zi)&&i&&(i={...i,phase:"done"}),e.is(Ui)&&(i=null);o.docChanged&&i&&(i={...i,params:{...i.params,from:o.changes.mapPos(i.params.from),to:o.changes.mapPos(i.params.to)}});let n=null;return i&&(n=t.resultTooltip&&t.resultTooltip.pos===i.params.from?t.resultTooltip:{pos:i.params.from,above:!1,create:t=>function(t,o,i){const n=document.createElement("div");n.className="cm-ai-result-panel",n.dataset.phase="streaming";let a=null;n.addEventListener("mousedown",e=>{e.target.closest(".cm-ai-result-content")||e.preventDefault()});const s=document.createElement("div");s.className="cm-ai-result-header",s.textContent=w("AI is writing..."),n.appendChild(s);const r=document.createElement("div");r.className="cm-ai-result-content",n.appendChild(r);const l=document.createElement("div");function c(){n.style.display="none"}function d(){null!==a&&(window.clearTimeout(a),a=null),b.textContent=w("Copy to Clipboard")}async function m(n){const a=t.state.field(o);if(!a.operation?.params.artifactKind)return;const s=i().createGeneratedArtifact;if(s)try{const e=await s({kind:a.operation.params.artifactKind,content:a.operation.result,sourceText:a.operation.params.originalText});if(c(),t.dispatch({effects:Ui.of(void 0)}),"embed"===n){const o=a.operation.params.from===a.operation.params.to?e.embedSyntax:`\n\n${e.embedSyntax}`,i=a.operation.params.to;t.dispatch({changes:{from:i,insert:o},selection:{anchor:i+o.length}})}t.focus()}catch(t){const o=t instanceof Error&&t.message?t.message:w("Failed to create AI file.");new e.Notice(o),console.error("[AI Artifact] Failed to create file:",t)}else new e.Notice(w("AI file creation is unavailable."))}function u(){const e=t.state.field(o).operation;return"base"===e?.params.artifactKind||"canvas"===e?.params.artifactKind}function p(){return"frontmatter"===t.state.field(o).operation?.params.artifactKind}function h(){const i=t.state.field(o);if(i.operation)try{const e=ri(i.operation.result,i.operation.params.preferredFrontmatterKeys);c(),t.dispatch({effects:Ui.of(void 0)}),t.dispatch({changes:{from:i.operation.params.from,to:i.operation.params.to,insert:e},selection:{anchor:e.length}}),t.focus()}catch(t){const o=t instanceof Error&&t.message?t.message:w("Failed to apply frontmatter.");new e.Notice(o)}}l.className="cm-ai-result-actions",l.style.display="none";const g=Vi(w("Replace"),"cm-ai-btn-primary",()=>{if(u())return void m("create");if(p())return void h();const e=t.state.field(o);if(!e.operation)return;const{from:i,to:n}=e.operation.params,a=e.operation.result;c(),t.dispatch({effects:Ui.of(void 0)}),t.dispatch({changes:{from:i,to:n,insert:a},selection:{anchor:i+a.length}}),t.focus()}),f=Vi(w("Insert below"),"cm-ai-btn-secondary",()=>{if(u())return void m("embed");if(p())return void h();const e=t.state.field(o);if(!e.operation)return;const{to:i}=e.operation.params,n=e.operation.result;c(),t.dispatch({effects:Ui.of(void 0)}),t.dispatch({changes:{from:i,insert:`\n\n${n}`},selection:{anchor:i+n.length+2}}),t.focus()}),b=Vi(w("Copy to Clipboard"),"cm-ai-btn-secondary",()=>{const i=t.state.field(o),n=i.operation?.result;n&&navigator.clipboard.writeText(n).then(()=>{null!==a&&window.clearTimeout(a),b.textContent=w("Copied!"),a=window.setTimeout(()=>{a=null,b.textContent=w("Copy to Clipboard")},1500)}).catch(t=>{console.error("[AI Rewrite] Failed to copy result:",t),new e.Notice(t instanceof Error&&t.message?t.message:w("Copy to Clipboard"))})}),y=Vi(w("Try again"),"cm-ai-btn-secondary",()=>{const e=t.state.field(o);e.operation&&(d(),t.dispatch({effects:_i.of(e.operation.params)}))}),C=Vi(w("Discard"),"cm-ai-btn-danger",()=>{d(),c(),t.dispatch({effects:Ui.of(void 0)}),t.focus()});return l.append(g,f,b,y,C),n.appendChild(l),{dom:n,update(e){const t=e.state.field(o);if(!t.operation)return n.style.display="none",void(n.dataset.phase="idle");n.style.display="",n.dataset.phase=t.operation.phase,r.textContent=t.operation.result||"","base"===t.operation.params.artifactKind||"canvas"===t.operation.params.artifactKind?(s.textContent=w("AI file suggestion"),g.textContent=w("Create"),f.textContent=w("Create & Embed"),f.style.display=""):"frontmatter"===t.operation.params.artifactKind?(s.textContent=w("AI frontmatter suggestion"),g.textContent=t.operation.params.from===t.operation.params.to?w("Insert frontmatter"):w("Replace frontmatter"),f.style.display="none"):(g.textContent=t.operation.params.from===t.operation.params.to?w("Insert at cursor"):w("Replace"),f.textContent=w("Insert below"),f.style.display=""),"done"===t.operation.phase?("base"!==t.operation.params.artifactKind&&"canvas"!==t.operation.params.artifactKind&&"frontmatter"!==t.operation.params.artifactKind&&(s.textContent=w("AI suggestion")),b.style.display="",l.style.display="flex"):(d(),s.textContent=w("AI is writing..."),l.style.display="none")},destroy(){null!==a&&window.clearTimeout(a)}}}(t,s,a)}),{operation:i,resultTooltip:n}},provide:e=>i.showTooltip.from(e,e=>e.resultTooltip??null)}),r=i.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(_i)&&this.startStreaming(e.value),e.is(Ui)&&this.abortController?.abort()}async startStreaming(e){this.abortController?.abort(),this.abortController=new AbortController;const o=this.abortController.signal,i=t();if(!i)return;let n="";try{for await(const t of i.rewrite({selectedText:e.originalText,instruction:e.instruction,customPrompt:e.customPrompt,context:e.context,artifactKind:e.artifactKind},o)){if(o.aborted)return;n+=t,this.view.dispatch({effects:$i.of(n)})}this.view.dispatch({effects:zi.of(void 0)})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;Bo(e)||console.error("[AI Rewrite] Error:",e),this.view.dispatch({effects:Ui.of(void 0)})}}destroy(){this.abortController?.abort()}}),l=o.Prec.highest(i.keymap.of([{key:"Ctrl-Shift-Space",run:e=>{const{from:t,to:o}=e.state.selection.main;return t!==o&&(function(e,t,o){const{from:i,to:n}=e.state.selection.main;if(i===n)return;const a=Ai(e,i,n);e.dispatch({effects:_i.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 Wi=i.EditorView.baseTheme({".cm-ai-loading":{display:"inline-flex",alignItems:"center",gap:"6px",marginLeft:"6px",color:"var(--text-muted)",opacity:"0.85",pointerEvents:"none",userSelect:"none",fontSize:"12px",whiteSpace:"nowrap"},".cm-ai-loading-spinner":{width:"10px",height:"10px",border:"1.5px solid currentColor",borderRightColor:"transparent",borderRadius:"999px",animation:"cm-ai-spin 0.8s linear infinite",flexShrink:"0"},".cm-ai-loading-label":{letterSpacing:"0.01em"},".cm-ai-loading-pill":{gap:"5px",marginLeft:"8px",padding:"2px 8px",borderRadius:"999px",border:"1px solid var(--background-modifier-border)",background:"color-mix(in srgb, var(--background-secondary) 76%, transparent)",color:"var(--text-faint)",opacity:"1",fontSize:"11px",lineHeight:"1.2",verticalAlign:"middle",backdropFilter:"blur(6px)"},".cm-ai-loading-pill .cm-ai-loading-spinner":{width:"8px",height:"8px",borderWidth:"1.25px",opacity:"0.9"},".cm-ai-loading-pill .cm-ai-loading-label":{fontWeight:"500",letterSpacing:"0.02em"},"&dark .cm-ai-loading-pill":{background:"color-mix(in srgb, var(--background-secondary-alt) 72%, transparent)",borderColor:"var(--background-modifier-border-hover)"},".cm-ai-ghost-text":{color:"#999",fontStyle:"italic",pointerEvents:"none",userSelect:"none"},".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",marginBottom:"8px",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"},".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)"}});class ji{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 oi(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(!zo())return;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(w("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(!zo())return new e.Notice(w("AI settings are currently available only in Simplified and Traditional Chinese.")),!1;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(w("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 ti(this.plugin.app,{source:e}).openAndWait()}createExtension(){return[Bi((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}),getRewriteConfig:()=>({actions:M,minSelectionLength:this.plugin.settings.ai.rewriteMinSelectionLength,showToolbarOnSelection:!1,createGeneratedArtifact:e=>this.createGeneratedArtifact(e)})}).getService,e.getCompletionConfig),Hi(e.getService,e.getRewriteConfig),Wi];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(`${w("PKMer quota refreshed:")} ${Number((t.quota/5e5).toFixed(2))}`):new e.Notice(w("Unable to refresh PKMer quota."))}getPKMerStatusText(){const e=this.plugin.settings.ai.pkmer.userInfo;if(!e)return w("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(`${w("Quota")}: ${Number((e.ai_quota.quota/5e5).toFixed(2))}`),t.join(" / ")||w("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?w("Current route: PKMer AI. If unavailable, it falls back to your custom model."):e?w("Current route: PKMer AI."):t?w("Current route: Custom model."):this.plugin.settings.ai.enableCustomModel?w("No provider available. Log in to PKMer or complete the custom model settings."):w("No provider available. Log in to PKMer to enable AI.")}catch(e){return console.error("[AI Settings] Failed to determine provider route:",e),w("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(w("Please fill in the required custom model settings first.")),!1;new e.Notice(w("Testing custom model connection..."));try{await this.aiService.testCustomProviderConnection();const t=this.plugin.settings.ai.customModel.model.trim();return new e.Notice(`${w("Custom model connection succeeded.")} ${t}`.trim()),!0}catch(t){const o=Ro(t);return new e.Notice(`${w("Custom model connection failed:")} ${o}`),!1}}async listCustomOllamaModels(){return this.aiService.listCustomOllamaModels()}triggerInlineCompletion(t){if(!this.plugin.settings.ai.enabled)return new e.Notice(w("AI features are disabled in settings.")),!1;if(!this.plugin.settings.ai.enableInlineCompletion)return new e.Notice(w("Inline completion is disabled in settings.")),!1;const o=this.getEditorView(t);return o?(o.dispatch({effects:Di.of(void 0)}),!0):(new e.Notice(w("Current editor does not support AI inline completion.")),!1)}async startRewrite(t,o="improve",i,n){if(!this.plugin.settings.ai.enabled)return new e.Notice(w("AI features are disabled in settings.")),!1;const a=this.resolveEditor(t);if(!a)return new e.Notice(w("Please select text first")),!1;const s=this.getEditorView(a);if(!s)return new e.Notice(w("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:"custom"===o});return s.dispatch({effects:_i.of({from:c.from,to:c.to,originalText:c.selectedText,instruction:o,customPrompt:i,context:c.context,artifactKind:n?.artifactKind})}),!0}async runToolboxAction(e,t){const o=function(e){switch(e){case"list":return[G,"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[G,"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[G,Z,"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[G,"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[G,J,"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 i=function(e){if("base"===e||"canvas"===e||"frontmatter"===e)return e}(t);return this.startRewrite(e,"custom",o,{artifactKind:i})}async startFrontmatterGeneration(t,o){if(!this.plugin.settings.ai.enabled)return new e.Notice(w("AI features are disabled in settings.")),!1;const i=this.resolveEditor(t),n=this.getEditorView(i);if(!i||!n)return new e.Notice(w("Current editor does not support AI rewrite.")),!1;const a=i.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),n.dispatch({effects:_i.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),i=this.collectFrontmatterStats(o,6),n=this.shouldFallbackToVaultFrontmatterStats(i),a=n?this.getVaultFrontmatterStats(t):this.createEmptyFrontmatterStats(),s=this.buildPreferredFrontmatterAliases(i.keyCounts,a.keyCounts),r=[];if(i.examples.length>0){const t=[...i.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:",...i.examples].join("\n"))}const l=n?[...a.keyCounts.entries()].sort((e,t)=>t[1]-e[1]).slice(0,14).map(([e,t])=>`- ${e} (${t})`).join("\n"):"";n&&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,i=[];let n=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(n+=1,r.forEach(([e])=>{o.set(e,(o.get(e)??0)+1)}),t>0&&i.length<t){const e=r.map(([e,t])=>` ${e}: ${this.serializeFrontmatterValue(t)}`).join("\n");i.push(`${a.basename}:\n${e}`)}t>0&&i.length}}return{keyCounts:o,examples:i,fileCount:n}}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 i=this.collectFrontmatterStats(e,0);return this.vaultFrontmatterStatsCache={expiresAt:t+6e5,sourceFileCount:e.length,stats:i},i}invalidateFrontmatterStatsCache(){this.vaultFrontmatterStatsCache=null}shouldFallbackToVaultFrontmatterStats(e){const t=e.keyCounts.size,o=e.fileCount>=6,i=e.fileCount>=3&&t>=6,n=this.hasStrongSiblingAliasSignal(e.keyCounts);return!(o||i||n)}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"]],i={};for(const n of o){const o=n.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)&&(i[e.key]=a.key)})}return i}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(),i=o?.parent?.path&&"/"!==o.parent.path?o.parent.path:"",n=(o?.basename||w("Untitled")).trim().replace(/[\\/:*?"<>|]/g," ").replace(/\s+/g," ").trim()||w("Untitled"),a="canvas"===t.kind?"canvas":"base",s="canvas"===t.kind?w("AI Canvas File"):w("AI Base File"),r=await this.getAvailableArtifactPath(i,`${n} ${s}`,a),l=si(t);return await this.plugin.app.vault.create(r,l),new e.Notice(`${w("Created AI file:")} ${r}`),{path:r,embedSyntax:`![[${r}]]`}}async getAvailableArtifactPath(e,t,o){let i=0;for(;i<200;){const n=`${t}${0===i?"":` ${i+1}`}.${o}`,a=e?`${e}/${n}`:n;if(!this.plugin.app.vault.getAbstractFileByPath(a))return a;i+=1}throw new Error(w("Unable to allocate a file name for the generated artifact."))}openCustomRewrite(t){const o=this.resolveEditor(t),i=this.getEditorView(o);return o&&i?(this.inlineCustomPromptEditor=o,this.renderInlineCustomPrompt(o,i),!0):(new e.Notice(w("Current editor does not support AI rewrite.")),!1)}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){const i=o.dom.ownerDocument;if(!this.inlineCustomPromptEl){const n=i.createElement("div");n.className="editing-toolbar-ai-inline-prompt";const a=i.createElement("div");a.className="editing-toolbar-ai-inline-prompt-header";const s=i.createElement("div");s.className="editing-toolbar-ai-inline-prompt-title",s.textContent=w("AI Custom Rewrite");const r=i.createElement("button");r.type="button",r.className="editing-toolbar-ai-inline-prompt-close",r.title=w("Close"),r.textContent="×",a.append(s,r);const l=i.createElement("textarea");l.className="editing-toolbar-ai-inline-prompt-input",l.placeholder=w("Please enter your custom AI instruction"),l.rows=3,l.wrap="soft";const c=i.createElement("div");c.className="editing-toolbar-ai-inline-prompt-hint";const d=e.Platform.isMobileApp?w("Enter inserts a newline. Tap Send to submit."):w("Press Enter to send, Shift+Enter for newline, Esc to close.");c.textContent=d+" "+w("If nothing is selected, AI will use the current block or cursor context.");const m=i.createElement("div");m.className="editing-toolbar-ai-inline-prompt-actions";const u=i.createElement("button");u.type="button",u.className="editing-toolbar-ai-inline-prompt-action",u.textContent=w("Cancel");const p=i.createElement("button");p.type="button",p.className="editing-toolbar-ai-inline-prompt-action mod-cta",p.textContent=w("Send"),m.append(u,p),n.append(a,l,c,m),i.body.appendChild(n);const h=()=>{l.style.height="0px",l.style.height=String(Math.min(Math.max(l.scrollHeight,72),180))+"px"},g=()=>{this.closeInlineCustomPrompt(),t.focus()},f=async()=>{const o=l.value.trim();if(!o)return;if("unavailable"===await this.getToolbarRouteState())return void new e.Notice(await this.getProviderRouteStatusText());await this.startRewrite(this.inlineCustomPromptEditor??t,"custom",o)&&this.closeInlineCustomPrompt()},b=()=>this.positionInlineCustomPrompt(t,o),y=()=>{p.disabled=0===l.value.trim().length};r.addEventListener("click",g),u.addEventListener("click",g),p.addEventListener("click",()=>{f()}),l.addEventListener("input",()=>{h(),y(),b()}),l.addEventListener("keydown",t=>"Escape"===t.key?(t.preventDefault(),void g()):"Enter"===t.key&&(t.metaKey||t.ctrlKey)?(t.preventDefault(),void f()):void(e.Platform.isMobileApp||"Enter"!==t.key||t.shiftKey||(t.preventDefault(),f())));const C=i.defaultView??window;C.addEventListener("resize",b),i.addEventListener("scroll",b,!0),this.inlineCustomPromptCleanup=[()=>C.removeEventListener("resize",b),()=>i.removeEventListener("scroll",b,!0)],this.inlineCustomPromptEl=n,this.inlineCustomPromptTextarea=l,h(),y()}this.positionInlineCustomPrompt(t,o),this.inlineCustomPromptTextarea?.focus()}positionInlineCustomPrompt(e,t){if(!this.inlineCustomPromptEl)return;const o=t.dom.ownerDocument.defaultView??window,i=e.getCursor("to"),n=e.posToOffset(i),a=t.coordsAtPos(n);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}}let Ki;const Yi=["top","following","fixed","mobile"],Gi=["toolbarBackgroundColor","toolbarIconColor","toolbarIconSize","aestheticStyle"];function Zi(e,t){e.appearanceByStyle&&"object"==typeof e.appearanceByStyle||(e.appearanceByStyle={});const o=e.appearanceByStyle;Yi.forEach(e=>{o[e]&&"object"==typeof o[e]||(o[e]={})}),t&&Gi.forEach(t=>{const i=e[t];void 0!==i&&Yi.forEach(e=>{const n=o[e];t in n||(n[t]=i)})})}class Ji 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.handleEditorContextMenu=(e,t,o)=>{this.addEditorContextSubmenu(e,w("Text Tools"),"whole-word",this.buildTextContextActions(t)),zo()&&this.addEditorContextSubmenu(e,w("AI Tools"),"sparkles",this.buildAIContextActions(t))},this.handleeditingToolbar=()=>{if(this.formatBrushActive||Ki.body.classList.remove("format-brush-cursor"),!this.settings.cMenuVisibility)return void["top","following","fixed"].forEach(e=>{const t=te(this.app,this,e);t&&(t.style.display="none")});const t=this.app.workspace.getActiveViewOfType(e.ItemView);if(!j.isAllowedViewType(t))return void["top","following","fixed"].forEach(e=>{const t=te(this.app,this,e);t&&(t.style.visibility="hidden")});const o=t?.getViewType(),i="markdown"===o,n=i&&j.isSourceMode(t);if(i&&!n)return void["top","following","fixed"].forEach(e=>{const t=te(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=te(this.app,this,e);if(!t){o&&(o.style.visibility="hidden");continue}o||Ce(this.app,this,e);const i=te(this.app,this,e);i&&(i.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(!j.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){X=e.requireApiVersion("0.15.0")?activeWindow.document:window.document;const o=X,i=o.querySelectorAll(".editingToolbarModalBar"),n=o.querySelectorAll(".editingToolbarPopoverBar");i.forEach(e=>{e.firstChild&&e.removeChild(e.firstChild),e.remove()}),n.forEach(e=>{e.firstChild&&e.removeChild(e.firstChild),e.remove()}),t&&t.clearToolbarCache()}(this),Ce(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;Zi(e,t);const o=e.appearanceByStyle,i=()=>{const t=this.appearanceEditStyle||this.positionStyle||e.positionStyle||"top";return Yi.includes(t)?t:"top"};Gi.forEach(t=>{if(!(t in e))return;const n=e[t];Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const e=i(),a=o[e];return a&&Object.prototype.hasOwnProperty.call(a,t)?a[t]:n},set(o){const n=i();Zi(e,!1);e.appearanceByStyle[n][t]=o}})})}removeToolbarCommandById(e,t){if(Array.isArray(e))for(let o=e.length-1;o>=0;o--){const i=e[o];i&&"object"==typeof i&&(i.id!==t?Array.isArray(i.SubmenuCommands)&&this.removeToolbarCommandById(i.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,K),this.settings.ai.enabled&&zo()&&e.unshift({id:K,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,i,n){n.length&&t.addItem(t=>{t.setTitle(o).setIcon(i),!e.requireApiVersion("0.15.0")||t.setSection("info");const a=t.setSubmenu();n.forEach(e=>this.addEditorContextAction(a,e))})}buildTextContextActions(e){const t=[],o=e.somethingSelected(),i=e.getCursor(),n=e.getLine(i.line),a=/^\d+\.\s/.test(n),s=n.includes("|");return o&&t.push({title:w("Split Lines"),commandId:"split-lines"},{title:w("Merge Lines"),commandId:"merge-lines"},{title:w("Full Half Converter"),commandId:"smart-symbols"},{title:w("Dedupe Lines"),commandId:"dedupe-lines"},{title:w("Add Prefix/Suffix"),commandId:"add-wrap"},{title:w("Number Lines (Custom)"),commandId:"number-lines"},{title:w("Trim Line Ends"),commandId:"remove-whitespace-trim"},{title:w("Shrink Extra Spaces"),commandId:"remove-whitespace-compress"},{title:w("Remove All Whitespace"),commandId:"remove-whitespace-all"},{title:w("Extract Between Strings"),commandId:"extract-between"},{title:w("List to Table"),commandId:"list-to-table"},{title:w("Table to List"),commandId:"table-to-list"}),o||t.push({title:w("Add Prefix/Suffix"),commandId:"add-wrap"},{title:w("Insert Blank Lines"),commandId:"insert-blank-lines"},{title:w("Extract Between Strings"),commandId:"extract-between"}),a&&t.push({title:w("Renumber List"),commandId:"renumber-ordered-list"}),!o&&s&&t.push({title:w("Table to List"),commandId:"table-to-list"}),t.length||t.push({title:w("Select text to see more tools"),disabled:!0}),t}buildAIContextActions(t){if(!zo())return[];if(!this.settings.ai.enabled)return[{title:w("Enable AI Editor"),callback:()=>this.openPluginSettingsTab()}];const o=t.somethingSelected(),i=e.Platform.isMobileApp,n=[{title:w("Trigger AI Inline Completion"),commandId:"ai-inline-completion"}],a=[{title:w("Improve writing"),commandId:"ai-rewrite-improve"},{title:w("Fix spelling & grammar"),commandId:"ai-rewrite-fix-grammar"},{title:w("Summarize"),commandId:"ai-rewrite-summarize"},{title:w("Explain this"),commandId:"ai-rewrite-explain"},{title:w("Continue writing"),commandId:"ai-rewrite-continue"},{title:w("AI Custom Rewrite"),commandId:"ai-rewrite-custom"},{title:w("Convert to list"),commandId:"ai-toolbox-list"},{title:w("Convert to table"),commandId:"ai-toolbox-table"},{title:w("Generate frontmatter"),commandId:"ai-toolbox-frontmatter"},{title:w("Convert to canvas"),commandId:"ai-toolbox-canvas"}];return o||i?[...n,...a]:[...n,{title:w("Continue writing"),commandId:"ai-rewrite-continue"},{title:w("AI Custom Rewrite"),commandId:"ai-rewrite-custom"},{title:w("Generate frontmatter"),commandId:"ai-toolbox-frontmatter"},{title:w("Convert to canvas"),commandId:"ai-toolbox-canvas"}]}async onload(){const t=this.manifest.version;console.log("editingToolbar v"+t+" loaded"),Ki=e.requireApiVersion("0.15.0")?activeWindow.document:window.document,await this.loadSettings(),this.aiManager=new ji(this),this.aiManager.onload(),e.requireApiVersion("0.15.0")&&"function"==typeof this.registerEditorExtension&&this.registerEditorExtension(this.aiManager.createExtension()),this.initPerStyleAppearance(),this.settingTab=new Wo(this.app,this),this.addSettingTab(this.settingTab),this.commandsManager=new ei(this),this.commandsManager.registerCommands();const o=this.commandsManager.getActiveEditor();this.app.workspace.onLayoutReady(()=>{this.statusBar=new Ko(this),this.statusBar.init(),setTimeout(()=>{this.settings.cMenuVisibility||this.handleeditingToolbar()},100),setTimeout(()=>{zo()&&this.aiManager.maybeShowAIOnboarding()},1200)}),this.init_evt(Ki,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()&&Ce(this.app,this,"following",e.doc);(this.settings.enableFixedToolbar||!this.settings.enableTopToolbar&&!this.settings.enableFollowingToolbar&&"fixed"===this.positionStyle)&&Ce(this.app,this,"fixed",e.doc)},50)});const i=this.settings?.lastVersion||"0.0.0",n=e=>{const t=e.split(".").map(e=>parseInt(e));return{major:t[0]||0,minor:t[1]||0,patch:t[2]||0}},a=n(i);n(t);const s=new To(this.app,this),r="0.0.0"===i;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(Ki,"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("url-menu",(e,t,o)=>{e.addItem(e=>e.setTitle("Edit Link(Modal)").setSection("info").setIcon("link").onClick(()=>{new Jo(this).open()}))})),Object.keys(jo).forEach(t=>{e.addIcon(t,jo[t])}),this.toolbarIconSize=this.settings.toolbarIconSize,this.positionStyle=this.settings.positionStyle,Ki.documentElement.style.setProperty("--editing-toolbar-background-color",this.settings.toolbarBackgroundColor),Ki.documentElement.style.setProperty("--editing-toolbar-icon-color",this.settings.toolbarIconColor),Ki.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(),ee(this),console.log("editingToolbar unloaded")}isView(){const t=this.app.workspace.getActiveViewOfType(e.ItemView);return j.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?.customModel?.baseUrl?.trim?.()||e?.ai?.customModel?.model?.trim?.()||e?.ai?.customModel?.apiKey?.trim?.());this.settings=Object.assign({},W,e),this.settings.ai={...W.ai,...e?.ai||{},enableCustomModel:e?.ai?.enableCustomModel??t,pkmerModelRouting:{...W.ai.pkmerModelRouting,...e?.ai?.pkmerModelRouting||{}},pkmer:{...W.ai.pkmer,...e?.ai?.pkmer||{}},customModel:{...W.ai.customModel,...e?.ai?.customModel||{}}};const o=e?.ai;if(void 0===o?.consentAccepted&&!0===o?.enabled&&(this.settings.ai.consentAccepted=!0),void 0!==o&&void 0===o?.onboardingShown&&(this.settings.ai.onboardingShown=!0),void 0===o?.pkmerModelRouting&&o?.pkmerModel?.trim?.()){const e=o.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 i=o;switch(i||(i=this.settings.isLoadOnMobile&&e.Platform.isMobileApp?"mobile":this.positionStyle),i){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,i="";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,i=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(),i=t.getLine(e.line),n=e.ch,a=[],s=/<u>([^<]+)<\/u>/g;let r;for(;null!==(r=s.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editing-toolbar:toggle-underline",name:"Underline",distance:Math.min(n-e,t-n)})}const l=/<center>([^<]+)<\/center>/g;for(;null!==(r=l.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editing-toolbar:center",name:"Center",distance:Math.min(n-e,t-n)})}const c=/<p align="left">([^<]+)<\/p>/g;for(;null!==(r=c.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editing-toolbar:left",name:"Left Align",distance:Math.min(n-e,t-n)})}const d=/<p align="right">([^<]+)<\/p>/g;for(;null!==(r=d.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editing-toolbar:right",name:"Right Align",distance:Math.min(n-e,t-n)})}const m=/<p align="justify">([^<]+)<\/p>/g;for(;null!==(r=m.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editing-toolbar:justify",name:"Justify",distance:Math.min(n-e,t-n)})}const u=/<sup>([^<]+)<\/sup>/g;for(;null!==(r=u.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editing-toolbar:superscript",name:"Superscript",distance:Math.min(n-e,t-n)})}const p=/<sub>([^<]+)<\/sub>/g;for(;null!==(r=p.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editing-toolbar:subscript",name:"Subscript",distance:Math.min(n-e,t-n)})}const h=/\*\*([^*]+)\*\*/g;for(;null!==(r=h.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editor:toggle-bold",name:"Bold",distance:Math.min(n-e,t-n)})}const g=/~~([^~]+)~~/g;for(;null!==(r=g.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editor:toggle-strikethrough",name:"Strikethrough",distance:Math.min(n-e,t-n)})}const f=/==([^=]+)==/g;for(;null!==(r=f.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editor:toggle-highlight",name:"Highlight",distance:Math.min(n-e,t-n)})}const b=/`([^`]+)`/g;for(;null!==(r=b.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editor:toggle-code",name:"Code",distance:Math.min(n-e,t-n)})}const y=/<font color="([^"]+)">([^<]+)<\/font>/g;for(;null!==(r=y.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editing-toolbar:change-font-color",name:"Font Color",distance:Math.min(n-e,t-n)})}const C=/<span style="background:([^"]+)">([^<]+)<\/span>/g;for(;null!==(r=C.exec(i));){const e=r.index,t=r.index+r[0].length;n>e&&n<t&&a.push({command:"editing-toolbar:change-background-color",name:"Background Color",distance:Math.min(n-e,t-n)})}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(i));)this.lastExecutedCommand="editor:toggle-italics",this.lastExecutedCommandName="Italic",o=!0}o||(/^# /.test(i)&&n>0?(this.lastExecutedCommand="editor:set-heading-1",this.lastExecutedCommandName="Heading 1",o=!0):/^## /.test(i)&&n>1?(this.lastExecutedCommand="editor:set-heading-2",this.lastExecutedCommandName="Heading 2",o=!0):/^### /.test(i)&&n>2?(this.lastExecutedCommand="editor:set-heading-3",this.lastExecutedCommandName="Heading 3",o=!0):/^#### /.test(i)&&n>3?(this.lastExecutedCommand="editor:set-heading-4",this.lastExecutedCommandName="Heading 4",o=!0):/^##### /.test(i)&&n>4?(this.lastExecutedCommand="editor:set-heading-5",this.lastExecutedCommandName="Heading 5",o=!0):/^###### /.test(i)&&n>5&&(this.lastExecutedCommand="editor:set-heading-6",this.lastExecutedCommandName="Heading 6",o=!0))}o||this.lastExecutedCommand?(this.formatBrushActive=!this.formatBrushActive,this.formatBrushActive?(Ki.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=i,this.formatBrushNotice&&this.formatBrushNotice.hide(),this.formatBrushNotice=new e.Notice(w("Format brush ON! Select text to apply【")+this.lastExecutedCommandName+w("】format"),0)):(Ki.body.classList.remove("format-brush-cursor"),this.formatBrushNotice&&(this.formatBrushNotice.hide(),this.formatBrushNotice=null))):new e.Notice(w("Please execute a format command or select format text first, then enable the format brush"))}applyCalloutFormat(e,t,o){const i=`> [!${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(i)}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,Ki.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 i=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",()=>{i()}):this.registerDomEvent(t,"mouseup",e=>{1!==e.button&&i()}),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}),fe(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=te(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?be(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(...i){const n=this;o||(e.apply(n,i),o=!0,setTimeout(()=>o=!1,t))}}showFollowingToolbar(e){if(!this.isFollowingToolbarActive())return;const t=this.getToolbarHostDocument(e),o=te(this.app,this,"following",t);o?(o.style.visibility="visible",o.classList.add("editingToolbarFlex"),o.classList.remove("editingToolbarGrid"),ye(this.app,this.toolbarIconSize,this,e,!0,t)):ye(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(w("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(w("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(w("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(w("Mobile style commands successfully initialized")))}this.toolbarIconSize=this.settings.toolbarIconSize;const i=Ki??document;i&&i.documentElement&&(i.documentElement.style.setProperty("--editing-toolbar-background-color",this.settings.toolbarBackgroundColor),i.documentElement.style.setProperty("--editing-toolbar-icon-color",this.settings.toolbarIconColor),i.documentElement.style.setProperty("--toolbar-icon-size",`${this.settings.toolbarIconSize}px`)),dispatchEvent(new Event("editingToolbar-NewCommand")),this.appearanceEditStyle=o}}module.exports=Ji;
|
||
|
||
|
||
/* nosourcemap */ |