digital-garden/.obsidian/plugins/homepage/main.js

3 lines
35 KiB
JavaScript

"use strict";var We=Object.create;var Y=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Be=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var je=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),qe=(n,t)=>{for(var e in t)Y(n,e,{get:t[e],enumerable:!0})},me=(n,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ue(t))!Ke.call(n,i)&&i!==e&&Y(n,i,{get:()=>t[i],enumerable:!(a=Ye(t,i))||a.enumerable});return n};var ze=(n,t,e)=>(e=n!=null?We(Be(n)):{},me(t||!n||!n.__esModule?Y(e,"default",{value:n,enumerable:!0}):e,n)),$e=n=>me(Y({},"__esModule",{value:!0}),n);var xe=je(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});var g=require("obsidian"),te="YYYY-MM-DD",ae="gggg-[W]ww",Ne="YYYY-MM",be="YYYY-[Q]Q",ke="YYYY";function F(n){let t=window.app.plugins.getPlugin("periodic-notes");return t&&t.settings?.[n]?.enabled}function O(){try{let{internalPlugins:n,plugins:t}=window.app;if(F("daily")){let{format:o,folder:s,template:c}=t.getPlugin("periodic-notes")?.settings?.daily||{};return{format:o||te,folder:s?.trim()||"",template:c?.trim()||""}}let{folder:e,format:a,template:i}=n.getPluginById("daily-notes")?.instance?.options||{};return{format:a||te,folder:e?.trim()||"",template:i?.trim()||""}}catch(n){console.info("No custom daily note settings found!",n)}}function L(){try{let n=window.app.plugins,t=n.getPlugin("calendar")?.options,e=n.getPlugin("periodic-notes")?.settings?.weekly;if(F("weekly"))return{format:e.format||ae,folder:e.folder?.trim()||"",template:e.template?.trim()||""};let a=t||{};return{format:a.weeklyNoteFormat||ae,folder:a.weeklyNoteFolder?.trim()||"",template:a.weeklyNoteTemplate?.trim()||""}}catch(n){console.info("No custom weekly note settings found!",n)}}function x(){let n=window.app.plugins;try{let t=F("monthly")&&n.getPlugin("periodic-notes")?.settings?.monthly||{};return{format:t.format||Ne,folder:t.folder?.trim()||"",template:t.template?.trim()||""}}catch(t){console.info("No custom monthly note settings found!",t)}}function H(){let n=window.app.plugins;try{let t=F("quarterly")&&n.getPlugin("periodic-notes")?.settings?.quarterly||{};return{format:t.format||be,folder:t.folder?.trim()||"",template:t.template?.trim()||""}}catch(t){console.info("No custom quarterly note settings found!",t)}}function C(){let n=window.app.plugins;try{let t=F("yearly")&&n.getPlugin("periodic-notes")?.settings?.yearly||{};return{format:t.format||ke,folder:t.folder?.trim()||"",template:t.template?.trim()||""}}catch(t){console.info("No custom yearly note settings found!",t)}}function Te(...n){let t=[];for(let a=0,i=n.length;a<i;a++)t=t.concat(n[a].split("/"));let e=[];for(let a=0,i=t.length;a<i;a++){let o=t[a];!o||o==="."||e.push(o)}return t[0]===""&&e.unshift(""),e.join("/")}function Ge(n){let t=n.substring(n.lastIndexOf("/")+1);return t.lastIndexOf(".")!=-1&&(t=t.substring(0,t.lastIndexOf("."))),t}async function Qe(n){let t=n.replace(/\\/g,"/").split("/");if(t.pop(),t.length){let e=Te(...t);window.app.vault.getAbstractFileByPath(e)||await window.app.vault.createFolder(e)}}async function R(n,t){t.endsWith(".md")||(t+=".md");let e=g.normalizePath(Te(n,t));return await Qe(e),e}async function A(n){let{metadataCache:t,vault:e}=window.app,a=g.normalizePath(n);if(a==="/")return Promise.resolve(["",null]);try{let i=t.getFirstLinkpathDest(a,""),o=await e.cachedRead(i),s=window.app.foldManager.load(i);return[o,s]}catch(i){return console.error(`Failed to read the daily note template '${a}'`,i),new g.Notice("Failed to read the daily note template"),["",null]}}function T(n,t="day"){let e=n.clone().startOf(t).format();return`${t}-${e}`}function Pe(n){return n.replace(/\[[^\]]*\]/g,"")}function Je(n,t){if(t==="week"){let e=Pe(n);return/w{1,2}/i.test(e)&&(/M{1,4}/.test(e)||/D{1,4}/.test(e))}return!1}function E(n,t){return De(n.basename,t)}function Ze(n,t){return De(Ge(n),t)}function De(n,t){let a={day:O,week:L,month:x,quarter:H,year:C}[t]().format.split("/").pop(),i=window.moment(n,a,!0);if(!i.isValid())return null;if(Je(a,t)&&t==="week"){let o=Pe(a);if(/w{1,2}/i.test(o))return window.moment(n,a.replace(/M{1,4}/g,"").replace(/D{1,4}/g,""),!1)}return i}var ne=class extends Error{};async function Me(n){let t=window.app,{vault:e}=t,a=window.moment,{template:i,format:o,folder:s}=O(),[c,m]=await A(i),r=n.format(o),d=await R(s,r);try{let p=await e.create(d,c.replace(/{{\s*date\s*}}/gi,r).replace(/{{\s*time\s*}}/gi,a().format("HH:mm")).replace(/{{\s*title\s*}}/gi,r).replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(P,D,M,v,w,f)=>{let Z=a(),X=n.clone().set({hour:Z.get("hour"),minute:Z.get("minute"),second:Z.get("second")});return M&&X.add(parseInt(v,10),w),f?X.format(f.substring(1).trim()):X.format(o)}).replace(/{{\s*yesterday\s*}}/gi,n.clone().subtract(1,"day").format(o)).replace(/{{\s*tomorrow\s*}}/gi,n.clone().add(1,"d").format(o)));return t.foldManager.save(p,m),p}catch(p){console.error(`Failed to create file: '${d}'`,p),new g.Notice("Unable to create new file.")}}function Xe(n,t){return t[T(n,"day")]??null}function et(){let{vault:n}=window.app,{folder:t}=O(),e=n.getAbstractFileByPath(g.normalizePath(t));if(!e)throw new ne("Failed to find daily notes folder");let a={};return g.Vault.recurseChildren(e,i=>{if(i instanceof g.TFile){let o=E(i,"day");if(o){let s=T(o,"day");a[s]=i}}}),a}var ie=class extends Error{};function tt(){let{moment:n}=window,t=n.localeData()._week.dow,e=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];for(;t;)e.push(e.shift()),t--;return e}function at(n){return tt().indexOf(n.toLowerCase())}async function Ae(n){let{vault:t}=window.app,{template:e,format:a,folder:i}=L(),[o,s]=await A(e),c=n.format(a),m=await R(i,c);try{let r=await t.create(m,o.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,p,P,D,M,v)=>{let w=window.moment(),f=n.clone().set({hour:w.get("hour"),minute:w.get("minute"),second:w.get("second")});return P&&f.add(parseInt(D,10),M),v?f.format(v.substring(1).trim()):f.format(a)}).replace(/{{\s*title\s*}}/gi,c).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*:(.*?)}}/gi,(d,p,P)=>{let D=at(p);return n.weekday(D).format(P.trim())}));return window.app.foldManager.save(r,s),r}catch(r){console.error(`Failed to create file: '${m}'`,r),new g.Notice("Unable to create new file.")}}function nt(n,t){return t[T(n,"week")]??null}function it(){let n={};if(!Se())return n;let{vault:t}=window.app,{folder:e}=L(),a=t.getAbstractFileByPath(g.normalizePath(e));if(!a)throw new ie("Failed to find weekly notes folder");return g.Vault.recurseChildren(a,i=>{if(i instanceof g.TFile){let o=E(i,"week");if(o){let s=T(o,"week");n[s]=i}}}),n}var oe=class extends Error{};async function Ee(n){let{vault:t}=window.app,{template:e,format:a,folder:i}=x(),[o,s]=await A(e),c=n.format(a),m=await R(i,c);try{let r=await t.create(m,o.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,p,P,D,M,v)=>{let w=window.moment(),f=n.clone().set({hour:w.get("hour"),minute:w.get("minute"),second:w.get("second")});return P&&f.add(parseInt(D,10),M),v?f.format(v.substring(1).trim()):f.format(a)}).replace(/{{\s*date\s*}}/gi,c).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi,c));return window.app.foldManager.save(r,s),r}catch(r){console.error(`Failed to create file: '${m}'`,r),new g.Notice("Unable to create new file.")}}function ot(n,t){return t[T(n,"month")]??null}function st(){let n={};if(!Fe())return n;let{vault:t}=window.app,{folder:e}=x(),a=t.getAbstractFileByPath(g.normalizePath(e));if(!a)throw new oe("Failed to find monthly notes folder");return g.Vault.recurseChildren(a,i=>{if(i instanceof g.TFile){let o=E(i,"month");if(o){let s=T(o,"month");n[s]=i}}}),n}var se=class extends Error{};async function rt(n){let{vault:t}=window.app,{template:e,format:a,folder:i}=H(),[o,s]=await A(e),c=n.format(a),m=await R(i,c);try{let r=await t.create(m,o.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,p,P,D,M,v)=>{let w=window.moment(),f=n.clone().set({hour:w.get("hour"),minute:w.get("minute"),second:w.get("second")});return P&&f.add(parseInt(D,10),M),v?f.format(v.substring(1).trim()):f.format(a)}).replace(/{{\s*date\s*}}/gi,c).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi,c));return window.app.foldManager.save(r,s),r}catch(r){console.error(`Failed to create file: '${m}'`,r),new g.Notice("Unable to create new file.")}}function lt(n,t){return t[T(n,"quarter")]??null}function ct(){let n={};if(!Oe())return n;let{vault:t}=window.app,{folder:e}=H(),a=t.getAbstractFileByPath(g.normalizePath(e));if(!a)throw new se("Failed to find quarterly notes folder");return g.Vault.recurseChildren(a,i=>{if(i instanceof g.TFile){let o=E(i,"quarter");if(o){let s=T(o,"quarter");n[s]=i}}}),n}var re=class extends Error{};async function dt(n){let{vault:t}=window.app,{template:e,format:a,folder:i}=C(),[o,s]=await A(e),c=n.format(a),m=await R(i,c);try{let r=await t.create(m,o.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,p,P,D,M,v)=>{let w=window.moment(),f=n.clone().set({hour:w.get("hour"),minute:w.get("minute"),second:w.get("second")});return P&&f.add(parseInt(D,10),M),v?f.format(v.substring(1).trim()):f.format(a)}).replace(/{{\s*date\s*}}/gi,c).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi,c));return window.app.foldManager.save(r,s),r}catch(r){console.error(`Failed to create file: '${m}'`,r),new g.Notice("Unable to create new file.")}}function pt(n,t){return t[T(n,"year")]??null}function ut(){let n={};if(!Le())return n;let{vault:t}=window.app,{folder:e}=C(),a=t.getAbstractFileByPath(g.normalizePath(e));if(!a)throw new re("Failed to find yearly notes folder");return g.Vault.recurseChildren(a,i=>{if(i instanceof g.TFile){let o=E(i,"year");if(o){let s=T(o,"year");n[s]=i}}}),n}function gt(){let{app:n}=window,t=n.internalPlugins.plugins["daily-notes"];if(t&&t.enabled)return!0;let e=n.plugins.getPlugin("periodic-notes");return e&&e.settings?.daily?.enabled}function Se(){let{app:n}=window;if(n.plugins.getPlugin("calendar"))return!0;let t=n.plugins.getPlugin("periodic-notes");return t&&t.settings?.weekly?.enabled}function Fe(){let{app:n}=window,t=n.plugins.getPlugin("periodic-notes");return t&&t.settings?.monthly?.enabled}function Oe(){let{app:n}=window,t=n.plugins.getPlugin("periodic-notes");return t&&t.settings?.quarterly?.enabled}function Le(){let{app:n}=window,t=n.plugins.getPlugin("periodic-notes");return t&&t.settings?.yearly?.enabled}function mt(n){let t={day:O,week:L,month:x,quarter:H,year:C}[n];return t()}function ht(n,t){return{day:Me,month:Ee,week:Ae}[n](t)}l.DEFAULT_DAILY_NOTE_FORMAT=te;l.DEFAULT_MONTHLY_NOTE_FORMAT=Ne;l.DEFAULT_QUARTERLY_NOTE_FORMAT=be;l.DEFAULT_WEEKLY_NOTE_FORMAT=ae;l.DEFAULT_YEARLY_NOTE_FORMAT=ke;l.appHasDailyNotesPluginLoaded=gt;l.appHasMonthlyNotesPluginLoaded=Fe;l.appHasQuarterlyNotesPluginLoaded=Oe;l.appHasWeeklyNotesPluginLoaded=Se;l.appHasYearlyNotesPluginLoaded=Le;l.createDailyNote=Me;l.createMonthlyNote=Ee;l.createPeriodicNote=ht;l.createQuarterlyNote=rt;l.createWeeklyNote=Ae;l.createYearlyNote=dt;l.getAllDailyNotes=et;l.getAllMonthlyNotes=st;l.getAllQuarterlyNotes=ct;l.getAllWeeklyNotes=it;l.getAllYearlyNotes=ut;l.getDailyNote=Xe;l.getDailyNoteSettings=O;l.getDateFromFile=E;l.getDateFromPath=Ze;l.getDateUID=T;l.getMonthlyNote=ot;l.getMonthlyNoteSettings=x;l.getPeriodicNoteSettings=mt;l.getQuarterlyNote=lt;l.getQuarterlyNoteSettings=H;l.getTemplateInfo=A;l.getWeeklyNote=nt;l.getWeeklyNoteSettings=L;l.getYearlyNote=pt;l.getYearlyNoteSettings=C});var vt={};qe(vt,{default:()=>J});module.exports=$e(vt);var b=require("obsidian");var N=require("obsidian");var He=require("obsidian");var he=require("obsidian");function k(n){return n?n.extension=="md"?n.path.slice(0,-3):n.path:""}function fe(n){return n.split("/").slice(-1)[0].contains(".")?n:`${n}.md`}function we(n){let t=n.vault.getFiles().filter(e=>["md","canvas"].contains(e.extension));if(t.length){let e=Math.floor(Math.random()*t.length);return k(t[e])}}function ye(n){return n.workspace.getActiveViewOfType(he.View)?.getViewType()=="empty"}function ee(n,t){return n.localeCompare(t,void 0,{sensitivity:"accent"})===0}function U(n){return new Promise(t=>setTimeout(t,n))}function ve(n,t){n.workspace.iterateRootLeaves(e=>{!e.view||!t.contains(e.view.getViewType())||e.detach()})}var u=ze(xe()),le={["Daily Note"]:{noun:"day",adjective:"daily",create:u.createDailyNote,get:u.getDailyNote,getAll:u.getAllDailyNotes},["Weekly Note"]:{noun:"week",adjective:"weekly",create:u.createWeeklyNote,get:u.getWeeklyNote,getAll:u.getAllWeeklyNotes},["Monthly Note"]:{noun:"month",adjective:"monthly",create:u.createMonthlyNote,get:u.getMonthlyNote,getAll:u.getAllMonthlyNotes},["Yearly Note"]:{noun:"year",adjective:"yearly",create:u.createYearlyNote,get:u.getYearlyNote,getAll:u.getAllYearlyNotes}},B=["Daily Note","Weekly Note","Monthly Note","Yearly Note"],Ce="Date-dependent file",ce="Date-dependent notes in Homepage have been removed. Set your Homepage as a Periodic or Daily Note instead.";async function Re(n,t){let e=t.communityPlugins["periodic-notes"],a=le[n],i=(0,He.moment)().startOf(a.noun),o;if(_e(e)){let s=a.getAll();Object.keys(s).length?o=a.get(i,s)||await a.create(i):o=await a.create(i)}else e.cache.initialize(),o=e.getPeriodicNote(a.noun,i)||await e.createPeriodicNote(a.noun,i);return k(o)}function Ie(n,t){if(n=="Daily Note"&&t.internalPlugins["daily-notes"]?.enabled)return!0;let e=t.communityPlugins["periodic-notes"];if(!e)return!1;if(_e(e)){let a=le[n].adjective;return e.settings[a]?.enabled}else{let a=le[n].noun;return e?.calendarSetManager?.getActiveSet()[a]?.enabled}}function K(n){let t=n.internalPlugins["daily-notes"];return t?.enabled&&t?.instance.options.autorun}function _e(n){return(n?.manifest.version||"0").startsWith("0")}var y=require("obsidian");var h=require("obsidian");var j=class extends h.AbstractInputSuggest{getSuggestions(e){let a=this.app.vault.getAllLoadedFiles(),i=[],o=e.toLowerCase();return a.forEach(s=>{s instanceof h.TFile&&["md","canvas"].contains(s.extension)&&s.path.toLowerCase().contains(o)&&i.push(s)}),i}renderSuggestion(e,a){e.extension=="md"?a.setText(k(e)):(a.setText(e.path.slice(0,-7)),a.insertAdjacentHTML("beforeend",'<div class="nav-file-tag" style="display:inline-block;vertical-align:middle">canvas</div>'))}selectSuggestion(e){this.textInputEl.value=k(e),this.textInputEl.trigger("input"),this.close()}},q=class extends h.AbstractInputSuggest{getSuggestions(e){let a=Object.keys(this.app.internalPlugins.plugins.workspaces?.instance.workspaces),i=e.toLowerCase();return a.filter(o=>o.toLowerCase().contains(i))}renderSuggestion(e,a){a.setText(e)}selectSuggestion(e){this.textInputEl.value=e,this.textInputEl.trigger("input"),this.close()}},z=class{constructor(t){this.app=t.plugin.app,this.homepage=t.plugin.homepage,this.tab=t,this.container=t.containerEl.createDiv({cls:"nv-command-box"}),this.dropzone=document.createElement("div"),this.dropzone.className="nv-command-pill nv-dropzone",this.dropzone.addEventListener("dragenter",e=>e.preventDefault()),this.dropzone.addEventListener("dragover",e=>e.preventDefault()),this.dropzone.addEventListener("drop",()=>this.terminateDrag()),this.update()}update(){this.container.innerHTML="",this.activeDrag=null,this.activeCommand=null;for(let t of this.homepage.data.commands){let e=this.app.commands.findCommand(t.id),a=this.container.createDiv({cls:"nv-command-pill",text:e?.name??t.id,attr:{draggable:!0}});a.addEventListener("dragstart",o=>{o.dataTransfer.effectAllowed="move",this.activeCommand=this.homepage.data.commands.splice(this.indexOf(a),1)[0],this.activeDrag=a,this.dropzone.style.width=`${a.clientWidth}px`,this.dropzone.style.height=`${a.clientHeight}px`}),a.addEventListener("dragover",o=>this.moveDropzone(a,o)),a.addEventListener("drop",o=>o.preventDefault()),a.addEventListener("dragend",()=>this.terminateDrag());let i=new h.ButtonComponent(a).setIcon("route").setClass("clickable-icon").setClass("nv-command-period").onClick(o=>this.showMenu(t,o));t.period!="Both"&&(i.setClass("nv-command-selected"),i.setIcon(""),i.buttonEl.createSpan({text:t.period})),new h.ButtonComponent(a).setIcon("trash-2").setClass("clickable-icon").setClass("nv-command-delete").onClick(()=>this.delete(t)),e||(a.classList.add("nv-command-invalid"),a.prepend((0,h.getIcon)("ban")),(0,h.setTooltip)(a,"This command can't be found, so it won't be executed. It may belong to a disabled plugin.",{delay:.001}))}new h.ButtonComponent(this.container).setClass("nv-command-add-button").setButtonText("Add...").onClick(()=>{new de(this.tab).open()})}delete(t){this.homepage.data.commands.remove(t),this.homepage.save(),this.update()}showMenu(t,e){let a=new h.Menu;for(let i of Object.values($))a.addItem(o=>{o.setTitle(i),o.setChecked(t.period==i),o.onClick(()=>{t.period=i,this.homepage.save(),this.update()})});a.showAtMouseEvent(e)}indexOf(t){return Array.from(this.container.children).indexOf(t)}moveDropzone(t,e){if(!this.activeDrag)return;this.activeDrag.hidden=!0;let a=t.getBoundingClientRect();e.x<a.left+a.width/2?this.container.insertBefore(this.dropzone,t):this.container.insertAfter(this.dropzone,t),e.preventDefault()}terminateDrag(){this.activeCommand&&(this.homepage.data.commands.splice(this.indexOf(this.dropzone),0,this.activeCommand),this.homepage.save(),this.update())}},de=class extends h.FuzzySuggestModal{constructor(e){super(e.plugin.app);this.homepage=e.plugin.homepage,this.tab=e}getItems(){return Object.values(this.app.commands.commands)}getItemText(e){return e.name}onChooseItem(e){if(e.id==="homepage:open-homepage"){new h.Notice("Really?");return}else this.homepage.data.commands||(this.homepage.data.commands=[]);this.homepage.data.commands.push({id:e.id,period:"Both"}),this.homepage.save(),this.tab.commandBox.update()}};var pe={version:4,homepages:{},separateMobile:!1},S={value:"Home",kind:"File",openOnStartup:!0,openMode:"Replace all open notes",manualOpenMode:"Keep open notes",view:"Default view",revertView:!0,openWhenEmpty:!1,refreshDataview:!1,autoCreate:!1,autoScroll:!1,pin:!1,commands:[],alwaysApply:!1,hideReleaseNotes:!1},ft={["File"]:"Enter a note or canvas to use.",["Workspace"]:"Enter an Obsidian workspace to use.",["Graph view"]:"Your graph view will be used.",["Nothing"]:"Nothing will occur by default. Any commands added will still take effect.",["Random file"]:"A random note or canvas from your Obsidian folder will be selected.",["Daily Note"]:"Your Daily Note or Periodic Daily Note will be used.",["Weekly Note"]:"Your Periodic Weekly Note will be used.",["Monthly Note"]:"Your Periodic Monthly Note will be used.",["Yearly Note"]:"Your Periodic Yearly Note will be used."},G=class extends y.PluginSettingTab{constructor(e,a){super(e,a);this.plugin=a,this.settings=a.settings,this.plugin.addCommand({id:"copy-debug-info",name:"Copy debug info",callback:async()=>await this.copyDebugInfo()})}sanitiseNote(e){return e===null||e.match(/^\s*$/)!==null?null:(0,y.normalizePath)(e)}display(){let e=this.plugin.homepage.data.kind=="Workspace",a=this.plugin.homepage.data.kind,i=K(this.plugin),o=!1,s=e?q:j;this.containerEl.empty(),this.elements={};let c=new y.Setting(this.containerEl).setName("Homepage").addDropdown(async d=>{for(let p of Object.values(I)){if(!this.plugin.hasRequiredPlugin(p))if(p==this.plugin.homepage.data.kind)o=!0;else{d.selectEl.createEl("option",{text:p,attr:{disabled:!0}});continue}d.addOption(p,p)}d.setValue(this.plugin.homepage.data.kind),d.onChange(async p=>{this.plugin.homepage.data.kind=p,await this.plugin.homepage.save(),this.display()})});c.settingEl.id="nv-main-setting";let m=c.settingEl.createEl("article",{text:ft[a],attr:{id:"nv-desc"}});o&&m.createDiv({text:"The plugin required for this homepage type isn't available.",cls:"mod-warning"}),ge.includes(a)?c.addText(d=>{d.setDisabled(!0)}):c.addText(d=>{new s(this.app,d.inputEl),d.setPlaceholder(S.value),d.setValue(S.value==this.plugin.homepage.data.value?"":this.plugin.homepage.data.value),d.onChange(async p=>{this.plugin.homepage.data.value=this.sanitiseNote(p)||S.value,await this.plugin.homepage.save()})}),this.addToggle("Open on startup","When launching Obsidian, open the homepage.","openOnStartup",d=>this.display()),i&&(this.elements.openOnStartup.descEl.createDiv({text:`This setting has been disabled, as it isn't compatible with Daily Notes' "Open daily note on startup" functionality. To use it, disable the Daily Notes setting.`,attr:{class:"mod-warning"}}),this.disableSetting("openOnStartup")),this.addToggle("Open when empty","When there are no tabs open, open the homepage.","openWhenEmpty"),this.addToggle("Use when opening normally","Use homepage settings when opening it normally, such as from a link or the file browser.","alwaysApply");let r=new y.Setting(this.containerEl).setName("Separate mobile homepage").setDesc("For mobile devices, store the homepage and its settings separately.").addToggle(d=>d.setValue(this.plugin.settings.separateMobile).onChange(async p=>{this.plugin.settings.separateMobile=p,this.plugin.homepage=this.plugin.getHomepage(),await this.plugin.saveSettings(),this.display()}));if(this.plugin.settings.separateMobile){let d=y.Platform.isMobile?"desktop":"mobile",p=document.createElement("div");r.setClass("nv-mobile-setting"),p.className="mod-warning nv-mobile-info",p.innerHTML=`<b>Mobile settings are stored separately.</b> Therefore, changes to other settings will not affect
${d} devices. To edit ${d} settings, use a ${d} device.`,r.settingEl.append(p)}this.addHeading("Commands","commandsHeading"),this.containerEl.createDiv({cls:"nv-command-desc setting-item-description",text:"Select commands that will be executed when opening the homepage."}),this.commandBox=new z(this),this.addHeading("Vault environment","vaultHeading"),this.addDropdown("Opening method","Determine how extant tabs and views are affected on startup.","openMode",Q),this.addDropdown("Manual opening method","Determine how extant tabs and views are affected when opening with commands or the ribbon button.","manualOpenMode",Q),this.addToggle("Pin","Pin the homepage when opening.","pin"),this.addToggle("Hide release notes","Never display release notes when Obsidian updates.","hideReleaseNotes"),this.addToggle("Auto-create","When the homepage doesn't exist, create a note with its name.","autoCreate"),this.elements.autoCreate.descEl.createDiv({text:"If this vault is synced using unofficial services, this may lead to content being overwritten.",cls:"mod-warning"}),this.addHeading("Opened view","paneHeading"),this.addDropdown("Homepage view","Choose what view to open the homepage in.","view",ue),this.addToggle("Revert view on close","When navigating away from the homepage, restore the default view.","revertView"),this.addToggle("Auto-scroll","When opening the homepage, scroll to the bottom and focus on the last line.","autoScroll"),"dataview"in this.plugin.communityPlugins&&(this.addToggle("Refresh Dataview","Always attempt to reload Dataview views when opening the homepage.","refreshDataview"),this.elements.refreshDataview.descEl.createDiv({text:"Requires Dataview auto-refresh to be enabled.",attr:{class:"mod-warning"}})),y.Platform.isMobile||new y.ButtonComponent(this.containerEl).setButtonText("Copy debug info").setClass("nv-debug-button").onClick(async()=>await this.copyDebugInfo()),(e||a==="Nothing")&&this.disableSettings("openWhenEmpty","alwaysApply","vaultHeading","openMode","manualOpenMode","autoCreate","pin"),(e||["Nothing","Graph view"].includes(a))&&this.disableSettings("paneHeading","view","revertView","autoScroll","refreshDataview"),(!this.plugin.homepage.data.openOnStartup||i)&&this.disableSetting("openMode"),B.includes(this.plugin.homepage.data.kind)&&this.disableSetting("autoCreate")}disableSetting(e){this.elements[e]?.settingEl.setAttribute("nv-greyed","")}disableSettings(...e){e.forEach(a=>this.disableSetting(a))}addHeading(e,a){let i=new y.Setting(this.containerEl).setHeading().setName(e);this.elements[a]=i}addDropdown(e,a,i,o,s){let c=new y.Setting(this.containerEl).setName(e).setDesc(a).addDropdown(async m=>{for(let r of Object.values(o))m.addOption(r,r);m.setValue(this.plugin.homepage.data[i]),m.onChange(async r=>{this.plugin.homepage.data[i]=r,await this.plugin.homepage.save(),s&&s(r)})});return this.elements[i]=c,c}addToggle(e,a,i,o){let s=new y.Setting(this.containerEl).setName(e).setDesc(a).addToggle(c=>c.setValue(this.plugin.homepage.data[i]).onChange(async m=>{this.plugin.homepage.data[i]=m,await this.plugin.homepage.save(),o&&o(m)}));return this.elements[i]=s,s}async copyDebugInfo(){let e=this.app.vault.config,a={...this.settings,_defaultViewMode:e.defaultViewMode||"default",_livePreview:e.livePreview!==void 0?e.livePreview:"default",_focusNewTab:e.focusNewTab!==void 0?e.focusNewTab:"default",_plugins:Object.keys(this.plugin.communityPlugins),_internalPlugins:Object.values(this.plugin.internalPlugins).flatMap(i=>i.enabled?[i.instance.id]:[]),_obsidianVersion:window.electron.ipcRenderer.sendSync("version")};await navigator.clipboard.writeText(JSON.stringify(a)),new y.Notice("Copied homepage debug information to clipboard")}};var Ve=["markdown","canvas","kanban"],wt=[...Ve,"audio","graph","image","pdf","video"],V="Main Homepage",W="Mobile Homepage",Q=(a=>(a.ReplaceAll="Replace all open notes",a.ReplaceLast="Replace last note",a.Retain="Keep open notes",a))(Q||{}),ue=(i=>(i.Default="Default view",i.Reading="Reading view",i.Source="Editing view (Source)",i.LivePreview="Editing view (Live Preview)",i))(ue||{}),I=(r=>(r.File="File",r.Workspace="Workspace",r.Random="Random file",r.Graph="Graph view",r.None="Nothing",r.DailyNote="Daily Note",r.WeeklyNote="Weekly Note",r.MonthlyNote="Monthly Note",r.YearlyNote="Yearly Note",r))(I||{}),$=(a=>(a.Both="Both",a.Startup="Startup only",a.Manual="Manual only",a))($||{}),ge=["Random file","Graph view","Nothing",...B],_=class{constructor(t,e){this.lastView=void 0;this.openedViews=new WeakMap;this.name=t,this.plugin=e,this.app=e.app;let a=this.plugin.settings.homepages[t];a?this.data=Object.assign(S,a):(this.plugin.settings.homepages[t]={...S},this.data=this.plugin.settings.homepages[t])}async open(t=!1){if(!this.plugin.hasRequiredPlugin(this.data.kind)){new N.Notice("Homepage cannot be opened due to plugin unavailablity.");return}if(this.data.kind==="Workspace")await this.launchWorkspace();else if(this.data.kind!=="Nothing"){let a=this.plugin.loaded?this.data.manualOpenMode:this.data.openMode;t&&(a="Keep open notes"),await this.launchLeaf(a)}if(!this.data.commands)return;let e=this.plugin.loaded?"Startup only":"Manual only";for(let{id:a,period:i}of this.data.commands)i!==e&&this.app.commands.executeCommandById(a)}async launchWorkspace(){let t=this.plugin.internalPlugins.workspaces?.instance;if(!(this.data.value in t.workspaces)){new N.Notice(`Cannot find the workspace "${this.data.value}" to use as the homepage.`);return}t.loadWorkspace(this.data.value),await U(100)}async launchLeaf(t){let e;if(this.computedValue=await this.computeValue(),this.plugin.executing=!0,!(K(this.plugin)&&!this.plugin.loaded)){if(t!=="Replace all open notes"){let a=this.getOpened();if(a.length>0){this.app.workspace.setActiveLeaf(a[0]),await this.configure(a[0]);return}else t=="Keep open notes"&&ye(this.app)&&(t="Replace last note")}t!=="Keep open notes"&&this.app.workspace.getActiveViewOfType(N.View)?.leaf.setPinned(!1),t==="Replace all open notes"&&(this.app.workspace?.floatingSplit?.children&&(await U(0),this.app.workspace.floatingSplit.children.forEach(a=>a.win.close())),ve(this.app,wt),await U(0),this.app.workspace.iterateRootLeaves(a=>this.app.workspace.setActiveLeaf(a))),this.data.kind==="Graph view"?e=await this.launchGraph(t):e=await this.launchNote(t),e&&await this.configure(e)}}async launchGraph(t){if(t==="Keep open notes"){let e=this.app.workspace.getLeaf("tab");this.app.workspace.setActiveLeaf(e)}return this.app.commands.executeCommandById("graph:open"),this.app.workspace.getActiveViewOfType(N.View)?.leaf}async launchNote(t){let e=this.app.metadataCache.getFirstLinkpathDest(this.computedValue,"/");if(!e){if(!this.data.autoCreate){new N.Notice(`Homepage "${this.computedValue}" does not exist.`);return}e=await this.app.vault.create(fe(this.computedValue),"")}let a=await this.app.vault.cachedRead(e),i=this.app.workspace.getLeaf(t=="Keep open notes");return await i.openFile(e),this.app.workspace.setActiveLeaf(i),a!==await this.app.vault.read(e)&&await this.app.vault.modify(e,a),i}async configure(t){this.plugin.executing=!1;let e=t.view;if(!(e instanceof N.MarkdownView)){this.data.pin&&e.leaf.setPinned(!0);return}let a=e.getState();if(this.data.revertView&&(this.lastView=new WeakRef(e)),this.data.autoScroll){let i=e.editor.lineCount();a.mode=="preview"?e.previewMode.applyScroll(i-4):(e.editor.setCursor(i),e.editor.focus())}if(this.data.pin&&e.leaf.setPinned(!0),this.data.view!="Default view"){switch(this.data.view){case"Editing view (Live Preview)":case"Editing view (Source)":a.mode="source",a.source=this.data.view!="Editing view (Live Preview)";break;case"Reading view":a.mode="preview";break}await e.leaf.setViewState({type:"markdown",state:a}),this.plugin.loaded&&this.data.refreshDataview&&this.plugin.communityPlugins.dataview?.index.touch()}}getOpened(){return this.data.kind=="Graph view"?this.app.workspace.getLeavesOfType("graph"):Ve.flatMap(e=>this.app.workspace.getLeavesOfType(e)).filter(e=>ee(k(e.view.file),this.computedValue))}async computeValue(){let t=this.data.value;switch(this.data.kind){case"Random file":let e=we(this.app);e&&(t=e);break;case"Daily Note":case"Weekly Note":case"Monthly Note":case"Yearly Note":t=await Re(this.data.kind,this.plugin);break}return t}async save(){this.plugin.settings.homepages[this.name]=this.data,await this.plugin.saveSettings()}async setToActiveFile(){this.data.value=k(this.app.workspace.getActiveFile()),await this.save(),new N.Notice(`The homepage has been changed to "${this.data.value}".`)}canSetToFile(){return this.app.workspace.getActiveFile()!==null&&!ge.includes(this.data.kind)}async revertView(){if(this.lastView==null||this.data.view=="Default view")return;let t=this.lastView.deref();if(!t||ee(k(t.file),this.computedValue))return;let e=t.getState(),a=this.app.vault.config,i=a.defaultViewMode||"source",o=a.livePreview!==void 0?!a.livePreview:!1;t.leaf.getViewState().type=="markdown"&&(i!=e.mode||o!=e.source)&&(e.mode=i,e.source=o,await t.leaf.setViewState({type:"markdown",state:e,active:!0})),this.lastView=void 0}async openWhenEmpty(){if(!this.plugin.loaded||this.plugin.executing)return;let t=this.app.workspace.getActiveViewOfType(N.View)?.leaf;t?.getViewState().type!=="empty"||t.parentSplit.children.length!=1||await this.open(!0)}async apply(){let t=this.app.workspace.getActiveViewOfType(N.FileView);if(!t)return;let e=k(t.file);this.openedViews.get(t)!==e&&(this.openedViews.set(t,e),e===await this.computeValue()&&this.plugin.loaded&&!this.plugin.executing&&await this.configure(t.leaf))}};var yt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:1.5"><path d="M10.025 21H6v-7H3v-1.5L12 3l9 9.5V14h-3v7h-4v-7h-3.975v7Z" style="fill:none;stroke:currentColor;stroke-width:2px"/></svg>',J=class extends b.Plugin{constructor(){super(...arguments);this.newRelease=!1;this.loaded=!1;this.executing=!1;this.onLayoutChange=async()=>{this.homepage.data.revertView&&await this.homepage.revertView(),this.homepage.data.openWhenEmpty&&await this.homepage.openWhenEmpty(),this.homepage.data.alwaysApply&&await this.homepage.apply()}}async onload(){let e=document.body.querySelector(".progress-bar");this.patchReleaseNotes(),this.showInterstitial(e),this.settings=await this.loadSettings(),this.internalPlugins=this.app.internalPlugins.plugins,this.communityPlugins=this.app.plugins.plugins,this.homepage=this.getHomepage(),this.app.workspace.onLayoutReady(async()=>{let a=this.homepage.data.openOnStartup&&e&&!await this.hasUrlParams();this.patchNewTabPage(),a&&await this.homepage.open(),this.loaded=!0,this.unpatchReleaseNotes(),this.interstitial?.detach()}),(0,b.addIcon)("homepage",yt),this.addRibbonIcon("homepage","Open homepage",a=>this.homepage.open(a.button==1||a.button==2||b.Keymap.isModifier(a,"Mod"))).setAttribute("id","nv-homepage-icon"),this.registerEvent(this.app.workspace.on("layout-change",this.onLayoutChange)),this.addSettingTab(new G(this.app,this)),this.addCommand({id:"open-homepage",name:"Open homepage",callback:()=>this.homepage.open()}),this.addCommand({id:"set-to-active-file",name:"Set to active file",checkCallback:a=>{if(a)return this.homepage.canSetToFile();this.homepage.setToActiveFile()}}),console.log(`Homepage: ${this.homepage.data.value} (method: ${this.homepage.data.openMode}, view: ${this.homepage.data.view}, kind: ${this.homepage.data.kind})`)}async onunload(){this.app.workspace.off("layout-change",this.onLayoutChange),this.unpatchNewTabPage()}getHomepage(){return this.settings.separateMobile&&b.Platform.isMobile?(W in this.settings.homepages||(this.settings.homepages[W]={...this.settings.homepages?.[V]},this.settings.homepages[W].commands=[...this.settings.homepages?.[V]?.commands]),new _(W,this)):new _(V,this)}async loadSettings(){let e=await this.loadData();return e?.version!==4?e?this.upgradeSettings(e):Object.assign({},pe):e}async saveSettings(){await this.saveData(this.settings)}showInterstitial(e){e&&(this.interstitial=createDiv({cls:"progress-bar nv-homepage-interstitial"}),document.body.insertBefore(this.interstitial,e))}async hasUrlParams(){let e,a;if(b.Platform.isMobile){let i=await window.Capacitor.Plugins.App.getLaunchUrl();if(!i)return!1;let o=new URL(i.url);a=Array.from(o.searchParams.keys()),e=o.hostname}else if(window.OBS_ACT)a=Object.keys(window.OBS_ACT),e=window.OBS_ACT.action;else return!1;return["open","advanced-uri"].includes(e)&&["file","filepath","workspace"].some(i=>a.includes(i))}hasRequiredPlugin(e){switch(e){case"Workspace":return this.internalPlugins.workspaces?.enabled;case"Graph view":return this.internalPlugins.graph?.enabled;case"Daily Note":case"Weekly Note":case"Monthly Note":case"Yearly Note":return Ie(e,this);default:return!0}}patchNewTabPage(){let e=this.communityPlugins["new-tab-default-page"];e&&(e.nvOrig_checkForNewTab=e.checkForNewTab,e.checkForNewTab=async a=>{if(!(this&&this.executing))return await e.nvOrig_checkForNewTab(a)})}unpatchNewTabPage(){let e=this.communityPlugins["new-tab-default-page"];e&&(e.checkForNewTab=e._checkForNewTab)}patchReleaseNotes(){this.app.nvOrig_showReleaseNotes=this.app.showReleaseNotes,this.app.showReleaseNotes=()=>this.newRelease=!0}unpatchReleaseNotes(){this.newRelease&&!this.homepage.data.hideReleaseNotes&&this.app.nvOrig_showReleaseNotes(),this.app.showReleaseNotes=this.app.nvOrig_showReleaseNotes}upgradeSettings(e){if(e.version==3){let i=e,o=!1;for(let s of Object.values(i.homepages))s.commands=s.commands.map(c=>({id:c,period:"Both"})),s.kind==Ce&&(o=!0,s.kind="Daily Note");return o&&new b.Notice(ce),i.version=4,this.saveData(i),i}let a=Object.assign({},pe);return e.workspaceEnabled?(e.value=e.workspace,e.kind="Workspace"):e.momentFormat?(e.kind="Daily Note",new b.Notice(ce)):(e.value=e.defaultNote,e.kind="File"),e.commands=[],delete e.workspace,delete e.momentFormat,delete e.defaultNote,delete e.useMoment,delete e.workspaceEnabled,a.homepages[V]=e,this.saveData(a),a}};