Files
fflow/main.js
T

6 lines
18 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
*/
var I=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var fe=(o,s)=>{for(var t in s)I(o,t,{get:s[t],enumerable:!0})},ge=(o,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of ue(s))!de.call(o,n)&&n!==t&&I(o,n,{get:()=>s[n],enumerable:!(e=pe(s,n))||e.enumerable});return o};var we=o=>ge(I({},"__esModule",{value:!0}),o);var Ce={};fe(Ce,{default:()=>R});module.exports=we(Ce);var ie=require("obsidian");var Y=require("obsidian");var X=require("obsidian");var N=require("obsidian"),U=String.raw`\{\{(date|time)(?::([^}]*))?\}\}`,he={date:"YYYY-MM-DD",time:"HH:mm"},z=(o,s)=>(s==null?void 0:s.trim())||he[o];function B(o){let s=(0,N.moment)();return o.replace(new RegExp(U,"g"),(t,e,n)=>s.format(z(e,n)))}function G(o,s){let t=new RegExp(U,"g"),e=[],n="^",r=0;for(let i=t.exec(o);i;i=t.exec(o))n+=W(o.slice(r,i.index))+"(.+?)",e.push(z(i[1],i[2])),r=i.index+i[0].length;if(e.length===0)return o===s;let a=new RegExp(n+W(o.slice(r))+"$").exec(s);return a!==null&&e.every((i,l)=>(0,N.moment)(a[l+1],i,!0).isValid())}function W(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function T(o,s,t){let e=o.workspace.getActiveViewOfType(X.MarkdownView);(e==null?void 0:e.file)===s&&await e.save(),await o.fileManager.processFrontMatter(s,t)}function Z(o,s,t,e){if(!e){o[s]=t;return}let n=H(o[s],s);n.includes(t)||n.push(t),o[s]=n}function M(o,s,t,e){var l;s[t.property]=e;let n=t.steps.find(c=>c.value===e),r=new Map,a=c=>{let d=r.get(c);return d===void 0&&r.set(c,d=me(o,s,c)),d},i=c=>c.property!==""&&c.property!==t.property;for(let c of t.steps)if(c!==n)for(let d of c.effects.filter(i)){let p=d.property;if(a(p)){let w=J(d.value),g=H(s[p],p).filter(F=>!w.some(y=>Q(y,F)));g.length?s[p]=g:delete s[p]}else p in s&&Q(d.value,s[p])&&delete s[p]}for(let c of(l=n==null?void 0:n.effects.filter(i))!=null?l:[]){let d=c.property;if(a(d)){let p=H(s[d],d);for(let w of J(c.value).map(B))p.includes(w)||p.push(w);p.length&&(s[d]=p)}else s[d]=ee(B(c.value))}}function me(o,s,t){if(["cssclasses","tags","aliases"].includes(t)||Array.isArray(s[t]))return!0;let e=Reflect.get(o,"metadataTypeManager");if(!e||typeof e!="object"||!("getPropertyInfo"in e)||typeof e.getPropertyInfo!="function")return!1;let n=e.getPropertyInfo(t),r=n&&typeof n=="object"&&"widget"in n?n.widget:null;return r==="multitext"||r==="tags"||r==="aliases"}function H(o,s){return Array.isArray(o)?o.map(String):o==null||o===""?[]:s==="cssclasses"?String(o).split(/[\s,]+/).filter(Boolean):[String(o)]}function J(o){return o.split(/,(?![^{]*\}\})/).map(s=>s.trim()).filter(Boolean)}function Q(o,s){let t=o.trim();return String(ee(t))===String(s)||G(t,String(s))}function ee(o){let s=o.trim();return s===""?null:s==="true"||s==="false"?s==="true":/^-?\d+(\.\d+)?$/.test(s)?Number(s):s}function v(o){return{id:Date.now().toString(36)+Math.random().toString(36).slice(2,6),name:"",symbol:"",property:"",kind:"ordered",valueMode:"single",loop:!1,steps:[],condition:{property:"",values:""},...o}}function te(o,s){let t=o.name||o.property||"New flow",e=new Set(s.map(i=>i.name)),n=`${t} (copy)`;for(let i=2;e.has(n);i++)n=`${t} (copy ${i})`;let{id:r,...a}=structuredClone(o);return v({...a,name:n})}function ye(){return{flows:[v({name:"Type",symbol:"&",property:"type",kind:"open"})]}}var j=o=>o.values.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),C=o=>o.condition.property!=="";function ve(o,s){if(!C(o))return!0;let t=s==null?void 0:s[o.condition.property],e=(Array.isArray(t)?t:[t]).filter(r=>r!=null&&String(r).trim()!=="").map(r=>String(r).trim().toLowerCase()),n=j(o.condition);return n.length===0?e.length>0:e.some(r=>n.includes(r))}function k(o,s){var t,e;return(e=(t=o.find(n=>C(n)&&ve(n,s)))!=null?t:o.find(n=>!C(n)))!=null?e:null}function ne(o,s){var n;let t=o[s];if(!t.symbol)return null;let e=j(t.condition);return(n=o.slice(0,s).find(r=>{if(r.symbol!==t.symbol)return!1;if(!C(t))return!C(r);if(r.condition.property!==t.condition.property)return!1;let a=j(r.condition);return a.length===0||e.length>0&&e.every(i=>a.includes(i))}))!=null?n:null}var D=["#","[","/",":"];function E(o){return o===""?null:[...o].length!==1?"Use exactly one character.":/[\p{L}\p{N}\s]/u.test(o)?"Letters, digits and spaces are not allowed.":D.includes(o)?`"${o}" is reserved (${D.join(" ")}).`:null}function oe(o){var n,r;if(!o||typeof o!="object")return ye();if("flows"in o&&!("rules"in o)&&Array.isArray(o.flows))return{flows:o.flows.map(a=>v({...a,condition:{property:"",values:"",...a.condition}}))};let s=o,t=(n=s.rules)!=null?n:[],e=((r=s.flows)!=null?r:[]).map(a=>{var i,l;return v({id:a.id,name:a.name,property:a.property,loop:a.loop,symbol:(l=(i=t.find(c=>c.source==="flow"&&c.flowId===a.id))==null?void 0:i.symbol)!=null?l:"",steps:a.steps.map(c=>({value:c.value,effects:c.cssclass.trim()?[{property:"cssclasses",value:c.cssclass.trim().split(/\s+/).join(", ")}]:[]}))})});for(let a of t)a.source==="open"&&e.push(v({name:a.property,symbol:a.symbol,property:a.property,kind:"open",valueMode:a.valueMode})),a.source==="finite"&&e.push(v({name:a.property,symbol:a.symbol,property:a.property,steps:a.values.map(i=>({value:i,effects:[]}))}));return{flows:e}}var L=class{constructor(s){this.plugin=s;this.registered=[]}sync(){var t,e;for(let n of this.registered)this.plugin.removeCommand(n);this.registered=[];let s=new Map;for(let n of this.plugin.settings.flows){if(n.kind!=="ordered")continue;let r=n.name||n.property||"Unnamed flow";this.add([n],`flow-${n.id}-next`,`${r}: next step`,1),this.add([n],`flow-${n.id}-previous`,`${r}: previous step`,-1),n.symbol&&s.set(n.symbol,[...(t=s.get(n.symbol))!=null?t:[],n])}for(let[n,r]of s){if(r.length<2)continue;let a=`symbol-${(e=n.codePointAt(0))==null?void 0:e.toString(16)}`,i=`${n} ${r.map(l=>l.name||l.property||"Unnamed flow").join(" / ")}`;this.add(r,`${a}-next`,`${i}: next step`,1),this.add(r,`${a}-previous`,`${i}: previous step`,-1)}}add(s,t,e,n){this.registered.push(t),this.plugin.addCommand({id:t,name:e,checkCallback:r=>{var c,d;let a=this.plugin.app,i=a.workspace.getActiveFile();if(!i||i.extension!=="md")return!1;let l=k(s,(d=(c=a.metadataCache.getFileCache(i))==null?void 0:c.frontmatter)!=null?d:null);return!(l!=null&&l.property)||!l.steps.some(p=>p.value)?!1:(r||Fe(this.plugin,i,s,n),!0)}})}};async function Fe(o,s,t,e){let n="",r="";try{await T(o.app,s,a=>{let i=k(t,a);if(!(i!=null&&i.property))return;r=i.property;let l=i.steps.filter(p=>p.value);if(l.length===0)return;let c=l.findIndex(p=>p.value===String(a[i.property])),d=c===-1?0:c+e;if(d<0||d>=l.length){if(!i.loop){n=`${i.property}: already at the ${e===1?"last":"first"} step`;return}d=(d+l.length)%l.length}M(o.app,a,i,l[d].value),n=`${i.property}: ${l[d].value}`}),n&&new Y.Notice(n)}catch(a){console.error("FFLOW: could not move flow step",a),new Y.Notice(`FFLOW: could not set "${r}". See console.`)}}var f=require("obsidian");var A=class extends f.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e;this.expanded=new Set;this.refreshers=[];this.save=()=>this.plugin.saveSettings()}async saveAndRedraw(){await this.save(),this.display()}display(){let{containerEl:t}=this,e=this.plugin.settings.flows;t.empty(),this.refreshers=[],new f.Setting(t).setHeading().setName("Flows").setDesc("Type a flow's symbol at the start of a word to pick a value. Ordered flows also get next/previous step commands.").addButton(r=>r.setButtonText("Hotkeys").onClick(()=>this.openHotkeys())).addButton(r=>r.setButtonText("Add flow").setCta().onClick(async()=>{let a=v({steps:[{value:"",effects:[]}]});e.push(a),this.expanded.add(a.id),await this.saveAndRedraw()}));let n=t.createDiv({cls:"fflow-list"});e.forEach((r,a)=>this.renderFlow(n,r,a)),e.length===0&&n.createDiv({cls:"fflow-empty",text:"No flows yet."})}renderFlow(t,e,n){let r=this.plugin.settings.flows,a=t.createDiv({cls:"fflow-card"});a.toggleClass("is-collapsed",!this.expanded.has(e.id));let i=a.createDiv({cls:"fflow-card-header"});(0,f.setIcon)(i.createSpan({cls:"fflow-chevron"}),"chevron-right");let l=i.createSpan({cls:"fflow-badge"}),c=i.createSpan({cls:"fflow-title"}),d=i.createSpan({cls:"fflow-summary"}),p=()=>{l.setText(e.symbol),l.toggle(e.symbol!==""),c.setText(e.name||e.property||"New flow");let u=e.steps.map(ce=>ce.value).filter(Boolean),{property:h,values:x}=e.condition;d.setText([e.property,h&&`when ${h}${x.trim()?` = ${x.trim()}`:""}`,e.kind==="open"?"open list":u.join(" \u2192 ")||"no steps"].filter(Boolean).join(" \xB7 "))};p(),i.addEventListener("click",()=>{let u=!this.expanded.has(e.id);u?this.expanded.add(e.id):this.expanded.delete(e.id),a.toggleClass("is-collapsed",!u)});let w=i.createDiv({cls:"fflow-header-actions"});w.addEventListener("click",u=>u.stopPropagation()),new f.ExtraButtonComponent(w).setIcon("copy").setTooltip("Duplicate flow").onClick(async()=>{let u=te(e,r);r.splice(n+1,0,u),this.expanded.add(u.id),await this.saveAndRedraw()}),new f.ExtraButtonComponent(w).setIcon("trash-2").setTooltip("Delete flow").onClick(async()=>{r.splice(n,1),this.expanded.delete(e.id),await this.saveAndRedraw()});let g=a.createDiv({cls:"fflow-card-body"}),F=g.createDiv({cls:"fflow-fields"}),y=(u,h="")=>{let x=F.createDiv({cls:`fflow-field ${h}`});return x.createDiv({cls:"fflow-label",text:u}),x};new f.TextComponent(y("Name","is-wide")).setPlaceholder("Status").setValue(e.name).onChange(async u=>{e.name=u,p(),await this.save()});let ae=y("Symbol","is-narrow"),S=new f.TextComponent(ae).setPlaceholder("\u2014").setValue(e.symbol);S.inputEl.addClass("fflow-symbol"),(0,f.setTooltip)(S.inputEl,`Optional. One character, not a letter or digit. Reserved: ${D.join(" ")}`);let b=g.createDiv({cls:"fflow-fields fflow-when"});b.createDiv({cls:"fflow-label",text:"Only on notes where"});let _=async()=>{p(),this.refreshers.forEach(u=>u()),await this.save()};new f.TextComponent(b).setPlaceholder("type").setValue(e.condition.property).onChange(async u=>{e.condition.property=u.trim(),await _()}),b.createSpan({cls:"fflow-equals",text:"="}),new f.TextComponent(b).setPlaceholder("project, area (empty: any value)").setValue(e.condition.values).onChange(async u=>{e.condition.values=u,await _()}).inputEl.addClass("fflow-when-values"),(0,f.setTooltip)(b,"Leave the property empty to use this flow on every note. Flows sharing a symbol: a matching condition wins over a flow without one.");let le=g.createDiv({cls:"fflow-error"}),V=()=>{let u=E(S.getValue()),h=u?null:ne(r,n);le.setText(u!=null?u:h?`Never runs: \u201C${h.name||h.property}\u201D takes ${e.symbol} on the same notes first.`:""),S.inputEl.toggleClass("is-invalid",u!==null)};if(this.refreshers.push(V),V(),S.onChange(async u=>{if(E(u)){V();return}e.symbol=u,p(),this.refreshers.forEach(h=>h()),await this.save()}),new f.TextComponent(y("Property","is-wide")).setPlaceholder("status").setValue(e.property).onChange(async u=>{e.property=u.trim(),p(),await this.save()}),new f.DropdownComponent(y("Kind")).addOptions({ordered:"Ordered list",open:"Open (vault)"}).setValue(e.kind).onChange(async u=>{e.kind=u,await this.saveAndRedraw()}),e.kind==="open"){new f.DropdownComponent(y("Values")).addOptions({single:"Single value",list:"List"}).setValue(e.valueMode).onChange(async u=>{e.valueMode=u,await this.save()}),g.createDiv({cls:"fflow-hint",text:"Suggests every value already used for this property in the vault. New values are allowed. No steps or hotkeys."});return}new f.ToggleComponent(y("Loop","is-toggle")).setValue(e.loop).setTooltip("After the last step, \u201Cnext\u201D goes back to the first").onChange(async u=>{e.loop=u,await this.save()});let q=g.createDiv({cls:"fflow-steps"}),O=q.createDiv({cls:"fflow-step-row fflow-steps-head"});O.createSpan(),O.createSpan({text:"Value"}),O.createSpan({text:"Also sets"}),e.steps.forEach((u,h)=>this.renderStep(q,e,u,h,p)),se(g.createDiv({cls:"fflow-add-step"}),"Add step",async()=>{e.steps.push({value:"",effects:[]}),await this.saveAndRedraw()}),g.createDiv({cls:"fflow-hint",text:"Values: true/false and numbers are typed. Lists take a, b. {{date}} and {{time}} insert the current date and time; set a format with {{date:DD/MM/YYYY}} or {{time:HH:mm:ss}} (moment.js)."})}renderStep(t,e,n,r,a){let i=t.createDiv({cls:"fflow-step-row"});i.createSpan({cls:"fflow-step-num",text:String(r+1)}),new f.TextComponent(i.createDiv({cls:"fflow-step-value"})).setPlaceholder("value").setValue(n.value).onChange(async p=>{n.value=p.trim(),a(),await this.save()});let l=i.createDiv({cls:"fflow-effects"});n.effects.forEach((p,w)=>{let g=l.createDiv({cls:"fflow-effect"});new f.TextComponent(g).setPlaceholder("property").setValue(p.property).onChange(async F=>{p.property=F.trim(),await this.save()}),g.createSpan({cls:"fflow-equals",text:"="}),new f.TextComponent(g).setPlaceholder("value (lists: a, b)").setValue(p.value).onChange(async F=>{p.value=F,await this.save()}),new f.ExtraButtonComponent(g).setIcon("minus").setTooltip("Remove this property").onClick(async()=>{n.effects.splice(w,1),await this.saveAndRedraw()})}),se(l,"property",async()=>{n.effects.push({property:"",value:""}),await this.saveAndRedraw()});let c=i.createDiv({cls:"fflow-step-actions"}),d=async p=>{e.steps.splice(p,0,...e.steps.splice(r,1)),await this.saveAndRedraw()};new f.ExtraButtonComponent(c).setIcon("arrow-up").setTooltip("Move up").setDisabled(r===0).onClick(()=>d(r-1)),new f.ExtraButtonComponent(c).setIcon("arrow-down").setTooltip("Move down").setDisabled(r===e.steps.length-1).onClick(()=>d(r+1)),new f.ExtraButtonComponent(c).setIcon("trash-2").setTooltip("Delete step").onClick(async()=>{e.steps.splice(r,1),await this.saveAndRedraw()})}openHotkeys(){let t=Reflect.get(this.app,"setting");if(!t||typeof t!="object"||!("openTabById"in t)||typeof t.openTabById!="function")return;let e=t.openTabById("hotkeys"),n=e&&typeof e=="object"&&"searchComponent"in e?e.searchComponent:null;n instanceof f.SearchComponent&&(n.setValue(this.plugin.manifest.name),n.inputEl.dispatchEvent(new Event("input")))}};function se(o,s,t){let e=o.createEl("button",{cls:"fflow-add clickable-icon"});(0,f.setIcon)(e.createSpan(),"plus"),e.createSpan({text:s}),e.addEventListener("click",()=>void t())}var m=require("obsidian");var P=class{constructor(s){this.app=s;this.cache=new Map}invalidate(){this.cache.clear()}get(s){var e,n,r;let t=this.cache.get(s);if(t)return t;t=new Map;for(let a of this.app.vault.getMarkdownFiles()){let i=(n=(e=this.app.metadataCache.getFileCache(a))==null?void 0:e.frontmatter)==null?void 0:n[s];for(let l of new Set(re(i)))t.set(l,((r=t.get(l))!=null?r:0)+1)}return this.cache.set(s,t),t}};function re(o){return Array.isArray(o)?o.flatMap(re):typeof o=="string"?o.trim()?[o.trim()]:[]:typeof o=="number"||typeof o=="boolean"?[String(o)]:[]}var K=o=>o!==void 0&&/\s/.test(o),$=class extends m.EditorSuggest{constructor(t,e,n){super(t);this.plugin=e;this.index=n;this.flow=null;this.header=null;let r=Reflect.get(this,"suggestEl");r instanceof HTMLElement&&(this.header=r.createDiv({cls:"fflow-header"}),r.prepend(this.header))}onTrigger(t,e,n){let r=e.getLine(t.line).slice(0,t.ch),a=r.length;for(;a>0&&!K(r[a-1]);)a--;let i=r.slice(a);if(!i)return null;let l=i[0];if(E(l))return null;let c=this.plugin.settings.flows.filter(w=>w.symbol===l&&w.property);if(c.length===0||be(e,t.line)||xe(e,t.line,r.slice(0,a)))return null;let d=Se(e),p=k(c,d);return p?(this.flow=p,this.renderHeader(p,d),{start:{line:t.line,ch:a},end:t,query:i.slice(1)}):null}renderHeader(t,e){let n=this.header;if(!n)return;n.empty();let r=e==null?void 0:e[t.property],a=(Array.isArray(r)?r:[r]).filter(c=>c!=null&&String(c)!==""),i=t.kind==="open"&&t.valueMode==="list",l=!i&&a.length>0;(0,m.setIcon)(n.createSpan({cls:"fflow-header-icon"}),l?"replace":"plus"),n.createSpan({cls:"fflow-header-action",text:i?"Add to":l?"Replace":"Set"}),n.createSpan({cls:"fflow-header-property",text:t.property}),l&&n.createSpan({cls:"fflow-header-current",text:a.map(String).join(", ")})}getSuggestions(t){let e=this.flow;if(!e)return[];let n=t.query.toLowerCase(),r=e.kind==="ordered"?e.steps.filter(i=>i.value).map(i=>({value:i.value,isNew:!1})):[...this.index.get(e.property)].sort((i,l)=>l[1]-i[1]||i[0].localeCompare(l[0])).map(([i,l])=>({value:i,count:l,isNew:!1})),a=r.filter(i=>i.value.toLowerCase().includes(n));return a.sort((i,l)=>+!i.value.toLowerCase().startsWith(n)-+!l.value.toLowerCase().startsWith(n)),e.kind==="open"&&n&&!r.some(i=>i.value.toLowerCase()===n)&&a.push({value:t.query,isNew:!0}),a}renderSuggestion(t,e){if(e.addClass("fflow-suggestion"),t.isNew){e.createSpan({cls:"fflow-new",text:"New: "}),e.createSpan({text:t.value});return}e.createSpan({text:t.value}),t.count!==void 0&&e.createSpan({cls:"fflow-count",text:String(t.count)})}selectSuggestion(t,e){let n=this.context,r=this.flow;!n||!r||this.apply(n,r,t.value)}async apply(t,e,n){let{editor:r,file:a,start:i}=t,l=r.getLine(i.line),c=t.end.ch;for(;c<l.length&&!K(l[c]);)c++;K(l[c])&&c++,r.replaceRange("",i,{line:i.line,ch:c}),r.setCursor(i);try{await T(this.app,a,d=>{e.kind==="ordered"?M(this.app,d,e,n):Z(d,e.property,n,e.valueMode==="list")})}catch(d){console.error("FFLOW: could not update frontmatter",d),new m.Notice(`FFLOW: could not set "${e.property}". See console.`)}}};function Se(o){let s=(0,m.getFrontMatterInfo)(o.getValue());if(!s.exists)return null;try{let t=(0,m.parseYaml)(s.frontmatter);return t&&typeof t=="object"?t:null}catch(t){return null}}function be(o,s){if(o.getLine(0)!=="---")return!1;for(let t=1;t<o.lineCount();t++)if(o.getLine(t)==="---")return s<=t;return!1}function xe(o,s,t){var n,r;let e=0;for(let a=0;a<s;a++)/^\s*(```|~~~)/.test(o.getLine(a))&&e++;return e%2===1?!0:((r=(n=t.match(/`/g))==null?void 0:n.length)!=null?r:0)%2===1}var R=class extends ie.Plugin{constructor(){super(...arguments);this.flowCommands=new L(this)}async onload(){let t=await this.loadData();this.settings=oe(t),t&&typeof t=="object"&&"rules"in t&&await this.saveData(this.settings);let e=new P(this.app);this.registerEvent(this.app.metadataCache.on("changed",()=>e.invalidate())),this.registerEvent(this.app.metadataCache.on("deleted",()=>e.invalidate())),this.registerEditorSuggest(new $(this.app,this,e)),this.flowCommands.sync(),this.addSettingTab(new A(this.app,this))}async saveSettings(){await this.saveData(this.settings),this.flowCommands.sync()}};