Files
fflow/main.js
T

6 lines
18 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
*/
var I=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var ue=Object.prototype.hasOwnProperty;var de=(s,o)=>{for(var t in o)I(s,t,{get:o[t],enumerable:!0})},fe=(s,o,t,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let n of pe(o))!ue.call(s,n)&&n!==t&&I(s,n,{get:()=>o[n],enumerable:!(e=ce(o,n))||e.enumerable});return s};var ge=s=>fe(I({},"__esModule",{value:!0}),s);var xe={};de(xe,{default:()=>R});module.exports=ge(xe);var re=require("obsidian");var Y=require("obsidian");var X=require("obsidian");var N=require("obsidian"),U=String.raw`\{\{(date|time)(?::([^}]*))?\}\}`,we={date:"YYYY-MM-DD",time:"HH:mm"},z=(s,o)=>(o==null?void 0:o.trim())||we[s];function B(s){let o=(0,N.moment)();return s.replace(new RegExp(U,"g"),(t,e,n)=>o.format(z(e,n)))}function G(s,o){let t=new RegExp(U,"g"),e=[],n="^",r=0;for(let i=t.exec(s);i;i=t.exec(s))n+=W(s.slice(r,i.index))+"(.+?)",e.push(z(i[1],i[2])),r=i.index+i[0].length;if(e.length===0)return s===o;let a=new RegExp(n+W(s.slice(r))+"$").exec(o);return a!==null&&e.every((i,l)=>(0,N.moment)(a[l+1],i,!0).isValid())}function W(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function T(s,o,t){let e=s.workspace.getActiveViewOfType(X.MarkdownView);(e==null?void 0:e.file)===o&&await e.save(),await s.fileManager.processFrontMatter(o,t)}function Z(s,o,t,e){if(!e){s[o]=t;return}let n=H(s[o],o);n.includes(t)||n.push(t),s[o]=n}function M(s,o,t,e){var l;o[t.property]=e;let n=t.steps.find(c=>c.value===e),r=new Map,a=c=>{let u=r.get(c);return u===void 0&&r.set(c,u=he(s,o,c)),u},i=c=>c.property!==""&&c.property!==t.property;for(let c of t.steps)if(c!==n)for(let u of c.effects.filter(i)){let p=u.property;if(a(p)){let h=J(u.value),g=H(o[p],p).filter(v=>!h.some(y=>Q(y,v)));g.length?o[p]=g:delete o[p]}else p in o&&Q(u.value,o[p])&&delete o[p]}for(let c of(l=n==null?void 0:n.effects.filter(i))!=null?l:[]){let u=c.property;if(a(u)){let p=H(o[u],u);for(let h of J(c.value).map(B))p.includes(h)||p.push(h);p.length&&(o[u]=p)}else o[u]=ee(B(c.value))}}function he(s,o,t){if(["cssclasses","tags","aliases"].includes(t)||Array.isArray(o[t]))return!0;let e=Reflect.get(s,"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(s,o){return Array.isArray(s)?s.map(String):s==null||s===""?[]:o==="cssclasses"?String(s).split(/[\s,]+/).filter(Boolean):[String(s)]}function J(s){return s.split(/,(?![^{]*\}\})/).map(o=>o.trim()).filter(Boolean)}function Q(s,o){let t=s.trim();return String(ee(t))===String(o)||G(t,String(o))}function ee(s){let o=s.trim();return o===""?null:o==="true"||o==="false"?o==="true":/^-?\d+(\.\d+)?$/.test(o)?Number(o):o}function F(s){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:""},...s}}function me(){return{flows:[F({name:"Type",symbol:"&",property:"type",kind:"open"})]}}var j=s=>s.values.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean),C=s=>s.condition.property!=="";function ye(s,o){if(!C(s))return!0;let t=o==null?void 0:o[s.condition.property],e=(Array.isArray(t)?t:[t]).filter(r=>r!=null&&String(r).trim()!=="").map(r=>String(r).trim().toLowerCase()),n=j(s.condition);return n.length===0?e.length>0:e.some(r=>n.includes(r))}function k(s,o){var t,e;return(e=(t=s.find(n=>C(n)&&ye(n,o)))!=null?t:s.find(n=>!C(n)))!=null?e:null}function te(s,o){var n;let t=s[o];if(!t.symbol)return null;let e=j(t.condition);return(n=s.slice(0,o).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 L=["#","[","/",":"];function E(s){return s===""?null:[...s].length!==1?"Use exactly one character.":/[\p{L}\p{N}\s]/u.test(s)?"Letters, digits and spaces are not allowed.":L.includes(s)?`"${s}" is reserved (${L.join(" ")}).`:null}function ne(s){var n,r;if(!s||typeof s!="object")return me();if("flows"in s&&!("rules"in s)&&Array.isArray(s.flows))return{flows:s.flows.map(a=>F({...a,condition:{property:"",values:"",...a.condition}}))};let o=s,t=(n=o.rules)!=null?n:[],e=((r=o.flows)!=null?r:[]).map(a=>{var i,l;return F({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(F({name:a.property,symbol:a.symbol,property:a.property,kind:"open",valueMode:a.valueMode})),a.source==="finite"&&e.push(F({name:a.property,symbol:a.symbol,property:a.property,steps:a.values.map(i=>({value:i,effects:[]}))}));return{flows:e}}var D=class{constructor(o){this.plugin=o;this.registered=[]}sync(){var t,e;for(let n of this.registered)this.plugin.removeCommand(n);this.registered=[];let o=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&&o.set(n.symbol,[...(t=o.get(n.symbol))!=null?t:[],n])}for(let[n,r]of o){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(o,t,e,n){this.registered.push(t),this.plugin.addCommand({id:t,name:e,checkCallback:r=>{var c,u;let a=this.plugin.app,i=a.workspace.getActiveFile();if(!i||i.extension!=="md")return!1;let l=k(o,(u=(c=a.metadataCache.getFileCache(i))==null?void 0:c.frontmatter)!=null?u:null);return!(l!=null&&l.property)||!l.steps.some(p=>p.value)?!1:(r||ve(this.plugin,i,o,n),!0)}})}};async function ve(s,o,t,e){let n="",r="";try{await T(s.app,o,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])),u=c===-1?0:c+e;if(u<0||u>=l.length){if(!i.loop){n=`${i.property}: already at the ${e===1?"last":"first"} step`;return}u=(u+l.length)%l.length}M(s.app,a,i,l[u].value),n=`${i.property}: ${l[u].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=F({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"}),u=i.createSpan({cls:"fflow-summary"}),p=()=>{l.setText(e.symbol),l.toggle(e.symbol!==""),c.setText(e.name||e.property||"New flow");let d=e.steps.map(le=>le.value).filter(Boolean),{property:w,values:x}=e.condition;u.setText([e.property,w&&`when ${w}${x.trim()?` = ${x.trim()}`:""}`,e.kind==="open"?"open list":d.join(" \u2192 ")||"no steps"].filter(Boolean).join(" \xB7 "))};p(),i.addEventListener("click",()=>{let d=!this.expanded.has(e.id);d?this.expanded.add(e.id):this.expanded.delete(e.id),a.toggleClass("is-collapsed",!d)}),new f.ExtraButtonComponent(i.createDiv({cls:"fflow-header-actions"})).setIcon("trash-2").setTooltip("Delete flow").onClick(async()=>{r.splice(n,1),this.expanded.delete(e.id),await this.saveAndRedraw()}).extraSettingsEl.addEventListener("click",d=>d.stopPropagation());let g=a.createDiv({cls:"fflow-card-body"}),v=g.createDiv({cls:"fflow-fields"}),y=(d,w="")=>{let x=v.createDiv({cls:`fflow-field ${w}`});return x.createDiv({cls:"fflow-label",text:d}),x};new f.TextComponent(y("Name","is-wide")).setPlaceholder("Status").setValue(e.name).onChange(async d=>{e.name=d,p(),await this.save()});let ie=y("Symbol","is-narrow"),S=new f.TextComponent(ie).setPlaceholder("\u2014").setValue(e.symbol);S.inputEl.addClass("fflow-symbol"),(0,f.setTooltip)(S.inputEl,`Optional. One character, not a letter or digit. Reserved: ${L.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(d=>d()),await this.save()};new f.TextComponent(b).setPlaceholder("type").setValue(e.condition.property).onChange(async d=>{e.condition.property=d.trim(),await _()}),b.createSpan({cls:"fflow-equals",text:"="}),new f.TextComponent(b).setPlaceholder("project, area (empty: any value)").setValue(e.condition.values).onChange(async d=>{e.condition.values=d,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 ae=g.createDiv({cls:"fflow-error"}),$=()=>{let d=E(S.getValue()),w=d?null:te(r,n);ae.setText(d!=null?d:w?`Never runs: \u201C${w.name||w.property}\u201D takes ${e.symbol} on the same notes first.`:""),S.inputEl.toggleClass("is-invalid",d!==null)};if(this.refreshers.push($),$(),S.onChange(async d=>{if(E(d)){$();return}e.symbol=d,p(),this.refreshers.forEach(w=>w()),await this.save()}),new f.TextComponent(y("Property","is-wide")).setPlaceholder("status").setValue(e.property).onChange(async d=>{e.property=d.trim(),p(),await this.save()}),new f.DropdownComponent(y("Kind")).addOptions({ordered:"Ordered list",open:"Open (vault)"}).setValue(e.kind).onChange(async d=>{e.kind=d,await this.saveAndRedraw()}),e.kind==="open"){new f.DropdownComponent(y("Values")).addOptions({single:"Single value",list:"List"}).setValue(e.valueMode).onChange(async d=>{e.valueMode=d,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 d=>{e.loop=d,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((d,w)=>this.renderStep(q,e,d,w,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,h)=>{let g=l.createDiv({cls:"fflow-effect"});new f.TextComponent(g).setPlaceholder("property").setValue(p.property).onChange(async v=>{p.property=v.trim(),await this.save()}),g.createSpan({cls:"fflow-equals",text:"="}),new f.TextComponent(g).setPlaceholder("value (lists: a, b)").setValue(p.value).onChange(async v=>{p.value=v,await this.save()}),new f.ExtraButtonComponent(g).setIcon("minus").setTooltip("Remove this property").onClick(async()=>{n.effects.splice(h,1),await this.saveAndRedraw()})}),se(l,"property",async()=>{n.effects.push({property:"",value:""}),await this.saveAndRedraw()});let c=i.createDiv({cls:"fflow-step-actions"}),u=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(()=>u(r-1)),new f.ExtraButtonComponent(c).setIcon("arrow-down").setTooltip("Move down").setDisabled(r===e.steps.length-1).onClick(()=>u(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(s,o,t){let e=s.createEl("button",{cls:"fflow-add clickable-icon"});(0,f.setIcon)(e.createSpan(),"plus"),e.createSpan({text:o}),e.addEventListener("click",()=>void t())}var m=require("obsidian");var P=class{constructor(o){this.app=o;this.cache=new Map}invalidate(){this.cache.clear()}get(o){var e,n,r;let t=this.cache.get(o);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[o];for(let l of new Set(oe(i)))t.set(l,((r=t.get(l))!=null?r:0)+1)}return this.cache.set(o,t),t}};function oe(s){return Array.isArray(s)?s.flatMap(oe):typeof s=="string"?s.trim()?[s.trim()]:[]:typeof s=="number"||typeof s=="boolean"?[String(s)]:[]}var K=s=>s!==void 0&&/\s/.test(s),V=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(h=>h.symbol===l&&h.property);if(c.length===0||Se(e,t.line)||be(e,t.line,r.slice(0,a)))return null;let u=Fe(e),p=k(c,u);return p?(this.flow=p,this.renderHeader(p,u),{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,u=>{e.kind==="ordered"?M(this.app,u,e,n):Z(u,e.property,n,e.valueMode==="list")})}catch(u){console.error("FFLOW: could not update frontmatter",u),new m.Notice(`FFLOW: could not set "${e.property}". See console.`)}}};function Fe(s){let o=(0,m.getFrontMatterInfo)(s.getValue());if(!o.exists)return null;try{let t=(0,m.parseYaml)(o.frontmatter);return t&&typeof t=="object"?t:null}catch(t){return null}}function Se(s,o){if(s.getLine(0)!=="---")return!1;for(let t=1;t<s.lineCount();t++)if(s.getLine(t)==="---")return o<=t;return!1}function be(s,o,t){var n,r;let e=0;for(let a=0;a<o;a++)/^\s*(```|~~~)/.test(s.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 re.Plugin{constructor(){super(...arguments);this.flowCommands=new D(this)}async onload(){let t=await this.loadData();this.settings=ne(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 V(this.app,this,e)),this.flowCommands.sync(),this.addSettingTab(new A(this.app,this))}async saveSettings(){await this.saveData(this.settings),this.flowCommands.sync()}};