Oscar Plaisant 5b65eb2b2a update
2024-10-01 11:38:50 +02:00

2 lines
104 KiB
JavaScript

"use strict";var e,t,s,i,n=require("obsidian"),a=require("electron");!function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.FolderOnly=2]="FolderOnly",e[e.FolderWithFilename=3]="FolderWithFilename",e[e.FolderPathFilenameOptional=4]="FolderPathFilenameOptional"}(e||(e={})),function(e){e[e.Standard=1]="Standard",e[e.EditorList=2]="EditorList",e[e.SymbolList=4]="SymbolList",e[e.WorkspaceList=8]="WorkspaceList",e[e.HeadingsList=16]="HeadingsList",e[e.BookmarksList=32]="BookmarksList",e[e.CommandList=64]="CommandList",e[e.RelatedItemsList=128]="RelatedItemsList",e[e.VaultList=256]="VaultList"}(t||(t={})),function(e){e[e.Link=1]="Link",e[e.Embed=2]="Embed",e[e.Tag=4]="Tag",e[e.Heading=8]="Heading",e[e.Callout=16]="Callout",e[e.CanvasNode=32]="CanvasNode"}(s||(s={})),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heading=2]="Heading",e[e.Block=4]="Block"}(i||(i={}));const o={};o[s.Link]="🔗",o[s.Embed]="!",o[s.Tag]="#",o[s.Heading]="H";const r={};var l,d,c;function h(e,t,s){let i=!1;return e&&void 0!==e[t]&&(i=!0,void 0!==s&&s!==e[t]&&(i=!1)),i}function m(e){return h(e,"type",l.SymbolList)}function u(e){return h(e,"type",l.HeadingsList)}function g(e){return h(e,"type",l.File)}function p(e){return h(e,"type",l.Alias)}function f(e){return h(e,"type",l.Unresolved)}function y(e){return e&&!(g(t=e)||f(t)||p(t));var t}function b(e){return h(e,"level")}function S(e){return h(e,"type","callout")}function k(e){return h(e,"extension")}function v(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function L(e,t){return e?.internalPlugins?.getEnabledPluginById(t)}function C(e){const t=function(e,t){return e?.internalPlugins?.getPluginById(t)}(e,"switcher");return t?.instance}function w(e){let t=null;if(e){const s=n.normalizePath(e),i=s.lastIndexOf("/");t=-1===i?s:s.slice(i+1)}return t}function I(e){e=e??[];const t=[];for(const s of e)try{const e=new RegExp(s);t.push(e)}catch(e){console.log(`Switcher++: error creating RegExp from string: ${s}`,e)}return e=>{for(const s of t)if(s.test(e))return!0;return!1}}function T(e){let t=i.None;if(e){const s=e.link.split("|")[0];t=s.includes("#^")?i.Block:s.includes("#")?i.Heading:i.Normal}return t}function E(e,t){let s=null;const i=t.getAbstractFileByPath(e);return k(i)&&(s=i),s}function F(e,t,s,i,a){let o=null;if(a=Object.assign({useBasenameAsAlias:!0,useHeadingAsAlias:!0},a),s){let r=function(e){let t=null;[l.Alias,l.Bookmark,l.HeadingsList,l.SymbolList,l.RelatedItemsList,l.EditorList,l.File].includes(e.type)&&(t=e.file);return t}(s),d=null,c=null;switch(s.type){case l.Unresolved:o=x(s.linktext);break;case l.Alias:d=s.alias;break;case l.Bookmark:{const{item:e}=s;"file"===e.type&&e.title&&(d=e.title);break}case l.HeadingsList:{const{heading:e}=s.item;({subpath:c,alias:d}=A(e,a.useHeadingAsAlias));break}case l.SymbolList:{const{item:{symbol:l}}=s;if(b(l))({subpath:c,alias:d}=A(l.heading,a.useHeadingAsAlias));else if(h(l,"link")){o=new RegExp(/^\[(.*?)\]\((.+?)\)/).test(l.original)?l.original:function(e,t,s,i,a,o){const{link:r,displayText:l}=i,{path:d,subpath:c}=n.parseLinktext(r);let h=l,m=null,u=null;m=d?.length?E(d,t):a;m?(!h?.length&&o&&(h=m.basename),u=e.generateMarkdownLink(m,s,c,h)):u=x(d,h);return u}(e,t,i,l,r,a.useBasenameAsAlias)}else r=null;break}case l.RelatedItemsList:{const{item:e}=s;e.unresolvedText&&(o=x(e.unresolvedText));break}}r&&!o&&(!d&&a.useBasenameAsAlias&&(d=r.basename),o=e.generateMarkdownLink(r,i,c,d))}return o}function A(e,t){const s=e.replace(/([:#|^\\\r\n]|%%|\[\[|]])/g," ").replace(/\s+/g," ").trim();return{subpath:`#${s}`,alias:t?s:null}}function x(e,t){return`[[${e}${t=t?.length?`|${t}`:""}]]`}r[1]="H₁",r[2]="H₂",r[3]="H₃",r[4]="H₄",r[5]="H₅",r[6]="H₆",function(e){e.EditorList="editorList",e.SymbolList="symbolList",e.WorkspaceList="workspaceList",e.HeadingsList="headingsList",e.Bookmark="bookmark",e.CommandList="commandList",e.RelatedItemsList="relatedItemsList",e.VaultList="vaultList",e.File="file",e.Alias="alias",e.Unresolved="unresolved"}(l||(l={})),function(e){e[e.None=0]="None",e[e.Primary=1]="Primary",e[e.Basename=2]="Basename",e[e.Path=3]="Path"}(d||(d={})),function(e){e.DiskLocation="disk-location",e.Backlink="backlink",e.OutgoingLink="outgoing-link"}(c||(c={}));class O{static getAliases(e){let t=[];return e&&(t=O.getValueForKey(e,/^alias(es)?$/i)),t}static getValueForKey(e,t){const s=[],i=Object.keys(e).find((e=>t.test(e)));if(i){let t=e[i];"string"==typeof t&&(t=t.split(",")),Array.isArray(t)&&t.forEach((e=>{"string"==typeof e&&s.push(e.trim())}))}return s}}class P{static getRootComponent(){return this.rootComponent||(this.rootComponent=new n.Component),this.rootComponent}static unload(){this.rootComponent?.unload()}}const M={file:"canvas-node-file",text:"canvas-node-text",link:"canvas-node-link",group:"canvas-node-group"},R=[{id:s[s.Heading],mode:t.SymbolList,label:"headings",isActive:!1,isAvailable:!0},{id:s[s.Tag],mode:t.SymbolList,label:"tags",isActive:!1,isAvailable:!0},{id:s[s.Callout],mode:t.SymbolList,label:"callouts",isActive:!1,isAvailable:!0},{id:s[s.Link],mode:t.SymbolList,label:"links",isActive:!1,isAvailable:!0},{id:s[s.Embed],mode:t.SymbolList,label:"embeds",isActive:!1,isAvailable:!0},{id:M.file,mode:t.SymbolList,label:"file cards",isActive:!1,isAvailable:!0},{id:M.text,mode:t.SymbolList,label:"text cards",isActive:!1,isAvailable:!0},{id:M.link,mode:t.SymbolList,label:"link cards",isActive:!1,isAvailable:!0},{id:M.group,mode:t.SymbolList,label:"groups",isActive:!1,isAvailable:!0}],H=[{id:c.Backlink,mode:t.RelatedItemsList,label:"backlinks",isActive:!1,isAvailable:!0},{id:c.OutgoingLink,mode:t.RelatedItemsList,label:"outgoing links",isActive:!1,isAvailable:!0},{id:c.DiskLocation,mode:t.RelatedItemsList,label:"disk location",isActive:!1,isAvailable:!0}],B={file:"bookmarks-file",folder:"bookmarks-folder",search:"bookmarks-search",group:"bookmarks-group"},N=[{id:B.file,mode:t.BookmarksList,label:"files",isActive:!1,isAvailable:!0},{id:B.folder,mode:t.BookmarksList,label:"folders",isActive:!1,isAvailable:!0},{id:B.search,mode:t.BookmarksList,label:"searches",isActive:!1,isAvailable:!0}];var V;!function(e){e.Pinned="pinnedCommands",e.Recent="recentCommands"}(V||(V={}));const W=[{id:V.Pinned,mode:t.CommandList,label:"pinned",isActive:!1,isAvailable:!0},{id:V.Recent,mode:t.CommandList,label:"recent",isActive:!1,isAvailable:!0}];var D;!function(e){e.RecentFiles="recentFilesSearch",e.Bookmarks="bookmarksSearch",e.Filenames="filenamesSearch",e.Headings="headingsSearch",e.ExternalFiles="externalFilesSearch"}(D||(D={}));const j=[{id:D.RecentFiles,mode:t.HeadingsList,label:"recent files",isActive:!1,isAvailable:!0},{id:D.Bookmarks,mode:t.HeadingsList,label:"bookmarks",isActive:!1,isAvailable:!0},{id:D.Filenames,mode:t.HeadingsList,label:"filenames",isActive:!1,isAvailable:!0},{id:D.Headings,mode:t.HeadingsList,label:"headings",isActive:!1,isAvailable:!0},{id:D.ExternalFiles,mode:t.HeadingsList,label:"external files",isActive:!1,isAvailable:!0}];function K(){const e={};return[R,H,N,W,j].flat().reduce(((e,t)=>(e[t.id]=Object.assign({},t),e)),e),e}const q=e=>{if("object"==typeof e&&null!==e){if("function"==typeof Object.getPrototypeOf){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}return"[object Object]"===Object.prototype.toString.call(e)}return!1},Q=(...e)=>e.reduce(((e,t)=>{if(Array.isArray(t))throw new TypeError("Arguments provided to ts-deepmerge must be objects, not arrays.");return Object.keys(t).forEach((s=>{["__proto__","constructor","prototype"].includes(s)||(Array.isArray(e[s])&&Array.isArray(t[s])?e[s]=Q.options.mergeArrays?Q.options.uniqueArrayItems?Array.from(new Set(e[s].concat(t[s]))):[...e[s],...t[s]]:t[s]:q(e[s])&&q(t[s])?e[s]=Q(e[s],t[s]):e[s]=void 0===t[s]?Q.options.allowUndefinedOverrides?t[s]:e[s]:t[s])})),e}),{}),$={allowUndefinedOverrides:!0,mergeArrays:!0,uniqueArrayItems:!0};Q.options=$,Q.withOptions=(e,...t)=>{Q.options=Object.assign(Object.assign({},$),e);const s=Q(...t);return Q.options=$,s};class z{static get defaults(){const i={};return i[s.Link]=!0,i[s.Embed]=!0,i[s.Tag]=!0,i[s.Heading]=!0,i[s.Callout]=!0,{version:"2.0.0",onOpenPreferNewTab:!0,alwaysNewTabForSymbols:!1,useActiveTabForSymbolsOnMobile:!1,symbolsInLineOrder:!0,editorListCommand:"edt ",symbolListCommand:"@",symbolListActiveEditorCommand:"$ ",workspaceListCommand:"+",headingsListCommand:"#",bookmarksListCommand:"'",commandListCommand:">",vaultListCommand:"vault ",relatedItemsListCommand:"~",relatedItemsListActiveEditorCommand:"^ ",shouldSearchHeadings:!0,strictHeadingsOnly:!1,searchAllHeadings:!0,headingsSearchDebounceMilli:250,excludeViewTypes:["empty"],referenceViews:["backlink","localgraph","outgoing-link","outline"],limit:50,includeSidePanelViewTypes:["backlink","image","markdown","pdf"],enabledSymbolTypes:i,selectNearestHeading:!0,excludeFolders:[],excludeLinkSubTypes:0,excludeRelatedFolders:[""],excludeOpenRelatedFiles:!1,excludeObsidianIgnoredFiles:!1,shouldSearchFilenames:!1,shouldSearchBookmarks:!1,shouldSearchRecentFiles:!0,pathDisplayFormat:e.FolderWithFilename,hidePathIfRoot:!0,enabledRelatedItems:Object.values(c),showOptionalIndicatorIcons:!0,overrideStandardModeBehaviors:!0,enabledRibbonCommands:[t[t.HeadingsList],t[t.SymbolList]],fileExtAllowList:["canvas"],matchPriorityAdjustments:{isEnabled:!1,adjustments:{isOpenInEditor:{value:0,label:"Open items"},isBookmarked:{value:0,label:"Bookmarked items"},isRecent:{value:0,label:"Recent items"},isAttachment:{value:0,label:"Attachment file types"},file:{value:0,label:"Filenames"},alias:{value:0,label:"Aliases"},unresolved:{value:0,label:"Unresolved filenames"},h1:{value:0,label:"H₁ headings"}},fileExtAdjustments:{canvas:{value:0,label:"Canvas files"}}},quickFilters:{resetKey:"0",keyList:["1","2","3","4","5","6","7","8","9"],modifiers:["Ctrl","Alt"],facetList:K(),shouldResetActiveFacets:!1,shouldShowFacetInstructions:!0},preserveCommandPaletteLastInput:!1,preserveQuickSwitcherLastInput:!1,shouldCloseModalOnBackspace:!1,maxRecentFileSuggestionsOnInit:25,orderEditorListByAccessTime:!0,insertLinkInEditor:{isEnabled:!0,keymap:{modifiers:["Mod"],key:"i",purpose:"insert in editor"},insertableEditorTypes:["markdown"],useBasenameAsAlias:!0,useHeadingAsAlias:!0},removeDefaultTabBinding:!0,navigationKeys:{nextKeys:[{modifiers:["Ctrl"],key:"n"},{modifiers:["Ctrl"],key:"j"}],prevKeys:[{modifiers:["Ctrl"],key:"p"},{modifiers:["Ctrl"],key:"k"}]},preferredSourceForTitle:"H1",closeWhenEmptyKeys:[{modifiers:null,key:"Backspace"}],navigateToHotkeySelectorKeys:{modifiers:["Ctrl","Shift"],key:"h"},togglePinnedCommandKeys:{modifiers:["Ctrl","Shift"],key:"p"},escapeCmdChar:"!",mobileLauncher:{isEnabled:!1,modeString:t[t.HeadingsList],iconName:"",coreLauncherButtonIconSelector:"span.clickable-icon",coreLauncherButtonSelector:".mobile-navbar-action:has(span.clickable-icon svg.svg-icon.lucide-plus-circle)"},allowCreateNewFileInModeNames:[t[t.Standard],t[t.HeadingsList]],showModeTriggerInstructions:!0,renderMarkdownContentInSuggestions:{isEnabled:!1,renderHeadings:!1,toggleContentRenderingKeys:{modifiers:["Shift","Ctrl"],key:"m"}},quickOpen:{isEnabled:!0,modifiers:["Alt"],keyList:["1","2","3","4","5","6","7","8","9"]}}}get version(){return this.data.version}set version(e){this.data.version=e}get builtInSystemOptions(){return C(this.plugin.app)?.options}get showAllFileTypes(){return this.builtInSystemOptions?.showAllFileTypes}get showAttachments(){return this.builtInSystemOptions?.showAttachments}get showExistingOnly(){return this.builtInSystemOptions?.showExistingOnly}get onOpenPreferNewTab(){return this.data.onOpenPreferNewTab}set onOpenPreferNewTab(e){this.data.onOpenPreferNewTab=e}get alwaysNewTabForSymbols(){return this.data.alwaysNewTabForSymbols}set alwaysNewTabForSymbols(e){this.data.alwaysNewTabForSymbols=e}get useActiveTabForSymbolsOnMobile(){return this.data.useActiveTabForSymbolsOnMobile}set useActiveTabForSymbolsOnMobile(e){this.data.useActiveTabForSymbolsOnMobile=e}get symbolsInLineOrder(){return this.data.symbolsInLineOrder}set symbolsInLineOrder(e){this.data.symbolsInLineOrder=e}get editorListPlaceholderText(){return z.defaults.editorListCommand}get editorListCommand(){return this.data.editorListCommand}set editorListCommand(e){this.data.editorListCommand=e}get symbolListPlaceholderText(){return z.defaults.symbolListCommand}get symbolListCommand(){return this.data.symbolListCommand}set symbolListCommand(e){this.data.symbolListCommand=e}get symbolListActiveEditorCommand(){return this.data.symbolListActiveEditorCommand}set symbolListActiveEditorCommand(e){this.data.symbolListActiveEditorCommand=e}get workspaceListCommand(){return this.data.workspaceListCommand}set workspaceListCommand(e){this.data.workspaceListCommand=e}get workspaceListPlaceholderText(){return z.defaults.workspaceListCommand}get headingsListCommand(){return this.data.headingsListCommand}set headingsListCommand(e){this.data.headingsListCommand=e}get headingsListPlaceholderText(){return z.defaults.headingsListCommand}get bookmarksListCommand(){return this.data.bookmarksListCommand}set bookmarksListCommand(e){this.data.bookmarksListCommand=e}get bookmarksListPlaceholderText(){return z.defaults.bookmarksListCommand}get commandListCommand(){return this.data.commandListCommand}set commandListCommand(e){this.data.commandListCommand=e}get commandListPlaceholderText(){return z.defaults.commandListCommand}get vaultListCommand(){return this.data.vaultListCommand}set vaultListCommand(e){this.data.vaultListCommand=e}get vaultListPlaceholderText(){return z.defaults.vaultListCommand}get relatedItemsListCommand(){return this.data.relatedItemsListCommand}set relatedItemsListCommand(e){this.data.relatedItemsListCommand=e}get relatedItemsListPlaceholderText(){return z.defaults.relatedItemsListCommand}get relatedItemsListActiveEditorCommand(){return this.data.relatedItemsListActiveEditorCommand}set relatedItemsListActiveEditorCommand(e){this.data.relatedItemsListActiveEditorCommand=e}get shouldSearchHeadings(){return this.data.shouldSearchHeadings}set shouldSearchHeadings(e){this.data.shouldSearchHeadings=e}get strictHeadingsOnly(){return this.data.strictHeadingsOnly}set strictHeadingsOnly(e){this.data.strictHeadingsOnly=e}get searchAllHeadings(){return this.data.searchAllHeadings}set searchAllHeadings(e){this.data.searchAllHeadings=e}get headingsSearchDebounceMilli(){return this.data.headingsSearchDebounceMilli}set headingsSearchDebounceMilli(e){this.data.headingsSearchDebounceMilli=e}get excludeViewTypes(){return this.data.excludeViewTypes}set excludeViewTypes(e){this.data.excludeViewTypes=e}get referenceViews(){return this.data.referenceViews}set referenceViews(e){this.data.referenceViews=e}get limit(){return this.data.limit}set limit(e){this.data.limit=e}get includeSidePanelViewTypes(){return this.data.includeSidePanelViewTypes}set includeSidePanelViewTypes(e){this.data.includeSidePanelViewTypes=[...new Set(e)]}get includeSidePanelViewTypesPlaceholder(){return z.defaults.includeSidePanelViewTypes.join("\n")}get selectNearestHeading(){return this.data.selectNearestHeading}set selectNearestHeading(e){this.data.selectNearestHeading=e}get excludeFolders(){return this.data.excludeFolders}set excludeFolders(e){this.data.excludeFolders=[...new Set(e)]}get excludeLinkSubTypes(){return this.data.excludeLinkSubTypes}set excludeLinkSubTypes(e){this.data.excludeLinkSubTypes=e}get excludeRelatedFolders(){return this.data.excludeRelatedFolders}set excludeRelatedFolders(e){this.data.excludeRelatedFolders=[...new Set(e)]}get excludeOpenRelatedFiles(){return this.data.excludeOpenRelatedFiles}set excludeOpenRelatedFiles(e){this.data.excludeOpenRelatedFiles=e}get excludeObsidianIgnoredFiles(){return this.data.excludeObsidianIgnoredFiles}set excludeObsidianIgnoredFiles(e){this.data.excludeObsidianIgnoredFiles=e}get shouldSearchFilenames(){return this.data.shouldSearchFilenames}set shouldSearchFilenames(e){this.data.shouldSearchFilenames=e}get shouldSearchBookmarks(){return this.data.shouldSearchBookmarks}set shouldSearchBookmarks(e){this.data.shouldSearchBookmarks=e}get shouldSearchRecentFiles(){return this.data.shouldSearchRecentFiles}set shouldSearchRecentFiles(e){this.data.shouldSearchRecentFiles=e}get pathDisplayFormat(){return this.data.pathDisplayFormat}set pathDisplayFormat(e){this.data.pathDisplayFormat=e}get hidePathIfRoot(){return this.data.hidePathIfRoot}set hidePathIfRoot(e){this.data.hidePathIfRoot=e}get enabledRelatedItems(){return this.data.enabledRelatedItems}set enabledRelatedItems(e){this.data.enabledRelatedItems=e}get showOptionalIndicatorIcons(){return this.data.showOptionalIndicatorIcons}set showOptionalIndicatorIcons(e){this.data.showOptionalIndicatorIcons=e}get overrideStandardModeBehaviors(){return this.data.overrideStandardModeBehaviors}set overrideStandardModeBehaviors(e){this.data.overrideStandardModeBehaviors=e}get enabledRibbonCommands(){return this.data.enabledRibbonCommands}set enabledRibbonCommands(e){this.data.enabledRibbonCommands=[...new Set(e)]}get fileExtAllowList(){return this.data.fileExtAllowList}set fileExtAllowList(e){this.data.fileExtAllowList=e}get matchPriorityAdjustments(){return this.data.matchPriorityAdjustments}set matchPriorityAdjustments(e){this.data.matchPriorityAdjustments=e}get quickFilters(){return this.data.quickFilters}set quickFilters(e){this.data.quickFilters=e}get preserveCommandPaletteLastInput(){return this.data.preserveCommandPaletteLastInput}set preserveCommandPaletteLastInput(e){this.data.preserveCommandPaletteLastInput=e}get preserveQuickSwitcherLastInput(){return this.data.preserveQuickSwitcherLastInput}set preserveQuickSwitcherLastInput(e){this.data.preserveQuickSwitcherLastInput=e}get shouldCloseModalOnBackspace(){return this.data.shouldCloseModalOnBackspace}set shouldCloseModalOnBackspace(e){this.data.shouldCloseModalOnBackspace=e}get maxRecentFileSuggestionsOnInit(){return this.data.maxRecentFileSuggestionsOnInit}set maxRecentFileSuggestionsOnInit(e){this.data.maxRecentFileSuggestionsOnInit=e}get orderEditorListByAccessTime(){return this.data.orderEditorListByAccessTime}set orderEditorListByAccessTime(e){this.data.orderEditorListByAccessTime=e}get insertLinkInEditor(){return this.data.insertLinkInEditor}set insertLinkInEditor(e){this.data.insertLinkInEditor=e}get removeDefaultTabBinding(){return this.data.removeDefaultTabBinding}set removeDefaultTabBinding(e){this.data.removeDefaultTabBinding=e}get navigationKeys(){return this.data.navigationKeys}set navigationKeys(e){this.data.navigationKeys=e}get preferredSourceForTitle(){return this.data.preferredSourceForTitle}set preferredSourceForTitle(e){this.data.preferredSourceForTitle=e}get closeWhenEmptyKeys(){return this.data.closeWhenEmptyKeys}set closeWhenEmptyKeys(e){this.data.closeWhenEmptyKeys=e}get navigateToHotkeySelectorKeys(){return this.data.navigateToHotkeySelectorKeys}set navigateToHotkeySelectorKeys(e){this.data.navigateToHotkeySelectorKeys=e}get togglePinnedCommandKeys(){return this.data.togglePinnedCommandKeys}set togglePinnedCommandKeys(e){this.data.togglePinnedCommandKeys=e}get escapeCmdChar(){return this.data.escapeCmdChar}set escapeCmdChar(e){this.data.escapeCmdChar=e}get mobileLauncher(){return this.data.mobileLauncher}set mobileLauncher(e){this.data.mobileLauncher=e}get allowCreateNewFileInModeNames(){return this.data.allowCreateNewFileInModeNames}set allowCreateNewFileInModeNames(e){this.data.allowCreateNewFileInModeNames=[...new Set(e)]}get showModeTriggerInstructions(){return this.data.showModeTriggerInstructions}set showModeTriggerInstructions(e){this.data.showModeTriggerInstructions=e}get renderMarkdownContentInSuggestions(){return this.data.renderMarkdownContentInSuggestions}set renderMarkdownContentInSuggestions(e){this.data.renderMarkdownContentInSuggestions=e}get quickOpen(){return this.data.quickOpen}set quickOpen(e){this.data.quickOpen=e}constructor(e){this.plugin=e,this.data=z.defaults}async updateDataAndLoadSettings(){return await z.transformDataFile(this.plugin,z.defaults),await this.loadSettings()}async loadSettings(){try{const e=await(this.plugin?.loadData());if(e){const t=Object.keys(z.defaults);((e,t,s)=>{const i=["matchPriorityAdjustments","quickFilters"],n=s=>Q.withOptions({mergeArrays:!1},t[s],e[s]);for(const a of s)a in e&&(t[a]=i.includes(a)?n(a):e[a])})(e,this.data,t)}}catch(e){console.log("Switcher++: error loading settings, using defaults. ",e)}}async saveSettings(){const{plugin:e,data:t}=this;await(e?.saveData(t))}save(){this.saveSettings().catch((e=>{console.log("Switcher++: error saving changes to settings",e)}))}isSymbolTypeEnabled(e){const{enabledSymbolTypes:t}=this.data;let s=z.defaults.enabledSymbolTypes[e];return Object.prototype.hasOwnProperty.call(t,e)&&(s=t[e]),s}setSymbolTypeEnabled(e,t){this.data.enabledSymbolTypes[e]=t}static async transformDataFile(e,t){await z.transformDataFileToV1(e,t),await z.transformDataFileToV2(e,t)}static async transformDataFileToV1(e,t){let s=!1;try{const i=await(e?.loadData());if(i&&"object"==typeof i){const n="version";if(!Object.prototype.hasOwnProperty.call(i,n)){const a="starredListCommand";Object.prototype.hasOwnProperty.call(i,a)&&(i.bookmarksListCommand=i[a]??t.bookmarksListCommand,delete i[a]);const o="isStarred",r=i.matchPriorityAdjustments;r&&Object.prototype.hasOwnProperty.call(r,o)&&(r.isBookmarked=r[o],delete r[o]),i[n]="1.0.0",await(e?.saveData(i)),s=!0}}}catch(e){console.log("Switcher++: error transforming data.json to v1.0.0",e)}return s}static async transformDataFileToV2(e,t){let s=!1;try{const i=await(e?.loadData());if(i&&"object"==typeof i){const n="version";if("1.0.0"===i[n]){const a="matchPriorityAdjustments";if(Object.prototype.hasOwnProperty.call(i,a)){const e=i[a],s={};i[a]={isEnabled:!!i.enableMatchPriorityAdjustments,adjustments:s},delete i.enableMatchPriorityAdjustments,Object.entries(e).forEach((([e,i])=>{const n=t.matchPriorityAdjustments.adjustments[e]?.label??"";s[e]={value:i,label:n}}))}const o="quickFilters";if(Object.prototype.hasOwnProperty.call(i,o)){const e="facetList",t=i[o],s=t[e],n=s?.reduce(((e,t)=>(e[t.id]=t,e)),{});t[e]=n}i[n]="2.0.0",await(e?.saveData(i)),s=!0}}}catch(e){console.log("Switcher++: error transforming data.json to v2.0.0",e)}return s}}class U{constructor(e,t,s){this.app=e,this.mainSettingsTab=t,this.config=s}createSetting(e,t,s){const i=new n.Setting(e);return i.setName(t),i.setDesc(s),i}addSectionTitle(e,t,s=""){const i=this.createSetting(e,t,s);return i.setHeading(),i}addTextSetting(e,t,s,i,n,a){const o=this.createSetting(e,t,s);return o.addText((e=>{e.setPlaceholder(a),e.setValue(i),e.onChange((e=>{const t=e.length?e:i;this.saveChangesToConfig(n,t)}))})),o}addToggleSetting(e,t,s,i,n,a){const o=this.createSetting(e,t,s);return o.addToggle((e=>{e.setValue(i),e.onChange((e=>{a?a(e,this.config):this.saveChangesToConfig(n,e)}))})),o}addTextAreaSetting(e,t,s,i,n,a){const o=this.createSetting(e,t,s);return o.addTextArea((e=>{e.setPlaceholder(a),e.setValue(i),e.onChange((e=>{const t=e.length?e:i,s=Array.isArray(this.config[n]);this.saveChangesToConfig(n,s?t.split("\n"):t)}))})),o}addDropdownSetting(e,t,s,i,n,a,o){const r=this.createSetting(e,t,s);return r.addDropdown((e=>{e.addOptions(n),e.setValue(i),e.onChange((e=>{o?o(e,this.config):this.saveChangesToConfig(a,e)}))})),r}addSliderSetting(e,t,s,i,n,a,o){const r=this.createSetting(e,t,s);return r.addExtraButton((e=>(e.setIcon("lucide-rotate-ccw"),e.setTooltip("Restore default"),e.onClick((()=>r.components[1].setValue(0))),e))),r.addSlider((e=>{e.setLimits(n[0],n[1],n[2]),e.setValue(i),e.setDynamicTooltip(),e.onChange((e=>{o?o(e,this.config):this.saveChangesToConfig(a,e)}))})),r}saveChangesToConfig(e,t){if(e){const{config:s}=this;s[e]=t,s.save()}}}class _ extends U{display(e){const{config:t}=this;this.addSectionTitle(e,"Bookmarks List Mode Settings"),this.addTextSetting(e,"Bookmarks list mode trigger","Character that will trigger bookmarks list mode in the switcher",t.bookmarksListCommand,"bookmarksListCommand",t.bookmarksListPlaceholderText)}}class G extends U{display(e){const{config:t}=this;this.addSectionTitle(e,"Command List Mode Settings"),this.addTextSetting(e,"Command list mode trigger","Character that will trigger command list mode in the switcher",t.commandListCommand,"commandListCommand",t.commandListPlaceholderText)}}class J extends U{display(e){const{config:t}=this;this.addSectionTitle(e,"Related Items List Mode Settings"),this.addTextSetting(e,"Related Items list mode trigger","Character that will trigger related items list mode in the switcher. This triggers a display of Related Items for the source file of the currently selected (highlighted) suggestion in the switcher. If there is not a suggestion, display results for the active editor.",t.relatedItemsListCommand,"relatedItemsListCommand",t.relatedItemsListPlaceholderText),this.addTextSetting(e,"Related Items list mode trigger - Active editor only","Character that will trigger related items list mode in the switcher. This always triggers a display of Related Items for the active editor only.",t.relatedItemsListActiveEditorCommand,"relatedItemsListActiveEditorCommand",t.relatedItemsListActiveEditorCommand),this.showEnabledRelatedItems(e,t),this.addToggleSetting(e,"Exclude open files","Enable, related files which are already open will not be displayed in the list. Disabled, All related files will be displayed in the list.",t.excludeOpenRelatedFiles,"excludeOpenRelatedFiles")}showEnabledRelatedItems(e,t){const s=Object.values(c).sort(),i=s.join(", "),n=`The types of related items to show in the list. Add one type per line. Available types: ${i}`;this.createSetting(e,"Show related item types",n).addTextArea((e=>{e.setValue(t.enabledRelatedItems.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const n=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0)),a=[...new Set(n)].filter((e=>!s.includes(e)));a?.length?this.showErrorPopup(a.join("<br/>"),i):(t.enabledRelatedItems=n,t.save())}))}))}showErrorPopup(e,t){const s=new n.Modal(this.app);s.titleEl.setText("Invalid related item type"),s.contentEl.innerHTML=`Changes not saved. Available relation types are: ${t}. The following types are invalid:<br/><br/>${e}`,s.open()}}class X extends U{display(e){const{config:t}=this;this.addSectionTitle(e,"General Settings"),this.showEnabledRibbonCommands(e,t),this.showOverrideMobileLauncher(e,t),this.showPreferredSourceForTitle(e,t),this.showPathDisplayFormat(e,t),this.addToggleSetting(e,"Hide path for root items","When enabled, path information will be hidden for items at the root of the vault.",t.hidePathIfRoot,"hidePathIfRoot").setClass("qsp-setting-item-indent"),this.addTextSetting(e,"Mode trigger escape character","Character to indicate that a mode trigger character should be treated just as a normal text.",t.escapeCmdChar,"escapeCmdChar"),this.addToggleSetting(e,"Default to open in new tab","When enabled, navigating to un-opened files will open a new editor tab whenever possible (as if cmd/ctrl were held). When the file is already open, the existing tab will be activated. This overrides all other tab settings.",t.onOpenPreferNewTab,"onOpenPreferNewTab"),this.addToggleSetting(e,"Override Standard mode behavior","When enabled, Switcher++ will change the default Obsidian builtin Switcher functionality (Standard mode) to inject custom behavior.",t.overrideStandardModeBehaviors,"overrideStandardModeBehaviors"),this.addToggleSetting(e,"Show indicator icons","Display icons to indicate that an item is recent, bookmarked, etc..",t.showOptionalIndicatorIcons,"showOptionalIndicatorIcons"),this.addToggleSetting(e,"Allow Backspace key to close the Switcher","When the search box is empty, pressing the backspace key will close Switcher++.",t.shouldCloseModalOnBackspace,"shouldCloseModalOnBackspace"),this.showMatchPriorityAdjustments(e,t),this.showInsertLinkInEditor(e,t),this.addToggleSetting(e,"Restore previous input in Command Mode","When enabled, restore the last typed input in Command Mode when launched via global command hotkey.",t.preserveCommandPaletteLastInput,"preserveCommandPaletteLastInput"),this.addToggleSetting(e,"Restore previous input","When enabled, restore the last typed input when launched via global command hotkey.",t.preserveQuickSwitcherLastInput,"preserveQuickSwitcherLastInput"),this.addToggleSetting(e,"Display mode trigger instructions","When enabled, the trigger key for each mode will be displayed in the instructions section of the Switcher.",t.showModeTriggerInstructions,"showModeTriggerInstructions"),this.showResetFacetEachSession(e,t),this.showRenderMarkdownContentAsHTML(e,t)}showPreferredSourceForTitle(e,t){this.addDropdownSetting(e,"Preferred suggestion title source",'The preferred source to use for the "title" text that will be searched and displayed for file based suggestions',t.preferredSourceForTitle,{H1:"First H₁ heading",Default:"Default"},"preferredSourceForTitle")}showPathDisplayFormat(t,s){const i={};i[e.None.toString()]="Hide path",i[e.Full.toString()]="Full path",i[e.FolderOnly.toString()]="Only parent folder",i[e.FolderWithFilename.toString()]="Parent folder & filename",i[e.FolderPathFilenameOptional.toString()]="Parent folder path (filename optional)",this.addDropdownSetting(t,"Preferred file path display format","The preferred way to display file paths in suggestions",s.pathDisplayFormat.toString(),i,null,((e,t)=>{t.pathDisplayFormat=Number(e),t.save()}))}showEnabledRibbonCommands(e,s){const i=Object.values(t).filter((e=>isNaN(Number(e)))).sort(),n=i.join(" "),a=`Display an icon in the ribbon menu to launch specific modes. Add one mode per line. Available modes: ${n}`;this.createSetting(e,"Show ribbon icons",a).addTextArea((e=>{e.setValue(s.enabledRibbonCommands.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const t=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0)),a=Array.from(new Set(t)).filter((e=>!i.includes(e)));a.length?this.showErrorPopup(a.join("<br/>"),n):(s.enabledRibbonCommands=t,s.save(),this.mainSettingsTab.plugin.registerRibbonCommandIcons())}))}))}showErrorPopup(e,t){const s=new n.Modal(this.app);s.titleEl.setText("Invalid mode"),s.contentEl.innerHTML=`Changes not saved. Available modes are: ${t}. The following are invalid:<br/><br/>${e}`,s.open()}showOverrideMobileLauncher(e,s){const{mobileLauncher:i}=s,n="disabled",a={[n]:"Do not override"},o=Object.values(t).filter((e=>isNaN(Number(e)))).sort();o.forEach((e=>{a[e]=e}));let r=n;i.isEnabled&&o.includes(i.modeString)&&(r=i.modeString),this.addDropdownSetting(e,'Override default Switcher launch button (the "⊕" button) on mobile platforms','Override the "⊕" button (in the Navigation Bar) on mobile platforms to launch Switcher++ instead of the default system switcher. Select the Mode to launch Switcher++ in, or select "Do not override" to disable the feature.',r,a,null,((e,t)=>{const s=e!==n;t.mobileLauncher.isEnabled=s,s&&(t.mobileLauncher.modeString=e),t.save(),this.mainSettingsTab.plugin.updateMobileLauncherButtonOverride(s)}))}showMatchPriorityAdjustments(e,t){const{matchPriorityAdjustments:{isEnabled:s,adjustments:i,fileExtAdjustments:n}}=t;this.addToggleSetting(e,"Result priority adjustments","Artificially increase the match score of the specified item types by a fixed percentage so they appear higher in the results list (does not apply to Standard Mode).",s,null,((e,t)=>{t.matchPriorityAdjustments.isEnabled=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>console.log('Switcher++: error saving "Result Priority Adjustments" setting. ',e)))})),s&&[i,n].forEach((t=>{Object.entries(t).forEach((([s,i])=>{const{value:n,label:a}=i,o=this.addSliderSetting(e,a,i.desc??"",n,[-1,1,.05],null,((e,i)=>{t[s].value=e,i.save()}));o.setClass("qsp-setting-item-indent")}))}))}showResetFacetEachSession(e,t){this.addToggleSetting(e,"Reset active Quick Filters","When enabled, the switcher will reset all Quick Filters back to inactive for each session.",t.quickFilters.shouldResetActiveFacets,null,((e,t)=>{t.quickFilters.shouldResetActiveFacets=e,t.save()}))}showRenderMarkdownContentAsHTML(e,t){const s=this.addToggleSetting(e,"Display Headings as Live Preview",'When enabled, Headings will be rendered as HTML similar to the Obsidian "Live Preview" display. When disabled, Headings will be rendered as raw text. Use the "toggle preview (selected heading)" hotkey to toggle the display for individual headings.',t.renderMarkdownContentInSuggestions.renderHeadings,null,((e,t)=>{const{renderMarkdownContentInSuggestions:s}=t;s.renderHeadings=e,s.isEnabled=e,t.save()}));s?.nameEl?.createSpan({cls:["qsp-tag","qsp-warning"],text:"Experimental"})}showInsertLinkInEditor(e,t){this.createSetting(e,"Insert link in editor","");let s=this.addToggleSetting(e,"Use filename as alias","When enabled, the file basename will be set as the link alias.",t.insertLinkInEditor.useBasenameAsAlias,null,((e,t)=>{t.insertLinkInEditor.useBasenameAsAlias=e,t.save()}));s.setClass("qsp-setting-item-indent"),s=this.addToggleSetting(e,"Use heading as alias",'When enabled, the file heading will be set as the link alias. This overrides the "use filename as alias" setting.',t.insertLinkInEditor.useHeadingAsAlias,null,((e,t)=>{t.insertLinkInEditor.useHeadingAsAlias=e,t.save()})),s.setClass("qsp-setting-item-indent")}}class Y extends U{display(e){const{config:t}=this;this.addSectionTitle(e,"Workspace List Mode Settings"),this.addTextSetting(e,"Workspace list mode trigger","Character that will trigger workspace list mode in the switcher",t.workspaceListCommand,"workspaceListCommand",t.workspaceListPlaceholderText)}}class Z extends U{display(e){const{config:t}=this;this.addSectionTitle(e,"Editor List Mode Settings"),this.addTextSetting(e,"Editor list mode trigger","Character that will trigger editor list mode in the switcher",t.editorListCommand,"editorListCommand",t.editorListPlaceholderText),this.showIncludeSidePanelViews(e,t),this.addToggleSetting(e,"Order default editor list by most recently accessed","When there is no search term, order the list of editors by most recent access time.",t.orderEditorListByAccessTime,"orderEditorListByAccessTime")}showIncludeSidePanelViews(e,t){const s=`When in Editor list mode, show the following view types from the side panels. Add one view type per line. Available view types: ${Object.keys(this.app.viewRegistry.viewByType).sort().join(" ")}`;this.addTextAreaSetting(e,"Include side panel views",s,t.includeSidePanelViewTypes.join("\n"),"includeSidePanelViewTypes",t.includeSidePanelViewTypesPlaceholder)}}class ee extends U{display(e){const{config:t}=this;this.addSectionTitle(e,"Headings List Mode Settings"),this.addTextSetting(e,"Headings list mode trigger","Character that will trigger headings list mode in the switcher",t.headingsListCommand,"headingsListCommand",t.headingsListPlaceholderText),this.showHeadingSettings(e,t),this.addToggleSetting(e,"Search Filenames","Enabled, search and show suggestions for filenames. Disabled, Don't search through filenames (except for fallback searches)",t.shouldSearchFilenames,"shouldSearchFilenames"),this.addToggleSetting(e,"Search Bookmarks","Enabled, search and show suggestions for Bookmarks. Disabled, Don't search through Bookmarks",t.shouldSearchBookmarks,"shouldSearchBookmarks"),this.addSliderSetting(e,"Max recent files to show","The maximum number of recent files to show when there is no search term",t.maxRecentFileSuggestionsOnInit,[0,75,1],"maxRecentFileSuggestionsOnInit"),this.showExcludeFolders(e,t),this.addToggleSetting(e,'Hide Obsidian "Excluded files"','Enabled, do not display suggestions for files that are in Obsidian\'s "Options > Files & Links > Excluded files" list. Disabled, suggestions for those files will be displayed but downranked.',t.excludeObsidianIgnoredFiles,"excludeObsidianIgnoredFiles"),this.showFileExtAllowList(e,t)}showHeadingSettings(e,t){const s=t.shouldSearchHeadings;if(this.addToggleSetting(e,"Search Headings","Enabled, search and show suggestions for Headings. Disabled, Don't search through Headings",s,null,((e,t)=>{t.shouldSearchHeadings=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>console.log('Switcher++: error saving "Search Headings" setting. ',e)))})),s){let s=this.addToggleSetting(e,"Turn off filename fallback","Enabled, strictly search through only the headings contained in the file. Do not fallback to searching the filename when an H1 match is not found. Disabled, fallback to searching against the filename when there is not a match in the first H1 contained in the file.",t.strictHeadingsOnly,"strictHeadingsOnly");s.setClass("qsp-setting-item-indent"),s=this.addToggleSetting(e,"Search all headings","Enabled, search through all headings contained in each file. Disabled, only search through the first H1 in each file.",t.searchAllHeadings,"searchAllHeadings"),s.setClass("qsp-setting-item-indent")}}showFileExtAllowList(e,t){this.createSetting(e,"File extension override",'Override the "Show attachments" and the "Show all file types" builtin, system Switcher settings and always search files with the listed extensions. Add one path per line. For example to add ".canvas" file extension, just add "canvas".').addTextArea((e=>{e.setValue(t.fileExtAllowList.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const s=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0));t.fileExtAllowList=s,t.save()}))}))}showExcludeFolders(e,t){const s="Exclude folders";this.createSetting(e,s,"When in Headings list mode, folder path that match any regex listed here will not be searched for suggestions. Path should start from the Vault Root. Add one path per line.").addTextArea((e=>{e.setValue(t.excludeFolders.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const i=e.getValue().split("\n").filter((e=>e.length>0));this.validateExcludeFolderList(s,i)&&(t.excludeFolders=i,t.save())}))}))}validateExcludeFolderList(e,t){let s=!0,i="";for(const e of t)try{new RegExp(e)}catch(t){i+=`<span class="qsp-warning">${e}</span><br/>${t}<br/><br/>`,s=!1}if(!s){const t=new n.Modal(this.app);t.titleEl.setText(e),t.contentEl.innerHTML=`Changes not saved. The following regex contain errors:<br/><br/>${i}`,t.open()}return s}}class te extends U{display(e){const{config:t}=this;this.addSectionTitle(e,"Symbol List Mode Settings"),this.addTextSetting(e,"Symbol list mode trigger","Character that will trigger symbol list mode in the switcher. This triggers a display of Symbols for the source file of the currently selected (highlighted) suggestion in the switcher. If there is not a suggestion, display results for the active editor.",t.symbolListCommand,"symbolListCommand",t.symbolListPlaceholderText),this.addTextSetting(e,"Symbol list mode trigger - Active editor only","Character that will trigger symbol list mode in the switcher. This always triggers a display of Symbols for the active editor only.",t.symbolListActiveEditorCommand,"symbolListActiveEditorCommand",t.symbolListActiveEditorCommand),this.addToggleSetting(e,"List symbols as indented outline","Enabled, symbols will be displayed in the (line) order they appear in the source text, indented under any preceding heading. Disabled, symbols will be grouped by type: Headings, Tags, Links, Embeds.",t.symbolsInLineOrder,"symbolsInLineOrder"),this.addToggleSetting(e,"Open Symbols in new tab","Enabled, always open a new tab when navigating to Symbols. Disabled, navigate in an already open tab (if one exists).",t.alwaysNewTabForSymbols,"alwaysNewTabForSymbols"),this.addToggleSetting(e,"Open Symbols in active tab on mobile devices","Enabled, navigate to the target file and symbol in the active editor tab. Disabled, open a new tab when navigating to Symbols, even on mobile devices.",t.useActiveTabForSymbolsOnMobile,"useActiveTabForSymbolsOnMobile"),this.addToggleSetting(e,"Auto-select nearest heading","Enabled, in an unfiltered symbol list, select the closest preceding Heading to the current cursor position. Disabled, the first symbol in the list is selected.",t.selectNearestHeading,"selectNearestHeading"),this.showEnableSymbolTypesToggle(e,t),this.showEnableLinksToggle(e,t)}showEnableSymbolTypesToggle(e,t){[["Show Headings",s.Heading],["Show Tags",s.Tag],["Show Embeds",s.Embed],["Show Callouts",s.Callout]].forEach((([s,i])=>{this.addToggleSetting(e,s,"",t.isSymbolTypeEnabled(i),null,(e=>{t.setSymbolTypeEnabled(i,e),t.save()}))}))}showEnableLinksToggle(e,t){const n=t.isSymbolTypeEnabled(s.Link);if(this.addToggleSetting(e,"Show Links","",n,null,(e=>{t.setSymbolTypeEnabled(s.Link,e),t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>console.log('Switcher++: error saving "Show Links" setting. ',e)))})),n){[["Links to headings",i.Heading],["Links to blocks",i.Block]].forEach((([s,i])=>{const n=(t.excludeLinkSubTypes&i)===i;this.addToggleSetting(e,s,"",!n,null,(e=>this.saveEnableSubLinkChange(i,e))).setClass("qsp-setting-item-indent")}))}}saveEnableSubLinkChange(e,t){const{config:s}=this;let i=s.excludeLinkSubTypes;t?i&=~e:i|=e,s.excludeLinkSubTypes=i,s.save()}}class se extends U{display(e){const{config:t}=this,s=this.addSectionTitle(e,"Vault List Mode Settings");s.nameEl?.createSpan({cls:["qsp-tag","qsp-warning"],text:"Experimental"}),this.addTextSetting(e,"Vault list mode trigger","Character that will trigger vault list mode in the switcher",t.vaultListCommand,"vaultListCommand",t.vaultListPlaceholderText)}}class ie extends n.PluginSettingTab{constructor(e,t,s){super(e,t),this.plugin=t,this.config=s}display(){const{containerEl:e}=this,t=[X,te,ee,Z,J,_,G,Y,se];e.empty(),e.createEl("h2",{text:"Quick Switcher++ Settings"}),t.forEach((e=>{this.displayTabSection(e)}))}displayTabSection(e){const{app:t,config:s,containerEl:i}=this;new e(t,this,s).display(i)}}class ne{static get defaultParsedCommand(){return{isValidated:!1,index:-1,parsedInput:null}}get searchQuery(){return this._searchQuery}get inputTextSansEscapeChar(){return this._inputTextSansEscapeChar??this.inputText}set inputTextSansEscapeChar(e){this._inputTextSansEscapeChar=e}constructor(e="",s=t.Standard,i){this.inputText=e,this.mode=s,this._inputTextSansEscapeChar=null,this.currentWorkspaceEnvList={openWorkspaceLeaves:new Set,openWorkspaceFiles:new Set,fileBookmarks:new Map,nonFileBookmarks:new Set,mostRecentFiles:new Set,attachmentFileExtensions:new Set},this.sessionOpts=i??{};const n={...ne.defaultParsedCommand,source:null},a={...ne.defaultParsedCommand,source:null},o={};this.parsedCommands=o,o[t.SymbolList]=n,o[t.RelatedItemsList]=a,[t.Standard,t.EditorList,t.WorkspaceList,t.HeadingsList,t.BookmarksList,t.CommandList,t.VaultList].forEach((e=>{o[e]=ne.defaultParsedCommand}))}buildSearchQuery(){const{mode:e}=this,t=this.parsedCommands[e].parsedInput??"",s=n.prepareQuery(t.trim().toLowerCase()),i=s?.query?.length>0;this._searchQuery={prepQuery:s,hasSearchTerm:i}}parsedCommand(e){return e=e??this.mode,this.parsedCommands[e]}}class ae{constructor(e,t){this.app=e,this.settings=t}reset(){}onNoResultsCreateAction(e,t){return!1}getFacets(e){if(!this.facets){const t=this.settings?.quickFilters?.facetList;t&&(this.facets=Object.values(t).filter((t=>t.mode===e)))}return this.facets??[]}getAvailableFacets(e){return this.getFacets(e.mode).filter((e=>e.isAvailable))}activateFacet(e,t){e.forEach((e=>e.isActive=t)),this.settings.quickFilters.shouldResetActiveFacets||this.settings.save()}getActiveFacetIds(e){const t=this.getAvailableFacets(e).filter((e=>e.isActive)).map((e=>e.id));return new Set(t)}isFacetedWith(e,t){const s=!!e.size;return s&&e.has(t)||!s}getEditorInfo(e){const{excludeViewTypes:t}=this.settings;let s=null,i=!1,n=null;if(e){const{view:a}=e,o=a.getViewType();s=a.file,n=this.getCursorPosition(a);i=!t.includes(o)&&!!s}return{isValidSource:i,leaf:e,file:s,suggestion:null,cursor:n}}getSuggestionInfo(e){const t=this.getSourceInfoFromSuggestion(e);let s=t.leaf;t.isValidSource&&({leaf:s}=this.findMatchingLeaf(t.file,t.leaf));const i=this.getCursorPosition(s?.view);return{...t,leaf:s,cursor:i}}getSourceInfoFromSuggestion(e){let t=null,s=null;const i=[l.SymbolList,l.Unresolved,l.WorkspaceList,l.CommandList,l.VaultList];e&&!i.includes(e.type)&&(t=e.file),h(e,"type",l.EditorList)&&(s=e.item);return{isValidSource:!!t,leaf:s,file:t,suggestion:e}}getCursorPosition(e){let t=null;if("markdown"===e?.getViewType()){const s=e;if("preview"!==s.getMode()){const{editor:e}=s;t=e.getCursor("head")}}return t}getTitleText(e){const t=function(e){let t=null;if(e){const{path:s}=e;if(t=s,"md"===e.extension){const e=s.lastIndexOf(".");-1!==e&&e!==s.length-1&&0!==e&&(t=s.slice(0,e))}}return t}(e),s=this.getFirstH1(e);return s?.heading??t}getFirstH1(e){return ae.getFirstH1(e,this.app.metadataCache)}static getFirstH1(e,t){let s=null;const i=t.getFileCache(e)?.headings?.filter((e=>1===e.level))??[];return i.length&&(s=i.reduce(((e,t)=>{const{line:s}=t.position.start;return s<e.position.start.line?t:e}))),s}findMatchingLeaf(e,t,s=!1){let i=null;const n=!!t,{settings:{referenceViews:a,excludeViewTypes:o,includeSidePanelViewTypes:r}}=this,l=i=>{let o=!1;if(i?.view){const r=a.includes(i.view.getViewType()),l=s||!r,d=n&&a.includes(t.view.getViewType());l&&(o=!n||!s&&d?i.view.file===e:i===t)}return o},d=this.getActiveLeaf();if(l(d))i=d;else{const e=this.getOpenLeaves(o,r);i=[t,...e].find(l)}return{leaf:i??null,file:e,suggestion:null,isValidSource:!1}}extractTabNavigationType(e,t,s){const i=e?.shiftKey?"horizontal":"vertical",a=e?.key;let o=n.Keymap.isModEvent(e)??!1;return!0!==o&&"tab"!==o||("o"===a?o="window":"\\"===a&&(o="split")),o=this.applyTabCreationPreferences(o,t,s),{navType:o,splitDirection:i}}applyTabCreationPreferences(e,s=!1,i){let a=e;const{onOpenPreferNewTab:o,alwaysNewTabForSymbols:r,useActiveTabForSymbolsOnMobile:l}=this.settings;return!1===e&&(o?a=!s:i===t.SymbolList&&(a=n.Platform.isMobile?!l:r)),a}isMainPanelLeaf(e){const{workspace:t}=this.app,s=e?.getRoot();return s===t.rootSplit||s===t.floatingSplit}activateLeaf(e,t){const{workspace:s}=this.app,i={focus:!0,...t};!this.isMainPanelLeaf(e)&&s.revealLeaf(e),s.setActiveLeaf(e,{focus:!0}),e.view.setEphemeralState(i)}getOpenLeaves(e,t,s){const i=[];return this.app.workspace.iterateAllLeaves((s=>{const n=s?.view?.getViewType();this.isMainPanelLeaf(s)?e?.includes(n)||i.push(s):t?.includes(n)&&i.push(s)})),s?.orderByAccessTime&&i.sort(((e,t)=>{const s=e?.activeTime??0;return(t?.activeTime??0)-s})),i}async openFileInLeaf(e,t,s,i="vertical"){const{workspace:n}=this.app,a="split"===t?n.getLeaf(t,i):n.getLeaf(t);await a.openFile(e,s)}navigateToLeafOrOpenFile(e,t,s,i,n,a,o=!1){this.navigateToLeafOrOpenFileAsync(e,t,i,n,a,o).catch((e=>{console.log(`Switcher++: error navigating to open file. ${s}`,e)}))}async navigateToLeafOrOpenFileAsync(e,t,s,i,n,a=!1){const{leaf:o}=this.findMatchingLeaf(t,i,a),r=!!o,{navType:l,splitDirection:d}=this.extractTabNavigationType(e,r,n);await this.activateLeafOrOpenFile(l,t,o,s,d)}async activateLeafOrOpenFile(e,t,s,i,n){if(i=i??{active:!0,eState:{active:!0,focus:!0}},s&&!1===e){const e=i?.eState;this.activateLeaf(s,e)}else await this.openFileInLeaf(t,e,i,n)}renderPath(t,s,i,a,o){if(t&&s){const r=s.parent.isRoot();let l=this.settings.pathDisplayFormat,d=l===e.None||r&&this.settings.hidePathIfRoot;if(o&&(l=e.FolderPathFilenameOptional,d=!1),!d){const e=t.createDiv({cls:["suggestion-note","qsp-note"]}),o=this.getPathDisplayText(s,l,i),r=e.createSpan({cls:["qsp-path-indicator"]});n.setIcon(r,"folder");const d=e.createSpan({cls:"qsp-path"});n.renderResults(d,o,a)}}}getPathDisplayText(t,s,i){let a="";if(t){const{parent:o}=t,r=o.name,l=o.isRoot(),d=this.app.vault.getRoot().path;switch(s){case e.FolderWithFilename:a=l?`${t.name}`:n.normalizePath(`${r}/${t.name}`);break;case e.FolderOnly:a=l?d:r;break;case e.Full:a=t.path;break;case e.FolderPathFilenameOptional:i?(a=o.path,l||(a+=d)):a=this.getPathDisplayText(t,e.Full)}}return a}renderContent(e,t,s,i){const{contentEl:a,titleEl:o}=ae.createContentStructureElements(e);return n.renderResults(o,t,s,i),a}static createContentStructureElements(e){const t=e.createDiv({cls:["suggestion-content","qsp-content"]}),s=t.createDiv({cls:["suggestion-title","qsp-title"]});return{contentEl:t,titleEl:s}}static renderMarkdownContentAsync(e,t,s,i){ae.renderMarkdownContent(e,t,s,i,P.getRootComponent()).catch((e=>{console.log("Switcher++: error rendering markdown to html. ",e,`content: ${s}`)}))}static async renderMarkdownContent(e,t,s,i,a){const o=t.createSpan({cls:["qsp-rendered-container"]});if(await n.MarkdownRenderer.render(e,s,o,i,a),1===o.childNodes.length&&"P"===o.firstChild.nodeName){const e=o.firstChild;e.replaceWith(...Array.from(e.childNodes))}return o}addClassesToSuggestionContainer(e,t){const s=["mod-complex"];t&&s.push(...t),e?.addClasses(s)}fuzzySearchStrings(e,t,s){let i=!1,a=null;return t&&(a=n.fuzzySearch(e,t),i=!!a),!a&&s&&(a=n.fuzzySearch(e,s),a&&(a.score-=1)),{isPrimary:i,match:a}}fuzzySearchWithFallback(e,t,s){let i,n=d.None,a=null,o=this.fuzzySearchStrings(e,t);if(o.match)a=o.match,n=d.Primary,i=t;else if(s){const{basename:t,path:r}=s;o=this.fuzzySearchStrings(e,t,r),o.isPrimary?(n=d.Basename,i=t):o.match&&(n=d.Path,i=r),a=o.match}return{matchType:n,matchText:i,match:a}}splitSearchMatchesAtBasename(e,t){let s=null,i=null;const n=(e,t)=>{e.forEach((e=>{e[0]-=t,e[1]-=t}))};if(e&&t?.matches){const a=e.path.lastIndexOf(e.basename);if(a>=0){const{matches:e,score:o}=t,r=e[0][0],l=e[e.length-1][1];if(r>=a)s=t,n(s.matches,a);else if(l<=a)i=t;else{let t=e.length;for(;t--;){const r=e[t][0],l=t+1;if(e[t][1]<=a){i={score:o,matches:e.slice(0,l)},s={score:o,matches:e.slice(l)},n(s.matches,a);break}if(r<a){let d=e.slice(0,l);d[d.length-1]=[r,a],i={score:o,matches:d},d=e.slice(t),n(d,a),d[0][0]=0,s={score:o,matches:d};break}}}}}return{pathMatch:i,basenameMatch:s}}renderAsFileInfoPanel(e,t,s,i,n,a,o=!0){let r=null,l=null;s?.length?n===d.Primary?r=a:n===d.Path&&(l=a):i&&(s=i.basename,n===d.Basename?r=a:n===d.Path&&({pathMatch:l,basenameMatch:r}=this.splitSearchMatchesAtBasename(i,a))),this.addClassesToSuggestionContainer(e,t);const c=this.renderContent(e,s,r);this.renderPath(c,i,o,l,!!l)}getActiveLeaf(){return ae.getActiveLeaf(this.app.workspace)}static getActiveLeaf(e){const t=e?.getActiveViewOfType(n.View)?.leaf;return t??null}renderOptionalIndicators(e,t,s=null){const{showOptionalIndicatorIcons:i}=this.settings,n=new Map;if(n.set("isRecent",{iconName:"history",parentElClass:"qsp-recent-file",indicatorElClass:"qsp-recent-indicator"}),n.set("isOpenInEditor",{iconName:"lucide-file-edit",parentElClass:"qsp-open-editor",indicatorElClass:"qsp-editor-indicator"}),n.set("isBookmarked",{iconName:"lucide-bookmark",parentElClass:"qsp-bookmarked-file",indicatorElClass:"qsp-bookmarked-indicator"}),s||(s=this.createFlairContainer(e)),i)for(const[i,a]of n.entries())!0===t[i]&&(a.parentElClass&&e?.addClass(a.parentElClass),this.renderIndicator(s,[a.indicatorElClass],a.iconName));return s}renderIndicator(e,t,s,i){const a=["suggestion-flair",...t],o=e?.createSpan({cls:a});return o&&(s&&(o.addClass("svg-icon"),n.setIcon(o,s)),i&&o.setText(i)),o}createFlairContainer(e){return e?.createDiv({cls:["suggestion-aux","qsp-aux"]})}getTFileByPath(e){return E(e,this.app.vault)}applyMatchPriorityPreferences(e){return ae.applyMatchPriorityPreferences(e,this.settings,this.app.metadataCache)}static applyMatchPriorityPreferences(e,t,s){if(e?.match){const{match:i,type:n,file:a}=e;if(a&&s?.isUserIgnored(a.path))e.downranked=!0,e.match.score-=10;else if(t?.matchPriorityAdjustments?.isEnabled){const{matchPriorityAdjustments:s}=t,o=s.adjustments??{},r=s.fileExtAdjustments??{};let d=0;const c=(e,t)=>{t=t??o;let s=0;return Object.prototype.hasOwnProperty.call(t,e)&&(s=Number(t[e]?.value)),isNaN(s)?0:s},h=(t,s)=>{let i=0;return(null!==t&&t===n||e[s])&&(i=c(s)),i};d+=h(l.Bookmark,"isBookmarked"),d+=h(l.EditorList,"isOpenInEditor"),d+=h(null,"isRecent"),d+=h(null,"isAttachment"),d+=c(a?.extension,r),u(e)&&(d+=c(`h${e.item?.level}`));const m=n.toString();d+=c(m),i.score+=Math.abs(i.score)/100*(100*d)}}return e}static updateWorkspaceEnvListStatus(e,t){if(e&&t?.file){const{file:s}=t;t.isOpenInEditor=e.openWorkspaceFiles?.has(s),t.isRecent=e.mostRecentFiles?.has(s),t.isBookmarked=e.fileBookmarks?.has(s),t.isAttachment=e.attachmentFileExtensions?.has(s.extension)}return t}renderFileCreationSuggestion(e,t){this.addClassesToSuggestionContainer(e);const s=this.renderContent(e,t,null),i=this.createFlairContainer(e);return i?.createSpan({cls:"suggestion-hotkey",text:"Enter to create"}),s}createFile(e,t){const{workspace:s}=this.app,{navType:i}=this.extractTabNavigationType(t),a=s.getActiveViewOfType(n.FileView);let o="";a?.file&&(o=a.file.path),s.openLinkText(e,o,i,{active:!0}).catch((e=>{console.log("Switcher++: error creating new file. ",e)}))}}class oe extends ae{getCommandString(e){return this.settings?.workspaceListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.WorkspaceList);return this.getEnabledWorkspacesPluginInstance()&&(e.mode=t.WorkspaceList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){e.buildSearchQuery();const{hasSearchTerm:s,prepQuery:i}=e.searchQuery;this.getItems().forEach((e=>{let a=!0,o=null;s&&(o=n.fuzzySearch(i,e.id),a=!!o),a&&t.push({type:l.WorkspaceList,item:e,match:o})})),s&&n.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;return e&&(this.addClassesToSuggestionContainer(t,["qsp-suggestion-workspace"]),this.renderContent(t,e.item.id,e.match),s=!0),s}onChooseSuggestion(e,t){let s=!1;if(e){const{id:t}=e.item,i=this.getEnabledWorkspacesPluginInstance();i&&i.loadWorkspace(t),s=!0}return s}onNoResultsCreateAction(e,s){const i=this.getEnabledWorkspacesPluginInstance();if(i){const s=e.parsedCommand(t.WorkspaceList)?.parsedInput;i.saveWorkspace(s),i.setActiveWorkspace(s)}return!0}getItems(){const e=[],t=this.getEnabledWorkspacesPluginInstance()?.workspaces;return t&&Object.keys(t).forEach((t=>e.push({id:t,type:"workspaceInfo"}))),e.sort(((e,t)=>e.id.localeCompare(t.id)))}getEnabledWorkspacesPluginInstance(){return L(this.app,"workspaces")}}class re extends ae{getCommandString(e){return""}validateCommand(e,t,s,i,n){throw new Error("Method not implemented.")}getSuggestions(e){throw new Error("Method not implemented.")}renderSuggestion(e,t){let s=!1;return s=g(e)?this.renderFileSuggestion(e,t):this.renderAliasSuggestion(e,t),e?.downranked&&t.addClass("mod-downranked"),s}onChooseSuggestion(e,t){let s=!1;if(e){const{file:i}=e;this.navigateToLeafOrOpenFile(t,i,`Unable to open file from SystemSuggestion ${i.path}`),s=!0}return s}renderFileSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-file"],null,i,n,a),this.renderOptionalIndicators(t,e),s=!0}return s}renderAliasSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-alias"],e.alias,i,n,a,!1);const o=this.renderOptionalIndicators(t,e);this.renderIndicator(o,["qsp-alias-indicator"],"lucide-forward"),s=!0}return s}addPropertiesToStandardSuggestions(e,t){const{match:s,file:i}=t,n=s?.matches;let a=d.None,o=null;n&&(p(t)?(a=d.Primary,o=t.alias):(a=d.Path,o=i?.path)),t.matchType=a,t.matchText=o,ae.updateWorkspaceEnvListStatus(e.currentWorkspaceEnvList,t)}static createUnresolvedSuggestion(e,t,s,i){const n={linktext:e,type:l.Unresolved,...t};return ae.applyMatchPriorityPreferences(n,s,i)}}class le extends ae{getCommandString(e){return this.settings?.editorListCommand}validateCommand(e,s,i,n,a){e.mode=t.EditorList;const o=e.parsedCommand(t.EditorList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}getSuggestions(e){const t=[];if(e){e.buildSearchQuery();const{hasSearchTerm:s,prepQuery:i}=e.searchQuery;this.getItems().forEach((n=>{const a=n.view?.file;let o=!0,r={matchType:d.None,match:null};const l=this.getPreferredTitle(n,this.settings.preferredSourceForTitle);s&&(r=this.fuzzySearchWithFallback(i,l,a),o=r.matchType!==d.None),o&&t.push(this.createSuggestion(e.currentWorkspaceEnvList,n,a,r,l))})),s&&n.sortSearchResults(t)}return t}getPreferredTitle(e,t){return le.getPreferredTitle(e,t,this.app.metadataCache)}static getPreferredTitle(e,t,s){const{view:i}=e,n=i?.file;let a=e.getDisplayText();if("H1"===t&&n){const e=le.getFirstH1(n,s);e&&(a=a.replace(n.basename,e.heading))}return a}getItems(){const{excludeViewTypes:e,includeSidePanelViewTypes:t,orderEditorListByAccessTime:s}=this.settings;return this.getOpenLeaves(e,t,{orderByAccessTime:s})}renderSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e,o=[d.None,d.Primary].includes(n);this.renderAsFileInfoPanel(t,["qsp-suggestion-editor"],e.preferredTitle,i,n,a,o),this.renderOptionalIndicators(t,e),s=!0}return s}onChooseSuggestion(e,t){let s=!1;return e&&(this.navigateToLeafOrOpenFile(t,e.file,"Unable to reopen existing editor in new Leaf.",null,e.item,null,!0),s=!0),s}createSuggestion(e,t,s,i,n){return le.createSuggestion(e,t,s,this.settings,this.app.metadataCache,n,i)}static createSuggestion(e,t,s,i,n,a,o){o=o??{matchType:d.None,match:null,matchText:null};let r={item:t,file:s,preferredTitle:a=a??null,type:l.EditorList,...o};return r=ae.updateWorkspaceEnvListStatus(e,r),ae.applyMatchPriorityPreferences(r,i,n)}}class de extends ae{getCommandString(e){return this.settings?.bookmarksListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.BookmarksList);return this.getEnabledBookmarksPluginInstance()&&(e.mode=t.BookmarksList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){e.buildSearchQuery();const{hasSearchTerm:s,prepQuery:i}=e.searchQuery,{allBookmarks:a}=this.getItems(e);a.forEach((n=>{let a=!0,o={matchType:d.None,match:null};s&&(o=this.fuzzySearchWithFallback(i,n.bookmarkPath),a=o.matchType!==d.None),a&&t.push(this.createSuggestion(e.currentWorkspaceEnvList,n,o))})),s&&n.sortSearchResults(t)}return t}renderSuggestion(e,t){return!1}onChooseSuggestion(e,t){return!1}getPreferredTitle(e,t,s,i){let n=e.getItemTitle(t);if("H1"===i&&s){const e=this.getFirstH1(s);e&&(n=n.replace(/^[^#]*/,e.heading))}return n}getItems(e){const t=[],s=new Map,i=new Set,n=this.getEnabledBookmarksPluginInstance();if(n){const a=e?this.getActiveFacetIds(e):new Set,o=(e,r)=>{e?.forEach((e=>{if(de.isBookmarksPluginGroupItem(e))o(e.items,`${r}${e.title}/`);else if(this.isFacetedWith(a,B[e.type])){let a;if(de.isBookmarksPluginFileItem(e)){const t=this.getTFileByPath(e.path);if(t){a={item:e,bookmarkPath:null,file:t};const i=s.get(t)??[];i.push(a),s.set(t,i)}}else a={item:e,bookmarkPath:null,file:null},i.add(a);if(a){const s=this.getPreferredTitle(n,e,a.file,this.settings.preferredSourceForTitle);a.bookmarkPath=r+s,t.push(a)}}}))};o(n.items,"")}return{allBookmarks:t,fileBookmarks:s,nonFileBookmarks:i}}getEnabledBookmarksPluginInstance(){return L(this.app,"bookmarks")}createSuggestion(e,t,s){return de.createSuggestion(e,t,this.settings,this.app.metadataCache,s)}static createSuggestion(e,t,s,i,n){let a={type:l.Bookmark,item:t.item,bookmarkPath:t.bookmarkPath,file:t.file,...n};return a=ae.updateWorkspaceEnvListStatus(e,a),ae.applyMatchPriorityPreferences(a,s,i)}static isBookmarksPluginFileItem(e){return h(e,"type","file")}static isBookmarksPluginGroupItem(e){return h(e,"type","group")}}class ce extends ae{getCommandString(e){return this.settings?.headingsListCommand}validateCommand(e,s,i,n,a){e.mode=t.HeadingsList;const o=e.parsedCommand(t.HeadingsList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}onChooseSuggestion(e,t){let s=!1;if(e){const{start:{line:i,col:n},end:a}=e.item.position,o={active:!0,focus:!0,startLoc:{line:i,col:n},endLoc:a,line:i,cursor:{from:{line:i,ch:n},to:{line:i,ch:n}}};this.navigateToLeafOrOpenFile(t,e.file,"Unable to navigate to heading for file.",{active:!0,eState:o}),s=!0}return s}renderSuggestion(e,t){let s=!1;if(e){const{item:i,file:n,match:a}=e,{app:o,settings:l}=this;this.addClassesToSuggestionContainer(t,["qsp-suggestion-headings",`qsp-headings-l${i.level}`]);const{contentEl:d,titleEl:c}=ae.createContentStructureElements(t);ce.renderHeadingContent(o,l,c,i,n,a),this.renderPath(d,n);const h=this.createFlairContainer(t);this.renderOptionalIndicators(t,e,h),this.renderIndicator(h,["qsp-headings-indicator"],null,r[i.level]),e.downranked&&t.addClass("mod-downranked"),s=!0}return s}static renderHeadingContent(e,t,s,i,a,o,r){const{heading:l}=i,{renderMarkdownContentInSuggestions:{isEnabled:d,renderHeadings:c}}=t;(r=r??(d&&c))?ae.renderMarkdownContentAsync(e,s,l,a.path):n.renderResults(s,l,o)}getAvailableFacets(e){const{settings:{shouldSearchHeadings:t,shouldSearchBookmarks:s,shouldSearchFilenames:i,shouldSearchRecentFiles:n,builtInSystemOptions:{showAttachments:a,showAllFileTypes:o}}}=this,r=a||o,l={[D.RecentFiles]:n,[D.Bookmarks]:s,[D.Filenames]:i,[D.Headings]:t,[D.ExternalFiles]:r};return this.getFacets(e.mode).filter((e=>(Object.prototype.hasOwnProperty.call(l,e.id)&&(e.isAvailable=l[e.id]),e.isAvailable)))}getSuggestions(e){let t=[];if(e){e.buildSearchQuery();const{hasSearchTerm:s}=e.searchQuery,{settings:i}=this,a=this.getActiveFacetIds(e),o=!!a.size;if(s||o){const{limit:s}=i,{app:{vault:o}}=this,r={headings:i.shouldSearchHeadings,allHeadings:i.searchAllHeadings,aliases:i.shouldShowAlias,bookmarks:i.shouldSearchBookmarks,filename:i.shouldSearchFilenames,filenameAsFallback:!i.strictHeadingsOnly,unresolved:!i.showExistingOnly};this.getItems([o.getRoot()],e,t,a,r),n.sortSearchResults(t),s>0&&t.length>s&&(t=t.slice(0,s))}else this.getSuggestionsForEditorsAndRecentFiles(e,t,new Set,{editors:!0,recentFiles:i.shouldSearchRecentFiles})}return t}getItems(e,t,s,i,n){const a=!!i.size;this.getSuggestionsForEditorsAndRecentFiles(t,s,i,{editors:!1,recentFiles:!1});const o={fileBookmarks:n.bookmarks,nonFileBookmarks:n.bookmarks};this.getSuggestionsForBookmarks(t,s,i,o);const r={headings:n.headings,allHeadings:n.allHeadings,aliases:n.aliases,filename:n.filename,filenameAsFallback:n.filenameAsFallback};this.getSuggestionForFiles(t,e,s,i,r),n.unresolved&&!a&&this.addUnresolvedSuggestions(s,t.searchQuery.prepQuery)}getSuggestionsForBookmarks(e,t,s,i){const n=s.size,{prepQuery:a}=e.searchQuery,{fileBookmarks:o,nonFileBookmarks:r}=e.currentWorkspaceEnvList;if(n){const e=s.has(D.Bookmarks);i=Object.assign(i,{fileBookmarks:e,nonFileBookmarks:e})}const l=s=>{for(const i of s)this.addBookmarkSuggestion(e,t,a,i)};i.fileBookmarks&&o.forEach((e=>{l(e)})),i.nonFileBookmarks&&l(r)}getSuggestionForFiles(e,t,s,i,n){if(!!i.size){const e=this.isFacetedWith(i,D.Headings),t=this.isFacetedWith(i,D.ExternalFiles)||this.isFacetedWith(i,D.Filenames);let s=!1,a=!1;e&&(s=!0===n.allHeadings,a=!0===n.filenameAsFallback),n=Object.assign(n,{headings:e,aliases:!1,filename:t,allHeadings:s,filenameAsFallback:a})}else n=Object.assign({headings:!0,allHeadings:!0,aliases:!0,filename:!0,filenameAsFallback:!0},n);if([n.headings,n.aliases,n.filename].some((e=>!0===e))){const{prepQuery:a}=e.searchQuery,{excludeFolders:o}=this.settings,r=I(o);let l=Array.prototype.concat(t);for(;l.length>0;){const t=l.pop();k(t)?this.shouldIncludeFile(t,i)&&this.addSuggestionsForFile(e,s,t,a,n):r(t.path)||(l=l.concat(t.children))}}}addSuggestionsForFile(e,t,s,i,n){let a=!1;n.headings&&(a=this.addHeadingSuggestions(e,t,i,s,n.allHeadings)),(n.filename||!a&&n.filenameAsFallback)&&this.addFileSuggestions(e,t,i,s),n.aliases&&this.addAliasSuggestions(e,t,i,s)}shouldIncludeFile(e,t=new Set){let s=!1;if(e){const i=new Set(["md","canvas"]),{extension:n}=e,{app:{viewRegistry:a,metadataCache:o},settings:{excludeObsidianIgnoredFiles:r,fileExtAllowList:l,builtInSystemOptions:{showAttachments:d,showAllFileTypes:c}}}=this;if(!(r&&o.isUserIgnored(e.path)))if(t.has(D.ExternalFiles)){const e=d||c;s=!i.has(n)&&e}else{s=this.isExternalFileTypeAllowed(e,a,d,c,l)||i.has(n)}}return s}isExternalFileTypeAllowed(e,t,s,i,n){const{extension:a}=e;let o=t.isExtensionRegistered(a)?s:i;if(!o){o=new Set(n).has(a)}return o}addAliasSuggestions(e,t,s,i){const{metadataCache:n}=this.app,a=n.getFileCache(i)?.frontmatter;if(a){const n=O.getAliases(a);let o=n.length;for(;o--;){const a=n[o],{match:r}=this.fuzzySearchWithFallback(s,a);r&&t.push(this.createAliasSuggestion(e,a,i,r))}}}addFileSuggestions(e,t,s,i){const{match:n,matchType:a,matchText:o}=this.fuzzySearchWithFallback(s,null,i);n&&t.push(this.createFileSuggestion(e,i,n,a,o))}addBookmarkSuggestion(e,t,s,i){const n=this.fuzzySearchWithFallback(s,i.bookmarkPath);if(n.match){const s=de.createSuggestion(e.currentWorkspaceEnvList,i,this.settings,this.app.metadataCache,n);t.push(s)}}addHeadingSuggestions(e,t,s,i,n){const{metadataCache:a}=this.app,o=a.getFileCache(i)?.headings??[];let r=null,l=!1,d=o.length;for(;d--;){const a=o[d];let c=!1;if(n&&(c=this.matchAndPushHeading(e,t,s,i,a)),1===a.level){const{line:e}=a.position.start;(null===r||e<r.position.start.line)&&(r=a,l=c)}}return!n&&r&&(l=this.matchAndPushHeading(e,t,s,i,r)),l}matchAndPushHeading(e,t,s,i,n){const{match:a}=this.fuzzySearchWithFallback(s,n.heading);return a&&t.push(this.createHeadingSuggestion(e,n,i,a)),!!a}addUnresolvedSuggestions(e,t){const{metadataCache:s}=this.app,{unresolvedLinks:i}=s,n=new Set,a=Object.keys(i);let o=a.length;for(;o--;){const e=a[o],t=Object.keys(i[e]);let s=t.length;for(;s--;)n.add(t[s])}const r=Array.from(n);for(o=r.length;o--;){const i=r[o],n=this.fuzzySearchWithFallback(t,i);n.matchType!==d.None&&e.push(re.createUnresolvedSuggestion(i,n,this.settings,s))}}createAliasSuggestion(e,t,s,i){let n={alias:t,file:s,...this.createSearchMatch(i,d.Primary,t),type:l.Alias};return n=ae.updateWorkspaceEnvListStatus(e.currentWorkspaceEnvList,n),this.applyMatchPriorityPreferences(n)}createFileSuggestion(e,t,s,i,n){let a={file:t,match:s,matchType:i,matchText:n,type:l.File};return a=ae.updateWorkspaceEnvListStatus(e.currentWorkspaceEnvList,a),this.applyMatchPriorityPreferences(a)}createHeadingSuggestion(e,t,s,i){let n={item:t,file:s,...this.createSearchMatch(i,d.Primary,t.heading),type:l.HeadingsList};return n=ae.updateWorkspaceEnvListStatus(e.currentWorkspaceEnvList,n),this.applyMatchPriorityPreferences(n)}createSearchMatch(e,t,s){let i=d.None,n=null;return e&&(i=t,n=s),{match:e,matchType:i,matchText:n}}addRecentFilesSuggestions(e,t,s,i){const n=this.getFirstH1(e),{match:a,matchType:o,matchText:r}=this.fuzzySearchWithFallback(s,n?.heading,e);if(a){let s;s=o===d.Primary?this.createHeadingSuggestion(t,n,e,a):this.createFileSuggestion(t,e,a,o,r),i.push(s)}}addOpenEditorSuggestions(e,t,s,i){const n=e?.view?.file,{settings:a,app:{metadataCache:o}}=this,r=le.getPreferredTitle(e,a.preferredSourceForTitle,o),l=this.fuzzySearchWithFallback(s,r,n);if(l.match){const s=le.createSuggestion(t.currentWorkspaceEnvList,e,n,a,o,r,l);i.push(s)}}getSuggestionsForEditorsAndRecentFiles(e,t,s,i){const n=e.searchQuery?.prepQuery;if((i=s.has(D.RecentFiles)?Object.assign(i,{editors:!1,recentFiles:!0}):Object.assign({editors:!0,recentFiles:!0},i)).editors){const s=e.currentWorkspaceEnvList?.openWorkspaceLeaves;s?.forEach((s=>{this.addOpenEditorSuggestions(s,e,n,t)}))}if(i.recentFiles){const i=e.currentWorkspaceEnvList?.mostRecentFiles;i?.forEach((i=>{this.shouldIncludeFile(i,s)&&this.addRecentFilesSuggestions(i,e,n,t)}))}}onNoResultsCreateAction(e,s){const i=e.parsedCommand(t.HeadingsList)?.parsedInput;return this.createFile(i,s),!0}}const he={file:"lucide-file-text",text:"lucide-sticky-note",link:"lucide-globe",group:"create-group"};class me extends ae{getCommandString(e){const{settings:t}=this;return e?.useActiveEditorAsSource?t.symbolListActiveEditorCommand:t.symbolListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.SymbolList),r=this.getSourceInfoForSymbolOperation(n,a,0===s,e.sessionOpts);return r&&(e.mode=t.SymbolList,o.source=r,o.index=s,o.parsedInput=i,o.isValidated=!0),o}async getSuggestions(e){const s=[];if(e){this.inputInfo=e,e.buildSearchQuery();const{hasSearchTerm:i,prepQuery:a}=e.searchQuery,o=e.parsedCommand(t.SymbolList);(await this.getItems(o.source,i)).forEach((e=>{let t=!0,r=null;if(i&&(r=n.fuzzySearch(a,me.getSuggestionTextForSymbol(e)),t=!!r),t){const{file:t}=o.source;s.push({type:l.SymbolList,file:t,item:e,match:r})}})),i&&n.sortSearchResults(s)}return s}renderSuggestion(e,t){let s=!1;if(e){const{item:i,file:a,match:o}=e,r=["qsp-suggestion-symbol"];Object.prototype.hasOwnProperty.call(i,"indentLevel")&&this.settings.symbolsInLineOrder&&!this.inputInfo?.searchQuery?.hasSearchTerm&&r.push(`qsp-symbol-l${i.indentLevel}`),this.addClassesToSuggestionContainer(t,r);const{titleEl:l}=ae.createContentStructureElements(t);if(b(i.symbol))ce.renderHeadingContent(this.app,this.settings,l,i.symbol,a,o);else{const e=me.getSuggestionTextForSymbol(i);n.renderResults(l,e,o)}this.addSymbolIndicator(i,t),s=!0}return s}onChooseSuggestion(e,i){let n=!1;if(e){const a=this.inputInfo.parsedCommand(),{leaf:o,file:r}=a.source,l={active:!0},{item:d}=e;d.symbolType!==s.CanvasNode&&(l.eState=this.constructMDFileNavigationState(d).eState),this.navigateToLeafOrOpenFileAsync(i,r,l,o,t.SymbolList).then((()=>{const{symbol:e}=d;me.isCanvasSymbolPayload(d,e)&&this.zoomToCanvasNode(this.getActiveLeaf().view,e)}),(e=>{console.log(`Switcher++: Unable to navigate to symbols for file ${r.path}`,e)})),n=!0}return n}reset(){this.inputInfo=null}getAvailableFacets(e){const i=e.parsedCommand(t.SymbolList),n=me.isCanvasFile(i?.source?.file),a=this.getFacets(e.mode),o=new Set(Object.values(M)),r=new Set(Object.values(s).filter((e=>isNaN(Number(e)))));return a.forEach((e=>{const{id:t}=e;e.isAvailable=n?o.has(t):r.has(t)})),a.filter((e=>e.isAvailable))}zoomToCanvasNode(e,t){if(me.isCanvasView(e)){const s=e.canvas,i=s.nodes.get(t.id);s.selectOnly(i),s.zoomToSelection()}}constructMDFileNavigationState(e){const{start:{line:t,col:s},end:i}=e.symbol.position;return{eState:{active:!0,focus:!0,startLoc:{line:t,col:s},endLoc:i,line:t,cursor:{from:{line:t,ch:s},to:{line:t,ch:s}}}}}getSourceInfoForSymbolOperation(e,s,i,n){const a=this.inputInfo;let o=null,r=t.Standard;a&&(o=a.parsedCommand().source,r=a.mode);const l=r===t.SymbolList&&!!o,d=this.getEditorInfo(s),c=this.getSuggestionInfo(e);let h=null;return l?h=o:c.isValidSource&&!n.useActiveEditorAsSource?h=c:d.isValidSource&&i&&(h=d),h}async getItems(e,t){let s=[],i=!1,n=!1;return t||({selectNearestHeading:n,symbolsInLineOrder:i}=this.settings),s=await this.getSymbolsFromSource(e,i),n&&me.FindNearestHeadingSymbol(s,e),s}static FindNearestHeadingSymbol(e,t){const s=t?.cursor?.line;if(s){let t=null;const i=e.filter((e=>b(e.symbol)));i.length&&(t=i.reduce(((e,t)=>{const{line:i}=t.symbol.position.start;return i>(e?e.symbol.position.start.line:-1)&&i<=s?t:e}))),t&&(t.isSelected=!0)}}async getSymbolsFromSource(e,t){const{app:{metadataCache:i},inputInfo:n}=this,a=[];if(e?.file){const{file:o}=e,r=this.getActiveFacetIds(n);if(me.isCanvasFile(o))await this.addCanvasSymbolsFromSource(o,a,r);else{const e=i.getFileCache(o);if(e){const i=(e=[],t)=>{this.shouldIncludeSymbol(t,r)&&e.forEach((e=>a.push({type:"symbolInfo",symbol:e,symbolType:t})))};i(e.headings,s.Heading),i(e.tags,s.Tag),this.addLinksFromSource(e.links,a,r),i(e.embeds,s.Embed),await this.addCalloutsFromSource(o,e.sections?.filter((e=>"callout"===e.type)),a,r),t&&me.orderSymbolsByLineNumber(a)}}}return a}shouldIncludeSymbol(e,t){let i=!1;return i="string"==typeof e?this.isFacetedWith(t,e):this.settings.isSymbolTypeEnabled(e)&&this.isFacetedWith(t,s[e]),i}async addCanvasSymbolsFromSource(e,t,i){let n;try{const t=await this.app.vault.cachedRead(e);n=JSON.parse(t).nodes}catch(t){console.log(`Switcher++: error reading file to extract canvas node information. ${e.path} `,t)}Array.isArray(n)&&n.forEach((e=>{this.shouldIncludeSymbol(M[e.type],i)&&t.push({type:"symbolInfo",symbolType:s.CanvasNode,symbol:{...e}})}))}async addCalloutsFromSource(e,t,i,n){const{app:{vault:a}}=this;if(this.shouldIncludeSymbol(s.Callout,n)&&t?.length&&e){let n=null;try{n=await a.cachedRead(e)}catch(t){console.log(`Switcher++: error reading file to extract callout information. ${e.path} `,t)}if(n)for(const e of t){const{start:t,end:a}=e.position,o=n.slice(t.offset,a.offset).match(/^> \[!([^\]]+)\][+-]?(.*?)(?:\n>|$)/);if(o){const t=o[1],n={calloutTitle:o[o.length-1].trim(),calloutType:t,...e};i.push({type:"symbolInfo",symbolType:s.Callout,symbol:n})}}}}addLinksFromSource(e,t,i){const{settings:n}=this;if(e=e??[],this.shouldIncludeSymbol(s.Link,i))for(const i of e){const e=T(i);(n.excludeLinkSubTypes&e)===e||t.push({type:"symbolInfo",symbol:i,symbolType:s.Link})}}static orderSymbolsByLineNumber(e){const t=e.sort(((e,t)=>{const{start:s}=e.symbol.position,{start:i}=t.symbol.position,n=s.line-i.line;return 0===n?s.col-i.col:n}));let s=0;return t.forEach((e=>{let t=0;b(e.symbol)?(s=e.symbol.level,t=e.symbol.level-1):t=s,e.indentLevel=t})),t}static getSuggestionTextForSymbol(e){const{symbol:t}=e;let s;if(b(t))s=t.heading;else if(h(t,"tag"))s=t.tag.slice(1);else if(S(t))s=t.calloutTitle;else if(me.isCanvasSymbolPayload(e,t))s=me.getSuggestionTextForCanvasNode(t);else{const e=t;({link:s}=e);const{displayText:i}=e;i&&i!==s&&(s+=`|${i}`)}return s}static getSuggestionTextForCanvasNode(e){let t="";const s={file:()=>e.file,text:()=>e.text,link:()=>e.url,group:()=>e.label}[e?.type];return s&&(t=s()),t}addSymbolIndicator(e,t){const{symbolType:s,symbol:i}=e,a=["qsp-symbol-indicator"],l=this.createFlairContainer(t);if(S(i)){a.push("suggestion-flair","callout","callout-icon","svg-icon");const e=l.createSpan({cls:a,attr:{"data-callout":i.calloutType}}),t=e.getCssPropertyValue("--callout-icon");n.setIcon(e,t)}else if(me.isCanvasSymbolPayload(e,i)){const e=he[i.type];this.renderIndicator(l,a,e,null)}else{let e;e=b(i)?r[i.level]:o[s],this.renderIndicator(l,a,null,e)}}static isCanvasSymbolPayload(e,t){return e.symbolType===s.CanvasNode}static isCanvasFile(e){return"canvas"===e?.extension}static isCanvasView(e){return"canvas"===e?.getViewType()}}const ue=[];class ge extends ae{getCommandString(e){return this.settings?.commandListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.CommandList);return this.getEnabledCommandPalettePluginInstance()&&(e.mode=t.CommandList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){e.buildSearchQuery();const{hasSearchTerm:s,prepQuery:i}=e.searchQuery;this.getItems(e,s).forEach((e=>{let a=!0,o=null;s&&(o=n.fuzzySearch(i,e.cmd.name),a=!!o),a&&t.push(this.createSuggestion(e,o))})),s&&n.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;if(e){const{item:i,match:n,isPinned:a,isRecent:o}=e;this.addClassesToSuggestionContainer(t,["qsp-suggestion-command"]),this.renderContent(t,i.name,n);const r=this.createFlairContainer(t);this.renderHotkeyForCommand(i.id,this.app,r),i.icon&&this.renderIndicator(r,[],i.icon),a?this.renderIndicator(r,[],"filled-pin"):o&&this.renderOptionalIndicators(t,e,r),s=!0}return s}renderHotkeyForCommand(e,t,s){try{const{hotkeyManager:i}=t;if(i.getHotkeys(e)||i.getDefaultHotkeys(e)){const t=i.printHotkeyForCommand(e);t?.length&&s.createEl("kbd",{cls:"suggestion-hotkey",text:t})}}catch(t){console.log("Switcher++: error rendering hotkey for command id: ",e,t)}}onChooseSuggestion(e){let t=!1;if(e){const{item:s}=e;this.app.commands.executeCommandById(s.id),this.saveUsageToList(s.id,ue),t=!0}return t}saveUsageToList(e,t){if(t){const s=t.indexOf(e);s>-1&&t.splice(s,1),t.unshift(e),t.splice(25)}}getItems(e,t){let s=[];const i=this.getActiveFacetIds(e);if(!!i.size)s=this.getPinnedAndRecentCommands(i);else if(t)s=this.getAllCommands();else{const e=this.getPinnedAndRecentCommands(i);s=e.length?e:this.getAllCommands()}return s}getPinnedAndRecentCommands(e){const t=[],s=this.getPinnedCommandIds(),i=this.getRecentCommandIds(),n=e=>{let t=null;const n=this.app.commands.findCommand(e);return n&&(t={isPinned:s.has(e),isRecent:i.has(e),cmd:n}),t},a=(s,i)=>{this.isFacetedWith(e,s)&&i.forEach((e=>{const s=n(e);s&&t.push(s)}))};a(V.Pinned,Array.from(s));const o=this.isFacetedWith(e,V.Pinned),r=Array.from(i).filter((e=>!o||o&&!s.has(e)));return a(V.Recent,r),t}getAllCommands(){const e=this.getPinnedCommandIds(),t=this.getRecentCommandIds();return this.app.commands.listCommands()?.sort(((e,t)=>e.name.localeCompare(t.name))).map((s=>({isPinned:e.has(s.id),isRecent:t.has(s.id),cmd:s})))}getPinnedCommandIds(){const e=this.getEnabledCommandPalettePluginInstance()?.options?.pinned;return new Set(e??[])}getRecentCommandIds(){return new Set(ue)}createSuggestion(e,t){const{cmd:s,isPinned:i,isRecent:n}=e,a={type:l.CommandList,item:s,isPinned:i,isRecent:n,match:t};return this.applyMatchPriorityPreferences(a)}getEnabledCommandPalettePluginInstance(){return ge.getEnabledCommandPalettePluginInstance(this.app)}static getEnabledCommandPalettePluginInstance(e){return L(e,"command-palette")}}class pe extends ae{getCommandString(e){const{settings:t}=this;return e?.useActiveEditorAsSource?t.relatedItemsListActiveEditorCommand:t.relatedItemsListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.RelatedItemsList),r=this.getSourceInfo(n,a,0===s,e.sessionOpts);return r&&(e.mode=t.RelatedItemsList,o.source=r,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const s=[];if(e){this.inputInfo=e,e.buildSearchQuery();const{hasSearchTerm:i}=e.searchQuery,a=e.parsedCommand(t.RelatedItemsList);this.getItems(a.source,e).forEach((t=>{const i=this.searchAndCreateSuggestion(e,t);i&&s.push(i)})),i&&n.sortSearchResults(s)}return s}renderSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a,item:o}=e,r=new Map([[c.Backlink,"links-coming-in"],[c.DiskLocation,"folder-tree"],[c.OutgoingLink,"links-going-out"]]);t.setAttribute("data-relation-type",o.relationType),this.renderAsFileInfoPanel(t,["qsp-suggestion-related"],e.preferredTitle,i,n,a);const l=this.renderOptionalIndicators(t,e);e.item.count&&this.renderIndicator(l,[],null,`${e.item.count}`),this.renderIndicator(l,["qsp-related-indicator"],r.get(o.relationType)),s=!0}return s}onChooseSuggestion(e,t){let s=!1;if(e){const{file:i}=e;this.navigateToLeafOrOpenFile(t,i,`Unable to open related file ${i.path}`),s=!0}return s}getPreferredTitle(e,t){let s=null;const{file:i,unresolvedText:n}=e;if(i)"H1"===t&&(s=this.getFirstH1(i)?.heading??null);else{!!n?.length&&(s=n)}return s}searchAndCreateSuggestion(e,t){const{file:s,unresolvedText:i}=t;let n={matchType:d.None,match:null};const a=null===s&&i?.length,{currentWorkspaceEnvList:o,searchQuery:{hasSearchTerm:r,prepQuery:l}}=e,{settings:c,app:{metadataCache:h}}=this,m=this.getPreferredTitle(t,c.preferredSourceForTitle);return r&&(n=this.fuzzySearchWithFallback(l,m,s),n.matchType===d.None)?null:a?re.createUnresolvedSuggestion(m,n,c,h):this.createSuggestion(o,t,n,m)}getItems(e,t){const s=[],{metadataCache:i}=this.app,{file:n,suggestion:a}=e,o=new Set(this.settings.enabledRelatedItems),r=this.getActiveFacetIds(t),l=e=>o.has(e)&&this.isFacetedWith(r,e);if(l(c.Backlink)){let e=n?.path,t=i.resolvedLinks;f(a)&&(e=a.linktext,t=i.unresolvedLinks),this.addBacklinks(e,t,s)}return l(c.DiskLocation)&&this.addRelatedDiskFiles(n,s),l(c.OutgoingLink)&&this.addOutgoingLinks(n,s),s}addRelatedDiskFiles(e,t){const{excludeRelatedFolders:s,excludeOpenRelatedFiles:i}=this.settings;if(e){const n=I(s);let a=[...e.parent.children];for(;a.length>0;){const s=a.pop();if(k(s)){s===e||i&&!!this.findMatchingLeaf(s).leaf||t.push({file:s,relationType:c.DiskLocation})}else n(s.path)||(a=a.concat(s.children))}}}addOutgoingLinks(e,t){if(e){const s=new Map,i=new Map,{metadataCache:n}=this.app,a=n.getFileCache(e).links??[],o=e=>!!e&&!!(e.count+=1);a.forEach((a=>{const r=a.link,l=n.getFirstLinkpathDest(r,e.path);let d;l?o(i.get(l))||l===e||(d={file:l,relationType:c.OutgoingLink,count:1},i.set(l,d),t.push(d)):o(s.get(r))||(d={file:null,relationType:c.OutgoingLink,unresolvedText:r,count:1},s.set(r,d),t.push(d))}))}}addBacklinks(e,t,s){for(const[i,n]of Object.entries(t))if(i!==e&&Object.prototype.hasOwnProperty.call(n,e)){const t=n[e],a=this.getTFileByPath(i);a&&s.push({count:t,file:a,relationType:c.Backlink})}}reset(){this.inputInfo=null}getSourceInfo(e,s,i,n){const a=this.inputInfo;let o=null,r=t.Standard;a&&(o=a.parsedCommand().source,r=a.mode);const l=r===t.RelatedItemsList&&!!o,d=this.getEditorInfo(s),c=this.getSuggestionInfo(e);!c.isValidSource&&f(e)&&(c.isValidSource=!0);let h=null;return l?h=o:c.isValidSource&&!n.useActiveEditorAsSource?h=c:d.isValidSource&&i&&(h=d),h}createSuggestion(e,t,s,i){let n={item:t,file:t?.file,type:l.RelatedItemsList,preferredTitle:i,...s};return n=ae.updateWorkspaceEnvListStatus(e,n),this.applyMatchPriorityPreferences(n)}}class fe extends ae{constructor(){super(...arguments),this.mobileVaultChooserMarker={type:l.VaultList,match:null,item:null,pathSegments:null}}getCommandString(e){return this.settings?.vaultListCommand}validateCommand(e,s,i,n,a){e.mode=t.VaultList;const o=e.parsedCommand(t.VaultList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}getSuggestions(e){const t=[];if(e){e.buildSearchQuery();const{hasSearchTerm:s,prepQuery:i}=e.searchQuery;(n.Platform.isDesktop?this.getItems():[this.mobileVaultChooserMarker]).forEach((e=>{let n=!0;if(s){const t=this.fuzzySearchWithFallback(i,null,e.pathSegments);Object.assign(e,t),n=!!t.match}n&&t.push(e)})),s&&n.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;return e&&(this.addClassesToSuggestionContainer(t,["qsp-suggestion-vault"]),s=!0,n.Platform.isDesktop?this.renderVaultSuggestion(e,t):e===this.mobileVaultChooserMarker&&this.renderMobileHintSuggestion(t)),s}renderMobileHintSuggestion(e){this.renderContent(e,"Show mobile vault chooser",null)}renderVaultSuggestion(e,t){const{pathSegments:s,matchType:i}=e;let{match:a}=e,o=null;i===d.Basename&&(o=a,a=null);const r=this.renderContent(t,s.basename,o).createDiv({cls:["suggestion-note","qsp-note"]}),l=r.createSpan({cls:["qsp-path-indicator"]}),c=r.createSpan({cls:"qsp-path"});n.setIcon(l,"folder"),n.renderResults(c,s.path,a)}onChooseSuggestion(e,t){let s=!1;return e&&(n.Platform.isDesktop?s=a.ipcRenderer.sendSync("vault-open",e.pathSegments?.path,!1):e===this.mobileVaultChooserMarker&&(this.app.openVaultChooser(),s=!0)),s}getItems(){const e=[];try{const t=a.ipcRenderer.sendSync("vault-list");if(t)for(const[s,{path:i,open:n}]of Object.entries(t)){const t=w(i),a={type:l.VaultList,match:null,item:s,isOpen:!!n,pathSegments:{basename:t,path:i}};e.push(a)}}catch(e){console.log("Switcher++: error retrieving list of available vaults. ",e)}return e.sort(((e,t)=>e.pathSegments.basename.localeCompare(t.pathSegments.basename)))}}const ye={};class be{constructor(e,s,i){this.app=e,this.settings=s,this.exKeymap=i,this.sessionOpts={},this.noResultActionModes=[t.HeadingsList,t.WorkspaceList];const a=new re(e,s),o=new Map([[t.SymbolList,new me(e,s)],[t.WorkspaceList,new oe(e,s)],[t.HeadingsList,new ce(e,s)],[t.EditorList,new le(e,s)],[t.BookmarksList,new de(e,s)],[t.CommandList,new ge(e,s)],[t.RelatedItemsList,new pe(e,s)],[t.VaultList,new fe(e,s)]]);this.handlersByMode=o,this.handlersByType=new Map([[l.CommandList,o.get(t.CommandList)],[l.EditorList,o.get(t.EditorList)],[l.HeadingsList,o.get(t.HeadingsList)],[l.RelatedItemsList,o.get(t.RelatedItemsList)],[l.Bookmark,o.get(t.BookmarksList)],[l.SymbolList,o.get(t.SymbolList)],[l.WorkspaceList,o.get(t.WorkspaceList)],[l.VaultList,o.get(t.VaultList)],[l.File,a],[l.Alias,a]]),this.handlersByCommand=new Map([[s.editorListCommand,o.get(t.EditorList)],[s.workspaceListCommand,o.get(t.WorkspaceList)],[s.headingsListCommand,o.get(t.HeadingsList)],[s.bookmarksListCommand,o.get(t.BookmarksList)],[s.commandListCommand,o.get(t.CommandList)],[s.symbolListCommand,o.get(t.SymbolList)],[s.symbolListActiveEditorCommand,o.get(t.SymbolList)],[s.relatedItemsListCommand,o.get(t.RelatedItemsList)],[s.vaultListCommand,o.get(t.VaultList)],[s.relatedItemsListActiveEditorCommand,o.get(t.RelatedItemsList)]]),this.debouncedGetSuggestions=n.debounce(this.getSuggestions.bind(this),s.headingsSearchDebounceMilli,!0),this.reset()}onOpen(){const{exKeymap:e,settings:t}=this;e.isOpen=!0,t.quickFilters?.shouldResetActiveFacets&&Object.values(t.quickFilters.facetList).forEach((e=>e.isActive=!1))}onClose(){this.exKeymap.isOpen=!1,P.unload()}setSessionOpenMode(e,s,i){if(this.reset(),s?.setSuggestions([]),e!==t.Standard){const t=this.getHandler(e).getCommandString(i);Object.assign(this.sessionOpts,i,{openModeString:t})}if(ye[e]&&(e===t.CommandList&&this.settings.preserveCommandPaletteLastInput||e!==t.CommandList&&this.settings.preserveQuickSwitcherLastInput)){const t=ye[e];this.lastInput=t.inputText}}insertSessionOpenModeOrLastInputString(e){const{sessionOpts:t,lastInput:s}=this,i=t.openModeString??null;if(s&&s!==i){e.value=s;const t=i?i.length:0;e.setSelectionRange(t,e.value.length)}else null!==i&&""!==i&&(e.value=i,t.openModeString=null);this.lastInput=null}updateSuggestions(e,s,i){const{exKeymap:n,settings:a,sessionOpts:o}=this;let r=!1;this.debouncedGetSuggestions.cancel();const l=ae.getActiveLeaf(this.app.workspace),d=be.getActiveSuggestion(s),c=this.determineRunMode(e,d,l,o);this.inputInfo=c;const{mode:h}=c;return ye[h]=c,this.updatedKeymapForMode(c,s,i,n,a,l),this.toggleMobileCreateFileButton(i,h,a),h!==t.Standard&&(h===t.HeadingsList&&c.parsedCommand().parsedInput?.length?this.debouncedGetSuggestions(c,s,i):this.getSuggestions(c,s,i),r=!0),r}toggleMobileCreateFileButton(e,s,i){if(!n.Platform.isMobile)return;const a=t[s];e.allowCreateNewFile=i.allowCreateNewFileInModeNames.includes(a),e.allowCreateNewFile||e.createButtonEl?.detach()}updatedKeymapForMode(e,t,s,i,n,a){const{mode:o}=e,r=this.getHandler(o),l=r?.getAvailableFacets(e)??[],d={mode:o,activeLeaf:a,facets:{facetList:l,facetSettings:n.quickFilters,onToggleFacet:((o,l)=>{if(l){const e=o.some((e=>!0===e.isActive));r.activateFacet(o,!e)}else r.activateFacet(o,!o[0].isActive);return this.updatedKeymapForMode(e,t,s,i,n,a),this.getSuggestions(e,t,s),!1}).bind(this)}};i.updateKeymapForMode(d)}renderSuggestion(e,s){const{inputInfo:i,settings:{overrideStandardModeBehaviors:n}}=this,{mode:a}=i,o=a===t.HeadingsList;let r=!1;const d=new Set([l.Unresolved,l.Bookmark]);if(null===e){if(o){const e=this.getHandler(a),t=i.parsedCommand(a)?.parsedInput;e.renderFileCreationSuggestion(s,t),r=!0}}else if(!d.has(e.type)&&(n||o||y(e))){const n=this.getHandler(e);n&&(a===t.Standard&&n.addPropertiesToStandardSuggestions(i,e),r=n.renderSuggestion(e,s))}return r}onChooseSuggestion(e,s){const{inputInfo:i,settings:{overrideStandardModeBehaviors:n}}=this,{mode:a}=i,o=a===t.HeadingsList;let r=!1;const d=new Set([l.Unresolved,l.Bookmark]);if(null===e){if(this.noResultActionModes.includes(a)){const e=this.getHandler(a);r=!!e?.onNoResultsCreateAction(i,s)}}else if(!d.has(e.type)&&(n||o||y(e))){const t=this.getHandler(e);t&&(r=t.onChooseSuggestion(e,s))}return r}determineRunMode(e,s,i,n){const a=e??"",o=new ne(a,t.Standard,n);return this.addWorkspaceEnvLists(o),0===a.length&&this.reset(),this.validatePrefixCommands(o,s,i,this.settings),o}getSuggestions(e,t,s){t.setSuggestions([]);const{mode:i}=e,n=this.getHandler(i).getSuggestions(e),a=n=>{n?.length?(t.setSuggestions(n),be.setActiveSuggestion(i,t),this.exKeymap?.renderQuickOpenFlairIcons(t.suggestions,this.settings)):this.noResultActionModes.includes(i)&&e.parsedCommand(i).parsedInput?s.onNoSuggestion():t.setSuggestions(null)};Array.isArray(n)?a(n):n.then((e=>{a(e)}),(e=>{console.log("Switcher++: error retrieving suggestions as Promise. ",e)}))}removeEscapeCommandCharFromInput(e,t,s){const i=e.inputTextSansEscapeChar.replace(new RegExp(`(?:${v(t)})(?:${v(s)})`),s);return e.inputTextSansEscapeChar=i,i}validatePrefixCommands(e,t,s,i){let n=null,a=null;const o=[i.symbolListActiveEditorCommand,i.relatedItemsListActiveEditorCommand],r=[i.editorListCommand,i.workspaceListCommand,i.headingsListCommand,i.bookmarksListCommand,i.commandListCommand,i.vaultListCommand].concat(o).map((e=>`(?:${v(e)})`)).sort(((e,t)=>t.length-e.length)),l=new RegExp(`^((?:${v(i.escapeCmdChar)})?)(${r.join("|")})`).exec(e.inputText);if(l){const t=!!l[1].length;n=l[2],t?(this.removeEscapeCommandCharFromInput(e,i.escapeCmdChar,n),n=null):a=this.getHandler(n)}if(!this.validateSourcedCommands(e,n,t,s,i)&&a){e.sessionOpts.useActiveEditorAsSource=o.includes(n);const i=e.inputTextSansEscapeChar.slice(n.length);a.validateCommand(e,l.index,i,t,s)}}validateSourcedCommands(e,t,s,i,n){let a=!1;const o=[],r=e.inputTextSansEscapeChar,l=[n.editorListCommand,n.headingsListCommand,n.bookmarksListCommand];if(!t||l.includes(t)){let t=null;const l=[n.symbolListCommand,n.relatedItemsListCommand].map((e=>`(?:${v(e)})`)).sort(((e,t)=>t.length-e.length)),d=new RegExp(`((?:${v(n.escapeCmdChar)})?)(${l.join("|")})`,"g");for(;null!==(t=d.exec(r));){const l=!!t[1].length,c=t[2];if(!l){const n=r.slice(d.lastIndex),l=this.getHandler(c);if(l){const r=l.validateCommand(e,t.index,n,s,i);a=!!r?.isValidated;const d=this.getSourcedHandlers().filter((e=>e!==l));o.push(...d)}break}this.removeEscapeCommandCharFromInput(e,n.escapeCmdChar,c)}}return this.resetSourcedHandlers(o.length?o:null),a}static setActiveSuggestion(e,s){if(e===t.SymbolList){const e=s.values.filter((e=>m(e))).findIndex((e=>e.item.isSelected));-1!==e&&(s.setSelectedItem(e,null),s.suggestions[s.selectedItem].scrollIntoView(!1))}}static getActiveSuggestion(e){let t=null;return e?.values&&(t=e.values[e.selectedItem]),t}reset(){this.inputInfo=new ne,this.sessionOpts={},this.resetSourcedHandlers()}resetSourcedHandlers(e){(e=e??this.getSourcedHandlers()).forEach((e=>e?.reset()))}getSourcedHandlers(){return[t.RelatedItemsList,t.SymbolList].map((e=>this.getHandler(e)))}addWorkspaceEnvLists(e){if(e){const s=this.getHandler(t.EditorList).getItems(),i=s.map((e=>e?.view?.file)).filter((e=>!!e)).reduce(((e,t)=>e.add(t)),new Set),{fileBookmarks:n,nonFileBookmarks:a}=this.getHandler(t.BookmarksList).getItems(null),o=e.currentWorkspaceEnvList;o.openWorkspaceLeaves=new Set(s),o.openWorkspaceFiles=i,o.fileBookmarks=n,o.nonFileBookmarks=a,o.attachmentFileExtensions=this.getAttachmentFileExtensions(this.app.viewRegistry,this.settings.fileExtAllowList);const r=i.size+this.settings.maxRecentFileSuggestionsOnInit;o.mostRecentFiles=this.getRecentFiles(i,r)}return e}getAttachmentFileExtensions(e,t){const s=new Set;try{const i=new Set(["md","canvas",...t]);Object.keys(e.typeByExtension).reduce(((e,t)=>(i.has(t)||e.add(t),e)),s)}catch(e){console.log("Switcher++: error retrieving attachment list from ViewRegistry",e)}return s}getRecentFiles(e,t=75){e=e??new Set;const s=new Set;if(t>0){const{workspace:i,vault:n}=this.app,a=i.getRecentFiles({showMarkdown:!0,showCanvas:!0,showNonImageAttachments:!0,showImages:!0,maxCount:t});a?.forEach((t=>{const i=n.getAbstractFileByPath(t);k(i)&&!e.has(i)&&s.add(i)}))}return s}inputTextForStandardMode(e){const{mode:s,inputTextSansEscapeChar:i}=this.inputInfo;let n=e;return s===t.Standard&&i?.length&&(n=i),n}getHandler(e){let t;const{handlersByMode:s,handlersByType:i,handlersByCommand:n}=this;return"number"==typeof e?t=s.get(e):h(e,"type")?t=i.get(e.type):"string"==typeof e&&(t=n.get(e)),t}}const Se={Enter:"↵",Backspace:"⌫",ArrowLeft:"←",ArrowUp:"↑",ArrowDown:"↓",ArrowRight:"→",Tab:"↹"},ke={...Se,Mod:"Ctrl",Ctrl:"Ctrl",Meta:"Win",Alt:"Alt",Shift:"Shift"},ve={...Se,Mod:"⌘",Ctrl:"⌃",Meta:"⌘",Alt:"⌥",Shift:"⇧"};class Le{get isOpen(){return this._isOpen}set isOpen(e){this._isOpen=e}static get modKey(){return n.Platform.isMacOS?"Meta":"Ctrl"}static get keyDisplayStr(){return n.Platform.isMacOS?ve:ke}constructor(e,t,s,i,n){this.app=e,this.scope=t,this.chooser=s,this.modal=i,this.config=n,this.standardKeysInfo=[],this.customKeysInfo=[],this.savedStandardKeysInfo=[],this.customInstructionEls=new Map,this.facetKeysInfo=[],this.insertIntoEditorKeysInfo=[],this.initKeysInfo(),this.removeDefaultTabKeyBinding(t,n),this.registerNavigationBindings(t,n.navigationKeys),this.registerEditorTabBindings(t),this.registerCloseWhenEmptyBindings(t,n),this.registerQuickOpenBindings(t,n),this.renderModeTriggerInstructions(i.modalEl,n),this.standardInstructionsEl=i.modalEl.querySelector(".prompt-instructions")}initKeysInfo(){this.standardKeysInfo.push(),this.addCustomKeymaps(this.config)}removeDefaultTabKeyBinding(e,t){if(t?.removeDefaultTabBinding){const t=e.keys.find((({modifiers:e,key:t})=>null===e&&"Tab"===t));e.unregister(t)}}registerNavigationBindings(e,t){const s=(t,s)=>{t.forEach((({modifiers:t,key:i})=>{e.register(t,i,((e,t)=>(this.navigateItems(e,s),!1)))}))};s(t?.nextKeys??[],!0),s(t?.prevKeys??[],!1)}registerFacetBinding(e,s){const{mode:i,facets:n}=s;if(n?.facetList?.length){const{facetList:s,facetSettings:a,onToggleFacet:o}=n,{keyList:r,modifiers:l,resetKey:d,resetModifiers:c}=a;let h=0;const m=(t,s,i,n)=>e.register(t,s,(()=>o(i,n)));for(let e=0;e<s.length;e++){const n=s[e],a=n.modifiers??l;let o;if(n.key?.length)o=n.key;else{if(!(h<r.length)){console.log(`Switcher++: unable to register hotkey for facet: ${n.label} in mode: ${t[i]} because a trigger key is not specified`);continue}o=r[h],++h}m(a,o,[n],!1),this.facetKeysInfo.push({facet:n,command:o,purpose:n.label,modifiers:a,key:o})}const u=c??l;m(u,d,s,!0),this.facetKeysInfo.push({facet:null,command:d,purpose:"toggle all",modifiers:u,key:d})}}registerEditorTabBindings(e){const{modKey:t}=Le;[[[t],"\\"],[[t,"Shift"],"\\"],[[t],"o"]].forEach((t=>{e.register(t[0],t[1],this.useSelectedItem.bind(this))}))}registerCloseWhenEmptyBindings(e,t){const s=t.closeWhenEmptyKeys;s?.forEach((({modifiers:t,key:s})=>{e.register(t,s,this.closeModalIfEmpty.bind(this))}))}registerQuickOpenBindings(e,t){const{isEnabled:s,modifiers:i,keyList:n}=t.quickOpen;s&&n?.forEach((t=>{e.register(i,t,this.quickOpenByIndex.bind(this))}))}quickOpenByIndex(e,t){const s=this.config.quickOpen.keyList.indexOf(t.vkey);if(-1!==s){const{chooser:i}=this;i.values.length>s&&(i.setSelectedItem(s,e),this.useSelectedItem(e,t))}return!1}renderQuickOpenFlairIcons(e,t){const{isEnabled:s,modifiers:i,keyList:n}=t.quickOpen;if(s)for(let t=0;t<n.length&&t<e.length;t++){const s=n[t],a=e[t].createDiv({cls:"qsp-quick-open-aux"});a?.createEl("kbd",{cls:["suggestion-hotkey","qsp-quick-open-hotkey"],text:Le.commandDisplayStr(i,s)})}}updateInsertIntoEditorCommand(e,s,i,n){const{isEnabled:a,keymap:o,insertableEditorTypes:r}=n;let l=null;if(a){const a=[t.CommandList,t.WorkspaceList,t.VaultList],d=s?.view?.getViewType();if(!(d&&!r.includes(d)||a.includes(e))){if(l=i.find((e=>e.purpose===o.purpose)),!l){const{modifiers:e,key:t,purpose:s}=o;l={isInstructionOnly:!1,command:Le.commandDisplayStr(e,t),modifiers:e,key:t,purpose:s},i.push(l)}l.eventListener=()=>{const{modal:e,chooser:t}=this;e.close();const i=t.values?.[t.selectedItem];return this.insertIntoEditorAsLink(i,s,n),!1},l.modes=[e]}}return l}updateKeymapForMode(e){const{mode:s,activeLeaf:i}=e,{modal:n,scope:a,customKeysInfo:o,facetKeysInfo:r,standardKeysInfo:l,savedStandardKeysInfo:d,config:{insertLinkInEditor:c,showModeTriggerInstructions:h}}=this;this.updateInsertIntoEditorCommand(s,i,o,c);const m=o.filter((e=>!e.isInstructionOnly));this.unregisterKeys(a,m),this.unregisterKeys(a,r),r.length=0;const u=m.filter((e=>e.modes?.includes(s)));s===t.Standard?this.updateKeymapForStandardMode(a,u,d):this.updateKeymapForCustomModes(a,u,l,e,n),this.showModeTriggerInstructions(n.modalEl,h)}updateKeymapForStandardMode(e,t,s){const i=s.map((([e,t])=>({eventListener:t.func,...e})));this.registerKeys(e,i),s.length=0,this.registerKeys(e,t),this.toggleStandardInstructions(!0)}updateKeymapForCustomModes(e,t,s,i,n){const{savedStandardKeysInfo:a,customKeysInfo:o,facetKeysInfo:r}=this,l=this.unregisterKeys(e,s);l.length&&a.push(...l),this.registerKeys(e,t),this.registerFacetBinding(e,i),this.showCustomInstructions(n,i,o,r)}registerKeys(e,t){t.forEach((({modifiers:t,key:s,eventListener:i})=>{e.register(t,s,i)}))}unregisterKeys(e,t){const s=[],i={};t.map((e=>{const{key:t,modifiers:s}=e,n=Le.modifiersToKeymapInfoStr(s),a=i[t];a?a[n]=e:i[t]={[n]:e}}));let n=e.keys.length;for(;n--;){const t=e.keys[n],a=i[t.key],o=a?.[t.modifiers];o&&(e.unregister(t),s.push([o,t]))}return s}detachCustomInstructionEls(){this.customInstructionEls.forEach((e=>{e.detach()}))}toggleStandardInstructions(e){const{standardInstructionsEl:t}=this;let s="none";e&&(s="",this.detachCustomInstructionEls()),t&&(t.style.display=s)}showCustomInstructions(e,t,s,i){const{mode:n,facets:a}=t,{modalEl:o}=e,r=s.filter((e=>e.modes?.includes(n)));this.toggleStandardInstructions(!1),this.renderCustomInstructions(o,r),this.renderFacetInstructions(o,a?.facetSettings,i)}renderFacetInstructions(e,t,s){if(s?.length&&t.shouldShowFacetInstructions){const i=this.getCustomInstructionsEl("facets",e);i.empty(),e.appendChild(i);const n=`filters | ${Le.commandDisplayStr(t.modifiers)}`;this.createPromptInstructionCommandEl(i,n),s.forEach((e=>{const{facet:s,command:n,purpose:a}=e;let o,r,l=null;s?(r=n,o=s.modifiers,s.isActive&&(l=["qsp-filter-active"])):(r=t.resetKey,o=t.resetModifiers);const d=o?`(${Le.commandDisplayStr(o)}) ${r}`:`${r}`;this.createPromptInstructionCommandEl(i,d,a,[],l)}))}}renderCustomInstructions(e,t){const s=this.getCustomInstructionsEl("custom",e);s.empty(),e.appendChild(s),t.forEach((e=>{this.createPromptInstructionCommandEl(s,e.command,e.purpose)}))}showModeTriggerInstructions(e,t){if(t){const t=this.customInstructionEls.get("modes");t&&e.appendChild(t)}}renderModeTriggerInstructions(e,t){const s=new Map([[t.headingsListCommand,"heading list"],[t.editorListCommand,"editor list"],[t.bookmarksListCommand,"bookmark list"],[t.commandListCommand,"command list"],[t.workspaceListCommand,"workspace list"],[t.vaultListCommand,"vault list"],[t.symbolListActiveEditorCommand,"symbol list (active editor)"],[t.symbolListCommand,"symbol list (embedded)"],[t.relatedItemsListActiveEditorCommand,"related items (active editor)"],[t.relatedItemsListCommand,"related items (embedded)"]]),i=this.getCustomInstructionsEl("modes",e);i.detach(),i.empty(),this.createPromptInstructionCommandEl(i,"mode triggers |"),s.forEach(((e,t)=>{this.createPromptInstructionCommandEl(i,t,e)}))}getCustomInstructionsEl(e,t){let s=this.customInstructionEls.get(e);if(!s){const i={custom:["qsp-prompt-instructions"],facets:["qsp-prompt-instructions-facets"],modes:["qsp-prompt-instructions-modes"]};s=this.createPromptInstructionsEl(i[e],t),this.customInstructionEls.set(e,s)}return s}createPromptInstructionsEl(e,t){const s={cls:["prompt-instructions",...e]};return t.createDiv(s)}createPromptInstructionCommandEl(e,t,s,i,n){i=i??[];const a=e.createDiv();return a.createSpan({cls:["prompt-instruction-command",...i],text:t}),s&&(n=n??[],a.createSpan({cls:n,text:s})),a}closeModalIfEmpty(e,t){const{modal:s,config:i}=this;i.shouldCloseModalOnBackspace&&!s?.inputEl.value&&(s.close(),e.preventDefault())}navigateToCommandHotkeySelector(e,t){const{modal:s,chooser:i,app:{setting:n}}=this,a=i.values?.[i.selectedItem];if(a){n.open();const e=n.openTabById("hotkeys");if(e){s.close();const t=a.item.id;e.setQuery(`${t}`)}}return!1}togglePinnedCommand(e,t){const{app:s,config:i,chooser:n}=this,a=n.values?.[n.selectedItem],o=ge.getEnabledCommandPalettePluginInstance(s);if(a&&o){const e=a.item.id,t=n.suggestions[n.selectedItem];let r=o.options?.pinned;if(r){const t=r.indexOf(e);a.isPinned=-1===t,a.isPinned?r.push(e):r.splice(t,1)}else r=[e],o.options.pinned=r;o.saveSettings(o.plugin),t.empty(),new ge(s,i).renderSuggestion(a,t)}return!1}toggleMarkdownContentRendering(e,t){const{app:s,config:i,chooser:n}=this,a=n.values?.[n.selectedItem];let o=null,r=null;if(m(a)&&b(a.item.symbol)?(o=a.item.symbol,r=a.file):u(a)&&(o=a.item,r=a.file),o&&r){const e=n.suggestions[n.selectedItem].querySelector(".qsp-title"),t=!e.querySelector(".qsp-rendered-container");e.empty(),ce.renderHeadingContent(s,i,e,o,r,a.match,t)}return!1}useSelectedItem(e,t){return this.chooser.useSelectedItem(e),!1}insertIntoEditorAsLink(e,t,s){const{app:{workspace:i,fileManager:a,vault:o}}=this,r=i.getActiveViewOfType(n.MarkdownView),l=r?.leaf===t,d=r?.file;if(l&&d){const t=F(a,o,e,d.path,s);t&&r.editor?.replaceSelection(t)}}navigateItems(e,t){const{isOpen:s,chooser:i}=this;if(s){let s=i.selectedItem;s=t?++s:--s,i.setSelectedItem(s,e)}}static commandDisplayStr(e,t){const{keyDisplayStr:s}=this;let i=null,n=null;return e&&(i=e.map((e=>s[e]?.toLocaleLowerCase())).sort().join(" ")),t&&(n=Object.prototype.hasOwnProperty.call(s,t)?s[t]:t),[i,n].filter((e=>e)).join(" ")}static modifiersToKeymapInfoStr(e){return e?.map((e=>"Mod"===e?this.modKey:e)).sort().join(",")}createCustomKeymap(e,t,s,i,n=!0,a=!1){let o=null;if(s){const{modifiers:r,key:l}=s;o={modes:t,modifiers:r,key:l,eventListener:i,purpose:e,command:Le.commandDisplayStr(r,l),isInstructionOnly:a},n&&this.customKeysInfo.push(o)}return o}addCustomKeymaps(e){const s=[t.EditorList,t.HeadingsList,t.RelatedItemsList,t.BookmarksList,t.SymbolList],{quickOpen:i}=this.config,n=i?.keyList;if(n?.length){const e=`${n[0]}~${n[n.length-1]}`;this.createCustomKeymap("open nth item",[t.CommandList,t.VaultList,t.WorkspaceList,...s],{modifiers:i.modifiers,key:e},null,i.isEnabled,!0)}this.createCustomKeymap("open in new tab",s,{modifiers:["Mod"],key:"Enter"},null,!0,!0),this.createCustomKeymap("open to the right",s,{modifiers:["Mod"],key:"\\"},null,!0,!0),this.createCustomKeymap("open below",s,{modifiers:["Mod","Shift"],key:"\\"},null,!0,!0),this.createCustomKeymap("open in new window",s,{modifiers:["Mod"],key:"o"},null,!0,!0),this.createCustomKeymap("execute command",[t.CommandList],{modifiers:[],key:"Enter"},null,!0,!0),this.createCustomKeymap("open workspace",[t.WorkspaceList],{modifiers:[],key:"Enter"},null,!0,!0),this.createCustomKeymap("set hotkey",[t.CommandList],e.navigateToHotkeySelectorKeys,this.navigateToCommandHotkeySelector.bind(this)),this.createCustomKeymap("toggle pinned",[t.CommandList],e.togglePinnedCommandKeys,this.togglePinnedCommand.bind(this));const{renderMarkdownContentInSuggestions:a}=e;this.createCustomKeymap("toggle preview (selected heading)",[t.HeadingsList,t.SymbolList],a.toggleContentRenderingKeys,this.toggleMarkdownContentRendering.bind(this),a.isEnabled)}}class Ce{static installMobileLauncherOverride(e,t,s){let i=null;if(!n.Platform.isMobile||!t.isEnabled||Ce.coreMobileLauncherButtonEl)return null;const a=function(e,t){let s=null;const i=e?.mobileNavbar?.containerEl;return i&&(s=i.querySelector(z.defaults.mobileLauncher.coreLauncherButtonSelector),s||(s=i.querySelector(t.coreLauncherButtonSelector))),s}(e,t);if(a){const e=function(e,t,s){let i=null;if(e&&(i=e.cloneNode(!0),i)){const{iconName:e,coreLauncherButtonIconSelector:a}=t;if(i.addClass("qsp-mobile-launcher-button"),i.addEventListener("click",s),e?.length){const t=i.querySelector(a);t&&n.setIcon(t,e)}}return i}(a,t,s);(function(e,t){let s=!1;if(e&&t){const i=t.style.display;t.style.display="none",e.insertAdjacentElement("beforebegin",t)&&(e.remove(),s=!0),t.style.display=i}return s})(a,e)&&(Ce.coreMobileLauncherButtonEl=a,Ce.qspMobileLauncherButtonEl=e,i=e)}return i}static removeMobileLauncherOverride(){let e=!1;if(!Ce.coreMobileLauncherButtonEl)return e;if(Ce.qspMobileLauncherButtonEl?.parentElement){const t=Ce.qspMobileLauncherButtonEl,s=Ce.coreMobileLauncherButtonEl,i=s.style.display;s.style.display="none",t.insertAdjacentElement("beforebegin",s)&&(t.remove(),Ce.qspMobileLauncherButtonEl=null,Ce.coreMobileLauncherButtonEl=null,e=!0),s.style.display=i}return e}}const we=[{id:"switcher-plus:open",name:"Open in Standard Mode",mode:t.Standard,iconId:"lucide-file-search",ribbonIconEl:null},{id:"switcher-plus:open-editors",name:"Open in Editor Mode",mode:t.EditorList,iconId:"lucide-file-edit",ribbonIconEl:null},{id:"switcher-plus:open-symbols",name:"Open Symbols for selected suggestion or editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",ribbonIconEl:null},{id:"switcher-plus:open-symbols-active",name:"Open Symbols for the active editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",ribbonIconEl:null,sessionOpts:{useActiveEditorAsSource:!0}},{id:"switcher-plus:open-workspaces",name:"Open in Workspaces Mode",mode:t.WorkspaceList,iconId:"lucide-album",ribbonIconEl:null},{id:"switcher-plus:open-headings",name:"Open in Headings Mode",mode:t.HeadingsList,iconId:"lucide-file-search",ribbonIconEl:null},{id:"switcher-plus:open-starred",name:"Open in Bookmarks Mode",mode:t.BookmarksList,iconId:"lucide-bookmark",ribbonIconEl:null},{id:"switcher-plus:open-commands",name:"Open in Commands Mode",mode:t.CommandList,iconId:"run-command",ribbonIconEl:null},{id:"switcher-plus:open-related-items",name:"Open Related Items for selected suggestion or editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",ribbonIconEl:null},{id:"switcher-plus:open-related-items-active",name:"Open Related Items for the active editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",ribbonIconEl:null,sessionOpts:{useActiveEditorAsSource:!0}},{id:"switcher-plus:open-vaults",name:"Open in Vaults Mode",mode:t.VaultList,iconId:"vault",ribbonIconEl:null}];class Ie extends n.Plugin{async onload(){const e=new z(this);await e.updateDataAndLoadSettings(),this.options=e,this.addSettingTab(new ie(this.app,this,e)),this.registerRibbonCommandIcons(),this.updateMobileLauncherButtonOverride(e.mobileLauncher.isEnabled),we.forEach((({id:e,name:t,mode:s,iconId:i,sessionOpts:n})=>{this.registerCommand(e,t,s,i,n)}))}onunload(){this.updateMobileLauncherButtonOverride(!1)}registerCommand(e,t,s,i,n){this.addCommand({id:e,name:t,icon:i,checkCallback:e=>this.createModalAndOpen(s,e,n)})}registerRibbonCommandIcons(){we.forEach((e=>{e.ribbonIconEl?.remove(),e.ribbonIconEl=null}));const e=we.reduce(((e,t)=>(e[t.mode]=t,e)),{});this.options.enabledRibbonCommands.forEach((s=>{const i=e[t[s]];i&&(i.ribbonIconEl=this.addRibbonIcon(i.iconId,i.name,(()=>{this.createModalAndOpen(i.mode,!1)})))}))}createModalAndOpen(e,t,s){if(!t){const t=function(e,t){const s=C(e)?.QuickSwitcherModal;return s?new class extends s{constructor(e,t){super(e,t.options.builtInSystemOptions),this.plugin=t;const{options:s}=t;s.shouldShowAlias=this.shouldShowAlias;const i=new Le(e,this.scope,this.chooser,this,s);this.exMode=new be(e,s,i)}openInMode(e,t){this.exMode.setSessionOpenMode(e,this.chooser,t),super.open()}onOpen(){this.exMode.onOpen(),super.onOpen()}onClose(){super.onClose(),this.exMode.onClose()}updateSuggestions(){const{exMode:e,inputEl:t,chooser:s}=this;e.insertSessionOpenModeOrLastInputString(t),e.updateSuggestions(t.value,s,this)||super.updateSuggestions()}getSuggestions(e){const t=this.exMode.inputTextForStandardMode(e);return super.getSuggestions(t)}onChooseSuggestion(e,t){this.exMode.onChooseSuggestion(e,t)||super.onChooseSuggestion(e,t)}renderSuggestion(e,t){this.exMode.renderSuggestion(e,t)||super.renderSuggestion(e,t)}}(e,t):(console.log("Switcher++: unable to extend system switcher. Plugin UI will not be loaded. Use the builtin switcher instead."),null)}(this.app,this);if(!t)return!1;t.openInMode(e,s)}return!0}updateMobileLauncherButtonOverride(e){if(e){const e=()=>{const e=this.options.mobileLauncher.modeString,s=t[e];s&&this.createModalAndOpen(s,!1)};Ce.installMobileLauncherOverride(this.app,this.options.mobileLauncher,e)}else Ce.removeMobileLauncherOverride()}}module.exports=Ie;