4 lines
38 KiB
JavaScript
4 lines
38 KiB
JavaScript
"use strict";var ze=Object.create;var j=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Je=Object.prototype.hasOwnProperty;var Qe=(a,t)=>()=>(t||a((t={exports:{}}).exports,t),t.exports),Ze=(a,t)=>{for(var e in t)j(a,e,{get:t[e],enumerable:!0})},ve=(a,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ge(t))!Je.call(a,i)&&i!==e&&j(a,i,{get:()=>t[i],enumerable:!(n=qe(t,i))||n.enumerable});return a};var Xe=(a,t,e)=>(e=a!=null?ze($e(a)):{},ve(t||!a||!a.__esModule?j(e,"default",{value:a,enumerable:!0}):e,a)),et=a=>ve(j({},"__esModule",{value:!0}),a);var _e=Qe(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});var g=require("obsidian"),te="YYYY-MM-DD",ne="gggg-[W]ww",De="YYYY-MM",Ee="YYYY-[Q]Q",Se="YYYY";function x(a){let t=window.app.plugins.getPlugin("periodic-notes");return t&&t.settings?.[a]?.enabled}function O(){try{let{internalPlugins:a,plugins:t}=window.app;if(x("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:n,template:i}=a.getPluginById("daily-notes")?.instance?.options||{};return{format:n||te,folder:e?.trim()||"",template:i?.trim()||""}}catch(a){console.info("No custom daily note settings found!",a)}}function C(){try{let a=window.app.plugins,t=a.getPlugin("calendar")?.options,e=a.getPlugin("periodic-notes")?.settings?.weekly;if(x("weekly"))return{format:e.format||ne,folder:e.folder?.trim()||"",template:e.template?.trim()||""};let n=t||{};return{format:n.weeklyNoteFormat||ne,folder:n.weeklyNoteFolder?.trim()||"",template:n.weeklyNoteTemplate?.trim()||""}}catch(a){console.info("No custom weekly note settings found!",a)}}function H(){let a=window.app.plugins;try{let t=x("monthly")&&a.getPlugin("periodic-notes")?.settings?.monthly||{};return{format:t.format||De,folder:t.folder?.trim()||"",template:t.template?.trim()||""}}catch(t){console.info("No custom monthly note settings found!",t)}}function R(){let a=window.app.plugins;try{let t=x("quarterly")&&a.getPlugin("periodic-notes")?.settings?.quarterly||{};return{format:t.format||Ee,folder:t.folder?.trim()||"",template:t.template?.trim()||""}}catch(t){console.info("No custom quarterly note settings found!",t)}}function I(){let a=window.app.plugins;try{let t=x("yearly")&&a.getPlugin("periodic-notes")?.settings?.yearly||{};return{format:t.format||Se,folder:t.folder?.trim()||"",template:t.template?.trim()||""}}catch(t){console.info("No custom yearly note settings found!",t)}}function Fe(...a){let t=[];for(let n=0,i=a.length;n<i;n++)t=t.concat(a[n].split("/"));let e=[];for(let n=0,i=t.length;n<i;n++){let o=t[n];!o||o==="."||e.push(o)}return t[0]===""&&e.unshift(""),e.join("/")}function nt(a){let t=a.substring(a.lastIndexOf("/")+1);return t.lastIndexOf(".")!=-1&&(t=t.substring(0,t.lastIndexOf("."))),t}async function at(a){let t=a.replace(/\\/g,"/").split("/");if(t.pop(),t.length){let e=Fe(...t);window.app.vault.getAbstractFileByPath(e)||await window.app.vault.createFolder(e)}}async function _(a,t){t.endsWith(".md")||(t+=".md");let e=g.normalizePath(Fe(a,t));return await at(e),e}async function F(a){let{metadataCache:t,vault:e}=window.app,n=g.normalizePath(a);if(n==="/")return Promise.resolve(["",null]);try{let i=t.getFirstLinkpathDest(n,""),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 '${n}'`,i),new g.Notice("Failed to read the daily note template"),["",null]}}function k(a,t="day"){let e=a.clone().startOf(t).format();return`${t}-${e}`}function Ae(a){return a.replace(/\[[^\]]*\]/g,"")}function it(a,t){if(t==="week"){let e=Ae(a);return/w{1,2}/i.test(e)&&(/M{1,4}/.test(e)||/D{1,4}/.test(e))}return!1}function A(a,t){return Me(a.basename,t)}function ot(a,t){return Me(nt(a),t)}function Me(a,t){let n={day:O,week:C,month:H,quarter:R,year:I}[t]().format.split("/").pop(),i=window.moment(a,n,!0);if(!i.isValid())return null;if(it(n,t)&&t==="week"){let o=Ae(n);if(/w{1,2}/i.test(o))return window.moment(a,n.replace(/M{1,4}/g,"").replace(/D{1,4}/g,""),!1)}return i}var ae=class extends Error{};async function Le(a){let t=window.app,{vault:e}=t,n=window.moment,{template:i,format:o,folder:s}=O(),[c,u]=await F(i),r=a.format(o),d=await _(s,r);try{let m=await e.create(d,c.replace(/{{\s*date\s*}}/gi,r).replace(/{{\s*time\s*}}/gi,n().format("HH:mm")).replace(/{{\s*title\s*}}/gi,r).replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(P,T,E,b,w,f)=>{let Q=n(),Z=a.clone().set({hour:Q.get("hour"),minute:Q.get("minute"),second:Q.get("second")});return E&&Z.add(parseInt(b,10),w),f?Z.format(f.substring(1).trim()):Z.format(o)}).replace(/{{\s*yesterday\s*}}/gi,a.clone().subtract(1,"day").format(o)).replace(/{{\s*tomorrow\s*}}/gi,a.clone().add(1,"d").format(o)));return t.foldManager.save(m,u),m}catch(m){console.error(`Failed to create file: '${d}'`,m),new g.Notice("Unable to create new file.")}}function st(a,t){return t[k(a,"day")]??null}function rt(){let{vault:a}=window.app,{folder:t}=O(),e=a.getAbstractFileByPath(g.normalizePath(t));if(!e)throw new ae("Failed to find daily notes folder");let n={};return g.Vault.recurseChildren(e,i=>{if(i instanceof g.TFile){let o=A(i,"day");if(o){let s=k(o,"day");n[s]=i}}}),n}var ie=class extends Error{};function lt(){let{moment:a}=window,t=a.localeData()._week.dow,e=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];for(;t;)e.push(e.shift()),t--;return e}function ct(a){return lt().indexOf(a.toLowerCase())}async function xe(a){let{vault:t}=window.app,{template:e,format:n,folder:i}=C(),[o,s]=await F(e),c=a.format(n),u=await _(i,c);try{let r=await t.create(u,o.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,m,P,T,E,b)=>{let w=window.moment(),f=a.clone().set({hour:w.get("hour"),minute:w.get("minute"),second:w.get("second")});return P&&f.add(parseInt(T,10),E),b?f.format(b.substring(1).trim()):f.format(n)}).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,m,P)=>{let T=ct(m);return a.weekday(T).format(P.trim())}));return window.app.foldManager.save(r,s),r}catch(r){console.error(`Failed to create file: '${u}'`,r),new g.Notice("Unable to create new file.")}}function dt(a,t){return t[k(a,"week")]??null}function pt(){let a={};if(!Ce())return a;let{vault:t}=window.app,{folder:e}=C(),n=t.getAbstractFileByPath(g.normalizePath(e));if(!n)throw new ie("Failed to find weekly notes folder");return g.Vault.recurseChildren(n,i=>{if(i instanceof g.TFile){let o=A(i,"week");if(o){let s=k(o,"week");a[s]=i}}}),a}var oe=class extends Error{};async function Oe(a){let{vault:t}=window.app,{template:e,format:n,folder:i}=H(),[o,s]=await F(e),c=a.format(n),u=await _(i,c);try{let r=await t.create(u,o.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,m,P,T,E,b)=>{let w=window.moment(),f=a.clone().set({hour:w.get("hour"),minute:w.get("minute"),second:w.get("second")});return P&&f.add(parseInt(T,10),E),b?f.format(b.substring(1).trim()):f.format(n)}).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: '${u}'`,r),new g.Notice("Unable to create new file.")}}function ut(a,t){return t[k(a,"month")]??null}function gt(){let a={};if(!He())return a;let{vault:t}=window.app,{folder:e}=H(),n=t.getAbstractFileByPath(g.normalizePath(e));if(!n)throw new oe("Failed to find monthly notes folder");return g.Vault.recurseChildren(n,i=>{if(i instanceof g.TFile){let o=A(i,"month");if(o){let s=k(o,"month");a[s]=i}}}),a}var se=class extends Error{};async function mt(a){let{vault:t}=window.app,{template:e,format:n,folder:i}=R(),[o,s]=await F(e),c=a.format(n),u=await _(i,c);try{let r=await t.create(u,o.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,m,P,T,E,b)=>{let w=window.moment(),f=a.clone().set({hour:w.get("hour"),minute:w.get("minute"),second:w.get("second")});return P&&f.add(parseInt(T,10),E),b?f.format(b.substring(1).trim()):f.format(n)}).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: '${u}'`,r),new g.Notice("Unable to create new file.")}}function ht(a,t){return t[k(a,"quarter")]??null}function ft(){let a={};if(!Re())return a;let{vault:t}=window.app,{folder:e}=R(),n=t.getAbstractFileByPath(g.normalizePath(e));if(!n)throw new se("Failed to find quarterly notes folder");return g.Vault.recurseChildren(n,i=>{if(i instanceof g.TFile){let o=A(i,"quarter");if(o){let s=k(o,"quarter");a[s]=i}}}),a}var re=class extends Error{};async function wt(a){let{vault:t}=window.app,{template:e,format:n,folder:i}=I(),[o,s]=await F(e),c=a.format(n),u=await _(i,c);try{let r=await t.create(u,o.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,m,P,T,E,b)=>{let w=window.moment(),f=a.clone().set({hour:w.get("hour"),minute:w.get("minute"),second:w.get("second")});return P&&f.add(parseInt(T,10),E),b?f.format(b.substring(1).trim()):f.format(n)}).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: '${u}'`,r),new g.Notice("Unable to create new file.")}}function yt(a,t){return t[k(a,"year")]??null}function vt(){let a={};if(!Ie())return a;let{vault:t}=window.app,{folder:e}=I(),n=t.getAbstractFileByPath(g.normalizePath(e));if(!n)throw new re("Failed to find yearly notes folder");return g.Vault.recurseChildren(n,i=>{if(i instanceof g.TFile){let o=A(i,"year");if(o){let s=k(o,"year");a[s]=i}}}),a}function bt(){let{app:a}=window,t=a.internalPlugins.plugins["daily-notes"];if(t&&t.enabled)return!0;let e=a.plugins.getPlugin("periodic-notes");return e&&e.settings?.daily?.enabled}function Ce(){let{app:a}=window;if(a.plugins.getPlugin("calendar"))return!0;let t=a.plugins.getPlugin("periodic-notes");return t&&t.settings?.weekly?.enabled}function He(){let{app:a}=window,t=a.plugins.getPlugin("periodic-notes");return t&&t.settings?.monthly?.enabled}function Re(){let{app:a}=window,t=a.plugins.getPlugin("periodic-notes");return t&&t.settings?.quarterly?.enabled}function Ie(){let{app:a}=window,t=a.plugins.getPlugin("periodic-notes");return t&&t.settings?.yearly?.enabled}function Nt(a){let t={day:O,week:C,month:H,quarter:R,year:I}[a];return t()}function kt(a,t){return{day:Le,month:Oe,week:xe}[a](t)}l.DEFAULT_DAILY_NOTE_FORMAT=te;l.DEFAULT_MONTHLY_NOTE_FORMAT=De;l.DEFAULT_QUARTERLY_NOTE_FORMAT=Ee;l.DEFAULT_WEEKLY_NOTE_FORMAT=ne;l.DEFAULT_YEARLY_NOTE_FORMAT=Se;l.appHasDailyNotesPluginLoaded=bt;l.appHasMonthlyNotesPluginLoaded=He;l.appHasQuarterlyNotesPluginLoaded=Re;l.appHasWeeklyNotesPluginLoaded=Ce;l.appHasYearlyNotesPluginLoaded=Ie;l.createDailyNote=Le;l.createMonthlyNote=Oe;l.createPeriodicNote=kt;l.createQuarterlyNote=mt;l.createWeeklyNote=xe;l.createYearlyNote=wt;l.getAllDailyNotes=rt;l.getAllMonthlyNotes=gt;l.getAllQuarterlyNotes=ft;l.getAllWeeklyNotes=pt;l.getAllYearlyNotes=vt;l.getDailyNote=st;l.getDailyNoteSettings=O;l.getDateFromFile=A;l.getDateFromPath=ot;l.getDateUID=k;l.getMonthlyNote=ut;l.getMonthlyNoteSettings=H;l.getPeriodicNoteSettings=Nt;l.getQuarterlyNote=ht;l.getQuarterlyNoteSettings=R;l.getTemplateInfo=F;l.getWeeklyNote=dt;l.getWeeklyNoteSettings=C;l.getYearlyNote=yt;l.getYearlyNoteSettings=I});var St={};Ze(St,{default:()=>J});module.exports=et(St);var N=require("obsidian");var v=require("obsidian");var ce=require("obsidian");var S=require("obsidian");function D(a){return a?a.extension=="md"?a.path.slice(0,-3):a.path:""}function be(a){return a.split("/").slice(-1)[0].contains(".")?a:`${a}.md`}function X(a,t=void 0){let e=a.vault.getFiles();if(t){let n=a.vault.getFolderByPath(t);if(!n)return;e=Ne(n)}if(e.filter(n=>["md","canvas"].contains(n.extension)),e.length){let n=Math.floor(Math.random()*e.length);return D(e[n])}}function Ne(a){let t=[];for(let e of a.children)e instanceof S.TFolder?t.push(...Ne(e)):t.push(e);return t}function ke(a){return a.workspace.getActiveViewOfType(S.View)?.getViewType()=="empty"}function ee(a,t){return a.localeCompare(t,void 0,{sensitivity:"accent"})===0}function U(a){return new Promise(t=>setTimeout(t,a))}async function Pe(a){let t=a.workspace.getLayout();t.main={id:"5324373015726ba8",type:"split",children:[{id:"4509724f8bf84da7",type:"tabs",children:[{id:"e7a7b303c61786dc",type:"leaf",state:{type:"empty",state:{},icon:"lucide-file",title:"New tab"}}]}],direction:"vertical"},t.active="e7a7b303c61786dc",await a.workspace.changeLayout(t),S.Platform.isMobile&&(a.workspace.rightSplit?.updateInfo(),tt(a))}function tt(a){let t=a.internalPlugins.plugins.sync?.instance;t&&a.workspace.onLayoutReady(()=>{t.statusIconEl=a.workspace.rightSplit.addHeaderButton("sync-small",t.openStatusIconMenu.bind(t)),t.statusIconEl.addEventListener("contextmenu",t.openStatusIconMenu.bind(t)),t.statusIconEl.addClass("sync-status-icon")})}function Te(a){let t=a.internalPlugins.plugins.sync,e=[new Promise(n=>{let i=async()=>{n(),a.workspace.off("layout-change",i)};a.workspace.on("layout-change",i)})];return t.enabled&&t.instance.syncing&&e.push(new Promise(n=>{let i=async()=>{n(),t.instance.off("status-change",i)};t.instance.on("status-change",i)})),Promise.race([Promise.all(e),new Promise(n=>setTimeout(n,1500))])}var p=Xe(_e()),Pt="custom-journal-locale",le={["Daily Note"]:{noun:"day",adjective:"daily",create:p.createDailyNote,get:p.getDailyNote,getAll:p.getAllDailyNotes},["Weekly Note"]:{noun:"week",adjective:"weekly",create:p.createWeeklyNote,get:p.getWeeklyNote,getAll:p.getAllWeeklyNotes},["Monthly Note"]:{noun:"month",adjective:"monthly",create:p.createMonthlyNote,get:p.getMonthlyNote,getAll:p.getAllMonthlyNotes},["Yearly Note"]:{noun:"year",adjective:"yearly",create:p.createYearlyNote,get:p.getYearlyNote,getAll:p.getAllYearlyNotes}},B=["Daily Note","Weekly Note","Monthly Note","Yearly Note"],We="Date-dependent file",de="Date-dependent notes in Homepage have been removed. Set your Homepage as a Periodic or Daily Note instead.";async function Ve(a,t){let e=t.communityPlugins["periodic-notes"],n=le[a],i=(0,ce.moment)().startOf(n.noun),o;if(je(e)){let s=n.getAll();Object.keys(s).length?o=n.get(i,s)||await n.create(i):o=await n.create(i),o||(o=n.get(i,s))}else e.cache.initialize(),o=e.getPeriodicNote(n.noun,i)||await e.createPeriodicNote(n.noun,i);return D(o)}function Ye(a,t){if(a=="Daily Note"&&t.internalPlugins["daily-notes"]?.enabled)return!0;let e=t.communityPlugins["periodic-notes"];if(!e)return!1;if(je(e)){let n=le[a].adjective;return e.settings[n]?.enabled}else{let n=le[a].noun;return e?.calendarSetManager?.getActiveSet()[n]?.enabled}}function K(a){let t=a.internalPlugins["daily-notes"];return t?.enabled&&t?.instance.options.autorun}function je(a){return(a?.manifest.version||"0").startsWith("0")}function Ue(a){return!!a.plugin.communityPlugins.journals.getJournal(a.data.value)}async function Be(a,t){let e=t.communityPlugins.journals,n=e.getJournal(a),i=n.config.value.autoCreate;e.reprocessNotes(),n.config.value.autoCreate=!0,await n.autoCreate(),n.config.value.autoCreate=i;let o=(0,ce.moment)().locale(Pt).startOf("day");return n.getNotePath(n?.get(o)).replace(/\.md$/,"")}var y=require("obsidian");var h=require("obsidian");var pe=class extends h.AbstractInputSuggest{getSuggestions(e){let n=this.app.vault.getAllLoadedFiles(),i=[],o=e.toLowerCase();return n.forEach(s=>{s instanceof h.TFile&&["md","canvas"].contains(s.extension)&&s.path.toLowerCase().contains(o)&&i.push(s)}),i}renderSuggestion(e,n){e.extension=="md"?n.setText(D(e)):(n.setText(e.path.slice(0,-7)),n.insertAdjacentHTML("beforeend",'<div class="nav-file-tag" style="display:inline-block;vertical-align:middle">canvas</div>'))}selectSuggestion(e){this.textInputEl.value=D(e),this.textInputEl.trigger("input"),this.close()}},ue=class extends h.AbstractInputSuggest{getSuggestions(e){let n=e.toLowerCase();return this.app.vault.getAllFolders().filter(i=>i.path.toLowerCase().contains(n))}renderSuggestion(e,n){n.setText(e.path)}selectSuggestion(e){this.textInputEl.value=e.path,this.textInputEl.trigger("input"),this.close()}},ge=class extends h.AbstractInputSuggest{getSuggestions(e){let n=Object.keys(this.app.internalPlugins.plugins.workspaces?.instance.workspaces),i=e.toLowerCase();return n.filter(o=>o.toLowerCase().contains(i))}renderSuggestion(e,n){n.setText(e)}selectSuggestion(e){this.textInputEl.value=e,this.textInputEl.trigger("input"),this.close()}},me=class extends h.AbstractInputSuggest{getSuggestions(e){let n=this.app.plugins.plugins.journals.journals.map(o=>o.name),i=e.toLowerCase();return n.filter(o=>o.toLowerCase().contains(i))}renderSuggestion(e,n){n.setText(e)}selectSuggestion(e){this.textInputEl.value=e,this.textInputEl.trigger("input"),this.close()}},Ke={["File"]:pe,["Workspace"]:ge,["Random in folder"]:ue,["Journal"]:me},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),n=this.container.createDiv({cls:"nv-command-pill",attr:{draggable:!0}});n.addEventListener("dragstart",o=>{o.dataTransfer.effectAllowed="move",this.activeCommand=this.homepage.data.commands.splice(this.indexOf(n),1)[0],this.activeDrag=n,this.dropzone.style.width=`${n.clientWidth}px`,this.dropzone.style.height=`${n.clientHeight}px`}),n.addEventListener("dragover",o=>this.moveDropzone(n,o)),n.addEventListener("drop",o=>o.preventDefault()),n.addEventListener("dragend",()=>this.terminateDrag()),n.createSpan({cls:"nv-command-text",text:e?.name??t.id});let i=new h.ButtonComponent(n).setIcon("route").setClass("clickable-icon").setClass("nv-command-period").onClick(o=>this.showMenu(t,o,i));t.period!="Both"&&(i.setClass("nv-command-selected"),i.setIcon(""),i.buttonEl.createSpan({text:t.period})),new h.ButtonComponent(n).setIcon("trash-2").setClass("clickable-icon").setClass("nv-command-delete").onClick(()=>this.delete(t)),e||(n.classList.add("nv-command-invalid"),n.prepend((0,h.getIcon)("ban")),(0,h.setTooltip)(n,"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 he(this.tab).open()})}delete(t){this.homepage.data.commands.remove(t),this.homepage.save(),this.update()}showMenu(t,e,n){let i=new h.Menu;for(let s of Object.values(q))i.addItem(c=>{c.setTitle(s),c.setChecked(t.period==s),c.onClick(()=>{t.period=s,this.homepage.save(),this.update()})});let o=n.buttonEl.getBoundingClientRect();i.showAtPosition({x:o.x-22,y:o.y+o.height+8})}indexOf(t){return Array.from(this.container.children).indexOf(t)}moveDropzone(t,e){if(!this.activeDrag)return;this.activeDrag.hidden=!0;let n=t.getBoundingClientRect();e.x<n.left+n.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())}},he=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 fe={version:4,homepages:{},separateMobile:!1},L={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},Tt={["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.",["Random in folder"]:"Enter a folder. A random note or canvas from it will be selected.",["Journal"]:"Enter a Journal to use.",["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,n){super(e,n);this.plugin=n,this.settings=n.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,n=K(this.plugin),i=!1,o=Ke[e];this.containerEl.empty(),this.elements={};let s=new y.Setting(this.containerEl).setName("Homepage").addDropdown(async r=>{for(let d of Object.values(M)){if(!this.plugin.hasRequiredPlugin(d))if(d==this.plugin.homepage.data.kind)i=!0;else{r.selectEl.createEl("option",{text:d,attr:{disabled:!0}});continue}r.addOption(d,d)}r.setValue(this.plugin.homepage.data.kind),r.onChange(async d=>{this.plugin.homepage.data.kind=d,d=="Random file"&&(this.plugin.homepage.data.value=""),await this.plugin.homepage.save(),this.display()})});s.settingEl.id="nv-main-setting";let c=s.settingEl.createEl("article",{text:Tt[e],attr:{id:"nv-desc"}});i&&c.createDiv({text:"The plugin required for this homepage type isn't available.",cls:"mod-warning"}),ye.includes(e)?s.addText(r=>{r.setDisabled(!0)}):s.addText(r=>{new o(this.app,r.inputEl),r.setPlaceholder(L.value),r.setValue(L.value==this.plugin.homepage.data.value?"":this.plugin.homepage.data.value),r.onChange(async d=>{this.plugin.homepage.data.value=this.sanitiseNote(d)||L.value,await this.plugin.homepage.save()})}),this.addToggle("Open on startup","When launching Obsidian, open the homepage.","openOnStartup",r=>this.display()),n&&(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 u=new y.Setting(this.containerEl).setName("Separate mobile homepage").setDesc("For mobile devices, store the homepage and its settings separately.").addToggle(r=>r.setValue(this.plugin.settings.separateMobile).onChange(async d=>{this.plugin.settings.separateMobile=d,this.plugin.homepage=this.plugin.getHomepage(),await this.plugin.saveSettings(),this.display()}));if(this.plugin.settings.separateMobile){let r=y.Platform.isMobile?"desktop":"mobile",d=document.createElement("div");u.setClass("nv-mobile-setting"),d.className="mod-warning nv-mobile-info",d.innerHTML=`<b>Mobile settings are stored separately.</b> Therefore, changes to other settings will not affect
|
|
${r} devices. To edit ${r} settings, use a ${r} device.`,u.settingEl.append(d)}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",$),this.addDropdown("Manual opening method","Determine how extant tabs and views are affected when opening with commands or the ribbon button.","manualOpenMode",$),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",we),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()),["Workspace","Nothing"].includes(e)&&this.disableSettings("openWhenEmpty","alwaysApply","vaultHeading","openMode","manualOpenMode","autoCreate","pin"),["Workspace","Nothing","Graph view"].includes(e)&&this.disableSettings("paneHeading","view","revertView","autoScroll","refreshDataview"),(!this.plugin.homepage.data.openOnStartup||n)&&this.disableSetting("openMode"),(B.includes(e)||e==="Journal")&&this.disableSetting("autoCreate")}disableSetting(e){this.elements[e]?.settingEl.setAttribute("nv-greyed","")}disableSettings(...e){e.forEach(n=>this.disableSetting(n))}addHeading(e,n){let i=new y.Setting(this.containerEl).setHeading().setName(e);this.elements[n]=i}addDropdown(e,n,i,o,s){let c=new y.Setting(this.containerEl).setName(e).setDesc(n).addDropdown(async u=>{for(let r of Object.values(o))u.addOption(r,r);u.setValue(this.plugin.homepage.data[i]),u.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,n,i,o){let s=new y.Setting(this.containerEl).setName(e).setDesc(n).addToggle(c=>c.setValue(this.plugin.homepage.data[i]).onChange(async u=>{this.plugin.homepage.data[i]=u,await this.plugin.homepage.save(),o&&o(u)}));return this.elements[i]=s,s}async copyDebugInfo(){let e=this.app.vault.config,n={...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")||"unknown"};await navigator.clipboard.writeText(JSON.stringify(n)),new y.Notice("Copied homepage debug information to clipboard")}};var Dt=["markdown","canvas","kanban"],V="Main Homepage",Y="Mobile Homepage",$=(n=>(n.ReplaceAll="Replace all open notes",n.ReplaceLast="Replace last note",n.Retain="Keep open notes",n))($||{}),we=(i=>(i.Default="Default view",i.Reading="Reading view",i.Source="Editing view (Source)",i.LivePreview="Editing view (Live Preview)",i))(we||{}),M=(m=>(m.File="File",m.Workspace="Workspace",m.Random="Random file",m.RandomFolder="Random in folder",m.Graph="Graph view",m.None="Nothing",m.Journal="Journal",m.DailyNote="Daily Note",m.WeeklyNote="Weekly Note",m.MonthlyNote="Monthly Note",m.YearlyNote="Yearly Note",m))(M||{}),q=(n=>(n.Both="Both",n.Startup="Startup only",n.Manual="Manual only",n))(q||{}),ye=["Random file","Graph view","Nothing",...B],W=class{constructor(t,e){this.lastView=void 0;this.openedViews=new WeakMap;this.name=t,this.plugin=e,this.app=e.app;let n=this.plugin.settings.homepages[t];n?this.data=Object.assign({},L,n):(this.plugin.settings.homepages[t]={...L},this.data=this.plugin.settings.homepages[t])}async open(t=!1){if(this.plugin.hasRequiredPlugin(this.data.kind)){if(this.data.kind==="Journal"&&!Ue(this)){new v.Notice(`Cannot find the journal "${this.data.value}" to use as the homepage.`);return}}else{new v.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 n=this.plugin.loaded?this.data.manualOpenMode:this.data.openMode;t&&(n="Keep open notes"),await this.launchLeaf(n)}if(this.data.commands.length<1)return;let e=this.plugin.loaded?"Startup only":"Manual only";await Te(this.app);for(let{id:n,period:i}of this.data.commands)i!==e&&this.app.commands.executeCommandById(n)}async launchWorkspace(){let t=this.plugin.internalPlugins.workspaces?.instance;if(!(this.data.value in t.workspaces)){new v.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 n=this.getOpened();if(n.length>0){this.app.workspace.setActiveLeaf(n[0]),await this.configure(n[0]);return}else t=="Keep open notes"&&ke(this.app)&&(t="Replace last note")}t!=="Keep open notes"&&this.app.workspace.getActiveViewOfType(v.View)?.leaf.setPinned(!1),t==="Replace all open notes"&&(this.app.workspace?.floatingSplit?.children&&(await U(0),this.app.workspace.floatingSplit.children.forEach(n=>n.win.close())),await Pe(this.app),await U(0)),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(v.View)?.leaf}async launchNote(t){let e=this.app.metadataCache.getFirstLinkpathDest(this.computedValue,"/");if(!e){if(!this.data.autoCreate){new v.Notice(`Homepage "${this.computedValue}" does not exist.`);return}e=await this.app.vault.create(be(this.computedValue),"")}let n=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),n!==await this.app.vault.read(e)&&await this.app.vault.modify(e,n),i}async configure(t){this.plugin.executing=!1;let e=t.view;if(!(e instanceof v.MarkdownView)){this.data.pin&&e.leaf.setPinned(!0),this.configurePlugins();return}let n=e.getState();if(this.data.revertView&&(this.lastView=new WeakRef(e)),this.data.autoScroll){let i=e.editor.lineCount();n.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)":n.mode="source",n.source=this.data.view!="Editing view (Live Preview)";break;case"Reading view":n.mode="preview";break}await e.leaf.setViewState({type:"markdown",state:n})}this.configurePlugins()}configurePlugins(){this.plugin.loaded&&this.data.refreshDataview&&this.plugin.communityPlugins.dataview?.index.touch(),this.plugin.communityPlugins["obsidian-file-color"]?.generateColorStyles()}getOpened(){return this.data.kind=="Graph view"?this.app.workspace.getLeavesOfType("graph"):Dt.flatMap(e=>this.app.workspace.getLeavesOfType(e)).filter(e=>{let n=e.view.getState().file;return ee(n.endsWith("md")?n.slice(0,-3):n,this.computedValue)})}async computeValue(){let t=this.data.value,e;switch(this.data.kind){case"Random file":e=X(this.app),e&&(t=e);break;case"Random in folder":e=X(this.app,t),e&&(t=e);break;case"Journal":t=await Be(t,this.plugin);break;case"Daily Note":case"Weekly Note":case"Monthly Note":case"Yearly Note":t=await Ve(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=D(this.app.workspace.getActiveFile()),await this.save(),new v.Notice(`The homepage has been changed to "${this.data.value}".`)}canSetToFile(){return this.app.workspace.getActiveFile()!==null&&!ye.includes(this.data.kind)}async revertView(){if(this.lastView==null||this.data.view=="Default view")return;let t=this.lastView.deref();if(!t||ee(D(t.file),this.computedValue))return;let e=t.getState(),n=this.app.vault.config,i=n.defaultViewMode||"source",o=n.livePreview!==void 0?!n.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(v.View)?.leaf;t?.getViewState().type!=="empty"||t.parentSplit.children.length!=1||await this.open(!0)}async apply(){let t=this.app.workspace.getActiveViewOfType(v.FileView);if(!t)return;let e=D(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 Et='<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 N.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()};this.hideInterstitial=()=>{this.interstitial?.detach(),window.removeEventListener("error",this.hideInterstitial)}}async onload(){let e=this.app.workspace.layoutReady;e||this.showInterstitial(),this.patchReleaseNotes(),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 n=this.homepage.data.openOnStartup&&!e&&!await this.hasUrlParams();this.patchNewTabPage(),n&&await this.homepage.open(),this.loaded=!0,this.unpatchReleaseNotes(),this.hideInterstitial()}),(0,N.addIcon)("homepage",Et),this.addRibbonIcon("homepage","Open homepage",n=>this.homepage.open(n.button==1||n.button==2||N.Keymap.isModifier(n,"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:n=>{if(n)return this.homepage.canSetToFile();this.homepage.setToActiveFile()}})}async onunload(){this.app.workspace.off("layout-change",this.onLayoutChange),this.unpatchNewTabPage()}getHomepage(){return this.settings.separateMobile&&N.Platform.isMobile?(Y in this.settings.homepages||(this.settings.homepages[Y]={...this.settings.homepages?.[V]},this.settings.homepages[Y].commands=[...this.settings.homepages?.[V]?.commands]),new W(Y,this)):new W(V,this)}async loadSettings(){let e=await this.loadData();return e?.version!==4?e?this.upgradeSettings(e):Object.assign({},fe):e}async saveSettings(){await this.saveData(this.settings)}showInterstitial(){this.interstitial=createDiv({cls:"nv-homepage-interstitial"}),document.body.append(this.interstitial),window.addEventListener("error",this.hideInterstitial)}async hasUrlParams(){let e,n;if(N.Platform.isMobile){let i=await window.Capacitor.Plugins.App.getLaunchUrl();if(!i)return!1;let o=new URL(i.url);n=Array.from(o.searchParams.keys()),e=o.hostname}else if(window.OBS_ACT)n=Object.keys(window.OBS_ACT),e=window.OBS_ACT.action;else return!1;return["open","advanced-uri"].includes(e)&&["file","filepath","workspace"].some(i=>n.includes(i))}hasRequiredPlugin(e){switch(e){case"Workspace":return this.internalPlugins.workspaces?.enabled;case"Graph view":return this.internalPlugins.graph?.enabled;case"Journal":return this.communityPlugins.journals;case"Daily Note":case"Weekly Note":case"Monthly Note":case"Yearly Note":return Ye(e,this);default:return!0}}patchNewTabPage(){let e=this.communityPlugins["new-tab-default-page"];e&&(e.nvOrig_checkForNewTab=e.checkForNewTab,e.checkForNewTab=async n=>{if(!(this&&this.executing))return await e.nvOrig_checkForNewTab(n)})}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==We&&(o=!0,s.kind="Daily Note");return o&&new N.Notice(de),i.version=4,this.saveData(i),i}let n=Object.assign({},fe);return e.workspaceEnabled?(e.value=e.workspace,e.kind="Workspace"):e.momentFormat?(e.kind="Daily Note",new N.Notice(de)):(e.value=e.defaultNote,e.kind="File"),e.commands=[],delete e.workspace,delete e.momentFormat,delete e.defaultNote,delete e.useMoment,delete e.workspaceEnabled,n.homepages[V]=e,this.saveData(n),n}};
|
|
|
|
/* nosourcemap */ |