Files
cours/.obsidian/plugins/darlal-switcher-plus/main.js
2026-02-03 18:51:24 +01:00

3 lines
124 KiB
JavaScript

"use strict";var e,t,s,i,n=require("obsidian");!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",e[e.BaseView=64]="BaseView"}(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 a={};a[s.Link]="🔗",a[s.Embed]="!",a[s.Tag]="#",a[s.Heading]="H";const o={};var r,l,d;function c(e,t,s){let i=!1;return e&&void 0!==e[t]&&(i=!0,void 0!==s&&s!==e[t]&&(i=!1)),i}function h(e){return c(e,"type",r.SymbolList)}function m(e){return c(e,"type",r.HeadingsList)}function u(e){return c(e,"type",r.File)}function g(e){return c(e,"type",r.Alias)}function p(e){return c(e,"type",r.Unresolved)}function f(e){return e&&!(u(t=e)||p(t)||g(t));var t}function y(e){return c(e,"level")}function b(e){return c(e,"tag")}function S(e){return c(e,"type","callout")}function k(e){return c(e,"extension")}function v(e,t){return e?.internalPlugins?.getEnabledPluginById(t)}function w(e){const t=function(e,t){return e?.internalPlugins?.getPluginById(t)}(e,"switcher");return t?.instance}function C(e){return v(e,"global-search")}function L(){return Object.values(t).filter((e=>isNaN(Number(e)))).sort()}function I(){return[t.RelatedItemsList,t.SymbolList]}function T(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 E(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 F(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 A(e,t){return t?.getFileByPath(e)}function x(e){let t=null;if(!e)return t;if(e.isDeferred){const s=e.getViewState()?.state?.file;s&&(t=A(s,e.app?.vault))}else e.view?.file&&(t=e.view.file);return t}function O(e,t,s,i,a){let o=null;if(a=Object.assign({useBasenameAsAlias:!0,useHeadingAsAlias:!0},a),s){let l=M(s),d=null,h=null;switch(s.type){case r.Unresolved:o=R(s.linktext);break;case r.Alias:d=s.alias;break;case r.Bookmark:{const{item:e}=s;"file"===e.type&&e.title&&(d=e.title);break}case r.HeadingsList:{const{heading:e}=s.item;({subpath:h,alias:d}=P(e,a.useHeadingAsAlias));break}case r.SymbolList:{const{item:{symbol:r}}=s;if(y(r))({subpath:h,alias:d}=P(r.heading,a.useHeadingAsAlias));else if(c(r,"link")){o=new RegExp(/^\[(.*?)\]\((.+?)\)/).test(r.original)?r.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?A(d,t):a;m?(!h?.length&&o&&(h=m.basename),u=e.generateMarkdownLink(m,s,c,h)):u=R(d,h);return u}(e,t,i,r,l,a.useBasenameAsAlias)}else l=null;break}case r.RelatedItemsList:{const{item:e}=s;e.unresolvedText&&(o=R(e.unresolvedText));break}}l&&!o&&(!d&&a.useBasenameAsAlias&&(d=l.basename),o=e.generateMarkdownLink(l,i,h,d))}return o}function P(e,t){const s=n.stripHeadingForLink(e);return{subpath:`#${s}`,alias:t?s:null}}function M(e){let t=null;return[r.Alias,r.Bookmark,r.HeadingsList,r.SymbolList,r.RelatedItemsList,r.EditorList,r.File].includes(e?.type)&&(t=e.file),t}function R(e,t){return`[[${e}${t=t?.length?`|${t}`:""}]]`}function B(e,t){return e?.view?.getViewType()===t&&!e.isDeferred}o[1]="H₁",o[2]="H₂",o[3]="H₃",o[4]="H₄",o[5]="H₅",o[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"}(r||(r={})),function(e){e[e.None=0]="None",e[e.Primary=1]="Primary",e[e.Basename=2]="Basename",e[e.Path=3]="Path"}(l||(l={})),function(e){e.DiskLocation="disk-location",e.Backlink="backlink",e.OutgoingLink="outgoing-link"}(d||(d={}));class H{static getAliases(e){let t=[];return e&&(t=H.getValueForKey(e,/^alias(es)?$/i)),t}static getTags(e){let t=[];return e&&(t=H.getValueForKey(e,/^tags?$/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 D{static rootComponent;static getRootComponent(){return this.rootComponent||(this.rootComponent=new n.Component),this.rootComponent}static unload(){this.rootComponent?.unload()}}const V={file:"canvas-node-file",text:"canvas-node-text",link:"canvas-node-link",group:"canvas-node-group"},W={table:"base-view-table",list:"base-view-list",cards:"base-view-cards"},N=[{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:V.file,mode:t.SymbolList,label:"file cards",isActive:!1,isAvailable:!0},{id:V.text,mode:t.SymbolList,label:"text cards",isActive:!1,isAvailable:!0},{id:V.link,mode:t.SymbolList,label:"link cards",isActive:!1,isAvailable:!0},{id:V.group,mode:t.SymbolList,label:"groups",isActive:!1,isAvailable:!0},{id:W.table,mode:t.SymbolList,label:"table views",isActive:!1,isAvailable:!0},{id:W.list,mode:t.SymbolList,label:"list views",isActive:!1,isAvailable:!0},{id:W.cards,mode:t.SymbolList,label:"card views",isActive:!1,isAvailable:!0}],K=[{id:d.Backlink,mode:t.RelatedItemsList,label:"backlinks",isActive:!1,isAvailable:!0},{id:d.OutgoingLink,mode:t.RelatedItemsList,label:"outgoing links",isActive:!1,isAvailable:!0},{id:d.DiskLocation,mode:t.RelatedItemsList,label:"disk location",isActive:!1,isAvailable:!0}],j={file:"bookmarks-file",folder:"bookmarks-folder",search:"bookmarks-search",group:"bookmarks-group"},q=[{id:j.file,mode:t.BookmarksList,label:"files",isActive:!1,isAvailable:!0},{id:j.folder,mode:t.BookmarksList,label:"folders",isActive:!1,isAvailable:!0},{id:j.search,mode:t.BookmarksList,label:"searches",isActive:!1,isAvailable:!0}];var $;!function(e){e.Pinned="pinnedCommands",e.Recent="recentCommands"}($||($={}));const U=[{id:$.Pinned,mode:t.CommandList,label:"pinned",isActive:!1,isAvailable:!0},{id:$.Recent,mode:t.CommandList,label:"recent",isActive:!1,isAvailable:!0}];var Q;!function(e){e.RecentFiles="recentFilesSearch",e.Bookmarks="bookmarksSearch",e.Filenames="filenamesSearch",e.Headings="headingsSearch",e.ExternalFiles="externalFilesSearch"}(Q||(Q={}));const _=[{id:Q.RecentFiles,mode:t.HeadingsList,label:"recent files",isActive:!1,isAvailable:!0},{id:Q.Bookmarks,mode:t.HeadingsList,label:"bookmarks",isActive:!1,isAvailable:!0},{id:Q.Filenames,mode:t.HeadingsList,label:"filenames",isActive:!1,isAvailable:!0},{id:Q.Headings,mode:t.HeadingsList,label:"headings",isActive:!1,isAvailable:!0},{id:Q.ExternalFiles,mode:t.HeadingsList,label:"external files",isActive:!1,isAvailable:!0}];function G(){const e={};return[N,K,q,U,_].flat().reduce(((e,t)=>(e[t.id]=Object.assign({},t),e)),e),e}const z=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},J=(...e)=>e.reduce(((e,t)=>{if(void 0===t)return e;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]=J.options.mergeArrays?J.options.uniqueArrayItems?Array.from(new Set(e[s].concat(t[s]))):[...e[s],...t[s]]:t[s]:z(e[s])&&z(t[s])?e[s]=J(e[s],t[s]):!z(e[s])&&z(t[s])?e[s]=J(t[s],void 0):e[s]=void 0===t[s]?J.options.allowUndefinedOverrides?t[s]:e[s]:t[s])})),e}),{}),Y={allowUndefinedOverrides:!0,mergeArrays:!0,uniqueArrayItems:!0};J.options=Y,J.withOptions=(e,...t)=>{J.options=Object.assign(Object.assign({},Y),e);const s=J(...t);return J.options=Y,s};class X{plugin;data;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:">",recentCommandDisplayOrder:"desc",maxRecentCommands:25,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(d),showOptionalIndicatorIcons:!0,isFileExtensionIndicatorsEnabled:!0,excludeFileExtensionIndicators:["md"],overrideStandardModeBehaviors:!0,overrideStandardModeRendering:!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:G(),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",frontmatterTitleProperty:"title",closeWhenEmptyKeys:[{modifiers:null,key:"Backspace"}],navigateToHotkeySelectorKeys:{modifiers:["Ctrl","Shift"],key:"h"},togglePinnedCommandKeys:{modifiers:["Ctrl","Shift"],key:"p"},escapeCmdChar:"!",mobileLauncher:{isEnabled:!1,isMobileButtonEnabled:!0,isEmptyTabButtonEnabled:!0,modeString:t[t.HeadingsList],iconName:"",coreLauncherButtonIconSelector:"span.clickable-icon",coreLauncherButtonSelector:".mobile-navbar-action.mobile-navbar-action-quick-switcher"},allowCreateNewFileInModeNames:[t[t.Standard],t[t.HeadingsList]],showModeTriggerInstructions:!0,renderMarkdownContentInSuggestions:{isEnabled:!1,renderHeadings:!1,renderLinks:!1,renderTags:!1,renderCallouts:!1,toggleContentRenderingKeys:{modifiers:["Shift","Ctrl"],key:"m"}},quickOpen:{isEnabled:!0,modifiers:["Alt"],keyList:["1","2","3","4","5","6","7","8","9"]},openDefaultApp:{isEnabled:!0,openInDefaultAppKeys:{modifiers:["Shift","Ctrl"],key:"o"},excludeFileExtensions:[]},fulltextSearch:{isEnabled:!0,searchKeys:{modifiers:["Mod","Shift"],key:"f"}},openInBackground:{isEnabled:!0,openKeys:[{openType:"tab",hotkey:{modifiers:["Mod","Shift"],key:"t"}},{openType:"vertical",hotkey:null},{openType:"horizontal",hotkey:null},{openType:"window",hotkey:null}]},saveWorkspaceAndSwitchKeys:{modifiers:["Mod","Shift"],key:"s"}}}shouldShowAlias;get version(){return this.data.version}set version(e){this.data.version=e}get builtInSystemOptions(){return w(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 X.defaults.editorListCommand}get editorListCommand(){return this.data.editorListCommand}set editorListCommand(e){this.data.editorListCommand=e}get symbolListPlaceholderText(){return X.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 X.defaults.workspaceListCommand}get headingsListCommand(){return this.data.headingsListCommand}set headingsListCommand(e){this.data.headingsListCommand=e}get headingsListPlaceholderText(){return X.defaults.headingsListCommand}get bookmarksListCommand(){return this.data.bookmarksListCommand}set bookmarksListCommand(e){this.data.bookmarksListCommand=e}get bookmarksListPlaceholderText(){return X.defaults.bookmarksListCommand}get commandListCommand(){return this.data.commandListCommand}set commandListCommand(e){this.data.commandListCommand=e}get recentCommandDisplayOrder(){return this.data.recentCommandDisplayOrder}set recentCommandDisplayOrder(e){this.data.recentCommandDisplayOrder=e}get maxRecentCommands(){return this.data.maxRecentCommands}set maxRecentCommands(e){this.data.maxRecentCommands=e}get commandListPlaceholderText(){return X.defaults.commandListCommand}get vaultListCommand(){return this.data.vaultListCommand}set vaultListCommand(e){this.data.vaultListCommand=e}get vaultListPlaceholderText(){return X.defaults.vaultListCommand}get relatedItemsListCommand(){return this.data.relatedItemsListCommand}set relatedItemsListCommand(e){this.data.relatedItemsListCommand=e}get relatedItemsListPlaceholderText(){return X.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 X.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 isFileExtensionIndicatorsEnabled(){return this.data.isFileExtensionIndicatorsEnabled}set isFileExtensionIndicatorsEnabled(e){this.data.isFileExtensionIndicatorsEnabled=e}get excludeFileExtensionIndicators(){return this.data.excludeFileExtensionIndicators}set excludeFileExtensionIndicators(e){this.data.excludeFileExtensionIndicators=[...new Set(e)]}get overrideStandardModeBehaviors(){return this.data.overrideStandardModeBehaviors}set overrideStandardModeBehaviors(e){this.data.overrideStandardModeBehaviors=e}get overrideStandardModeRendering(){return this.data.overrideStandardModeRendering}set overrideStandardModeRendering(e){this.data.overrideStandardModeRendering=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 frontmatterTitleProperty(){return this.data.frontmatterTitleProperty}set frontmatterTitleProperty(e){this.data.frontmatterTitleProperty=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}get openDefaultApp(){return this.data.openDefaultApp}set openDefaultApp(e){this.data.openDefaultApp=e}get fulltextSearch(){return this.data.fulltextSearch}set fulltextSearch(e){this.data.fulltextSearch=e}get openInBackground(){return this.data.openInBackground}set openInBackground(e){this.data.openInBackground=e}get saveWorkspaceAndSwitchKeys(){return this.data.saveWorkspaceAndSwitchKeys}set saveWorkspaceAndSwitchKeys(e){this.data.saveWorkspaceAndSwitchKeys=e}constructor(e){this.plugin=e,this.data=X.defaults}async updateDataAndLoadSettings(){return await X.transformDataFile(this.plugin,X.defaults),await this.loadSettings()}async loadSettings(){try{const e=await(this.plugin?.loadData());if(e){const t=Object.keys(X.defaults);((e,t,s)=>{const i=["matchPriorityAdjustments","quickFilters","mobileLauncher"],n=s=>J.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=X.defaults.enabledSymbolTypes[e];return Object.prototype.hasOwnProperty.call(t,e)&&(s=t[e]),s}setSymbolTypeEnabled(e,t){this.data.enabledSymbolTypes[e]=t}shouldRenderSymbolAsHTML(e){const{renderMarkdownContentInSuggestions:t}=this.data;if(!t.isEnabled)return!1;const i={[s.Heading]:"renderHeadings",[s.Link]:"renderLinks",[s.Tag]:"renderTags",[s.Callout]:"renderCallouts"}[e];return!!i&&t[i]}static async transformDataFile(e,t){await X.transformDataFileToV1(e,t),await X.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 Z{app;mainSettingsTab;config;constructor(e,t,s){this.app=e,this.mainSettingsTab=t,this.config=s}createSetting(e,t,s){let i;return e instanceof n.SettingGroup?e.addSetting((e=>{i=e,e.setName(t),e.setDesc(s)})):(i=new n.Setting(e),i.setName(t),i.setDesc(s)),i}withSetting(e,t,s,i){let a;return e instanceof n.SettingGroup?e.addSetting((e=>{a=e,e.setName(t).setDesc(s),i(e)})):(a=this.createSetting(e,t,s),i(a)),a}createOnChangeHandler(e,t){return s=>{t?t(s,this.config):e&&this.saveChangesToConfig(e,s)}}addSectionTitle(e,t,s=""){const i=this.createSetting(e,t,s);return i.setHeading(),i}addTextSetting(e,t,s,i,n,a){return this.withSetting(e,t,s,(e=>{e.addText((e=>{e.setPlaceholder(a),e.setValue(i),e.onChange((e=>{const t=e.length?e:i;this.saveChangesToConfig(n,t)}))}))}))}addToggleSetting(e,t,s,i,n,a){return this.withSetting(e,t,s,(e=>{e.addToggle((e=>{e.setValue(i),e.onChange(this.createOnChangeHandler(n,a))}))}))}addTextAreaSetting(e,t,s,i,n,a){return this.withSetting(e,t,s,(e=>{e.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)}))}))}))}addDropdownSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addDropdown((e=>{e.addOptions(n),e.setValue(i),e.onChange(this.createOnChangeHandler(a,o))}))}))}addSliderSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addExtraButton((t=>(t.setIcon("lucide-rotate-ccw"),t.setTooltip("Restore default"),t.onClick((()=>e.components[1].setValue(n[3]))),t))),e.addSlider((e=>{e.setLimits(n[0],n[1],n[2]),e.setValue(i),e.setDynamicTooltip(),e.onChange(this.createOnChangeHandler(a,o))}))}))}saveChangesToConfig(e,t){if(e){const{config:s}=this;s[e]=t,s.save()}}}class ee extends Z{display(e){const{config:t}=this;this.addSectionTitle(e,"Bookmarks List Mode"),this.addTextSetting(e,"Bookmarks list mode trigger","Character that will trigger bookmarks list mode in the switcher",t.bookmarksListCommand,"bookmarksListCommand",t.bookmarksListPlaceholderText)}}class te extends Z{display(e){const{config:t}=this;this.addSectionTitle(e,"Command List Mode"),this.addTextSetting(e,"Command list mode trigger","Character that will trigger command list mode in the switcher",t.commandListCommand,"commandListCommand",t.commandListPlaceholderText),this.addSliderSetting(e,"Max recent commands","The maximum number of commands to save in the recent list.",t.maxRecentCommands,[0,75,1,25],"maxRecentCommands"),this.showRecentCommandDisplayOrder(e,t)}showRecentCommandDisplayOrder(e,t){this.addDropdownSetting(e,"Recent commands display order","Select the sort order for recently used commands.",t.recentCommandDisplayOrder,{desc:"Most recent first (descending)",asc:"Most recent last (ascending)"},"recentCommandDisplayOrder")}}class se extends Z{display(e){const{config:t}=this;this.addSectionTitle(e,"Related Items List Mode"),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(d).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 ie extends Z{display(e){const{config:t}=this;this.addSectionTitle(e,"General"),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.showLauncherButtonOverrides(e,t),this.showEnabledRibbonCommands(e,t),this.addToggleSetting(e,"Show indicator icons","Display icons to indicate that an item is recent, bookmarked, etc..",t.showOptionalIndicatorIcons,"showOptionalIndicatorIcons"),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.showStandardModeOverrides(e,t),this.showPathDisplayGroup(e,t),this.showPreferredSourceForTitle(e,t),this.showQuickOpen(e,t),this.showRenderMarkdownContentAsHTML(e,t),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,"Allow Backspace key to close the Switcher","When the search box is empty, pressing the backspace key will close Switcher++.",t.shouldCloseModalOnBackspace,"shouldCloseModalOnBackspace"),this.showRestoreInput(e,t),this.showInsertLinkInEditor(e,t),this.showResetFacetEachSession(e,t),this.showMatchPriorityAdjustments(e,t)}showPreferredSourceForTitle(e,t){const s=new n.SettingGroup(e);this.addDropdownSetting(s,"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",FrontMatter:"Frontmatter property"},"preferredSourceForTitle",((e,t)=>{t.preferredSourceForTitle=e,t.save(),this.mainSettingsTab.display()})),"FrontMatter"===t.preferredSourceForTitle&&this.addTextSetting(s,"Frontmatter property path",'The path to the frontmatter property to use as the title. Use dot notation for nested properties (e.g., "title" or "meta.display_name"). The property value must be a string, number, or boolean. If the property doesn\'t exist or has an invalid type, the default filename will be used.',t.frontmatterTitleProperty,"frontmatterTitleProperty","title")}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()}))}showPathDisplayGroup(e,t){const s=new n.SettingGroup(e);this.createSetting(s,"Path Display Settings","Configure how file paths are displayed in suggestions."),this.showPathDisplayFormat(s,t),this.addToggleSetting(s,"Hide path for root items","When enabled, path information will be hidden for items at the root of the vault.",t.hidePathIfRoot,"hidePathIfRoot")}showStandardModeOverrides(e,t){const s=new n.SettingGroup(e);this.createSetting(s,"Standard Mode Overrides","Configure how Switcher++ overrides the default Obsidian Switcher behavior in Standard mode."),this.addToggleSetting(s,"Override Standard mode file open behavior","When enabled, Switcher++ will change the default Obsidian builtin Switcher functionality (Standard mode) to inject custom file open behavior.",t.overrideStandardModeBehaviors,"overrideStandardModeBehaviors"),this.addToggleSetting(s,"Override Standard mode rendering","When enabled, Switcher++ will change the default Obsidian builtin Switcher functionality (Standard mode) to render suggestions as multi-line.",t.overrideStandardModeRendering,"overrideStandardModeRendering")}showRestoreInput(e,t){const s=new n.SettingGroup(e);this.createSetting(s,"Restore Previous Input","Configure whether to restore the last typed input when launching the Switcher."),this.addToggleSetting(s,"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(s,"Restore previous input","When enabled, restore the last typed input when launched via global command hotkey.",t.preserveQuickSwitcherLastInput,"preserveQuickSwitcherLastInput")}showEnabledRibbonCommands(e,t){const s=L(),i=s.join(" "),n=`Display an icon in the ribbon menu to launch specific modes. Add one mode per line. Available modes: ${i}`;this.createSetting(e,"Show ribbon icons",n).addTextArea((e=>{e.setValue(t.enabledRibbonCommands.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const n=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0)),a=Array.from(new Set(n)).filter((e=>!s.includes(e)));a.length?this.showErrorPopup(a.join("<br/>"),i):(t.enabledRibbonCommands=n,t.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()}showLauncherButtonOverrides(e,t){const{mobileLauncher:s}=t,i=new n.SettingGroup(e),a="disabled",o={[a]:"Do not override"},r=L();r.forEach((e=>{o[e]=e}));let l=a;s.isEnabled&&r.includes(s.modeString)&&(l=s.modeString),this.addDropdownSetting(i,"New tab and mobile launcher buttons",'Select the Mode to launch Switcher++ in from the empty tab page and mobile navigation Bar button, or select "Do not override" to disable the feature.',l,o,null,((e,t)=>{const s=e!==a;t.mobileLauncher.isEnabled=s,s&&(t.mobileLauncher.modeString=e),t.save(),this.mainSettingsTab.display(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(s)})),s.isEnabled&&(this.addToggleSetting(i,"Override default Switcher launch button on mobile platforms",'When enabled, override the "🔍" button (in the Navigation Bar) on mobile platforms to launch Switcher++ instead of the default system switcher.',s.isMobileButtonEnabled,null,((e,t)=>{t.mobileLauncher.isMobileButtonEnabled=e,t.save(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(t.mobileLauncher.isEnabled)})),this.addToggleSetting(i,'Display launch button on the "New tab" page','When enabled, a button to launch Switcher++ using the selected mode above will be added to the default Obsidian "New tab" page.',s.isEmptyTabButtonEnabled,null,((e,t)=>{t.mobileLauncher.isEmptyTabButtonEnabled=e,t.save(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(t.mobileLauncher.isEnabled)})))}showMatchPriorityAdjustments(e,t){const{matchPriorityAdjustments:{isEnabled:s,adjustments:i,fileExtAdjustments:a}}=t,o=new n.SettingGroup(e);this.addToggleSetting(o,"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,a].forEach((e=>{Object.entries(e).forEach((([t,s])=>{const{value:i,label:n}=s;this.addSliderSetting(o,n,s.desc??"",i,[-1,1,.05,0],null,((s,i)=>{e[t].value=s,i.save()}))}))}))}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{renderMarkdownContentInSuggestions:s}=t,i=new n.SettingGroup(e),a=this.addToggleSetting(i,"Display markdown content as Live Preview",'When enabled, markdown content in symbol suggestions will be rendered as HTML similar to the Obsidian "Live Preview" display. When disabled, content will be rendered as raw text. Use the "toggle preview (selected item)" hotkey to toggle the display for individual items.',s.isEnabled,null,((e,t)=>{const{renderMarkdownContentInSuggestions:s}=t;s.isEnabled=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>console.log('Switcher++: error saving "Display markdown content as Live Preview" setting. ',e)))}));if(a?.nameEl?.createSpan({cls:["qsp-tag","qsp-warning"],text:"Experimental"}),s.isEnabled){[{name:"Headings",property:"renderHeadings",description:"Render headings as HTML"},{name:"Links",property:"renderLinks",description:"Render links as HTML"},{name:"Tags",property:"renderTags",description:"Render tags as HTML"},{name:"Callouts",property:"renderCallouts",description:"Render callouts as HTML"}].forEach((({name:e,property:t,description:n})=>{this.addToggleSetting(i,e,n,s[t],null,((e,s)=>{s.renderMarkdownContentInSuggestions[t]=e,s.save()}))}))}}showInsertLinkInEditor(e,t){const s=new n.SettingGroup(e);this.createSetting(s,"Insert link in editor","Configure alias options when inserting links into the editor."),this.addToggleSetting(s,"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()})),this.addToggleSetting(s,"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()}))}showQuickOpen(e,t){this.addToggleSetting(e,"Enable quick open hotkeys for top results","When enabled, hotkeys will be defined for each of the top N results displayed in the Switcher. These hotkeys can be used to quickly open the associated suggestion directly. when disabled, no hotkeys are defined.",t.quickOpen.isEnabled,null,((e,t)=>{t.quickOpen.isEnabled=e,t.save()}))}}class ne extends Z{display(e){const{config:t}=this;this.addSectionTitle(e,"Workspace List Mode"),this.addTextSetting(e,"Workspace list mode trigger","Character that will trigger workspace list mode in the switcher",t.workspaceListCommand,"workspaceListCommand",t.workspaceListPlaceholderText)}}class ae extends Z{display(e){const{config:t}=this;this.addSectionTitle(e,"Editor List Mode"),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 oe extends Z{display(e){const{config:t}=this;this.addSectionTitle(e,"Headings List Mode"),this.addTextSetting(e,"Headings list mode trigger","Character that will trigger headings list mode in the switcher",t.headingsListCommand,"headingsListCommand",t.headingsListPlaceholderText),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,25],"maxRecentFileSuggestionsOnInit"),this.showFileExtAllowList(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.showHeadingSettings(e,t),this.showExclusionsGroup(e,t)}showHeadingSettings(e,t){const s=t.shouldSearchHeadings,i=new n.SettingGroup(e);this.addToggleSetting(i,"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&&(this.addToggleSetting(i,"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"),this.addToggleSetting(i,"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"))}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()}))}))}showExclusionsGroup(e,t){const s=new n.SettingGroup(e);this.createSetting(s,"Exclusions","Configure which folders and files should be excluded from search results in Headings list mode."),this.showExcludeFolders(s,t),this.addToggleSetting(s,'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")}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 re extends Z{display(e){const{config:t}=this;this.addSectionTitle(e,"Symbol List Mode"),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,"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),this.showSymbolTabNavigationBehavior(e,t)}showSymbolTabNavigationBehavior(e,t){const s=new n.SettingGroup(e);this.createSetting(s,"Symbol Tab navigation behavior","Configure how symbols are opened when navigating from the symbol list."),this.addToggleSetting(s,"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(s,"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")}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 a=t.isSymbolTypeEnabled(s.Link),o=new n.SettingGroup(e);if(this.addToggleSetting(o,"Show Links","",a,null,(e=>{t.setSymbolTypeEnabled(s.Link,e),t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>console.log('Switcher++: error saving "Show Links" setting. ',e)))})),a){[["Links to headings",i.Heading],["Links to blocks",i.Block]].forEach((([e,s])=>{const i=(t.excludeLinkSubTypes&s)===s;this.addToggleSetting(o,e,"",!i,null,(e=>this.saveEnableSubLinkChange(s,e)))}))}}saveEnableSubLinkChange(e,t){const{config:s}=this;let i=s.excludeLinkSubTypes;t?i&=~e:i|=e,s.excludeLinkSubTypes=i,s.save()}}class le extends Z{display(e){const{config:t}=this,s=this.addSectionTitle(e,"Vault List Mode");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 de extends n.PluginSettingTab{plugin;config;constructor(e,t,s){super(e,t),this.plugin=t,this.config=s,this.containerEl.addClass("qsp-settings-container")}display(){const{containerEl:e}=this,t=[ie,re,oe,ae,se,ee,te,ne,le];e.empty(),t.forEach((e=>{this.displayTabSection(e)}))}displayTabSection(e){const{app:t,config:s,containerEl:i}=this;new e(t,this,s).display(i)}}class ce{inputText;mode;parsedCommands;_cleanInput=null;static get defaultParsedCommand(){return{isValidated:!1,index:-1,parsedInput:null}}sessionOpts;currentWorkspaceEnvList={openWorkspaceLeaves:new Set,openWorkspaceFiles:new Set,fileBookmarks:new Map,nonFileBookmarks:new Set,mostRecentFiles:new Set,attachmentFileExtensions:new Set};get parsedInputQuery(){const e=(this.parsedCommand()?.parsedInput??"").trim().toLowerCase();return{query:e,hasSearchTerm:!!e.length}}get cleanInput(){return this._cleanInput??this.inputText}set cleanInput(e){this._cleanInput=e}constructor(e="",s=t.Standard,i){this.inputText=e,this.mode=s,this.sessionOpts=i??{};const n=I();this.parsedCommands={},L().forEach((e=>{const s=t[e];n.includes(s)?this.parsedCommands[s]={...ce.defaultParsedCommand,source:null}:this.parsedCommands[s]=ce.defaultParsedCommand}))}parsedCommand(e){return e=e??this.mode,this.parsedCommands[e]}}class he{app;settings;facets;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){s=x(e),n=this.getCursorPosition(e);i=!t.includes(e.view.getViewType())&&!!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);return{...t,leaf:s,cursor:i}}getSourceInfoFromSuggestion(e){let t=null,s=null;const i=[r.SymbolList,r.Unresolved,r.WorkspaceList,r.CommandList,r.VaultList];e&&!i.includes(e.type)&&(t=e.file),c(e,"type",r.EditorList)&&(s=e.item);return{isValidSource:!!t,leaf:s,file:t,suggestion:e}}getCursorPosition(e){let t=null;if(B(e,"markdown")){const s=e.view;"preview"!==s.getMode()&&(t=s.editor.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 he.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}static getFrontmatterProperty(e,t){if(!e||!t)return null;const s=t.split(".");let i=e;for(const e of s){if(!i||"object"!=typeof i||!(e in i))return null;i=i[e]}return"string"==typeof i&&i.trim().length>0?i.trim():"number"==typeof i||"boolean"==typeof i?String(i):null}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?x(i)===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}async activateLeaf(e,t){const{workspace:s}=this.app;try{await s.revealLeaf(e),s.setActiveLeaf(e,{focus:!0}),e.view.setEphemeralState({focus:!0,...t})}catch(t){const s=e?.getDisplayText();console.log(`Switcher++: error activating WorkspaceLeaf with title: ${s}`,t)}}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}static async openFileInLeaf(e,t,s,i,n="vertical"){const a="split"===t?s.getLeaf(t,n):s.getLeaf(t);await a.openFile(e,i)}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??this.getOpenViewActiveState(),s&&!1===e){const e=i?.eState;await this.activateLeaf(s,e)}else await he.openFileInLeaf(t,e,this.app.workspace,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}=he.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){he.renderMarkdownContent(e,t,s,i,D.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)}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,d=null;s?.length?n===l.Primary?r=a:n===l.Path&&(d=a):i&&(s=i.basename,n===l.Basename?r=a:n===l.Path&&({pathMatch:d,basenameMatch:r}=this.splitSearchMatchesAtBasename(i,a))),this.addClassesToSuggestionContainer(e,t);const c=this.renderContent(e,s,r);this.renderPath(c,i,o,d,!!d)}getActiveLeaf(){return he.getActiveLeaf(this.app.workspace)}static getActiveLeaf(e){const t=e?.getActiveViewOfType(n.View)?.leaf;return t??null}renderOptionalIndicators(e,t,s=null){const{settings:i}=this,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.showOptionalIndicatorIcons){const a=M(t);this.renderFileExtensionIndicator(s,a,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}renderFileExtensionIndicator(e,t,s){let i=null;const{isFileExtensionIndicatorsEnabled:n,excludeFileExtensionIndicators:a}=s;return n&&t?(a?.includes(t.extension)||(i=e?.createDiv({cls:["suggestion-flair","nav-file-tag","qsp-file-ext-indicator"],text:t.extension})),i):i}createFlairContainer(e){return e?.createDiv({cls:["suggestion-aux","qsp-aux"]})}getTFileByPath(e){return A(e,this.app.vault)}applyMatchPriorityPreferences(e){return he.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??{},l=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(r.Bookmark,"isBookmarked"),d+=h(r.EditorList,"isOpenInEditor"),d+=h(null,"isRecent"),d+=h(null,"isAttachment"),d+=c(a?.extension,l),m(e)&&(d+=c(`h${e.item?.level}`));const u=n.toString();d+=c(u),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)}))}getOpenViewState(e,t){const s=this.getPreferredViewLinePosition(e),{eState:i}=this.getOpenViewLinePositionState(s),n=this.getOpenViewActiveState(t);return Object.assign(n.eState,i),n}getOpenViewActiveState(e){const{active:t,focus:s}=Object.assign({active:!0,focus:!0},e);return{active:t,eState:{active:t,focus:s}}}getPreferredViewLinePosition(e){const t={line:0,col:0,offset:0};return{start:t,end:t}}getOpenViewLinePositionState(e){const t=Object.assign({line:0,col:0,offset:0},e?.start),s=Object.assign({line:0,col:0,offset:0},e?.end),{line:i,col:n}=t;return{eState:{startLoc:t,endLoc:s,line:i,cursor:{from:{line:i,ch:n},to:{line:i,ch:n}}}}}}class me{useSimpleSearch;_searchDelegate;query;hasSearchTerm;constructor(e,t){this.useSimpleSearch=t,this.query=(e??"").trim().toLowerCase(),this.hasSearchTerm=!!this.query.length}static create(e,t=!1){return new me(e,t)}searchWithFallback(e,t){let s,i=l.None,n=null,a=this.searchAndDownrankSecondaryMatch(e);if(a.match)n=a.match,i=l.Primary,s=e;else if(t){const{basename:e,path:o}=t;a=this.searchAndDownrankSecondaryMatch(e,o),a.isPrimary?(i=l.Basename,s=e):a.match&&(i=l.Path,s=o),n=a.match}return{matchType:i,matchText:s,match:n}}searchAndDownrankSecondaryMatch(e,t){let s=!1,i=null;return e&&(i=this.executeSearch(e),s=!!i),!i&&t&&(i=this.executeSearch(t),i&&(i.score-=1)),{isPrimary:s,match:i}}executeSearch(e){const t=this.getSearchDelegate();return t?t(e):null}getSearchDelegate(){if(!this._searchDelegate){const{query:e,useSimpleSearch:t}=this;this._searchDelegate=t?n.prepareSimpleSearch(e):n.prepareFuzzySearch(e)}return this._searchDelegate}}class ue extends he{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){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,a=me.create(s);this.getItems().forEach((e=>{let s=!0,n=null;i&&(({match:n}=a.searchWithFallback(e.id)),s=!!n),s&&t.push({type:r.WorkspaceList,item:e,match:n})})),i&&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 ue.getEnabledWorkspacesPluginInstance(this.app)}static getEnabledWorkspacesPluginInstance(e){return v(e,"workspaces")}}class ge extends he{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 u(e)?s=this.renderFileSuggestion(e,t):g(e)&&(s=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}=t;let i=l.None,n=null;s?.matches&&(g(t)?(i=l.Primary,n=t.alias):u(t)&&(i=l.Path,n=t.file.path)),t.matchType=i,t.matchText=n,he.updateWorkspaceEnvListStatus(e,t)}static createUnresolvedSuggestion(e,t,s,i){const n={linktext:e,type:r.Unresolved,...t};return he.applyMatchPriorityPreferences(n,s,i)}}class pe extends he{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){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,a=me.create(s);this.getItems().forEach((s=>{const n=x(s);let o=!0,r={matchType:l.None,match:null};const d=this.getPreferredTitle(s,this.settings.preferredSourceForTitle);i&&(r=a.searchWithFallback(d,n),o=r.matchType!==l.None),o&&t.push(this.createSuggestion(e.currentWorkspaceEnvList,s,n,r,d))})),i&&n.sortSearchResults(t)}return t}getPreferredTitle(e,t){return pe.getPreferredTitle(e,t,this.app.metadataCache,this.settings.frontmatterTitleProperty)}static getPreferredTitle(e,t,s,i){const n=x(e);let a=e.getDisplayText();if("H1"===t&&n){const e=pe.getFirstH1(n,s);e&&(a=a.replace(n.basename,e.heading))}else if("FrontMatter"===t&&n&&i){const e=s.getFileCache(n)?.frontmatter,t=he.getFrontmatterProperty(e,i);t&&(a=a.replace(n.basename,t))}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=[l.None,l.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 pe.createSuggestion(e,t,s,this.settings,this.app.metadataCache,n,i)}static createSuggestion(e,t,s,i,n,a,o){o=o??{matchType:l.None,match:null,matchText:null};let d={item:t,file:s,preferredTitle:a=a??null,type:r.EditorList,...o};return d=he.updateWorkspaceEnvListStatus(e,d),he.applyMatchPriorityPreferences(d,i,n)}}class fe extends he{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){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,a=me.create(s),{allBookmarks:o}=this.getItems(e);o.forEach((s=>{let n=!0,o={matchType:l.None,match:null};i&&(o=a.searchWithFallback(s.bookmarkPath),n=o.matchType!==l.None),n&&t.push(this.createSuggestion(e.currentWorkspaceEnvList,s,o))})),i&&n.sortSearchResults(t)}return t}renderSuggestion(e,t){return!1}onChooseSuggestion(e,t){let s=!1;if(fe.isBookmarksPluginFileItem(e?.item)){const{file:i}=e;this.navigateToLeafOrOpenFile(t,i,`Unable to open file from BookmarkSuggestion ${i?.path}`),s=!0}return s}getPreferredTitle(e,t,s,i){let n=e.getItemTitle(t);if(s)if("H1"===i){const e=this.getFirstH1(s);e&&(n=n.replace(/^[^#]*/,e.heading))}else if("FrontMatter"===i){const e=this.app.metadataCache.getFileCache(s)?.frontmatter,t=he.getFrontmatterProperty(e,this.settings.frontmatterTitleProperty);t&&(n=n.replace(/^[^#]*/,t))}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(fe.isBookmarksPluginGroupItem(e))o(e.items,`${r}${e.title}/`);else if(this.isFacetedWith(a,j[e.type])){let a;if(fe.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 v(this.app,"bookmarks")}createSuggestion(e,t,s){return fe.createSuggestion(e,t,this.settings,this.app.metadataCache,s)}static createSuggestion(e,t,s,i,n){let a={type:r.Bookmark,item:t.item,bookmarkPath:t.bookmarkPath,file:t.file,...n};return a=he.updateWorkspaceEnvListStatus(e,a),he.applyMatchPriorityPreferences(a,s,i)}static isBookmarksPluginFileItem(e){return c(e,"type","file")}static isBookmarksPluginGroupItem(e){return c(e,"type","group")}addPropertiesToStandardSuggestions(e,t){const{match:s,item:i}=t;let n=l.None,a=null;if(!t.file&&fe.isBookmarksPluginFileItem(i)){const e=i.path;t.file=this.getTFileByPath(e)}s?.matches&&(n=l.Primary,a=t.bookmarkPath),t.matchType=n,t.matchText=a,he.updateWorkspaceEnvListStatus(e,t)}}const ye={file:"lucide-file-text",text:"lucide-sticky-note",link:"lucide-globe",group:"create-group"},be={table:"lucide-table",list:"lucide-list",cards:"lucide-layout-grid"};class Se extends he{inputInfo;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;const{query:i,hasSearchTerm:a}=e.parsedInputQuery,o=me.create(i),l=e.parsedCommand(t.SymbolList);(await this.getItems(l.source,a)).forEach((e=>{let t=!0,i=null;if(a){const s=Se.getSuggestionTextForSymbol(e);({match:i}=o.searchWithFallback(s)),t=!!i}if(t){const{file:t}=l.source;s.push({type:r.SymbolList,file:t,item:e,match:i})}})),a&&n.sortSearchResults(s)}return s}renderSuggestion(e,t){let s=!1;if(e){const{item:i,file:n,match:a}=e,o=["qsp-suggestion-symbol"];Object.prototype.hasOwnProperty.call(i,"indentLevel")&&this.settings.symbolsInLineOrder&&!this.inputInfo?.parsedInputQuery?.hasSearchTerm&&o.push(`qsp-symbol-l${i.indentLevel}`),this.addClassesToSuggestionContainer(t,o);const{titleEl:r}=he.createContentStructureElements(t);Se.renderSymbolContent(this.app,this.settings,r,i,n,a),this.addSymbolIndicator(i,t),s=!0}return s}onChooseSuggestion(e,s){let i=!1;if(e){const n=this.inputInfo.parsedCommand(),{leaf:a,file:o}=n.source,r=this.getOpenViewState(e),{item:l}=e;this.navigateToLeafOrOpenFileAsync(s,o,r,a,t.SymbolList).then((()=>{if(Se.isCanvasSymbolPayload(l)&&this.zoomToCanvasNode(this.getActiveLeaf().view,l.symbol),Se.isBaseViewSymbolPayload(l)){const t=l.symbol,s=e.file?.path,i=`${s}#${t.name}`;this.app.workspace.openLinkText(i,s,!1).catch((e=>{console.log(`Switcher++: Unable to navigate to Base view ${t.name} in file ${s}`,e)}))}}),(e=>{console.log(`Switcher++: Unable to navigate to symbols for file ${o?.path}`,e)})),i=!0}return i}reset(){this.inputInfo=null}getAvailableFacets(e){const i=e.parsedCommand(t.SymbolList),n=Se.isBaseFile(i?.source?.file),a=Se.isCanvasFile(i?.source?.file),o=this.getFacets(e.mode),r=new Set(Object.values(W)),l=new Set(Object.values(V)),d=new Set(Object.values(s).filter((e=>isNaN(Number(e)))));return o.forEach((e=>{const{id:t}=e;e.isAvailable=n?r.has(t):a?l.has(t):d.has(t)})),o.filter((e=>e.isAvailable))}zoomToCanvasNode(e,t){if(Se.isCanvasView(e)&&t){const s=e.canvas,i=s.nodes.get(t.id);s.selectOnly(i),s.zoomToSelection()}}getPreferredViewLinePosition(e){let t=super.getPreferredViewLinePosition();if(e?.item?.symbol){const{item:s}=e;if(!Se.isCanvasSymbolPayload(s)&&!Se.isBaseViewSymbolPayload(s)){t=s.symbol.position}}return t}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&&Se.FindNearestHeadingSymbol(s,e),s}static FindNearestHeadingSymbol(e,t){const s=t?.cursor?.line;if(s){let t=null;const i=e.filter((e=>y(e.symbol)));i.length&&(t=i.reduce(((e,t)=>{const{line:i}=t.symbol.position.start,n=e?e.symbol.position.start.line:-1;return e?i>n&&i<=s?t:e:i<=s?t:null}),null)),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(Se.isBaseFile(o))await this.addBaseViewsFromSource(o,a,r);else if(Se.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),this.addTagsFromSource(e,a,r),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&&Se.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(V[e.type],i)&&t.push({type:"symbolInfo",symbolType:s.CanvasNode,symbol:{...e}})}))}async addBaseViewsFromSource(e,t,i){let a;try{const t=await this.app.vault.cachedRead(e);a=n.parseYaml(t)}catch(t){return void console.log(`Switcher++: error reading file to extract base view information. ${e.path} `,t)}a&&a?.views&&Array.isArray(a.views)&&a.views.forEach((e=>{const n=W[e.type];(n?this.shouldIncludeSymbol(n,i):0===i.size)&&t.push({type:"symbolInfo",symbolType:s.BaseView,symbol:{type:e.type,name:e.name}})}))}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=F(i);(n.excludeLinkSubTypes&e)===e||t.push({type:"symbolInfo",symbol:i,symbolType:s.Link})}}addTagsFromSource(e,t,i){if(!this.shouldIncludeSymbol(s.Tag,i))return;const n=new Set,a=e.tags??[];for(const e of a)n.add(e.tag.toLowerCase()),t.push({type:"symbolInfo",symbol:e,symbolType:s.Tag});const o=e.frontmatter;if(o){const i=H.getTags(o),a=e.frontmatterPosition??{start:{line:0,col:0,offset:0},end:{line:0,col:0,offset:0}};for(const e of i){const i=e.startsWith("#")?e:`#${e}`;if(n.has(i.toLowerCase()))continue;const o={tag:i,position:a};t.push({type:"symbolInfo",symbol:o,symbolType:s.Tag})}}}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;y(e.symbol)?(s=e.symbol.level,t=e.symbol.level-1):t=s,e.indentLevel=t})),t}static getMarkdownContentForSymbol(e,t){const{symbol:s}=e;if(y(s))return s.heading;if(b(s))return s.tag;if(S(s))return s.calloutTitle;const i=s;return i.original?i.original:null}static renderSymbolContent(e,t,s,i,a,o,r){const l=Se.getMarkdownContentForSymbol(i,a);if((r??(null!==l&&t.shouldRenderSymbolAsHTML(i.symbolType)))&&null!==l)he.renderMarkdownContentAsync(e,s,l,a.path);else{const e=Se.getSuggestionTextForSymbol(i);n.renderResults(s,e,o)}}static getSuggestionTextForSymbol(e){const{symbol:t}=e;let s;if(y(t))s=t.heading;else if(b(t))s=t.tag.slice(1);else if(S(t))s=t.calloutTitle;else if(Se.isCanvasSymbolPayload(e))s=Se.getSuggestionTextForCanvasNode(e.symbol);else if(Se.isBaseViewSymbolPayload(e))s=e.symbol.name;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,r=["qsp-symbol-indicator"],l=this.createFlairContainer(t);if(S(i)){r.push("suggestion-flair","callout","callout-icon","svg-icon");const e=l.createSpan({cls:r,attr:{"data-callout":i.calloutType}}),t=e.getCssPropertyValue("--callout-icon");n.setIcon(e,t)}else if(Se.isCanvasSymbolPayload(e)){const t=ye[e.symbol.type];this.renderIndicator(l,r,t,null)}else if(Se.isBaseViewSymbolPayload(e)){const t=e.symbol,s=be[t.type]||be.table;this.renderIndicator(l,r,s,null)}else{let e;e=y(i)?o[i.level]:a[s],this.renderIndicator(l,r,null,e)}}static isCanvasSymbolPayload(e){return e.symbolType===s.CanvasNode}static isBaseViewSymbolPayload(e){return e.symbolType===s.BaseView}static isCanvasFile(e){return"canvas"===e?.extension}static isCanvasView(e){return"canvas"===e?.getViewType()}static isBaseFile(e){return"base"===e?.extension}static isBaseView(e){return"bases"===e?.getViewType()}}class ke extends he{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 i=this.getOpenViewState(e);this.navigateToLeafOrOpenFile(t,e.file,"Unable to navigate to heading for file.",i),s=!0}return s}getPreferredViewLinePosition(e){return e?.item?.position}renderSuggestion(e,t){let s=!1;if(e){const{item:i,file:n,match:a}=e,{app:r,settings:l}=this;this.addClassesToSuggestionContainer(t,["qsp-suggestion-headings",`qsp-headings-l${i.level}`]);const{contentEl:d,titleEl:c}=he.createContentStructureElements(t);ke.renderHeadingContent(r,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,o[i.level]),e.downranked&&t.addClass("mod-downranked"),s=!0}return s}static renderHeadingContent(e,t,i,n,a,o,r){const l={type:"symbolInfo",symbol:n,symbolType:s.Heading};Se.renderSymbolContent(e,t,i,l,a,o,r)}getAvailableFacets(e){const{settings:{shouldSearchHeadings:t,shouldSearchBookmarks:s,shouldSearchFilenames:i,shouldSearchRecentFiles:n,builtInSystemOptions:{showAttachments:a,showAllFileTypes:o}}}=this,r=a||o,l={[Q.RecentFiles]:n,[Q.Bookmarks]:s,[Q.Filenames]:i,[Q.Headings]:t,[Q.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){const{hasSearchTerm:s}=e.parsedInputQuery,{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,o=me.create(t.parsedInputQuery.query);this.getSuggestionsForEditorsAndRecentFiles(t,s,i,{editors:!1,recentFiles:!1});const r={fileBookmarks:n.bookmarks,nonFileBookmarks:n.bookmarks};this.getSuggestionsForBookmarks(t,o,s,i,r);const l={headings:n.headings,allHeadings:n.allHeadings,aliases:n.aliases,filename:n.filename,filenameAsFallback:n.filenameAsFallback};this.getSuggestionForFiles(t,o,e,s,i,l),n.unresolved&&!a&&this.addUnresolvedSuggestions(s,o)}getSuggestionsForBookmarks(e,t,s,i,n){const a=!!i.size,{fileBookmarks:o,nonFileBookmarks:r}=e.currentWorkspaceEnvList;if(a){const e=i.has(Q.Bookmarks);n=Object.assign(n,{fileBookmarks:e,nonFileBookmarks:e})}const l=i=>{for(const n of i)this.addBookmarkSuggestion(e,s,t,n)};n.fileBookmarks&&o.forEach((e=>{l(e)})),n.nonFileBookmarks&&l(r)}getSuggestionForFiles(e,t,s,i,n,a){if(!!n.size){const e=this.isFacetedWith(n,Q.Headings),t=this.isFacetedWith(n,Q.ExternalFiles)||this.isFacetedWith(n,Q.Filenames);let s=!1,i=!1;e&&(s=!0===a.allHeadings,i=!0===a.filenameAsFallback),a=Object.assign(a,{headings:e,aliases:!1,filename:t,allHeadings:s,filenameAsFallback:i})}else a=Object.assign({headings:!0,allHeadings:!0,aliases:!0,filename:!0,filenameAsFallback:!0},a);if([a.headings,a.aliases,a.filename].some((e=>!0===e))){const{excludeFolders:o}=this.settings,r=E(o);let l=Array.prototype.concat(s);for(;l.length>0;){const s=l.pop();k(s)?this.shouldIncludeFile(s,n)&&this.addSuggestionsForFile(e,t,i,s,a):r(s.path)||(l=l.concat(s.children))}}}addSuggestionsForFile(e,t,s,i,n){let a=!1;n.headings&&(a=this.addHeadingSuggestions(e,t,s,i,n.allHeadings)),(n.filename||!a&&n.filenameAsFallback)&&this.addFileSuggestions(e,t,s,i),n.aliases&&this.addAliasSuggestions(e,t,s,i)}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(Q.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=H.getAliases(a);let o=n.length;for(;o--;){const a=n[o],{match:r}=t.searchWithFallback(a);r&&s.push(this.createAliasSuggestion(e,a,i,r))}}}addFileSuggestions(e,t,s,i){const{match:n,matchType:a,matchText:o}=t.searchWithFallback(null,i);n&&s.push(this.createFileSuggestion(e,i,n,a,o))}addBookmarkSuggestion(e,t,s,i){const n=s.searchWithFallback(i.bookmarkPath);if(n.match){const s=fe.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}=t.searchWithFallback(n.heading);return a&&s.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=t.searchWithFallback(i);n.matchType!==l.None&&e.push(ge.createUnresolvedSuggestion(i,n,this.settings,s))}}createAliasSuggestion(e,t,s,i){let n={alias:t,file:s,...this.createSearchMatch(i,l.Primary,t),type:r.Alias};return n=he.updateWorkspaceEnvListStatus(e.currentWorkspaceEnvList,n),this.applyMatchPriorityPreferences(n)}createFileSuggestion(e,t,s,i,n){let a={file:t,match:s,matchType:i,matchText:n,type:r.File};return a=he.updateWorkspaceEnvListStatus(e.currentWorkspaceEnvList,a),this.applyMatchPriorityPreferences(a)}createHeadingSuggestion(e,t,s,i){let n={item:t,file:s,...this.createSearchMatch(i,l.Primary,t.heading),type:r.HeadingsList};return n=he.updateWorkspaceEnvListStatus(e.currentWorkspaceEnvList,n),this.applyMatchPriorityPreferences(n)}createSearchMatch(e,t,s){let i=l.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}=s.searchWithFallback(n?.heading,e);if(a){let s;s=o===l.Primary?this.createHeadingSuggestion(t,n,e,a):this.createFileSuggestion(t,e,a,o,r),i.push(s)}}addOpenEditorSuggestions(e,t,s,i){const n=x(e),{settings:a,app:{metadataCache:o}}=this,r=pe.getPreferredTitle(e,a.preferredSourceForTitle,o,a.frontmatterTitleProperty),l=s.searchWithFallback(r,n);if(l.match){const s=pe.createSuggestion(t.currentWorkspaceEnvList,e,n,a,o,r,l);i.push(s)}}getSuggestionsForEditorsAndRecentFiles(e,t,s,i){const{query:n}=e.parsedInputQuery,a=me.create(n);if((i=s.has(Q.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,a,t)}))}if(i.recentFiles){const i=e.currentWorkspaceEnvList?.mostRecentFiles;i?.forEach((i=>{this.shouldIncludeFile(i,s)&&this.addRecentFilesSuggestions(i,e,a,t)}))}}onNoResultsCreateAction(e,s){const i=e.parsedCommand(t.HeadingsList)?.parsedInput;return this.createFile(i,s),!0}}class ve extends he{static recentlyUsedCommandIds=[];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){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,a=me.create(s);this.getItems(e,i).forEach((e=>{let s=!0,n=null;i&&(({match:n}=a.searchWithFallback(e.cmd.name)),s=!!n),s&&t.push(this.createSuggestion(e,n))})),i&&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,ve.recentlyUsedCommandIds),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(this.settings.maxRecentCommands)}}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($.Pinned,Array.from(s));const o=this.isFacetedWith(e,$.Pinned),r=Array.from(i).filter((e=>!o||o&&!s.has(e)));return"asc"===this.settings.recentCommandDisplayOrder&&r.reverse(),a($.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(ve.recentlyUsedCommandIds)}createSuggestion(e,t){const{cmd:s,isPinned:i,isRecent:n}=e,a={type:r.CommandList,item:s,isPinned:i,isRecent:n,match:t};return this.applyMatchPriorityPreferences(a)}getEnabledCommandPalettePluginInstance(){return ve.getEnabledCommandPalettePluginInstance(this.app)}static getEnabledCommandPalettePluginInstance(e){return v(e,"command-palette")}}class we extends he{inputInfo;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;const i=me.create(e.parsedInputQuery.query),a=e.parsedCommand(t.RelatedItemsList);this.getItems(a.source,e).forEach((t=>{const n=this.searchAndCreateSuggestion(e,i,t);n&&s.push(n)})),i.hasSearchTerm&&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([[d.Backlink,"links-coming-in"],[d.DiskLocation,"folder-tree"],[d.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){if("H1"===t)s=this.getFirstH1(i)?.heading??null;else if("FrontMatter"===t){const e=this.app.metadataCache.getFileCache(i)?.frontmatter;s=he.getFrontmatterProperty(e,this.settings.frontmatterTitleProperty)}}else{!!n?.length&&(s=n)}return s}searchAndCreateSuggestion(e,t,s){const{file:i,unresolvedText:n}=s;let a={matchType:l.None,match:null};const o=null===i&&n?.length,{currentWorkspaceEnvList:r}=e,{settings:d,app:{metadataCache:c}}=this,h=this.getPreferredTitle(s,d.preferredSourceForTitle);return t.hasSearchTerm&&(a=t.searchWithFallback(h,i),a.matchType===l.None)?null:o?ge.createUnresolvedSuggestion(h,a,d,c):this.createSuggestion(r,s,a,h)}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(d.Backlink)){let e=n?.path,t=i.resolvedLinks;p(a)&&(e=a.linktext,t=i.unresolvedLinks),this.addBacklinks(e,t,s)}return l(d.DiskLocation)&&this.addRelatedDiskFiles(n,s),l(d.OutgoingLink)&&this.addOutgoingLinks(n,s),s}addRelatedDiskFiles(e,t){const{excludeRelatedFolders:s,excludeOpenRelatedFiles:i}=this.settings;if(e){const n=E(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:d.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 c;l?o(i.get(l))||l===e||(c={file:l,relationType:d.OutgoingLink,count:1},i.set(l,c),t.push(c)):o(s.get(r))||(c={file:null,relationType:d.OutgoingLink,unresolvedText:r,count:1},s.set(r,c),t.push(c))}))}}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:d.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&&p(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:r.RelatedItemsList,preferredTitle:i,...s};return n=he.updateWorkspaceEnvListStatus(e,n),this.applyMatchPriorityPreferences(n)}}class Ce extends he{mobileVaultChooserMarker={type:r.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){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,a=me.create(s);this.getItems().forEach((e=>{let s=!0;if(i){const t=a.searchWithFallback(null,e.pathSegments);Object.assign(e,t),s=!!t.match}s&&t.push(e)})),i&&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===l.Basename&&(o=a,a=null);const r=this.renderContent(t,s.basename,o).createDiv({cls:["suggestion-note","qsp-note"]}),d=r.createSpan({cls:["qsp-path-indicator"]}),c=r.createSpan({cls:"qsp-path"});n.setIcon(d,"folder"),n.renderResults(c,s.path,a)}onChooseSuggestion(e,t){let s=!1;return e&&(n.Platform.isDesktop?(this.openVaultOnDesktop(e.pathSegments?.path),s=!0):e===this.mobileVaultChooserMarker&&(this.app.openVaultChooser(),s=!0)),s}getItems(){const e=[];if(n.Platform.isDesktop)try{const t=this.getVaultListDataOnDesktop();for(const[s,{path:i,open:n}]of Object.entries(t)){const t=T(i),a={type:r.VaultList,match:null,item:s,isOpen:!!n,pathSegments:{basename:t,path:i}};e.push(a)}}catch(e){console.log("Switcher++: error parsing vault data. ",e)}else e.push(this.mobileVaultChooserMarker);return e.sort(((e,t)=>e.pathSegments.basename.localeCompare(t.pathSegments.basename)))}getIpcRenderer(){if(!n.Platform.isDesktop)return null;try{return window.require("electron").ipcRenderer}catch{return null}}openVaultOnDesktop(e){const t=this.getIpcRenderer();if(t)try{t.sendSync("vault-open",e,!1)}catch(t){console.log(`Switcher++: error opening vault with path: ${e} `,t)}}getVaultListDataOnDesktop(){let e=null;const t=this.getIpcRenderer();if(t)try{e=t.sendSync("vault-list")}catch(e){console.log("Switcher++: error retrieving list of available vaults. ",e)}return e}}class Le{app;config;static instance;instanceCache=new Map;modeToHandlerClass=new Map;suggestionTypeToMode=new Map;cmdStrToMode=new Map;sourcedHandlerModes=new Set;constructor(e,t,s){this.app=e,this.config=t;for(const e of s)e.handlerClass&&(this.modeToHandlerClass.set(e.mode,e.handlerClass),this.mapSuggestionTypesToMode(e),this.mapCommandStrToMode(e),this.registerSourcedHandler(e))}static initialize(e,t,s){this.instance?console.warn("Switcher++: HandlerRegistry already initialized."):this.instance=new Le(e,t,s)}static reset(){this.instance=null}static getInstance(){return this.instance??null}getHandler(e){let t=null;const s=this.resolveMode(e);if(s)if(this.instanceCache.has(s))t=this.instanceCache.get(s)??null;else{const e=this.modeToHandlerClass.get(s);if(e){const i=new e(this.app,this.config);this.instanceCache.set(s,i),t=i}}return t}resetSourcedHandlers(e){const t=new Set(e);for(const e of this.sourcedHandlerModes){const s=this.instanceCache.get(e);s&&!t.has(s)&&s.reset()}}mapSuggestionTypesToMode(e){e.ownSuggestionTypes?.forEach((t=>{this.suggestionTypeToMode.set(t,e.mode)}))}mapCommandStrToMode(e){const t=e.parserCommand?.getCommandStr();t?.length&&this.cmdStrToMode.set(t,e.mode)}registerSourcedHandler(e){"sourced"===e.parserCommand?.type&&this.sourcedHandlerModes.add(e.mode)}resolveMode(e){let s;return"number"==typeof e&&Object.values(t).includes(e)?s=e:c(e,"type")?s=this.suggestionTypeToMode.get(e.type):"string"==typeof e&&(s=this.cmdStrToMode.get(e)),s}}class Ie{commandMap=new Map;escapeCmdChar;handlerRegistry;constructor(e,t,s){this.handlerRegistry=e,this.escapeCmdChar=t.escapeCmdChar,this.commandMap=this.buildCommandMap(s)}parseInputForMode(e,s,i){const{cleanInput:n,resolvedCommands:a}=this.parse(e.inputText);e.cleanInput=n;this.findFirstValidCommand(a,e,s,i)||(this.handlerRegistry.resetSourcedHandlers(),e.mode=t.Standard)}parse(e){let t="";const s=[],i=this.escapeCmdChar.length;let n=0;for(;n<e.length;){if(e.startsWith(this.escapeCmdChar,n)){const s=this.findCommandMatch(e,n+i);if(s){t+=s.cmdStr,n+=i+s.cmdStr.length;continue}}const a=this.findCommandMatch(e,n);a?(s.push({...a,indexInCleanInput:t.length}),t+=a.cmdStr,n+=a.cmdStr.length):(t+=e[n],n+=1)}return{cleanInput:t,resolvedCommands:this.resolveCommandPrecedence(s,t)}}buildCommandMap(e){const t=new Map;for(const s of e){const e=s.parserCommand.getCommandStr()??"";if(e.length>0){const i=e[0];t.has(i)||t.set(i,[]),t.get(i)?.push({cmdDef:s,cmdStr:e})}}for(const e of t.values())e.sort(((e,t)=>t.cmdStr.length-e.cmdStr.length));return t}findCommandMatch(e,t){const s=this.commandMap.get(e[t]);if(!s)return null;for(const i of s)if(e.startsWith(i.cmdStr,t))return i;return null}resolveCommandPrecedence(e,t){const s=[];let i;for(const n of e){const e=n.indexInCleanInput+n.cmdStr.length,a=t.substring(e),o={cmdDef:n.cmdDef,cmdStr:n.cmdStr,indexInCleanInput:n.indexInCleanInput,filterText:a},r=n.cmdDef.parserCommand.type;"prefix"!==r||0!==n.indexInCleanInput||i?"sourced"===r&&s.push(o):i=o}return s.sort(((e,t)=>e.indexInCleanInput-t.indexInCleanInput)),i?[...s,i]:s}findFirstValidCommand(e,t,s,i){for(const n of e){const e=this.handlerRegistry.getHandler(n.cmdDef.mode);if(!e)continue;t.sessionOpts.useActiveEditorAsSource=n.cmdDef.parserCommand.useActiveEditorAsSource;if(e.validateCommand(t,n.indexInCleanInput,n.filterText,s,i).isValidated){const t="sourced"===n.cmdDef.parserCommand.type?[e]:[];return this.handlerRegistry.resetSourcedHandlers(t),!0}}return!1}}const Te={};class Ee{app;settings;exKeymap;_inputInfo;get inputInfo(){return this._inputInfo}get previousInputHistory(){return Te}_handlerRegistry;get handlerRegistry(){return this._handlerRegistry}_inputParser;get inputParser(){return this._inputParser}debouncedGetSuggestions;workspaceEnvList=null;sessionOpts={};noResultActionModes=[t.HeadingsList,t.WorkspaceList];constructor(e,s,i){this.app=e,this.settings=s,this.exKeymap=i;const a=(o=s,[{commandId:"switcher-plus:open",commandName:"Open in Standard Mode",mode:t.Standard,iconId:"lucide-file-search",handlerClass:ge,ownSuggestionTypes:[r.Alias,r.File],parserCommand:{type:"none",getCommandStr:()=>""}},{commandId:"switcher-plus:open-editors",commandName:"Open in Editor Mode",mode:t.EditorList,iconId:"lucide-file-edit",handlerClass:pe,ownSuggestionTypes:[r.EditorList],parserCommand:{type:"prefix",getCommandStr:()=>o.editorListCommand}},{commandId:"switcher-plus:open-symbols",commandName:"Open Symbols for selected suggestion or editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",handlerClass:Se,ownSuggestionTypes:[r.SymbolList],parserCommand:{type:"sourced",getCommandStr:()=>o.symbolListCommand}},{commandId:"switcher-plus:open-symbols-active",commandName:"Open Symbols for the active editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",handlerClass:Se,parserCommand:{type:"prefix",getCommandStr:()=>o.symbolListActiveEditorCommand,useActiveEditorAsSource:!0}},{commandId:"switcher-plus:open-workspaces",commandName:"Open in Workspaces Mode",mode:t.WorkspaceList,iconId:"lucide-album",handlerClass:ue,ownSuggestionTypes:[r.WorkspaceList],parserCommand:{type:"prefix",getCommandStr:()=>o.workspaceListCommand}},{commandId:"switcher-plus:open-headings",commandName:"Open in Headings Mode",mode:t.HeadingsList,iconId:"lucide-file-search",handlerClass:ke,ownSuggestionTypes:[r.HeadingsList],parserCommand:{type:"prefix",getCommandStr:()=>o.headingsListCommand}},{commandId:"switcher-plus:open-starred",commandName:"Open in Bookmarks Mode",mode:t.BookmarksList,iconId:"lucide-bookmark",handlerClass:fe,ownSuggestionTypes:[r.Bookmark],parserCommand:{type:"prefix",getCommandStr:()=>o.bookmarksListCommand}},{commandId:"switcher-plus:open-commands",commandName:"Open in Commands Mode",mode:t.CommandList,iconId:"run-command",handlerClass:ve,ownSuggestionTypes:[r.CommandList],parserCommand:{type:"prefix",getCommandStr:()=>o.commandListCommand}},{commandId:"switcher-plus:open-related-items",commandName:"Open Related Items for selected suggestion or editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",handlerClass:we,ownSuggestionTypes:[r.RelatedItemsList],parserCommand:{type:"sourced",getCommandStr:()=>o.relatedItemsListCommand}},{commandId:"switcher-plus:open-related-items-active",commandName:"Open Related Items for the active editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",handlerClass:we,parserCommand:{type:"prefix",getCommandStr:()=>o.relatedItemsListActiveEditorCommand,useActiveEditorAsSource:!0}},{commandId:"switcher-plus:open-vaults",commandName:"Open in Vaults Mode",mode:t.VaultList,iconId:"vault",handlerClass:Ce,ownSuggestionTypes:[r.VaultList],parserCommand:{type:"prefix",getCommandStr:()=>o.vaultListCommand}}]);var o;Le.getInstance()||Le.initialize(e,s,a),this._handlerRegistry=Le.getInstance(),this._inputParser=new Ie(this._handlerRegistry,s,a),this.debouncedGetSuggestions=n.debounce(this.getSuggestions.bind(this),s.headingsSearchDebounceMilli,!0),this.reset()}onOpen(){const{app:e,exKeymap:t,handlerRegistry:s,settings:i}=this;t.isOpen=!0,i.quickFilters?.shouldResetActiveFacets&&Object.values(i.quickFilters.facetList).forEach((e=>e.isActive=!1)),this.workspaceEnvList=this.buildWorkspaceEnvList(e.workspace,e.vault,e.viewRegistry,s,i)}onClose(){this.exKeymap.isOpen=!1,D.unload()}setSessionOpenMode(e,t){this.reset(),e?.setSuggestions([]),this.sessionOpts=Object.assign({},t)}setInitialInputForSession(e){const{mode:s}=this.sessionOpts;if(!s)return;this.sessionOpts.mode=null;const i=this.previousInputHistory[s]?.parsedCommand(s)?.parsedInput,n=this.handlerRegistry.getHandler(s),a=s!==t.Standard?n.getCommandString(this.sessionOpts):"";if((s===t.CommandList&&this.settings.preserveCommandPaletteLastInput||s!==t.CommandList&&this.settings.preserveQuickSwitcherLastInput)&&void 0!==i){e.value=a+i;const t=a?.length??0;e.setSelectionRange(t,e.value.length)}else a&&(e.value=a)}updateSuggestions(e,s,i){const{exKeymap:n,settings:a,sessionOpts:o}=this;let r=!1;this.debouncedGetSuggestions.cancel();const l=he.getActiveLeaf(this.app.workspace),d=Ee.getActiveSuggestion(s),c=this.determineRunMode(e,d,l,o);this._inputInfo=c;const{mode:h}=c;return this.previousInputHistory[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.handlerRegistry.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{handlerRegistry:i,inputInfo:n,settings:{overrideStandardModeRendering:a}}=this,{mode:o}=n,l=o===t.HeadingsList;let d=!1;const c=new Set([r.Unresolved]);if(null===e){if(l){const e=i.getHandler(o),t=n.parsedCommand(o)?.parsedInput;e.renderFileCreationSuggestion(s,t),d=!0}}else if(!c.has(e.type)&&(a||l||f(e))){const t=i.getHandler(e);t&&(d=t.renderSuggestion(e,s))}return d}onChooseSuggestion(e,s){const{handlerRegistry:i,inputInfo:n,settings:{overrideStandardModeBehaviors:a}}=this,{mode:o}=n,l=o===t.HeadingsList;let d=!1;const c=new Set([r.Unresolved]);if(null===e){if(this.noResultActionModes.includes(o)){const e=i.getHandler(o);d=!!e?.onNoResultsCreateAction(n,s)}}else if(!c.has(e.type)&&(a||l||f(e))){const t=i.getHandler(e);t&&(d=t.onChooseSuggestion(e,s))}return d}determineRunMode(e,s,i,n){const a=e??"",o=new ce(a,t.Standard,n);return 0===a.length?(this.reset(),o):(o.currentWorkspaceEnvList=this.workspaceEnvList,this.inputParser.parseInputForMode(o,s,i),o)}getSuggestions(e,t,s){t.setSuggestions([]);const{mode:i}=e,n=this.handlerRegistry.getHandler(i).getSuggestions(e),a=n=>{n?.length?(t.setSuggestions(n),Ee.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)}))}static setActiveSuggestion(e,s){if(e===t.SymbolList){const e=s.values.filter((e=>h(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 ce,this.sessionOpts={},this.handlerRegistry.resetSourcedHandlers()}buildWorkspaceEnvList(e,s,i,n,a){const o=n.getHandler(t.EditorList).getItems(),r=o.reduce(((e,t)=>{const s=x(t);return s&&e.add(s),e}),new Set),{fileBookmarks:l,nonFileBookmarks:d}=n.getHandler(t.BookmarksList).getItems(null),c=this.getAttachmentFileExtensions(i,a.fileExtAllowList),h=r.size+a.maxRecentFileSuggestionsOnInit,m=this.getRecentFiles(e,s,r,h);return{openWorkspaceLeaves:new Set(o),openWorkspaceFiles:r,fileBookmarks:l,nonFileBookmarks:d,attachmentFileExtensions:c,mostRecentFiles:m}}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,s,i=75){s=s??new Set;const n=new Set;if(i>0){const a=e.getRecentFiles({showMarkdown:!0,showCanvas:!0,showNonImageAttachments:!0,showImages:!0,maxCount:i});a?.forEach((e=>{const i=t.getAbstractFileByPath(e);k(i)&&!s.has(i)&&n.add(i)}))}return n}inputTextForStandardMode(e){const{mode:s,cleanInput:i}=this.inputInfo;let n=e;return s===t.Standard&&i?.length&&(n=i),n}inputTextForFulltextSearch(){const{inputInfo:e}=this,s=e.mode;let i=null,n=e.cleanInput;if(s!==t.Standard){const t=e.parsedCommand();n=t.parsedInput,I().includes(s)&&(i=t.source?.file)}return{mode:s,parsedInput:n,file:i}}addPropertiesToStandardSuggestions(e,s){if(!e||!s.overrideStandardModeBehaviors&&!s.overrideStandardModeRendering)return;const{handlerRegistry:i,inputInfo:{currentWorkspaceEnvList:n}}=this;for(let s=0;s<e.length;s++){const a=e[s];if(c(a,"type",r.Bookmark)){i.getHandler(t.BookmarksList).addPropertiesToStandardSuggestions(n,a)}else if(u(a)||g(a)){i.getHandler(t.Standard).addPropertiesToStandardSuggestions(n,a)}}}openSuggestionInBackground(e,t,s){const i=M(e);if(!i)return void console.log("Switcher++: error cannot open in background. The selected suggestion object does not seem to have an associated file. Suggestion obj: ",e);const n=this.handlerRegistry.getHandler(e)?.getOpenViewState(e,{active:!1,focus:!1});he.openFileInLeaf(i,t,this.app.workspace,n,s).catch((e=>{console.log(`Switcher++: error opening file (${i?.path}) in background. `,e)}))}}const Fe={Enter:"↵",Backspace:"⌫",ArrowLeft:"←",ArrowUp:"↑",ArrowDown:"↓",ArrowRight:"→",Tab:"↹"},Ae={...Fe,Mod:"Ctrl",Ctrl:"Ctrl",Meta:"Win",Alt:"Alt",Shift:"Shift"},xe={...Fe,Mod:"⌘",Ctrl:"⌃",Meta:"⌘",Alt:"⌥",Shift:"⇧"},Oe=[t.EditorList,t.HeadingsList,t.RelatedItemsList,t.BookmarksList,t.SymbolList],Pe=[t.CommandList,t.VaultList,t.WorkspaceList,...Oe];class Me{app;scope;chooser;modal;config;standardKeysInfo=[];customKeysInfo=[];savedStandardKeysInfo=[];_isOpen;customInstructionEls=new Map;standardInstructionsEl;facetKeysInfo=[];insertIntoEditorKeysInfo=[];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?xe:Ae}get exModeHandler(){return this.modal?.exMode}constructor(e,t,s,i,n){this.app=e,this.scope=t,this.chooser=s,this.modal=i,this.config=n,this.initKeysInfo(n,t),this.renderModeTriggerInstructions(i.modalEl,n),this.standardInstructionsEl=i.modalEl.querySelector(".prompt-instructions")}initKeysInfo(e,t){this.standardKeysInfo.push(),this.addCustomKeymaps(this.config),this.removeDefaultTabKeyBinding(t,e),this.registerNavigationBindings(t,e.navigationKeys),this.registerEditorTabBindings(t),this.registerCloseWhenEmptyBindings(t,e),this.registerQuickOpenBindings(t,e),this.registerFulltextSearchBindings(t,e),this.registerOpenInBackgroundBindings(t,e)}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}=Me;[[[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}registerFulltextSearchBindings(e,t){const{isEnabled:s,searchKeys:i}=t.fulltextSearch;if(s){C(this.app)&&e.register(i.modifiers,i.key,this.LaunchSystemGlobalSearch.bind(this))}}LaunchSystemGlobalSearch(e,t){const{parsedInput:s,file:i}=this.modal.exMode.inputTextForFulltextSearch();let n="";return i&&(n=`path:"${i.path}" `),this.modal.close(),C(this.app)?.openGlobalSearch(`${n}${s}`),!1}registerOpenInBackgroundBindings(e,t){const{openInBackground:{isEnabled:s,openKeys:i}}=t;if(s){const t={tab:"open in background tab",vertical:"open in background to the right",horizontal:"open in background below",window:"open in background window"};i?.filter((e=>e.hotkey)).forEach((({openType:s,hotkey:i})=>{e.register(i.modifiers,i.key,(()=>this.openInBackground(this.chooser,s))),this.createCustomKeymap(t[s],Pe,i,null,!0,!0)}))}}openInBackground(e,t){let s,i="vertical";"vertical"===t||"horizontal"===t?(s="split",i=t):s=t;const n=e?.values?.[e.selectedItem];return this.exModeHandler.openSuggestionInBackground(n,s,i),!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-flair","suggestion-hotkey","qsp-quick-open-hotkey"],text:Me.commandDisplayStr(i,s)})}}updateInsertIntoEditorCommand(e,s,i,n){let a=null;if(n?.isEnabled){const{keymap:o,insertableEditorTypes:r}=n,l=[t.CommandList,t.WorkspaceList,t.VaultList],d=s?.view?.getViewType();if(!(d&&!r.includes(d)||l.includes(e))){if(a=i.find((e=>e.purpose===o.purpose)),!a){const{modifiers:e,key:t,purpose:s}=o;a={isInstructionOnly:!1,command:Me.commandDisplayStr(e,t),modifiers:e,key:t,purpose:s},i.push(a)}a.eventListener=()=>{const{modal:e,chooser:t}=this;e.close();const i=t.values?.[t.selectedItem];return this.insertIntoEditorAsLink(i,s,n),!1},a.modes=[e]}}return a}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=Me.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 | ${Me.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?`(${Me.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=ve.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 ve(s,i).renderSuggestion(a,t)}return!1}toggleMarkdownContentRendering(e,t){const{app:i,config:n,chooser:a}=this,o=a.values?.[a.selectedItem],r=o.file;let l=null;if(h(o)?l=o.item:m(o)&&(l={type:"symbolInfo",symbol:o.item,symbolType:s.Heading}),l&&r&&n.shouldRenderSymbolAsHTML(l.symbolType)){const e=a.suggestions[a.selectedItem].querySelector(".qsp-title"),t=!e.querySelector(".qsp-rendered-container");e.empty(),Se.renderSymbolContent(i,n,e,l,r,o.match,t)}return!1}openDefaultApp(e,t){const{app:s,config:{openDefaultApp:{excludeFileExtensions:i}},chooser:n}=this,a=n.values?.[n.selectedItem],o=M(a);if(o&&!i.includes(o.extension)){const e=`Switcher++: error opening file (${o.path}) in default app. `;s.openWithDefaultApp(o.path).catch((t=>{console.log(e,t)}))}return!1}saveCurrentAndOpenSelectedWorkspace(){const{app:e,chooser:t,modal:s}=this,i=t?.values?.[t.selectedItem];if(i&&i.item){const t=ue.getEnabledWorkspacesPluginInstance(e);t&&(t.saveWorkspace(t.activeWorkspace),t.loadWorkspace(i.item.id),s.close())}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=O(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:Me.commandDisplayStr(r,l),isInstructionOnly:a},n&&this.customKeysInfo.push(o)}return o}addCustomKeymaps(e){const{quickOpen:s}=e,i=s?.keyList;if(i?.length){const e=`${i[0]}~${i[i.length-1]}`;this.createCustomKeymap("open nth item",Pe,{modifiers:s.modifiers,key:e},null,s.isEnabled,!0)}this.createCustomKeymap("open in new tab",Oe,{modifiers:["Mod"],key:"Enter"},null,!0,!0),this.createCustomKeymap("open to the right",Oe,{modifiers:["Mod"],key:"\\"},null,!0,!0),this.createCustomKeymap("open below",Oe,{modifiers:["Mod","Shift"],key:"\\"},null,!0,!0),this.createCustomKeymap("open in new window",Oe,{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("save and switch workspace",[t.WorkspaceList],e.saveWorkspaceAndSwitchKeys,this.saveCurrentAndOpenSelectedWorkspace.bind(this)),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:n}=e;this.createCustomKeymap("toggle preview (selected item)",[t.HeadingsList,t.SymbolList],n.toggleContentRenderingKeys,this.toggleMarkdownContentRendering.bind(this),n.isEnabled);const{openDefaultApp:a}=e;this.createCustomKeymap("open default app",Oe,a.openInDefaultAppKeys,this.openDefaultApp.bind(this),a.isEnabled);const{fulltextSearch:o}=e;this.createCustomKeymap("fulltext search",Pe,o.searchKeys,null,o.isEnabled,!0)}}class Re{static coreMobileLauncherButtonEl;static qspMobileLauncherButtonEl;static installMobileLauncherOverride(e,t,s){let i=null;if(!(n.Platform.isMobile&&t.isEnabled&&t.isMobileButtonEnabled)||Re.coreMobileLauncherButtonEl)return null;const a=function(e,t){let s=null;const i=e?.mobileNavbar?.containerEl;return i&&(s=i.querySelector(X.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)&&(Re.coreMobileLauncherButtonEl=a,Re.qspMobileLauncherButtonEl=e,i=e)}return i}static removeMobileLauncherOverride(){let e=!1;if(!Re.coreMobileLauncherButtonEl)return e;if(Re.qspMobileLauncherButtonEl?.parentElement){const t=Re.qspMobileLauncherButtonEl,s=Re.coreMobileLauncherButtonEl,i=s.style.display;s.style.display="none",t.insertAdjacentElement("beforebegin",s)&&(t.remove(),Re.qspMobileLauncherButtonEl=null,Re.coreMobileLauncherButtonEl=null,e=!0),s.style.display=i}return e}}class Be{static emptyLeaves=new Map;static layoutChangeEventRef;static installEmptyTabMonitor(e,t){if(!t?.isEnabled)return;const{workspace:s}=e.app;Be.layoutChangeEventRef=s.on("layout-change",(()=>{Be.updateEmptyTabs(s,t)})),e.registerEvent(Be.layoutChangeEventRef),s.onLayoutReady((()=>{Be.updateEmptyTabs(s,t)}))}static removeEmptyTabButtons(e){e.offref(Be.layoutChangeEventRef),Be.layoutChangeEventRef=null;const{emptyLeaves:t}=Be;for(const e of t.keys())t.get(e)?.detach(),t.delete(e)}static updateEmptyTabs(e,t){if(!t.isEnabled)return;const{buttonLabel:s,onclickListener:i}=t;e.iterateAllLeaves((e=>{const{emptyLeaves:t}=Be;if(B(e,"empty")&&!t.has(e)){const{containerEl:n}=e.view,a=function(e,t,s){let i=null;const n=e.querySelector(".empty-state-action-list");return n&&(i=n.createDiv({cls:["empty-state-action","tappable","qsp-empty-state-action-launch"],text:t}),i.addEventListener("click",s),n.firstElementChild!==i&&n.insertAfter(i,n.firstElementChild)),i}(n,s,i);a&&t.set(e,a)}}))}}const He=[{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 De extends n.Plugin{options;async onload(){const e=new X(this);await e.updateDataAndLoadSettings(),this.options=e,this.addSettingTab(new de(this.app,this,e)),this.registerRibbonCommandIcons(),this.updateLauncherButtonOverrides(!0),He.forEach((({id:e,name:t,mode:s,iconId:i,sessionOpts:n})=>{this.registerCommand(e,t,s,i,n)}))}onunload(){this.updateLauncherButtonOverrides(!1)}registerCommand(e,t,s,i,n){this.addCommand({id:e,name:t,icon:i,checkCallback:e=>this.createModalAndOpen(s,e,n)})}registerRibbonCommandIcons(){He.forEach((e=>{e.ribbonIconEl?.remove(),e.ribbonIconEl=null}));const e=He.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=w(e)?.QuickSwitcherModal;return s?new class extends s{plugin;_exMode;get exMode(){return this._exMode}constructor(e,t){super(e,t.options.builtInSystemOptions),this.plugin=t;const{options:s}=t;s.shouldShowAlias=this.shouldShowAlias;const i=new Me(e,this.scope,this.chooser,this,s);this._exMode=new Ee(e,s,i)}openInMode(e){this.exMode.setSessionOpenMode(this.chooser,e),super.open()}onOpen(){this.exMode.onOpen(),super.onOpen()}onClose(){super.onClose(),this.exMode.onClose()}updateSuggestions(){const{exMode:e,inputEl:t,chooser:s}=this;e.setInitialInputForSession(t),e.updateSuggestions(t.value,s,this)||super.updateSuggestions()}getSuggestions(e){const{exMode:t,plugin:s}=this,i=t.inputTextForStandardMode(e),n=super.getSuggestions(i);return t.addPropertiesToStandardSuggestions(n,s.options),n}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;const i=Object.assign({mode:e},s);t.openInMode(i)}return!0}updateLauncherButtonOverrides(e){const{app:s,options:{mobileLauncher:i}}=this;if(Re.removeMobileLauncherOverride(),Be.removeEmptyTabButtons(s.workspace),e){const e=i.modeString,n=t[e],a=()=>{n&&this.createModalAndOpen(n,!1)};Re.installMobileLauncherOverride(s,i,a);const o=He.find((e=>e.mode===n)),r="Switcher++: "+(o?.name??"");Be.installEmptyTabMonitor(this,{isEnabled:i.isEnabled&&i.isEmptyTabButtonEnabled,buttonLabel:r,onclickListener:a})}}}module.exports=De;
/* nosourcemap */