diff --git a/README.md b/README.md index 28bc974..e35c1b5 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ The top of the popup says what the pick will do: **Set** a property that is empt ## Flows -Everything is a flow (Settings → FFLOW). A flow has: +Everything is a flow (Settings → FFLOW). Each card's header has **Duplicate** (copies the flow right below it, named "… (copy)", with its own hotkey commands) and **Delete**. A flow has: - **Name**: labels its hotkey commands. - **Symbol** (optional): one character that is not a letter, digit or space. `# [ / :` are reserved (tags, links, slash commands, emoji). It fires only at the start of a word (line start or after a space), never inside frontmatter or code. diff --git a/ROADMAP.md b/ROADMAP.md index 20223ce..a21eb3e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -10,6 +10,7 @@ Nothing planned. ## Done +- 0.6.0 — Duplicate a flow from its card header: an independent deep copy inserted right below, with a unique name and id and its own next/previous commands. Keeps the original symbol and conditions. - 0.5.0 — Conditional flows: "only on notes where property = values". Several flows can share a symbol; the note's frontmatter picks the flow. Per-flow next/previous commands only run on matching notes; flows sharing a symbol also get a shared pair. The popup header shows the property and whether the pick sets, replaces or adds. Default symbol for Type is now `&`. - 0.4.0 — Date/time values in "also sets": `{{date}}`, `{{time}}`, `{{date:FORMAT}}`, `{{time:FORMAT}}` (moment.js). Leaving the step removes a date the flow wrote. - 0.3.1 — Settings redesigned: collapsible flow cards with a step summary, one row of labelled fields, steps as a table with their "also sets" properties. diff --git a/main.js b/main.js index 05c6e43..7812f49 100644 --- a/main.js +++ b/main.js @@ -2,4 +2,4 @@ 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{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;te.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()}}; +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{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;te.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()}}; diff --git a/manifest.json b/manifest.json index 9845443..d5df704 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "fflow", "name": "FFLOW", - "version": "0.5.0", + "version": "0.6.0", "minAppVersion": "1.11.0", "description": "Frontmatter Flow: type a trigger symbol (like @) to autocomplete and set a frontmatter property.", "author": "Olivier Legendre", diff --git a/package.json b/package.json index cbd8e02..21512bb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fflow", - "version": "0.5.0", + "version": "0.6.0", "description": "Frontmatter Flow: set properties from the editor with trigger symbols.", "main": "main.js", "scripts": { diff --git a/src/settings-tab.ts b/src/settings-tab.ts index 009a786..8366fad 100644 --- a/src/settings-tab.ts +++ b/src/settings-tab.ts @@ -11,7 +11,17 @@ import { ToggleComponent, } from "obsidian"; import type FflowPlugin from "./main"; -import { BLOCKED_SYMBOLS, Flow, FlowKind, FlowStep, newFlow, shadowingFlow, symbolError, ValueMode } from "./settings"; +import { + BLOCKED_SYMBOLS, + duplicateFlow, + Flow, + FlowKind, + FlowStep, + newFlow, + shadowingFlow, + symbolError, + ValueMode, +} from "./settings"; export class FflowSettingTab extends PluginSettingTab { /** Flows shown open. Kept across redraws, not saved: every visit starts with compact cards. */ @@ -93,7 +103,18 @@ export class FflowSettingTab extends PluginSettingTab { else this.expanded.delete(flow.id); card.toggleClass("is-collapsed", !open); }); - const remove = new ExtraButtonComponent(header.createDiv({ cls: "fflow-header-actions" })) + const actions = header.createDiv({ cls: "fflow-header-actions" }); + actions.addEventListener("click", (e) => e.stopPropagation()); + new ExtraButtonComponent(actions) + .setIcon("copy") + .setTooltip("Duplicate flow") + .onClick(async () => { + const copy = duplicateFlow(flow, flows); + flows.splice(index + 1, 0, copy); + this.expanded.add(copy.id); + await this.saveAndRedraw(); + }); + new ExtraButtonComponent(actions) .setIcon("trash-2") .setTooltip("Delete flow") .onClick(async () => { @@ -101,7 +122,6 @@ export class FflowSettingTab extends PluginSettingTab { this.expanded.delete(flow.id); await this.saveAndRedraw(); }); - remove.extraSettingsEl.addEventListener("click", (e) => e.stopPropagation()); const body = card.createDiv({ cls: "fflow-card-body" }); diff --git a/src/settings.ts b/src/settings.ts index a0d61fd..189adf1 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -59,6 +59,16 @@ export function newFlow(fields: Partial): Flow { }; } +/** A deep copy of `flow` with a fresh id (so its own commands) and a name no other flow uses: "Status (copy)", "Status (copy 2)"… */ +export function duplicateFlow(flow: Flow, flows: Flow[]): Flow { + const base = flow.name || flow.property || "New flow"; + const taken = new Set(flows.map((f) => f.name)); + let name = `${base} (copy)`; + for (let n = 2; taken.has(name); n++) name = `${base} (copy ${n})`; + const { id: _id, ...fields } = structuredClone(flow); + return newFlow({ ...fields, name }); +} + export function defaultSettings(): FflowSettings { return { flows: [newFlow({ name: "Type", symbol: "&", property: "type", kind: "open" })] }; }