From 60582bcb03f06f106f51a17f4bfcdceaa764ccb6 Mon Sep 17 00:00:00 2001 From: Olivier Date: Tue, 27 Oct 2026 12:58:58 -0400 Subject: [PATCH] FFLOW 0.5.0: conditional flows share symbols; per-flow and per-symbol step commands; popup header shows set/replace/add --- README.md | 22 +++++++++++++-- ROADMAP.md | 1 + main.js | 2 +- manifest.json | 2 +- package-lock.json | 4 +-- package.json | 2 +- src/flows.ts | 52 +++++++++++++++++++++++++----------- src/settings-tab.ts | 65 ++++++++++++++++++++++++++++++++++++++++----- src/settings.ts | 61 ++++++++++++++++++++++++++++++++++++++---- src/suggest.ts | 64 +++++++++++++++++++++++++++++++++++++++----- styles.css | 56 ++++++++++++++++++++++++++++++++++++++ 11 files changed, 291 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index e41871d..28bc974 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,9 @@ Set frontmatter properties from the editor with trigger symbols, the way `#` autocompletes tags. -Type `@mee`, pick `meeting`: the text `@mee` disappears and the note gets `type: meeting`. +Type `&mee`, pick `meeting`: the text `&mee` disappears and the note gets `type: meeting`. + +The top of the popup says what the pick will do: **Set** a property that is empty, **Replace** its current value (shown), or **Add to** a list. ## Flows @@ -12,8 +14,24 @@ Everything is a flow (Settings → FFLOW). A flow has: - **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. - **Property**: the frontmatter key the flow sets. - **Kind**: - - **Ordered list**: fixed steps, in order. Each step can also set other properties (**Also sets**). Gets **FFLOW: : next step** / **previous step** commands for hotkeys; **Loop** wraps around at the ends. + - **Ordered list**: fixed steps, in order. Each step can also set other properties (**Also sets**). Gets next/previous step commands for hotkeys (see below); **Loop** wraps around at the ends. Also the way to offer a fixed list of values: only the listed values are proposed. - **Open (vault)**: suggests every value already used for the property in the vault, ranked by use, and accepts new values. *Single value* replaces, *List* appends without duplicates. No steps, no hotkeys. +- **Only on notes where** (optional): a property and comma-separated values, e.g. `type` = `highlight, source`. The flow runs only on notes whose property holds one of the values (case-insensitive; for a list property, any item). Leave the values empty to match any note where the property is set. + +### Several flows on one symbol + +Flows can share a symbol when they have conditions. On a given note, the first flow whose condition matches runs; a flow without a condition runs when none matches. Example: + +| Symbol | Flow | Only on notes where | Property | +|---|---|---|---| +| `@` | Author | `type` = `highlight, source` | `author` | +| `@` | Participants | `type` = `meeting` | `participants` (list) | +| `!` | Project status | `type` = `project` | `status`: inactive → active → done | +| `!` | Client status | `type` = `business` | `status`: active → inactive | + +On a note that matches none of them, `!` and `@` do nothing. The condition is read from the note as typed, so `&project` then `!` works right away. A flow that can never run (an earlier flow with the same symbol covers the same notes) is flagged in the settings. + +Every ordered flow gets **FFLOW: : next step** / **previous step**, available only on notes its condition matches. Command ids derive from the flow id, so hotkeys and toolbar buttons (e.g. Note Toolbar) survive renames. Ordered flows sharing a symbol also get a shared pair, **FFLOW: ! Project status / Client status: next step** / **previous step**, that moves whichever flow matches the note: one hotkey for every status. ### Step effects diff --git a/ROADMAP.md b/ROADMAP.md index d3aa189..20223ce 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -10,6 +10,7 @@ Nothing planned. ## Done +- 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. - 0.3.0 — Everything is a flow. Ordered flows: steps with "also sets" effects on any property (cssclasses included), undone when leaving the step; symbol and next/previous hotkeys apply the same thing. Open flows: vault values, single or list. Old settings migrated. diff --git a/main.js b/main.js index 810bf2e..05c6e43 100644 --- a/main.js +++ b/main.js @@ -2,4 +2,4 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD */ -var P=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var oe=Object.prototype.hasOwnProperty;var ie=(s,n)=>{for(var t in n)P(s,t,{get:n[t],enumerable:!0})},re=(s,n,t,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of se(n))!oe.call(s,o)&&o!==t&&P(s,o,{get:()=>n[o],enumerable:!(e=ne(n,o))||e.enumerable});return s};var ae=s=>re(P({},"__esModule",{value:!0}),s);var ge={};ie(ge,{default:()=>L});module.exports=ae(ge);var Z=require("obsidian");var I=require("obsidian");var U=require("obsidian");var R=require("obsidian"),Y=String.raw`\{\{(date|time)(?::([^}]*))?\}\}`,le={date:"YYYY-MM-DD",time:"HH:mm"},K=(s,n)=>(n==null?void 0:n.trim())||le[s];function V(s){let n=(0,R.moment)();return s.replace(new RegExp(Y,"g"),(t,e,o)=>n.format(K(e,o)))}function _(s,n){let t=new RegExp(Y,"g"),e=[],o="^",a=0;for(let r=t.exec(s);r;r=t.exec(s))o+=j(s.slice(a,r.index))+"(.+?)",e.push(K(r[1],r[2])),a=r.index+r[0].length;if(e.length===0)return s===n;let i=new RegExp(o+j(s.slice(a))+"$").exec(n);return i!==null&&e.every((r,l)=>(0,R.moment)(i[l+1],r,!0).isValid())}function j(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function x(s,n,t){let e=s.workspace.getActiveViewOfType(U.MarkdownView);(e==null?void 0:e.file)===n&&await e.save(),await s.fileManager.processFrontMatter(n,t)}function z(s,n,t,e){if(!e){s[n]=t;return}let o=O(s[n],n);o.includes(t)||o.push(t),s[n]=o}function b(s,n,t,e){var l;n[t.property]=e;let o=t.steps.find(p=>p.value===e),a=new Map,i=p=>{let d=a.get(p);return d===void 0&&a.set(p,d=pe(s,n,p)),d},r=p=>p.property!==""&&p.property!==t.property;for(let p of t.steps)if(p!==o)for(let d of p.effects.filter(r)){let c=d.property;if(i(c)){let h=W(d.value),g=O(n[c],c).filter(v=>!h.some(w=>q(w,v)));g.length?n[c]=g:delete n[c]}else c in n&&q(d.value,n[c])&&delete n[c]}for(let p of(l=o==null?void 0:o.effects.filter(r))!=null?l:[]){let d=p.property;if(i(d)){let c=O(n[d],d);for(let h of W(p.value).map(V))c.includes(h)||c.push(h);c.length&&(n[d]=c)}else n[d]=G(V(p.value))}}function pe(s,n,t){if(["cssclasses","tags","aliases"].includes(t)||Array.isArray(n[t]))return!0;let e=Reflect.get(s,"metadataTypeManager");if(!e||typeof e!="object"||!("getPropertyInfo"in e)||typeof e.getPropertyInfo!="function")return!1;let o=e.getPropertyInfo(t),a=o&&typeof o=="object"&&"widget"in o?o.widget:null;return a==="multitext"||a==="tags"||a==="aliases"}function O(s,n){return Array.isArray(s)?s.map(String):s==null||s===""?[]:n==="cssclasses"?String(s).split(/[\s,]+/).filter(Boolean):[String(s)]}function W(s){return s.split(/,(?![^{]*\}\})/).map(n=>n.trim()).filter(Boolean)}function q(s,n){let t=s.trim();return String(G(t))===String(n)||_(t,String(n))}function G(s){let n=s.trim();return n===""?null:n==="true"||n==="false"?n==="true":/^-?\d+(\.\d+)?$/.test(n)?Number(n):n}var C=class{constructor(n){this.plugin=n;this.registered=[]}sync(){for(let n of this.registered)this.plugin.removeCommand(n);this.registered=[];for(let n of this.plugin.settings.flows)n.kind==="ordered"&&(this.add(n,1,"next","next step"),this.add(n,-1,"previous","previous step"))}add(n,t,e,o){let a=`flow-${n.id}-${e}`;this.registered.push(a),this.plugin.addCommand({id:a,name:`${n.name||n.property||"Unnamed flow"}: ${o}`,checkCallback:i=>{let r=this.plugin.app.workspace.getActiveFile();return!r||r.extension!=="md"||!n.property||!n.steps.some(l=>l.value)?!1:(i||ce(this.plugin,r,n,t),!0)}})}};async function ce(s,n,t,e){let o=t.steps.filter(i=>i.value),a="";try{await x(s.app,n,i=>{let r=o.findIndex(p=>p.value===String(i[t.property])),l=r===-1?0:r+e;if(l<0||l>=o.length){if(!t.loop){a=`${t.property}: already at the ${e===1?"last":"first"} step`;return}l=(l+o.length)%o.length}b(s.app,i,t,o[l].value),a=`${t.property}: ${o[l].value}`}),new I.Notice(a)}catch(i){console.error("FFLOW: could not move flow step",i),new I.Notice(`FFLOW: could not set "${t.property}". See console.`)}}function y(s){return{id:Date.now().toString(36)+Math.random().toString(36).slice(2,6),name:"",symbol:"",property:"",kind:"ordered",valueMode:"single",loop:!1,steps:[],...s}}function ue(){return{flows:[y({name:"Type",symbol:"@",property:"type",kind:"open"})]}}var E=["#","[","/",":"];function S(s,n,t){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.":E.includes(s)?`"${s}" is reserved (${E.join(" ")}).`:n.some((e,o)=>o!==t&&e.symbol===s)?`"${s}" is already used by another flow.`:null}function J(s){var o,a;if(!s||typeof s!="object")return ue();if("flows"in s&&!("rules"in s)&&Array.isArray(s.flows))return{flows:s.flows.map(i=>y(i))};let n=s,t=(o=n.rules)!=null?o:[],e=((a=n.flows)!=null?a:[]).map(i=>{var r,l;return y({id:i.id,name:i.name,property:i.property,loop:i.loop,symbol:(l=(r=t.find(p=>p.source==="flow"&&p.flowId===i.id))==null?void 0:r.symbol)!=null?l:"",steps:i.steps.map(p=>({value:p.value,effects:p.cssclass.trim()?[{property:"cssclasses",value:p.cssclass.trim().split(/\s+/).join(", ")}]:[]}))})});for(let i of t)i.source==="open"&&e.push(y({name:i.property,symbol:i.symbol,property:i.property,kind:"open",valueMode:i.valueMode})),i.source==="finite"&&e.push(y({name:i.property,symbol:i.symbol,property:i.property,steps:i.values.map(r=>({value:r,effects:[]}))}));return{flows:e}}var u=require("obsidian");var k=class extends u.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e;this.expanded=new Set;this.save=()=>this.plugin.saveSettings()}async saveAndRedraw(){await this.save(),this.display()}display(){let{containerEl:t}=this,e=this.plugin.settings.flows;t.empty(),new u.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(a=>a.setButtonText("Hotkeys").onClick(()=>this.openHotkeys())).addButton(a=>a.setButtonText("Add flow").setCta().onClick(async()=>{let i=y({steps:[{value:"",effects:[]}]});e.push(i),this.expanded.add(i.id),await this.saveAndRedraw()}));let o=t.createDiv({cls:"fflow-list"});e.forEach((a,i)=>this.renderFlow(o,a,i)),e.length===0&&o.createDiv({cls:"fflow-empty",text:"No flows yet."})}renderFlow(t,e,o){var B;let a=this.plugin.settings.flows,i=t.createDiv({cls:"fflow-card"});i.toggleClass("is-collapsed",!this.expanded.has(e.id));let r=i.createDiv({cls:"fflow-card-header"});(0,u.setIcon)(r.createSpan({cls:"fflow-chevron"}),"chevron-right");let l=r.createSpan({cls:"fflow-badge"}),p=r.createSpan({cls:"fflow-title"}),d=r.createSpan({cls:"fflow-summary"}),c=()=>{l.setText(e.symbol),l.toggle(e.symbol!==""),p.setText(e.name||e.property||"New flow");let f=e.steps.map(m=>m.value).filter(Boolean);d.setText([e.property,e.kind==="open"?"open list":f.join(" \u2192 ")||"no steps"].filter(Boolean).join(" \xB7 "))};c(),r.addEventListener("click",()=>{let f=!this.expanded.has(e.id);f?this.expanded.add(e.id):this.expanded.delete(e.id),i.toggleClass("is-collapsed",!f)}),new u.ExtraButtonComponent(r.createDiv({cls:"fflow-header-actions"})).setIcon("trash-2").setTooltip("Delete flow").onClick(async()=>{a.splice(o,1),this.expanded.delete(e.id),await this.saveAndRedraw()}).extraSettingsEl.addEventListener("click",f=>f.stopPropagation());let g=i.createDiv({cls:"fflow-card-body"}),v=g.createDiv({cls:"fflow-fields"}),w=(f,m="")=>{let H=v.createDiv({cls:`fflow-field ${m}`});return H.createDiv({cls:"fflow-label",text:f}),H};new u.TextComponent(w("Name","is-wide")).setPlaceholder("Status").setValue(e.name).onChange(async f=>{e.name=f,c(),await this.save()});let ee=w("Symbol","is-narrow"),F=new u.TextComponent(ee).setPlaceholder("\u2014").setValue(e.symbol);F.inputEl.addClass("fflow-symbol"),(0,u.setTooltip)(F.inputEl,`Optional. One character, not a letter or digit. Reserved: ${E.join(" ")}`);let te=g.createDiv({cls:"fflow-error",text:(B=S(e.symbol,a,o))!=null?B:""});if(F.onChange(async f=>{let m=S(f,a,o);te.setText(m!=null?m:""),F.inputEl.toggleClass("is-invalid",m!==null),!m&&(e.symbol=f,c(),await this.save())}),new u.TextComponent(w("Property","is-wide")).setPlaceholder("status").setValue(e.property).onChange(async f=>{e.property=f.trim(),c(),await this.save()}),new u.DropdownComponent(w("Kind")).addOptions({ordered:"Ordered list",open:"Open (vault)"}).setValue(e.kind).onChange(async f=>{e.kind=f,await this.saveAndRedraw()}),e.kind==="open"){new u.DropdownComponent(w("Values")).addOptions({single:"Single value",list:"List"}).setValue(e.valueMode).onChange(async f=>{e.valueMode=f,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 u.ToggleComponent(w("Loop","is-toggle")).setValue(e.loop).setTooltip("After the last step, \u201Cnext\u201D goes back to the first").onChange(async f=>{e.loop=f,await this.save()});let $=g.createDiv({cls:"fflow-steps"}),A=$.createDiv({cls:"fflow-step-row fflow-steps-head"});A.createSpan(),A.createSpan({text:"Value"}),A.createSpan({text:"Also sets"}),e.steps.forEach((f,m)=>this.renderStep($,e,f,m,c)),Q(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,o,a,i){let r=t.createDiv({cls:"fflow-step-row"});r.createSpan({cls:"fflow-step-num",text:String(a+1)}),new u.TextComponent(r.createDiv({cls:"fflow-step-value"})).setPlaceholder("value").setValue(o.value).onChange(async c=>{o.value=c.trim(),i(),await this.save()});let l=r.createDiv({cls:"fflow-effects"});o.effects.forEach((c,h)=>{let g=l.createDiv({cls:"fflow-effect"});new u.TextComponent(g).setPlaceholder("property").setValue(c.property).onChange(async v=>{c.property=v.trim(),await this.save()}),g.createSpan({cls:"fflow-equals",text:"="}),new u.TextComponent(g).setPlaceholder("value (lists: a, b)").setValue(c.value).onChange(async v=>{c.value=v,await this.save()}),new u.ExtraButtonComponent(g).setIcon("minus").setTooltip("Remove this property").onClick(async()=>{o.effects.splice(h,1),await this.saveAndRedraw()})}),Q(l,"property",async()=>{o.effects.push({property:"",value:""}),await this.saveAndRedraw()});let p=r.createDiv({cls:"fflow-step-actions"}),d=async c=>{e.steps.splice(c,0,...e.steps.splice(a,1)),await this.saveAndRedraw()};new u.ExtraButtonComponent(p).setIcon("arrow-up").setTooltip("Move up").setDisabled(a===0).onClick(()=>d(a-1)),new u.ExtraButtonComponent(p).setIcon("arrow-down").setTooltip("Move down").setDisabled(a===e.steps.length-1).onClick(()=>d(a+1)),new u.ExtraButtonComponent(p).setIcon("trash-2").setTooltip("Delete step").onClick(async()=>{e.steps.splice(a,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"),o=e&&typeof e=="object"&&"searchComponent"in e?e.searchComponent:null;o instanceof u.SearchComponent&&(o.setValue(this.plugin.manifest.name),o.inputEl.dispatchEvent(new Event("input")))}};function Q(s,n,t){let e=s.createEl("button",{cls:"fflow-add clickable-icon"});(0,u.setIcon)(e.createSpan(),"plus"),e.createSpan({text:n}),e.addEventListener("click",()=>void t())}var M=require("obsidian");var T=class{constructor(n){this.app=n;this.cache=new Map}invalidate(){this.cache.clear()}get(n){var e,o,a;let t=this.cache.get(n);if(t)return t;t=new Map;for(let i of this.app.vault.getMarkdownFiles()){let r=(o=(e=this.app.metadataCache.getFileCache(i))==null?void 0:e.frontmatter)==null?void 0:o[n];for(let l of new Set(X(r)))t.set(l,((a=t.get(l))!=null?a:0)+1)}return this.cache.set(n,t),t}};function X(s){return Array.isArray(s)?s.flatMap(X):typeof s=="string"?s.trim()?[s.trim()]:[]:typeof s=="number"||typeof s=="boolean"?[String(s)]:[]}var N=s=>s!==void 0&&/\s/.test(s),D=class extends M.EditorSuggest{constructor(t,e,o){super(t);this.plugin=e;this.index=o;this.flow=null}onTrigger(t,e,o){let a=e.getLine(t.line).slice(0,t.ch),i=a.length;for(;i>0&&!N(a[i-1]);)i--;let r=a.slice(i);if(!r)return null;let l=this.plugin.settings.flows,p=l.findIndex(c=>c.symbol!==""&&c.symbol===r[0]),d=l[p];return!d||!d.property||S(d.symbol,l,p)||de(e,t.line)||fe(e,t.line,a.slice(0,i))?null:(this.flow=d,{start:{line:t.line,ch:i},end:t,query:r.slice(1)})}getSuggestions(t){let e=this.flow;if(!e)return[];let o=t.query.toLowerCase(),a=e.kind==="ordered"?e.steps.filter(r=>r.value).map(r=>({value:r.value,isNew:!1})):[...this.index.get(e.property)].sort((r,l)=>l[1]-r[1]||r[0].localeCompare(l[0])).map(([r,l])=>({value:r,count:l,isNew:!1})),i=a.filter(r=>r.value.toLowerCase().includes(o));return i.sort((r,l)=>+!r.value.toLowerCase().startsWith(o)-+!l.value.toLowerCase().startsWith(o)),e.kind==="open"&&o&&!a.some(r=>r.value.toLowerCase()===o)&&i.push({value:t.query,isNew:!0}),i}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 o=this.context,a=this.flow;!o||!a||this.apply(o,a,t.value)}async apply(t,e,o){let{editor:a,file:i,start:r}=t,l=a.getLine(r.line),p=t.end.ch;for(;p{e.kind==="ordered"?b(this.app,d,e,o):z(d,e.property,o,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 de(s,n){if(s.getLine(0)!=="---")return!1;for(let t=1;te.invalidate())),this.registerEvent(this.app.metadataCache.on("deleted",()=>e.invalidate())),this.registerEditorSuggest(new D(this.app,this,e)),this.flowCommands.sync(),this.addSettingTab(new k(this.app,this))}async saveSettings(){await this.saveData(this.settings),this.flowCommands.sync()}}; +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()}}; diff --git a/manifest.json b/manifest.json index fda0c12..9845443 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "fflow", "name": "FFLOW", - "version": "0.4.0", + "version": "0.5.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-lock.json b/package-lock.json index 53ab362..78ce89c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "fflow", - "version": "0.1.0", + "version": "0.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "fflow", - "version": "0.1.0", + "version": "0.5.0", "license": "MIT", "devDependencies": { "builtin-modules": "4.0.0", diff --git a/package.json b/package.json index 44e3a16..cbd8e02 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fflow", - "version": "0.4.0", + "version": "0.5.0", "description": "Frontmatter Flow: set properties from the editor with trigger symbols.", "main": "main.js", "scripts": { diff --git a/src/flows.ts b/src/flows.ts index 64db862..cd0ed69 100644 --- a/src/flows.ts +++ b/src/flows.ts @@ -1,11 +1,15 @@ import { Notice, TFile } from "obsidian"; import { setFlowStep, updateFrontmatter } from "./frontmatter"; import type FflowPlugin from "./main"; -import type { Flow } from "./settings"; +import { Flow, pickFlow } from "./settings"; type Direction = 1 | -1; -/** Re-registers the next/previous commands of every ordered flow. Ids derive from the flow id, so hotkeys survive renames. */ +/** + * Re-registers the next/previous commands of ordered flows. Every flow gets its own pair, available only on notes its + * condition matches; ids derive from the flow id, so hotkeys and toolbar buttons survive renames. Flows sharing a symbol + * also get a shared pair that runs whichever of them matches the note, so one hotkey moves a project's or a client's status. + */ export class FlowCommands { private registered: string[] = []; @@ -14,35 +18,53 @@ export class FlowCommands { sync(): void { for (const id of this.registered) this.plugin.removeCommand(id); this.registered = []; + + const bySymbol = new Map(); for (const flow of this.plugin.settings.flows) { if (flow.kind !== "ordered") continue; - this.add(flow, 1, "next", "next step"); - this.add(flow, -1, "previous", "previous step"); + const name = flow.name || flow.property || "Unnamed flow"; + this.add([flow], `flow-${flow.id}-next`, `${name}: next step`, 1); + this.add([flow], `flow-${flow.id}-previous`, `${name}: previous step`, -1); + if (flow.symbol) bySymbol.set(flow.symbol, [...(bySymbol.get(flow.symbol) ?? []), flow]); + } + for (const [symbol, flows] of bySymbol) { + if (flows.length < 2) continue; + const id = `symbol-${symbol.codePointAt(0)?.toString(16)}`; + const label = `${symbol} ${flows.map((f) => f.name || f.property || "Unnamed flow").join(" / ")}`; + this.add(flows, `${id}-next`, `${label}: next step`, 1); + this.add(flows, `${id}-previous`, `${label}: previous step`, -1); } } - private add(flow: Flow, direction: Direction, suffix: string, label: string): void { - const id = `flow-${flow.id}-${suffix}`; + private add(flows: Flow[], id: string, name: string, direction: Direction): void { this.registered.push(id); this.plugin.addCommand({ id, - name: `${flow.name || flow.property || "Unnamed flow"}: ${label}`, + name, checkCallback: (checking) => { - const file = this.plugin.app.workspace.getActiveFile(); - if (!file || file.extension !== "md" || !flow.property || !flow.steps.some((s) => s.value)) return false; - if (!checking) void moveStep(this.plugin, file, flow, direction); + const app = this.plugin.app; + const file = app.workspace.getActiveFile(); + if (!file || file.extension !== "md") return false; + const flow = pickFlow(flows, app.metadataCache.getFileCache(file)?.frontmatter ?? null); + if (!flow?.property || !flow.steps.some((s) => s.value)) return false; + if (!checking) void moveStep(this.plugin, file, flows, direction); return true; }, }); } } -async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction: Direction): Promise { - const steps = flow.steps.filter((s) => s.value); +async function moveStep(plugin: FflowPlugin, file: TFile, flows: Flow[], direction: Direction): Promise { let message = ""; + let property = ""; try { - // Read the current value inside the update: the metadata cache can lag behind the editor. + // Read the current values inside the update: the metadata cache can lag behind the editor. await updateFrontmatter(plugin.app, file, (fm) => { + const flow = pickFlow(flows, fm); + if (!flow?.property) return; + property = flow.property; + const steps = flow.steps.filter((s) => s.value); + if (steps.length === 0) return; const index = steps.findIndex((s) => s.value === String(fm[flow.property])); // A note outside the flow (no value, or a value not in the steps) enters at the first step. let target = index === -1 ? 0 : index + direction; @@ -56,9 +78,9 @@ async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction: setFlowStep(plugin.app, fm, flow, steps[target].value); message = `${flow.property}: ${steps[target].value}`; }); - new Notice(message); + if (message) new Notice(message); } catch (err) { console.error("FFLOW: could not move flow step", err); - new Notice(`FFLOW: could not set "${flow.property}". See console.`); + new Notice(`FFLOW: could not set "${property}". See console.`); } } diff --git a/src/settings-tab.ts b/src/settings-tab.ts index 37bdc8d..009a786 100644 --- a/src/settings-tab.ts +++ b/src/settings-tab.ts @@ -11,11 +11,13 @@ import { ToggleComponent, } from "obsidian"; import type FflowPlugin from "./main"; -import { BLOCKED_SYMBOLS, Flow, FlowKind, FlowStep, newFlow, symbolError, ValueMode } from "./settings"; +import { BLOCKED_SYMBOLS, 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. */ private expanded = new Set(); + /** Re-check every card's symbol message: a symbol or condition change in one flow can shadow another. */ + private refreshers: (() => void)[] = []; constructor(app: App, private plugin: FflowPlugin) { super(app, plugin); @@ -33,6 +35,7 @@ export class FflowSettingTab extends PluginSettingTab { const { containerEl } = this; const flows = this.plugin.settings.flows; containerEl.empty(); + this.refreshers = []; new Setting(containerEl) .setHeading() @@ -72,8 +75,15 @@ export class FflowSettingTab extends PluginSettingTab { badge.toggle(flow.symbol !== ""); title.setText(flow.name || flow.property || "New flow"); const values = flow.steps.map((s) => s.value).filter(Boolean); + const { property, values: when } = flow.condition; summary.setText( - [flow.property, flow.kind === "open" ? "open list" : values.join(" → ") || "no steps"].filter(Boolean).join(" · "), + [ + flow.property, + property && `when ${property}${when.trim() ? ` = ${when.trim()}` : ""}`, + flow.kind === "open" ? "open list" : values.join(" → ") || "no steps", + ] + .filter(Boolean) + .join(" · "), ); }; updateHeader(); @@ -116,15 +126,56 @@ export class FflowSettingTab extends PluginSettingTab { const symbol = new TextComponent(symbolField).setPlaceholder("—").setValue(flow.symbol); symbol.inputEl.addClass("fflow-symbol"); setTooltip(symbol.inputEl, `Optional. One character, not a letter or digit. Reserved: ${BLOCKED_SYMBOLS.join(" ")}`); - const error = body.createDiv({ cls: "fflow-error", text: symbolError(flow.symbol, flows, index) ?? "" }); - symbol.onChange(async (value) => { - const problem = symbolError(value, flows, index); - error.setText(problem ?? ""); + + // Condition: lets several flows share a symbol, each on its own notes. + const when = body.createDiv({ cls: "fflow-fields fflow-when" }); + when.createDiv({ cls: "fflow-label", text: "Only on notes where" }); + const onCondition = async () => { + updateHeader(); + this.refreshers.forEach((refresh) => refresh()); + await this.save(); + }; + new TextComponent(when) + .setPlaceholder("type") + .setValue(flow.condition.property) + .onChange(async (value) => { + flow.condition.property = value.trim(); + await onCondition(); + }); + when.createSpan({ cls: "fflow-equals", text: "=" }); + const whenValues = new TextComponent(when) + .setPlaceholder("project, area (empty: any value)") + .setValue(flow.condition.values) + .onChange(async (value) => { + flow.condition.values = value; + await onCondition(); + }); + whenValues.inputEl.addClass("fflow-when-values"); + setTooltip( + when, + "Leave the property empty to use this flow on every note. Flows sharing a symbol: a matching condition wins over a flow without one.", + ); + + const error = body.createDiv({ cls: "fflow-error" }); + const refresh = () => { + const problem = symbolError(symbol.getValue()); + const other = problem ? null : shadowingFlow(flows, index); + error.setText( + problem ?? (other ? `Never runs: “${other.name || other.property}” takes ${flow.symbol} on the same notes first.` : ""), + ); symbol.inputEl.toggleClass("is-invalid", problem !== null); + }; + this.refreshers.push(refresh); + refresh(); + symbol.onChange(async (value) => { // Invalid input stays in the field but is never saved. - if (problem) return; + if (symbolError(value)) { + refresh(); + return; + } flow.symbol = value; updateHeader(); + this.refreshers.forEach((r) => r()); await this.save(); }); diff --git a/src/settings.ts b/src/settings.ts index dc6a160..a0d61fd 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -15,6 +15,15 @@ export interface FlowStep { effects: FlowEffect[]; } +/** + * Limits a flow to notes whose `property` holds one of `values` (comma-separated, case-insensitive; list properties match + * if any item matches). No property: every note. No values: any note where the property has a value. + */ +export interface FlowCondition { + property: string; + values: string; +} + export interface Flow { /** Stable id: command ids derive from it, so hotkeys survive renames. */ id: string; @@ -27,6 +36,8 @@ export interface Flow { /** After the last step, "next" goes back to the first (and "previous" the other way). */ loop: boolean; steps: FlowStep[]; + /** Several flows can share a symbol: the note's frontmatter decides which one runs. */ + condition: FlowCondition; } export interface FflowSettings { @@ -43,24 +54,64 @@ export function newFlow(fields: Partial): Flow { valueMode: "single", loop: false, steps: [], + condition: { property: "", values: "" }, ...fields, }; } export function defaultSettings(): FflowSettings { - return { flows: [newFlow({ name: "Type", symbol: "@", property: "type", kind: "open" })] }; + return { flows: [newFlow({ name: "Type", symbol: "&", property: "type", kind: "open" })] }; +} + +const conditionValues = (c: FlowCondition) => + c.values + .split(",") + .map((v) => v.trim().toLowerCase()) + .filter(Boolean); + +const isConditional = (flow: Flow) => flow.condition.property !== ""; + +function matches(flow: Flow, fm: Record | null): boolean { + if (!isConditional(flow)) return true; + const raw = fm?.[flow.condition.property]; + const actual = (Array.isArray(raw) ? raw : [raw]) + .filter((v) => v !== null && v !== undefined && String(v).trim() !== "") + .map((v) => String(v).trim().toLowerCase()); + const wanted = conditionValues(flow.condition); + return wanted.length === 0 ? actual.length > 0 : actual.some((v) => wanted.includes(v)); +} + +/** The flow that runs on a note: the first matching flow with a condition, else the first one without. */ +export function pickFlow(candidates: Flow[], fm: Record | null): Flow | null { + return candidates.find((f) => isConditional(f) && matches(f, fm)) ?? candidates.find((f) => !isConditional(f)) ?? null; +} + +/** An earlier flow with the same symbol that always wins over flow `index`, so `index` never runs; null if none. */ +export function shadowingFlow(flows: Flow[], index: number): Flow | null { + const flow = flows[index]; + if (!flow.symbol) return null; + const wanted = conditionValues(flow.condition); + return ( + flows.slice(0, index).find((other) => { + if (other.symbol !== flow.symbol) return false; + if (!isConditional(flow)) return !isConditional(other); + if (other.condition.property !== flow.condition.property) return false; + const otherValues = conditionValues(other.condition); + // Empty values match any value, so they cover every value list. + return otherValues.length === 0 || (wanted.length > 0 && wanted.every((v) => otherValues.includes(v))); + }) ?? null + ); } /** Reserved by Obsidian or common plugins: tags, links, slash commands, emoji shortcodes. */ export const BLOCKED_SYMBOLS = ["#", "[", "/", ":"]; -/** Returns an error message, or null when `symbol` is usable by flow `index`. Empty means "no trigger" and is valid. */ -export function symbolError(symbol: string, flows: Flow[], index: number): string | null { +/** Returns an error message, or null when `symbol` is a usable trigger. Empty means "no trigger" and is valid. */ +export function symbolError(symbol: string): string | null { if (symbol === "") return null; if ([...symbol].length !== 1) return "Use exactly one character."; if (/[\p{L}\p{N}\s]/u.test(symbol)) return "Letters, digits and spaces are not allowed."; if (BLOCKED_SYMBOLS.includes(symbol)) return `"${symbol}" is reserved (${BLOCKED_SYMBOLS.join(" ")}).`; - if (flows.some((f, i) => i !== index && f.symbol === symbol)) return `"${symbol}" is already used by another flow.`; return null; } @@ -86,7 +137,7 @@ export function loadSettings(saved: unknown): FflowSettings { if (!saved || typeof saved !== "object") return defaultSettings(); if ("flows" in saved && !("rules" in saved) && Array.isArray(saved.flows)) { // Current format: fill fields added since the flow was saved. - return { flows: saved.flows.map((f: Partial) => newFlow(f)) }; + return { flows: saved.flows.map((f: Partial) => newFlow({ ...f, condition: { property: "", values: "", ...f.condition } })) }; } // Own persisted blob from an older version of this plugin; fields were always written together. diff --git a/src/suggest.ts b/src/suggest.ts index 544300e..397b166 100644 --- a/src/suggest.ts +++ b/src/suggest.ts @@ -1,7 +1,19 @@ -import { App, Editor, EditorPosition, EditorSuggest, EditorSuggestContext, EditorSuggestTriggerInfo, Notice, TFile } from "obsidian"; +import { + App, + Editor, + EditorPosition, + EditorSuggest, + EditorSuggestContext, + EditorSuggestTriggerInfo, + getFrontMatterInfo, + Notice, + parseYaml, + setIcon, + TFile, +} from "obsidian"; import { setFlowStep, setOpenValue, updateFrontmatter } from "./frontmatter"; import type FflowPlugin from "./main"; -import { Flow, symbolError } from "./settings"; +import { Flow, pickFlow, symbolError } from "./settings"; interface Suggestion { value: string; @@ -44,9 +56,17 @@ const isSpace = (ch: string | undefined) => ch !== undefined && /\s/.test(ch); export class TriggerSuggest extends EditorSuggest { private flow: Flow | null = null; + /** "Replace status (active)" / "Add to participants", above the suggestions. */ + private header: HTMLElement | null = null; constructor(app: App, private plugin: FflowPlugin, private index: ValueIndex) { super(app); + // `suggestEl` (the popup container) is internal API: probe it, and go without a header if it changes. + const container: unknown = Reflect.get(this, "suggestEl"); + if (container instanceof HTMLElement) { + this.header = container.createDiv({ cls: "fflow-header" }); + container.prepend(this.header); + } } onTrigger(cursor: EditorPosition, editor: Editor, _file: TFile | null): EditorSuggestTriggerInfo | null { @@ -57,16 +77,35 @@ export class TriggerSuggest extends EditorSuggest { const word = before.slice(start); if (!word) return null; - const flows = this.plugin.settings.flows; - const index = flows.findIndex((f) => f.symbol !== "" && f.symbol === word[0]); - const flow = flows[index]; - if (!flow || !flow.property || symbolError(flow.symbol, flows, index)) return null; + const symbol = word[0]; + if (symbolError(symbol)) return null; + const candidates = this.plugin.settings.flows.filter((f) => f.symbol === symbol && f.property); + if (candidates.length === 0) return null; if (inFrontmatter(editor, cursor.line) || inCode(editor, cursor.line, before.slice(0, start))) return null; + const fm = readFrontmatter(editor); + const flow = pickFlow(candidates, fm); + if (!flow) return null; + this.flow = flow; + this.renderHeader(flow, fm); return { start: { line: cursor.line, ch: start }, end: cursor, query: word.slice(1) }; } + private renderHeader(flow: Flow, fm: Record | null): void { + const header = this.header; + if (!header) return; + header.empty(); + const raw = fm?.[flow.property]; + const current = (Array.isArray(raw) ? raw : [raw]).filter((v) => v !== null && v !== undefined && String(v) !== ""); + const adds = flow.kind === "open" && flow.valueMode === "list"; + const replaces = !adds && current.length > 0; + setIcon(header.createSpan({ cls: "fflow-header-icon" }), replaces ? "replace" : "plus"); + header.createSpan({ cls: "fflow-header-action", text: adds ? "Add to" : replaces ? "Replace" : "Set" }); + header.createSpan({ cls: "fflow-header-property", text: flow.property }); + if (replaces) header.createSpan({ cls: "fflow-header-current", text: current.map(String).join(", ") }); + } + getSuggestions(context: EditorSuggestContext): Suggestion[] { const flow = this.flow; if (!flow) return []; @@ -129,6 +168,19 @@ export class TriggerSuggest extends EditorSuggest { } } +/** The note's frontmatter as typed in the editor: the metadata cache lags behind, e.g. right after `&` set the type. */ +function readFrontmatter(editor: Editor): Record | null { + const info = getFrontMatterInfo(editor.getValue()); + if (!info.exists) return null; + try { + const fm: unknown = parseYaml(info.frontmatter); + return fm && typeof fm === "object" ? (fm as Record) : null; + } catch { + // Half-typed YAML: behave as if the note had no properties. + return null; + } +} + /** True when `line` lies inside a closed `---` frontmatter block at the top of the note. */ function inFrontmatter(editor: Editor, line: number): boolean { if (editor.getLine(0) !== "---") return false; diff --git a/styles.css b/styles.css index 61ddfad..963df87 100644 --- a/styles.css +++ b/styles.css @@ -117,6 +117,21 @@ color: var(--text-muted); } +/* Condition row: "Only on notes where [property] = [values]". */ +.fflow-when { + margin-top: var(--size-4-3); + align-items: center; + gap: var(--size-2-3); +} + +.fflow-when input { + width: 9em; +} + +.fflow-when input.fflow-when-values { + flex: 1 1 12em; +} + .fflow-symbol { width: 3em; text-align: center; @@ -249,6 +264,47 @@ button.fflow-add:hover { /* ---------- Editor suggestions ---------- */ +/* What the pick will do: icon, action, property, current value. */ +.fflow-header { + display: flex; + align-items: center; + gap: var(--size-2-3); + padding: var(--size-4-1) var(--size-4-3); + border-bottom: 1px solid var(--background-modifier-border); + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} + +.fflow-header:empty { + display: none; +} + +.fflow-header-icon { + display: flex; + color: var(--text-accent); +} + +.fflow-header-icon svg { + width: var(--icon-xs); + height: var(--icon-xs); +} + +.fflow-header-property { + font-family: var(--font-monospace); + color: var(--text-normal); +} + +.fflow-header-current { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.fflow-header-current::before { + content: "· "; +} + .fflow-suggestion { display: flex; gap: var(--size-4-2);