FFLOW 0.3.0: everything is a flow; steps set any properties, symbol and hotkeys share them

This commit is contained in:
olivier committed 2026-10-25 18:03:02 -04:00
1 parent 68e390fb37
commit 8553b7c75a
12 files changed
+389 -301

No files matched your search

+29 -16
View File
@@ -4,25 +4,36 @@ Set frontmatter properties from the editor with trigger symbols, the way `#` aut
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`.
## Triggers
Each trigger (Settings → FFLOW) has:
- **Symbol**: one character that is not a letter, digit or space. `# [ / :` are reserved (tags, links, slash commands, emoji). Default: `@`.
- **Values from**: *Vault (open list)* lists every value already used for that property in the vault, ranked by use, and accepts new values. *Fixed list* only offers the values listed in the settings. *Flow: …* offers the steps of a flow (see below).
- **Property** and **value mode** (open and fixed lists): the frontmatter key to write (default `type`); *Single value* replaces the value, *List* appends without duplicates.
A trigger fires only at the start of a word (line start or after a space), and never inside frontmatter or code.
## Flows ## Flows
A flow is an ordered list of values for one property, e.g. `status`: `todo` → `started` → `in-progress` → `done`. Everything is a flow (Settings → FFLOW). A flow has:
- Each flow adds two commands, **FFLOW: <name>: next step** and **previous step**. Assign hotkeys in Settings → Hotkeys (the *Hotkeys* button opens it filtered on FFLOW). - **Name**: labels its hotkey commands.
- A note without a value, or with a value outside the flow, enters at the first step. At the ends, the move stops unless **Loop** is on. - **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.
- Each step can list cssclasses (space-separated). Moving to a step removes the classes of the flow's other steps from `cssclasses` and adds its own; other classes are kept. - **Property**: the frontmatter key the flow sets.
- A trigger whose values come from a flow applies the same cssclasses, so `!done` and the hotkey give the same result. - **Kind**:
- cssclasses change only through FFLOW (hotkeys or triggers), not when the property is edited by hand. - **Ordered list**: fixed steps, in order. Each step can also set other properties (**Also sets**). Gets **FFLOW: <name>: next step** / **previous step** commands for hotkeys; **Loop** wraps around at the ends.
- **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.
### Step effects
Example, flow `status`:
| Step | Also sets |
|---|---|
| todo | `cssclasses: st-todo` |
| started | `cssclasses: st-started`, `priority: high` |
| done | `cssclasses: st-done`, `archived: true` |
Picking a step, by symbol or by hotkey:
1. sets the flow's property;
2. undoes the other steps' effects: their items are removed from list properties, and scalar properties are removed only if they still hold the value the flow wrote (a value you edited by hand is kept);
3. applies the step's effects.
List properties (`cssclasses`, `tags`, `aliases`, any property Obsidian types as a list, or one that already holds a list) take comma-separated items and are merged with what's there. Other properties are replaced; `true`/`false` and plain numbers are written typed.
A note without a value, or with a value outside the flow, enters at the first step. Properties change only through FFLOW, not when edited by hand.
## Development ## Development
@@ -33,4 +44,6 @@ npm run build
Copy `main.js`, `manifest.json` and `styles.css` to `<vault>/.obsidian/plugins/fflow/`. Copy `main.js`, `manifest.json` and `styles.css` to `<vault>/.obsidian/plugins/fflow/`.
Settings from 0.1–0.2 (separate triggers and flows) are converted to flows on first load.
See [ROADMAP.md](ROADMAP.md) for planned features. See [ROADMAP.md](ROADMAP.md) for planned features.
+4 -2
View File
@@ -2,9 +2,11 @@
## Next ## Next
- **Fixed list from a note.** Setting per trigger: take the fixed list from the plugin settings (current) or from a note in the vault (one value per line or list items). - **Steps from a note.** Per ordered flow: take the steps from the plugin settings (current) or from a note in the vault (one value per line or list items).
- **Dynamic effect values**, e.g. `completed: {{date}}` on a `done` step.
## Done ## Done
- 0.2.0 — Flows: ordered steps per property, next/previous commands for hotkeys, optional loop, cssclasses per step. Triggers can take their values from a flow. - 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.
- 0.2.0 — Flows with per-step cssclasses and next/previous commands, separate from triggers.
- 0.1.0 — Triggers: symbol → property, open (vault) or fixed list, single value or list. - 0.1.0 — Triggers: symbol → property, open (vault) or fixed list, single value or list.
+1 -3
View File
@@ -2,6 +2,4 @@
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
*/ */
var N=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var W=(n,i)=>{for(var e in i)N(n,e,{get:i[e],enumerable:!0})},_=(n,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of $(i))!O.call(n,s)&&s!==e&&N(n,s,{get:()=>i[s],enumerable:!(t=R(i,s))||t.enumerable});return n};var H=n=>_(N({},"__esModule",{value:!0}),n);var G={};W(G,{default:()=>k});module.exports=H(G);var I=require("obsidian");var L=require("obsidian");var P=require("obsidian");async function y(n,i,e){let t=n.workspace.getActiveViewOfType(P.MarkdownView);(t==null?void 0:t.file)===i&&await t.save(),await n.fileManager.processFrontMatter(i,e)}function v(n,i,e){var r;n[i.property]=e;let t=o=>o.split(/\s+/).filter(Boolean),s=new Set(i.steps.flatMap(o=>t(o.cssclass))),a=n.cssclasses,l=(Array.isArray(a)?a:typeof a=="string"?t(a):[]).map(String),d=i.steps.find(o=>o.value===e),p=l.filter(o=>!s.has(o));for(let o of t((r=d==null?void 0:d.cssclass)!=null?r:""))p.includes(o)||p.push(o);p.length?n.cssclasses=p:a!==void 0&&delete n.cssclasses}var m={symbol:"",property:"",valueMode:"single",source:"open",values:[],flowId:""},A={rules:[{...m,symbol:"@",property:"type"}],flows:[]},S=["#","[","/",":"];function F(n,i,e){return[...n].length!==1?"Use exactly one character.":/[\p{L}\p{N}\s]/u.test(n)?"Letters, digits and spaces are not allowed.":S.includes(n)?`"${n}" is reserved (${S.join(" ")}).`:i.some((t,s)=>s!==e&&t.symbol===n)?`"${n}" is already used by another trigger.`:null}function D(n,i){let e=n.rules[i];if(F(e.symbol,n.rules,i))return null;if(e.source==="flow"){let t=n.flows.find(s=>s.id===e.flowId);return t&&t.property?{property:t.property,flow:t}:null}return e.property?{property:e.property,flow:null}:null}function w(n){return n.steps.filter(i=>i.value.trim()!=="")}var x=class{constructor(i){this.plugin=i;this.registered=[]}sync(){for(let i of this.registered)this.plugin.removeCommand(i);this.registered=[];for(let i of this.plugin.settings.flows)this.add(i,1,"next","next step"),this.add(i,-1,"previous","previous step")}add(i,e,t,s){let a=`flow-${i.id}-${t}`;this.registered.push(a),this.plugin.addCommand({id:a,name:`${i.name||i.property||"Unnamed flow"}: ${s}`,checkCallback:l=>{let d=this.plugin.app.workspace.getActiveFile();return!d||d.extension!=="md"||!i.property||w(i).length===0?!1:(l||U(this.plugin,d,i,e),!0)}})}};async function U(n,i,e,t){let s=w(e),a="";try{await y(n.app,i,l=>{let d=s.findIndex(r=>r.value===String(l[e.property])),p=d===-1?0:d+t;if(p<0||p>=s.length){if(!e.loop){a=`${e.property}: already at the ${t===1?"last":"first"} step`;return}p=(p+s.length)%s.length}v(l,e,s[p].value),a=`${e.property}: ${s[p].value}`}),new L.Notice(a)}catch(l){console.error("FFLOW: could not move flow step",l),new L.Notice(`FFLOW: could not set "${e.property}". See console.`)}}var h=require("obsidian");var T=class extends h.PluginSettingTab{constructor(e,t){super(e,t);this.plugin=t;this.save=()=>this.plugin.saveSettings()}display(){let{containerEl:e}=this,t=this.plugin.settings;e.empty(),new h.Setting(e).setHeading().setName("Triggers").setDesc(`Type a symbol at the start of a word, pick a value: the typed text disappears and the value goes to the frontmatter. Reserved: ${S.join(" ")}`).addButton(s=>s.setButtonText("Add trigger").onClick(async()=>{t.rules.push({...m,values:[]}),await this.save(),this.display()})),t.rules.forEach((s,a)=>this.renderRule(s,a)),new h.Setting(e).setHeading().setName("Flows").setDesc("Ordered values for a property. Each step can add cssclasses. Every flow gets \u201Cnext step\u201D and \u201Cprevious step\u201D commands for hotkeys.").addButton(s=>s.setButtonText("Hotkeys").onClick(()=>this.openHotkeys())).addButton(s=>s.setButtonText("Add flow").onClick(async()=>{t.flows.push({id:Date.now().toString(36),name:"",property:"",loop:!1,steps:[{value:"",cssclass:""}]}),await this.save(),this.display()})),t.flows.forEach((s,a)=>this.renderFlow(s,a))}renderRule(e,t){let s=this.plugin.settings,a=e.source==="flow"?s.flows.find(o=>o.id===e.flowId):void 0,l=createFragment(),d=l.createSpan(),p=()=>{let o=a?a.property:e.property;d.setText(`${e.symbol||"?"} \u2192 ${o||"?"}`)};p();let r=new h.SettingGroup(this.containerEl).setHeading(l).addClass("fflow-group");if(r.addExtraButton(o=>o.setIcon("trash").setTooltip("Delete trigger").onClick(async()=>{s.rules.splice(t,1),await this.save(),this.display()})),r.addSetting(o=>{o.setName("Symbol");let c=o.descEl.createDiv({cls:"fflow-error"}),u=g=>{var f;return c.setText(g?(f=F(g,s.rules,t))!=null?f:"":"Pick a symbol.")};u(e.symbol),o.addText(g=>{g.setPlaceholder("@").setValue(e.symbol),g.inputEl.addClass("fflow-symbol"),g.onChange(async f=>{u(f),!F(f,s.rules,t)&&(e.symbol=f,p(),await this.save())})})}),r.addSetting(o=>o.setName("Values from").setDesc(e.source==="open"?"Every value already used for the property in the vault. New values are allowed.":e.source==="finite"?"Only the values listed below.":"The steps oLine truncated var A=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var K=Object.prototype.hasOwnProperty;var H=(n,s)=>{for(var e in s)A(n,e,{get:s[e],enumerable:!0})},W=(n,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let o of j(s))!K.call(n,o)&&o!==e&&A(n,o,{get:()=>s[o],enumerable:!(t=$(s,o))||t.enumerable});return n};var q=n=>W(A({},"__esModule",{value:!0}),n);var J={};H(J,{default:()=>T});module.exports=q(J);var R=require("obsidian");var M=require("obsidian");var N=require("obsidian");async function v(n,s,e){let t=n.workspace.getActiveViewOfType(N.MarkdownView);(t==null?void 0:t.file)===s&&await t.save(),await n.fileManager.processFrontMatter(s,e)}function I(n,s,e,t){if(!t){n[s]=e;return}let o=L(n[s],s);o.includes(e)||o.push(e),n[s]=o}function F(n,s,e,t){var a;s[e.property]=t;let o=e.steps.find(l=>l.value===t),i=new Map,r=l=>{let d=i.get(l);return d===void 0&&i.set(l,d=_(n,s,l)),d},p=l=>l.property!==""&&l.property!==e.property;for(let l of e.steps)if(l!==o)for(let d of l.effects.filter(p)){let u=d.property;if(r(u)){let c=new Set(B(d.value)),m=L(s[u],u).filter(y=>!c.has(y));m.length?s[u]=m:delete s[u]}else u in s&&String(s[u])===String(D(d.value))&&delete s[u]}for(let l of(a=o==null?void 0:o.effects.filter(p))!=null?a:[]){let d=l.property;if(r(d)){let u=L(s[d],d);for(let c of B(l.value))u.includes(c)||u.push(c);u.length&&(s[d]=u)}else s[d]=D(l.value)}}function _(n,s,e){if(["cssclasses","tags","aliases"].includes(e)||Array.isArray(s[e]))return!0;let t=Reflect.get(n,"metadataTypeManager");if(!t||typeof t!="object"||!("getPropertyInfo"in t)||typeof t.getPropertyInfo!="function")return!1;let o=t.getPropertyInfo(e),i=o&&typeof o=="object"&&"widget"in o?o.widget:null;return i==="multitext"||i==="tags"||i==="aliases"}function L(n,s){return Array.isArray(n)?n.map(String):n==null||n===""?[]:s==="cssclasses"?String(n).split(/[\s,]+/).filter(Boolean):[String(n)]}function B(n){return n.split(",").map(s=>s.trim()).filter(Boolean)}function D(n){let s=n.trim();return s===""?null:s==="true"||s==="false"?s==="true":/^-?\d+(\.\d+)?$/.test(s)?Number(s):s}var S=class{constructor(s){this.plugin=s;this.registered=[]}sync(){for(let s of this.registered)this.plugin.removeCommand(s);this.registered=[];for(let s of this.plugin.settings.flows)s.kind==="ordered"&&(this.add(s,1,"next","next step"),this.add(s,-1,"previous","previous step"))}add(s,e,t,o){let i=`flow-${s.id}-${t}`;this.registered.push(i),this.plugin.addCommand({id:i,name:`${s.name||s.property||"Unnamed flow"}: ${o}`,checkCallback:r=>{let p=this.plugin.app.workspace.getActiveFile();return!p||p.extension!=="md"||!s.property||!s.steps.some(a=>a.value)?!1:(r||G(this.plugin,p,s,e),!0)}})}};async function G(n,s,e,t){let o=e.steps.filter(r=>r.value),i="";try{await v(n.app,s,r=>{let p=o.findIndex(l=>l.value===String(r[e.property])),a=p===-1?0:p+t;if(a<0||a>=o.length){if(!e.loop){i=`${e.property}: already at the ${t===1?"last":"first"} step`;return}a=(a+o.length)%o.length}F(n.app,r,e,o[a].value),i=`${e.property}: ${o[a].value}`}),new M.Notice(i)}catch(r){console.error("FFLOW: could not move flow step",r),new M.Notice(`FFLOW: could not set "${e.property}". See console.`)}}function f(n){return{id:Date.now().toString(36)+Math.random().toString(36).slice(2,6),name:"",symbol:"",property:"",kind:"ordered",valueMode:"single",loop:!1,steps:[],...n}}function U(){return{flows:[f({name:"Type",symbol:"@",property:"type",kind:"open"})]}}var b=["#","[","/",":"];function h(n,s,e){return n===""?null:[...n].length!==1?"Use exactly one character.":/[\p{L}\p{N}\s]/u.test(n)?"Letters, digits and spaces are not allowed.":b.includes(n)?`"${n}" is reserved (${b.join(" ")}).`:s.some((t,o)=>o!==e&&t.symbol===n)?`"${n}" is already used by another flow.`:null}function O(n){var o,i;if(!n||typeof n!="object")return U();if("flows"in n&&!("rules"in n)&&Array.isArray(n.flows))return{flows:n.flows.map(r=>f(r))};let s=n,e=(o=s.rules)!=null?o:[],t=((i=s.flows)!=null?i:[]).map(r=>{var p,a;return f({id:r.id,name:r.name,property:r.property,loop:r.loop,symbol:(a=(p=e.find(l=>l.source==="flow"&&l.flowId===r.id))==null?void 0:p.symbol)!=null?a:"",steps:r.steps.map(l=>({value:l.value,effects:l.cssclass.trim()?[{property:"cssclasses",value:l.cssclass.trim().split(/\s+/).join(", ")}]:[]}))})});for(let r of e)r.source==="open"&&t.push(f({name:r.property,symbol:r.symbol,property:r.property,kind:"open",valueMode:r.valueMode})),r.source==="finite"&&t.push(f({name:r.property,symbol:r.symbol,property:r.property,steps:r.values.map(p=>({value:p,effects:[]}))}));return{flows:t}}var g=require("obsidian");var x=class extends g.PluginSettingTab{constructor(e,t){super(e,t);this.plugin=t;this.save=()=>this.plugin.saveSettings()}async saveAndRedraw(){await this.save(),this.display()}display(){let{containerEl:e}=this,t=this.plugin.settings.flows;e.empty(),new g.Setting(e).setHeading().setName("Flows").setDesc(`Type a flow's symbol at the start of a word and pick a value: the text disappears Line truncated
`)).onChange(async u=>{e.values=u.split(`
`).map(g=>g.trim()).filter(Boolean),await this.save()}),c.inputEl.rows=5}))}renderFlow(e,t){let s=this.plugin.settings,a=createFragment(),l=a.createSpan(),d=()=>l.setText(e.name||e.property||"New flow");d();let p=new h.SettingGroup(this.containerEl).setHeading(a).addClass("fflow-group");p.addExtraButton(r=>r.setIcon("trash").setTooltip("Delete flow").onClick(async()=>{s.flows.splice(t,1);for(let o of s.rules)o.source==="flow"&&o.flowId===e.id&&(o.source="open",o.property=e.property);await this.save(),this.display()})),p.addSetting(r=>r.setName("Name and property").setDesc("The name labels the hotkey commands.").addText(o=>o.setPlaceholder("Status").setValue(e.name).onChange(async c=>{e.name=c,d(),await this.save()})).addText(o=>o.setPlaceholder("status").setValue(e.property).onChange(async c=>{e.property=c.trim(),d(),await this.save()}))),p.addSetting(r=>r.setName("Loop").setDesc("After the last step, \u201Cnext\u201D goes back to the first.").addToggle(o=>o.setValue(e.loop).onChange(async c=>{e.loop=c,await this.save()}))),e.steps.forEach((r,o)=>{p.addSetting(c=>{c.setName(`Step ${o+1}`).setClass("fflow-step"),c.addText(g=>g.setPlaceholder("value").setValue(r.value).onChange(async f=>{r.value=f.trim(),await this.save()})),c.addText(g=>g.setPlaceholder("cssclasses (optional)").setValue(r.cssclass).onChange(async f=>{r.cssclass=f.trim(),await this.save()}));let u=async g=>{e.steps.splice(g,0,...e.steps.splice(o,1)),await this.save(),this.display()};c.addExtraButton(g=>g.setIcon("arrow-up").setTooltip("Move up").setDisabled(o===0).onClick(()=>u(o-1))),c.addExtraButton(g=>g.setIcon("arrow-down").setTooltip("Move down").setDisabled(o===e.steps.length-1).onClick(()=>u(o+1))),c.addExtraButton(g=>g.setIcon("x").setTooltip("Remove step").onClick(async()=>{e.steps.splice(o,1),await this.save(),this.display()}))})}),p.addSetting(r=>r.addButton(o=>o.setButtonText("Add step").onClick(async()=>{e.steps.push({value:"",cssclass:""}),await this.save(),this.display()})))}openHotkeys(){let e=Reflect.get(this.app,"setting");if(!e||typeof e!="object"||!("openTabById"in e)||typeof e.openTabById!="function")return;let t=e.openTabById("hotkeys"),s=t&&typeof t=="object"&&"searchComponent"in t?t.searchComponent:null;s instanceof h.SearchComponent&&(s.setValue(this.plugin.manifest.name),s.inputEl.dispatchEvent(new Event("input")))}};var b=require("obsidian");var E=class{constructor(i){this.app=i;this.cache=new Map}invalidate(){this.cache.clear()}get(i){var t,s,a;let e=this.cache.get(i);if(e)return e;e=new Map;for(let l of this.app.vault.getMarkdownFiles()){let d=(s=(t=this.app.metadataCache.getFileCache(l))==null?void 0:t.frontmatter)==null?void 0:s[i];for(let p of new Set(B(d)))e.set(p,((a=e.get(p))!=null?a:0)+1)}return this.cache.set(i,e),e}};function B(n){return Array.isArray(n)?n.flatMap(B):typeof n=="string"?n.trim()?[n.trim()]:[]:typeof n=="number"||typeof n=="boolean"?[String(n)]:[]}var M=n=>n!==void 0&&/\s/.test(n),C=class extends b.EditorSuggest{constructor(e,t,s){super(e);this.plugin=t;this.index=s;this.active=null}onTrigger(e,t,s){let a=t.getLine(e.line).slice(0,e.ch),l=a.length;for(;l>0&&!M(a[l-1]);)l--;let d=a.slice(l);if(!d)return null;let p=this.plugin.settings,r=p.rules.findIndex(c=>c.symbol===d[0]),o=r===-1?null:D(p,r);return!o||j(t,e.line)||q(t,e.line,a.slice(0,l))?null:(this.active={rule:p.rules[r],...o},{start:{line:e.line,ch:l},end:e,query:d.slice(1)})}getSuggestions(e){let t=this.active;if(!t)return[];let{rule:s,flow:a}=t,l=e.query.toLowerCase(),d=a?w(a).map(r=>({value:r.value,isNew:!1})):s.source==="finite"?s.values.map(r=>({value:r,isNew:!1})):[...this.index.get(t.property)].sort((r,o)=>o[1]-r[1]||r[0].localeCompare(o[0])).map(([r,o])=>({value:r,count:o,isNew:!1})),p=d.filter(r=>r.value.toLowerCase().includes(l));return p.sort((r,o)=>+!r.value.toLowerCase().startsWith(l)-+!o.value.toLowerCase().startsWith(l)),s.source==="open"&&l&&!d.some(r=>r.value.toLowerCase()===l)&&p.push({value:e.query,isNew:!0}),p}renderSuggestion(e,t){if(t.addClass("fflow-suggestion"),e.isNew){t.createSpan({cls:"fflow-new",text:"New: "}),t.createSpan({text:e.value});return}t.createSpan({text:e.value}),e.count!==void 0&&t.createSpan({cls:"fflow-count",text:String(e.count)})}selectSuggestion(e,t){let s=this.context,a=this.active;!s||!a||this.apply(s,a,e.value)}async apply(e,{rule:t,property:s,flow:a},l){let{editor:d,file:p,start:r}=e,o=d.getLine(r.line),c=e.end.ch;for(;c<o.length&&!M(o[c]);)c++;M(o[c])&&c++,d.replaceRange("",r,{line:r.line,ch:c}),d.setCursor(r);try{await y(this.app,p,u=>{if(a){v(u,a,l);return}if(t.valueMode==="single"){u[s]=l;return}let g=u[s],f=g==null?[]:Array.isArray(g)?g:[g];f.some(V=>String(V)===l)||f.push(l),u[s]=f})}catch(u){console.error("FFLOW: could not update frontmatter",u),new b.Notice(`FFLOW: could not set "${s}". See console.`)}}};function j(n,i){if(n.getLine(0)!=="---")return!1;for(let e=1;e<n.lineCount();e++)if(n.getLine(e)==="---")return i<=e;return!1}function q(n,i,e){var s,a;let t=0;for(let l=0;l<i;l Line truncated
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"id": "fflow", "id": "fflow",
"name": "FFLOW", "name": "FFLOW",
"version": "0.2.0", "version": "0.3.0",
"minAppVersion": "1.11.0", "minAppVersion": "1.11.0",
"description": "Frontmatter Flow: type a trigger symbol (like @) to autocomplete and set a frontmatter property.", "description": "Frontmatter Flow: type a trigger symbol (like @) to autocomplete and set a frontmatter property.",
"author": "Olivier Legendre", "author": "Olivier Legendre",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "fflow", "name": "fflow",
"version": "0.2.0", "version": "0.3.0",
"description": "Frontmatter Flow: set properties from the editor with trigger symbols.", "description": "Frontmatter Flow: set properties from the editor with trigger symbols.",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
+6 -5
View File
@@ -1,11 +1,11 @@
import { Notice, TFile } from "obsidian"; import { Notice, TFile } from "obsidian";
import { setFlowStep, updateFrontmatter } from "./frontmatter"; import { setFlowStep, updateFrontmatter } from "./frontmatter";
import type FflowPlugin from "./main"; import type FflowPlugin from "./main";
import { Flow, flowSteps } from "./settings"; import type { Flow } from "./settings";
type Direction = 1 | -1; type Direction = 1 | -1;
/** Re-registers the next/previous commands of every flow. Ids derive from the flow id, so hotkeys survive renames. */ /** Re-registers the next/previous commands of every ordered flow. Ids derive from the flow id, so hotkeys survive renames. */
export class FlowCommands { export class FlowCommands {
private registered: string[] = []; private registered: string[] = [];
@@ -15,6 +15,7 @@ export class FlowCommands {
for (const id of this.registered) this.plugin.removeCommand(id); for (const id of this.registered) this.plugin.removeCommand(id);
this.registered = []; this.registered = [];
for (const flow of this.plugin.settings.flows) { for (const flow of this.plugin.settings.flows) {
if (flow.kind !== "ordered") continue;
this.add(flow, 1, "next", "next step"); this.add(flow, 1, "next", "next step");
this.add(flow, -1, "previous", "previous step"); this.add(flow, -1, "previous", "previous step");
} }
@@ -28,7 +29,7 @@ export class FlowCommands {
name: `${flow.name || flow.property || "Unnamed flow"}: ${label}`, name: `${flow.name || flow.property || "Unnamed flow"}: ${label}`,
checkCallback: (checking) => { checkCallback: (checking) => {
const file = this.plugin.app.workspace.getActiveFile(); const file = this.plugin.app.workspace.getActiveFile();
if (!file || file.extension !== "md" || !flow.property || flowSteps(flow).length === 0) return false; if (!file || file.extension !== "md" || !flow.property || !flow.steps.some((s) => s.value)) return false;
if (!checking) void moveStep(this.plugin, file, flow, direction); if (!checking) void moveStep(this.plugin, file, flow, direction);
return true; return true;
}, },
@@ -37,7 +38,7 @@ export class FlowCommands {
} }
async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction: Direction): Promise<void> { async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction: Direction): Promise<void> {
const steps = flowSteps(flow); const steps = flow.steps.filter((s) => s.value);
let message = ""; let message = "";
try { try {
// Read the current value inside the update: the metadata cache can lag behind the editor. // Read the current value inside the update: the metadata cache can lag behind the editor.
@@ -52,7 +53,7 @@ async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction:
} }
target = (target + steps.length) % steps.length; target = (target + steps.length) % steps.length;
} }
setFlowStep(fm, flow, steps[target].value); setFlowStep(plugin.app, fm, flow, steps[target].value);
message = `${flow.property}: ${steps[target].value}`; message = `${flow.property}: ${steps[target].value}`;
}); });
new Notice(message); new Notice(message);
+84 -14
View File
@@ -1,5 +1,5 @@
import { App, MarkdownView, TFile } from "obsidian"; import { App, MarkdownView, TFile } from "obsidian";
import type { Flow } from "./settings"; import type { Flow, FlowEffect } from "./settings";
export type Frontmatter = Record<string, unknown>; export type Frontmatter = Record<string, unknown>;
@@ -10,22 +10,92 @@ export async function updateFrontmatter(app: App, file: TFile, fn: (fm: Frontmat
await app.fileManager.processFrontMatter(file, fn); await app.fileManager.processFrontMatter(file, fn);
} }
/** Sets `value` on a single-value property, or appends it to a list property without duplicates. */
export function setOpenValue(fm: Frontmatter, property: string, value: string, asList: boolean): void {
if (!asList) {
fm[property] = value;
return;
}
const list = toList(fm[property], property);
if (!list.includes(value)) list.push(value);
fm[property] = list;
}
/** /**
* Put the note on `value` of `flow`: set the property, drop the classes of every * Puts the note on step `value` of an ordered flow:
* step of this flow from `cssclasses`, then add the classes of the new step. * 1. sets the flow's property;
* Classes that don't belong to the flow are kept. * 2. undoes the effects of every other step (list items removed, scalars removed only if unchanged since the flow wrote them);
* 3. applies the new step's effects (list items added, scalars replaced).
*/ */
export function setFlowStep(fm: Frontmatter, flow: Flow, value: string): void { export function setFlowStep(app: App, fm: Frontmatter, flow: Flow, value: string): void {
fm[flow.property] = value; fm[flow.property] = value;
const target = flow.steps.find((s) => s.value === value);
// Decide list vs scalar before any edit: deleting a property would hide its array shape.
const listness = new Map<string, boolean>();
const isList = (p: string) => {
let result = listness.get(p);
if (result === undefined) listness.set(p, (result = isListProperty(app, fm, p)));
return result;
};
const usable = (e: FlowEffect) => e.property !== "" && e.property !== flow.property;
for (const step of flow.steps) {
if (step === target) continue;
for (const effect of step.effects.filter(usable)) {
const p = effect.property;
if (isList(p)) {
const remove = new Set(listItems(effect.value));
const kept = toList(fm[p], p).filter((item) => !remove.has(item));
if (kept.length) fm[p] = kept;
else delete fm[p];
} else if (p in fm && String(fm[p]) === String(parseScalar(effect.value))) {
delete fm[p];
}
}
}
for (const effect of target?.effects.filter(usable) ?? []) {
const p = effect.property;
if (isList(p)) {
const list = toList(fm[p], p);
for (const item of listItems(effect.value)) if (!list.includes(item)) list.push(item);
if (list.length) fm[p] = list;
} else {
fm[p] = parseScalar(effect.value);
}
}
}
/** Known list properties, current array values, and properties Obsidian types as lists (internal API, probed). */
function isListProperty(app: App, fm: Frontmatter, property: string): boolean {
if (["cssclasses", "tags", "aliases"].includes(property) || Array.isArray(fm[property])) return true;
const types: unknown = Reflect.get(app, "metadataTypeManager");
if (!types || typeof types !== "object" || !("getPropertyInfo" in types) || typeof types.getPropertyInfo !== "function") return false;
const info: unknown = types.getPropertyInfo(property);
const widget = info && typeof info === "object" && "widget" in info ? info.widget : null;
return widget === "multitext" || widget === "tags" || widget === "aliases";
}
function toList(raw: unknown, property: string): string[] {
if (Array.isArray(raw)) return raw.map(String);
if (raw == null || raw === "") return [];
// Obsidian also accepts `cssclasses: a b` as a space-separated string.
return property === "cssclasses" ? String(raw).split(/[\s,]+/).filter(Boolean) : [String(raw)];
}
const split = (s: string) => s.split(/\s+/).filter(Boolean); function listItems(value: string): string[] {
const flowClasses = new Set(flow.steps.flatMap((s) => split(s.cssclass))); return value
const current = fm.cssclasses; .split(",")
const existing = (Array.isArray(current) ? current : typeof current === "string" ? split(current) : []).map(String); .map((v) => v.trim())
const step = flow.steps.find((s) => s.value === value); .filter(Boolean);
const next = existing.filter((c) => !flowClasses.has(c)); }
for (const c of split(step?.cssclass ?? "")) if (!next.includes(c)) next.push(c);
if (next.length) fm.cssclasses = next; /** "true"/"false" become booleans and plain numbers become numbers, so checkbox and number properties stay typed. */
else if (current !== undefined) delete fm.cssclasses; function parseScalar(value: string): string | number | boolean | null {
const v = value.trim();
if (v === "") return null;
if (v === "true" || v === "false") return v === "true";
if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v);
return v;
} }
+5 -11
View File
@@ -1,6 +1,6 @@
import { Plugin } from "obsidian"; import { Plugin } from "obsidian";
import { FlowCommands } from "./flows"; import { FlowCommands } from "./flows";
import { DEFAULT_SETTINGS, FflowSettings, NEW_RULE } from "./settings"; import { FflowSettings, loadSettings } from "./settings";
import { FflowSettingTab } from "./settings-tab"; import { FflowSettingTab } from "./settings-tab";
import { TriggerSuggest, ValueIndex } from "./suggest"; import { TriggerSuggest, ValueIndex } from "./suggest";
@@ -9,7 +9,10 @@ export default class FflowPlugin extends Plugin {
private flowCommands = new FlowCommands(this); private flowCommands = new FlowCommands(this);
async onload(): Promise<void> { async onload(): Promise<void> {
await this.loadSettings(); const saved: unknown = await this.loadData();
this.settings = loadSettings(saved);
// Persist a migration from the old trigger/flow format right away.
if (saved && typeof saved === "object" && "rules" in saved) await this.saveData(this.settings);
const index = new ValueIndex(this.app); const index = new ValueIndex(this.app);
this.registerEvent(this.app.metadataCache.on("changed", () => index.invalidate())); this.registerEvent(this.app.metadataCache.on("changed", () => index.invalidate()));
@@ -20,15 +23,6 @@ export default class FflowPlugin extends Plugin {
this.addSettingTab(new FflowSettingTab(this.app, this)); this.addSettingTab(new FflowSettingTab(this.app, this));
} }
async loadSettings(): Promise<void> {
const saved = ((await this.loadData()) ?? {}) as Partial<FflowSettings>;
this.settings = {
// Fill fields added after a rule was saved (e.g. flowId in 0.2.0).
rules: (saved.rules ?? DEFAULT_SETTINGS.rules).map((r) => ({ ...NEW_RULE, ...r })),
flows: saved.flows ?? [],
};
}
async saveSettings(): Promise<void> { async saveSettings(): Promise<void> {
await this.saveData(this.settings); await this.saveData(this.settings);
this.flowCommands.sync(); this.flowCommands.sync();
+128 -171
View File
@@ -1,6 +1,6 @@
import { App, PluginSettingTab, SearchComponent, Setting, SettingGroup } from "obsidian"; import { App, PluginSettingTab, SearchComponent, Setting, SettingGroup } from "obsidian";
import type FflowPlugin from "./main"; import type FflowPlugin from "./main";
import { BLOCKED_SYMBOLS, Flow, NEW_RULE, symbolError, TriggerRule, ValueMode } from "./settings"; import { BLOCKED_SYMBOLS, Flow, FlowKind, FlowStep, newFlow, symbolError, ValueMode } from "./settings";
export class FflowSettingTab extends PluginSettingTab { export class FflowSettingTab extends PluginSettingTab {
constructor(app: App, private plugin: FflowPlugin) { constructor(app: App, private plugin: FflowPlugin) {
@@ -9,164 +9,45 @@ export class FflowSettingTab extends PluginSettingTab {
private save = () => this.plugin.saveSettings(); private save = () => this.plugin.saveSettings();
/** Saves, then redraws: for edits that add, remove or reorder rows. */
private async saveAndRedraw(): Promise<void> {
await this.save();
this.display();
}
display(): void { display(): void {
const { containerEl } = this; const { containerEl } = this;
const settings = this.plugin.settings; const flows = this.plugin.settings.flows;
containerEl.empty(); containerEl.empty();
new Setting(containerEl)
.setHeading()
.setName("Triggers")
.setDesc(
`Type a symbol at the start of a word, pick a value: the typed text disappears and the value goes to the frontmatter. Reserved: ${BLOCKED_SYMBOLS.join(" ")}`,
)
.addButton((b) =>
b.setButtonText("Add trigger").onClick(async () => {
settings.rules.push({ ...NEW_RULE, values: [] });
await this.save();
this.display();
}),
);
settings.rules.forEach((rule, index) => this.renderRule(rule, index));
new Setting(containerEl) new Setting(containerEl)
.setHeading() .setHeading()
.setName("Flows") .setName("Flows")
.setDesc("Ordered values for a property. Each step can add cssclasses. Every flow gets “next step” and “previous step” commands for hotkeys.") .setDesc(
`Type a flow's symbol at the start of a word and pick a value: the text disappears, the property is set, and the step's other properties are applied. Ordered flows get “next step” and “previous step” commands for hotkeys. Reserved symbols: ${BLOCKED_SYMBOLS.join(" ")}`,
)
.addButton((b) => b.setButtonText("Hotkeys").onClick(() => this.openHotkeys())) .addButton((b) => b.setButtonText("Hotkeys").onClick(() => this.openHotkeys()))
.addButton((b) => .addButton((b) =>
b.setButtonText("Add flow").onClick(async () => { b.setButtonText("Add flow").onClick(async () => {
settings.flows.push({ id: Date.now().toString(36), name: "", property: "", loop: false, steps: [{ value: "", cssclass: "" }] }); flows.push(newFlow({ steps: [{ value: "", effects: [] }] }));
await this.save(); await this.saveAndRedraw();
this.display();
}),
);
settings.flows.forEach((flow, index) => this.renderFlow(flow, index));
}
private renderRule(rule: TriggerRule, index: number): void {
const settings = this.plugin.settings;
const flow = rule.source === "flow" ? settings.flows.find((f) => f.id === rule.flowId) : undefined;
const title = createFragment();
const titleEl = title.createSpan();
const updateTitle = () => {
const property = flow ? flow.property : rule.property;
titleEl.setText(`${rule.symbol || "?"} → ${property || "?"}`);
};
updateTitle();
const group = new SettingGroup(this.containerEl).setHeading(title).addClass("fflow-group");
group.addExtraButton((b) =>
b
.setIcon("trash")
.setTooltip("Delete trigger")
.onClick(async () => {
settings.rules.splice(index, 1);
await this.save();
this.display();
}), }),
); );
group.addSetting((s) => { flows.forEach((flow, index) => this.renderFlow(flow, index));
s.setName("Symbol");
const error = s.descEl.createDiv({ cls: "fflow-error" });
const check = (value: string) => error.setText(value ? (symbolError(value, settings.rules, index) ?? "") : "Pick a symbol.");
check(rule.symbol);
s.addText((t) => {
t.setPlaceholder("@").setValue(rule.symbol);
t.inputEl.addClass("fflow-symbol");
t.onChange(async (value) => {
check(value);
// Invalid input stays in the field but is never saved.
if (symbolError(value, settings.rules, index)) return;
rule.symbol = value;
updateTitle();
await this.save();
});
});
});
group.addSetting((s) =>
s
.setName("Values from")
.setDesc(
rule.source === "open"
? "Every value already used for the property in the vault. New values are allowed."
: rule.source === "finite"
? "Only the values listed below."
: "The steps of the flow. Picking one also applies its cssclasses.",
)
.addDropdown((d) => {
d.addOption("open", "Vault (open list)").addOption("finite", "Fixed list");
for (const f of settings.flows) d.addOption(`flow:${f.id}`, `Flow: ${f.name || f.property || "unnamed"}`);
d.setValue(rule.source === "flow" ? `flow:${rule.flowId}` : rule.source).onChange(async (value) => {
if (value.startsWith("flow:")) {
rule.source = "flow";
rule.flowId = value.slice("flow:".length);
} else {
rule.source = value as "open" | "finite";
}
await this.save();
this.display();
});
}),
);
if (rule.source === "flow") {
if (!flow) group.addSetting((s) => s.setName("Flow deleted").setDesc("Pick another source.").descEl.addClass("fflow-error"));
return;
}
group.addSetting((s) =>
s
.setName("Property")
.addText((t) =>
t
.setPlaceholder("type")
.setValue(rule.property)
.onChange(async (value) => {
rule.property = value.trim();
updateTitle();
await this.save();
}),
)
.addDropdown((d) =>
d
.addOptions({ single: "Single value", list: "List" })
.setValue(rule.valueMode)
.onChange(async (value) => {
rule.valueMode = value as ValueMode;
await this.save();
}),
),
);
if (rule.source === "finite") {
group.addSetting((s) =>
s
.setName("Values")
.setDesc("One per line, in display order.")
.addTextArea((t) => {
t.setValue(rule.values.join("\n")).onChange(async (value) => {
rule.values = value
.split("\n")
.map((v) => v.trim())
.filter(Boolean);
await this.save();
});
t.inputEl.rows = 5;
}),
);
}
} }
private renderFlow(flow: Flow, index: number): void { private renderFlow(flow: Flow, index: number): void {
const settings = this.plugin.settings; const flows = this.plugin.settings.flows;
const title = createFragment(); const title = createFragment();
const titleEl = title.createSpan(); const badge = title.createSpan({ cls: "fflow-badge" });
const updateTitle = () => titleEl.setText(flow.name || flow.property || "New flow"); const name = title.createSpan();
const updateTitle = () => {
badge.setText(flow.symbol);
badge.toggle(flow.symbol !== "");
name.setText(flow.name || flow.property || "New flow");
};
updateTitle(); updateTitle();
const group = new SettingGroup(this.containerEl).setHeading(title).addClass("fflow-group"); const group = new SettingGroup(this.containerEl).setHeading(title).addClass("fflow-group");
@@ -175,23 +56,15 @@ export class FflowSettingTab extends PluginSettingTab {
.setIcon("trash") .setIcon("trash")
.setTooltip("Delete flow") .setTooltip("Delete flow")
.onClick(async () => { .onClick(async () => {
settings.flows.splice(index, 1); flows.splice(index, 1);
// Triggers that used this flow keep writing the same property, from the vault's values. await this.saveAndRedraw();
for (const rule of settings.rules) {
if (rule.source === "flow" && rule.flowId === flow.id) {
rule.source = "open";
rule.property = flow.property;
}
}
await this.save();
this.display();
}), }),
); );
group.addSetting((s) => group.addSetting((s) =>
s s
.setName("Name and property") .setName("Name")
.setDesc("The name labels the hotkey commands.") .setDesc(flow.kind === "ordered" ? "Labels the hotkey commands." : "For your reference.")
.addText((t) => .addText((t) =>
t t
.setPlaceholder("Status") .setPlaceholder("Status")
@@ -201,6 +74,34 @@ export class FflowSettingTab extends PluginSettingTab {
updateTitle(); updateTitle();
await this.save(); await this.save();
}), }),
),
);
group.addSetting((s) => {
s.setName("Symbol").setDesc("Optional. One character, not a letter or digit.");
const error = s.descEl.createDiv({ cls: "fflow-error" });
error.setText(symbolError(flow.symbol, flows, index) ?? "");
s.addText((t) => {
t.setPlaceholder("@").setValue(flow.symbol);
t.inputEl.addClass("fflow-symbol");
t.onChange(async (value) => {
const problem = symbolError(value, flows, index);
error.setText(problem ?? "");
// Invalid input stays in the field but is never saved.
if (problem) return;
flow.symbol = value;
updateTitle();
await this.save();
});
});
});
group.addSetting((s) => {
s.setName("Property")
.setDesc(
flow.kind === "ordered"
? "Ordered: the steps below, in order. Each step can set other properties."
: "Open: every value already used in the vault; new values allowed. No steps or hotkeys.",
) )
.addText((t) => .addText((t) =>
t t
@@ -211,8 +112,30 @@ export class FflowSettingTab extends PluginSettingTab {
updateTitle(); updateTitle();
await this.save(); await this.save();
}), }),
), )
.addDropdown((d) =>
d
.addOptions({ ordered: "Ordered list", open: "Open (vault)" })
.setValue(flow.kind)
.onChange(async (value) => {
flow.kind = value as FlowKind;
await this.saveAndRedraw();
}),
); );
if (flow.kind === "open") {
s.addDropdown((d) =>
d
.addOptions({ single: "Single value", list: "List" })
.setValue(flow.valueMode)
.onChange(async (value) => {
flow.valueMode = value as ValueMode;
await this.save();
}),
);
}
});
if (flow.kind === "open") return;
group.addSetting((s) => group.addSetting((s) =>
s s
@@ -226,7 +149,19 @@ export class FflowSettingTab extends PluginSettingTab {
), ),
); );
flow.steps.forEach((step, i) => { flow.steps.forEach((step, i) => this.renderStep(group, flow, step, i));
group.addSetting((s) =>
s.addButton((b) =>
b.setButtonText("Add step").onClick(async () => {
flow.steps.push({ value: "", effects: [] });
await this.saveAndRedraw();
}),
),
);
}
private renderStep(group: SettingGroup, flow: Flow, step: FlowStep, i: number): void {
group.addSetting((s) => { group.addSetting((s) => {
s.setName(`Step ${i + 1}`).setClass("fflow-step"); s.setName(`Step ${i + 1}`).setClass("fflow-step");
s.addText((t) => s.addText((t) =>
@@ -238,19 +173,18 @@ export class FflowSettingTab extends PluginSettingTab {
await this.save(); await this.save();
}), }),
); );
s.addText((t) => s.addExtraButton((b) =>
t b
.setPlaceholder("cssclasses (optional)") .setIcon("list-plus")
.setValue(step.cssclass) .setTooltip("Also set a property")
.onChange(async (value) => { .onClick(async () => {
step.cssclass = value.trim(); step.effects.push({ property: "", value: "" });
await this.save(); await this.saveAndRedraw();
}), }),
); );
const move = async (to: number) => { const move = async (to: number) => {
flow.steps.splice(to, 0, ...flow.steps.splice(i, 1)); flow.steps.splice(to, 0, ...flow.steps.splice(i, 1));
await this.save(); await this.saveAndRedraw();
this.display();
}; };
s.addExtraButton((b) => b.setIcon("arrow-up").setTooltip("Move up").setDisabled(i === 0).onClick(() => move(i - 1))); s.addExtraButton((b) => b.setIcon("arrow-up").setTooltip("Move up").setDisabled(i === 0).onClick(() => move(i - 1)));
s.addExtraButton((b) => s.addExtraButton((b) =>
@@ -266,20 +200,43 @@ export class FflowSettingTab extends PluginSettingTab {
.setTooltip("Remove step") .setTooltip("Remove step")
.onClick(async () => { .onClick(async () => {
flow.steps.splice(i, 1); flow.steps.splice(i, 1);
await this.save(); await this.saveAndRedraw();
this.display();
}), }),
); );
}); });
});
step.effects.forEach((effect, j) =>
group.addSetting((s) => group.addSetting((s) =>
s.addButton((b) => s
b.setButtonText("Add step").onClick(async () => { .setClass("fflow-effect")
flow.steps.push({ value: "", cssclass: "" }); .setDesc(j === 0 ? "Also sets" : "")
.addText((t) =>
t
.setPlaceholder("property")
.setValue(effect.property)
.onChange(async (value) => {
effect.property = value.trim();
await this.save(); await this.save();
this.display();
}), }),
)
.addText((t) =>
t
.setPlaceholder("value (lists: a, b)")
.setValue(effect.value)
.onChange(async (value) => {
effect.value = value;
await this.save();
}),
)
.addExtraButton((b) =>
b
.setIcon("x")
.setTooltip("Remove property")
.onClick(async () => {
step.effects.splice(j, 1);
await this.saveAndRedraw();
}),
),
), ),
); );
} }
+77 -33
View File
@@ -1,71 +1,115 @@
/** ordered: a fixed list of steps with effects and next/previous commands. open: any value already used in the vault. */
export type FlowKind = "ordered" | "open";
/** single: replace the value. list: append to a list, no duplicates. Ordered flows are always single. */
export type ValueMode = "single" | "list"; export type ValueMode = "single" | "list";
export type SourceMode = "open" | "finite" | "flow";
export interface TriggerRule { /** Another property written when the note reaches a step. */
/** One non-alphanumeric character that opens the suggestions. */ export interface FlowEffect {
symbol: string;
/** Frontmatter property written on selection. Ignored for flow sources: the flow owns it. */
property: string; property: string;
/** single: replace the value. list: append to a list, no duplicates. Flows are always single. */ /** Scalars: true/false and numbers are typed. List properties: comma-separated items. */
valueMode: ValueMode; value: string;
/** open: values already used in the vault. finite: `values`. flow: the steps of `flowId`. */
source: SourceMode;
values: string[];
flowId: string;
} }
export interface FlowStep { export interface FlowStep {
value: string; value: string;
/** Space-separated classes added to `cssclasses` while the note is on this step. */ effects: FlowEffect[];
cssclass: string;
} }
export interface Flow { export interface Flow {
/** Stable id: command ids derive from it, so hotkeys survive renames. */ /** Stable id: command ids derive from it, so hotkeys survive renames. */
id: string; id: string;
name: string; name: string;
/** Optional trigger: one non-alphanumeric character typed at the start of a word. */
symbol: string;
property: string; property: string;
kind: FlowKind;
valueMode: ValueMode;
/** After the last step, "next" goes back to the first (and "previous" the other way). */ /** After the last step, "next" goes back to the first (and "previous" the other way). */
loop: boolean; loop: boolean;
steps: FlowStep[]; steps: FlowStep[];
} }
export interface FflowSettings { export interface FflowSettings {
rules: TriggerRule[];
flows: Flow[]; flows: Flow[];
} }
export const NEW_RULE: TriggerRule = { symbol: "", property: "", valueMode: "single", source: "open", values: [], flowId: "" }; export function newFlow(fields: Partial<Flow>): Flow {
return {
export const DEFAULT_SETTINGS: FflowSettings = { id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
rules: [{ ...NEW_RULE, symbol: "@", property: "type" }], name: "",
flows: [], symbol: "",
property: "",
kind: "ordered",
valueMode: "single",
loop: false,
steps: [],
...fields,
}; };
}
export function defaultSettings(): FflowSettings {
return { flows: [newFlow({ name: "Type", symbol: "@", property: "type", kind: "open" })] };
}
/** Reserved by Obsidian or common plugins: tags, links, slash commands, emoji shortcodes. */ /** Reserved by Obsidian or common plugins: tags, links, slash commands, emoji shortcodes. */
export const BLOCKED_SYMBOLS = ["#", "[", "/", ":"]; export const BLOCKED_SYMBOLS = ["#", "[", "/", ":"];
/** Returns an error message, or null when `symbol` is usable by rule `index`. */ /** 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, rules: TriggerRule[], index: number): string | null { export function symbolError(symbol: string, flows: Flow[], index: number): string | null {
if (symbol === "") return null;
if ([...symbol].length !== 1) return "Use exactly one character."; 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 (/[\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 (BLOCKED_SYMBOLS.includes(symbol)) return `"${symbol}" is reserved (${BLOCKED_SYMBOLS.join(" ")}).`;
if (rules.some((r, i) => i !== index && r.symbol === symbol)) return `"${symbol}" is already used by another trigger.`; if (flows.some((f, i) => i !== index && f.symbol === symbol)) return `"${symbol}" is already used by another flow.`;
return null; return null;
} }
/** What a usable trigger writes to; null when the rule is incomplete or points to a missing flow. */ /** 0.1–0.2 stored separate triggers and flows; the shapes below are only read during migration. */
export function resolveRule(settings: FflowSettings, index: number): { property: string; flow: Flow | null } | null { interface LegacyRule {
const rule = settings.rules[index]; symbol: string;
if (symbolError(rule.symbol, settings.rules, index)) return null; property: string;
if (rule.source === "flow") { valueMode: ValueMode;
const flow = settings.flows.find((f) => f.id === rule.flowId); source: "open" | "finite" | "flow";
return flow && flow.property ? { property: flow.property, flow } : null; values: string[];
flowId?: string;
} }
return rule.property ? { property: rule.property, flow: null } : null; interface LegacyFlow {
id: string;
name: string;
property: string;
loop: boolean;
steps: { value: string; cssclass: string }[];
} }
/** Steps usable at runtime: blank values are skipped. */ /** Builds settings from saved data, converting the 0.1–0.2 trigger/flow split into flows. */
export function flowSteps(flow: Flow): FlowStep[] { export function loadSettings(saved: unknown): FflowSettings {
return flow.steps.filter((s) => s.value.trim() !== ""); 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<Flow>) => newFlow(f)) };
}
// Own persisted blob from an older version of this plugin; fields were always written together.
const legacy = saved as { rules?: LegacyRule[]; flows?: LegacyFlow[] };
const rules = legacy.rules ?? [];
const flows: Flow[] = (legacy.flows ?? []).map((f) =>
newFlow({
id: f.id,
name: f.name,
property: f.property,
loop: f.loop,
symbol: rules.find((r) => r.source === "flow" && r.flowId === f.id)?.symbol ?? "",
steps: f.steps.map((s) => ({
value: s.value,
effects: s.cssclass.trim() ? [{ property: "cssclasses", value: s.cssclass.trim().split(/\s+/).join(", ") }] : [],
})),
}),
);
for (const r of rules) {
if (r.source === "open") flows.push(newFlow({ name: r.property, symbol: r.symbol, property: r.property, kind: "open", valueMode: r.valueMode }));
if (r.source === "finite") {
flows.push(newFlow({ name: r.property, symbol: r.symbol, property: r.property, steps: r.values.map((value) => ({ value, effects: [] })) }));
}
}
return { flows };
} }
+23 -40
View File
@@ -1,13 +1,7 @@
import { App, Editor, EditorPosition, EditorSuggest, EditorSuggestContext, EditorSuggestTriggerInfo, Notice, TFile } from "obsidian"; import { App, Editor, EditorPosition, EditorSuggest, EditorSuggestContext, EditorSuggestTriggerInfo, Notice, TFile } from "obsidian";
import { setFlowStep, updateFrontmatter } from "./frontmatter"; import { setFlowStep, setOpenValue, updateFrontmatter } from "./frontmatter";
import type FflowPlugin from "./main"; import type FflowPlugin from "./main";
import { Flow, flowSteps, resolveRule, TriggerRule } from "./settings"; import { Flow, symbolError } from "./settings";
interface ActiveTrigger {
rule: TriggerRule;
property: string;
flow: Flow | null;
}
interface Suggestion { interface Suggestion {
value: string; value: string;
@@ -49,7 +43,7 @@ function flatten(raw: unknown): string[] {
const isSpace = (ch: string | undefined) => ch !== undefined && /\s/.test(ch); const isSpace = (ch: string | undefined) => ch !== undefined && /\s/.test(ch);
export class TriggerSuggest extends EditorSuggest<Suggestion> { export class TriggerSuggest extends EditorSuggest<Suggestion> {
private active: ActiveTrigger | null = null; private flow: Flow | null = null;
constructor(app: App, private plugin: FflowPlugin, private index: ValueIndex) { constructor(app: App, private plugin: FflowPlugin, private index: ValueIndex) {
super(app); super(app);
@@ -63,33 +57,32 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
const word = before.slice(start); const word = before.slice(start);
if (!word) return null; if (!word) return null;
const settings = this.plugin.settings; const flows = this.plugin.settings.flows;
const index = settings.rules.findIndex((r) => r.symbol === word[0]); const index = flows.findIndex((f) => f.symbol !== "" && f.symbol === word[0]);
const target = index === -1 ? null : resolveRule(settings, index); const flow = flows[index];
if (!target || inFrontmatter(editor, cursor.line) || inCode(editor, cursor.line, before.slice(0, start))) return null; if (!flow || !flow.property || symbolError(flow.symbol, flows, index)) return null;
if (inFrontmatter(editor, cursor.line) || inCode(editor, cursor.line, before.slice(0, start))) return null;
this.active = { rule: settings.rules[index], ...target }; this.flow = flow;
return { start: { line: cursor.line, ch: start }, end: cursor, query: word.slice(1) }; return { start: { line: cursor.line, ch: start }, end: cursor, query: word.slice(1) };
} }
getSuggestions(context: EditorSuggestContext): Suggestion[] { getSuggestions(context: EditorSuggestContext): Suggestion[] {
const active = this.active; const flow = this.flow;
if (!active) return []; if (!flow) return [];
const { rule, flow } = active;
const query = context.query.toLowerCase(); const query = context.query.toLowerCase();
const pool: Suggestion[] = flow const pool: Suggestion[] =
? flowSteps(flow).map((s) => ({ value: s.value, isNew: false })) flow.kind === "ordered"
: rule.source === "finite" ? flow.steps.filter((s) => s.value).map((s) => ({ value: s.value, isNew: false }))
? rule.values.map((value) => ({ value, isNew: false })) : [...this.index.get(flow.property)]
: [...this.index.get(active.property)]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.map(([value, count]) => ({ value, count, isNew: false })); .map(([value, count]) => ({ value, count, isNew: false }));
const matches = pool.filter((s) => s.value.toLowerCase().includes(query)); const matches = pool.filter((s) => s.value.toLowerCase().includes(query));
// Stable sort: prefix matches first, original ranking kept inside each group. // Stable sort: prefix matches first, original ranking kept inside each group.
matches.sort((a, b) => Number(!a.value.toLowerCase().startsWith(query)) - Number(!b.value.toLowerCase().startsWith(query))); matches.sort((a, b) => Number(!a.value.toLowerCase().startsWith(query)) - Number(!b.value.toLowerCase().startsWith(query)));
if (rule.source === "open" && query && !pool.some((s) => s.value.toLowerCase() === query)) { if (flow.kind === "open" && query && !pool.some((s) => s.value.toLowerCase() === query)) {
matches.push({ value: context.query, isNew: true }); matches.push({ value: context.query, isNew: true });
} }
return matches; return matches;
@@ -108,12 +101,12 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
selectSuggestion(s: Suggestion, _evt: MouseEvent | KeyboardEvent): void { selectSuggestion(s: Suggestion, _evt: MouseEvent | KeyboardEvent): void {
const context = this.context; const context = this.context;
const active = this.active; const flow = this.flow;
if (!context || !active) return; if (!context || !flow) return;
void this.apply(context, active, s.value); void this.apply(context, flow, s.value);
} }
private async apply(context: EditorSuggestContext, { rule, property, flow }: ActiveTrigger, value: string): Promise<void> { private async apply(context: EditorSuggestContext, flow: Flow, value: string): Promise<void> {
const { editor, file, start } = context; const { editor, file, start } = context;
const line = editor.getLine(start.line); const line = editor.getLine(start.line);
@@ -126,22 +119,12 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
try { try {
await updateFrontmatter(this.app, file, (fm) => { await updateFrontmatter(this.app, file, (fm) => {
if (flow) { if (flow.kind === "ordered") setFlowStep(this.app, fm, flow, value);
setFlowStep(fm, flow, value); else setOpenValue(fm, flow.property, value, flow.valueMode === "list");
return;
}
if (rule.valueMode === "single") {
fm[property] = value;
return;
}
const current = fm[property];
const list: unknown[] = current == null ? [] : Array.isArray(current) ? current : [current];
if (!list.some((v) => String(v) === value)) list.push(value);
fm[property] = list;
}); });
} catch (err) { } catch (err) {
console.error("FFLOW: could not update frontmatter", err); console.error("FFLOW: could not update frontmatter", err);
new Notice(`FFLOW: could not set "${property}". See console.`); new Notice(`FFLOW: could not set "${flow.property}". See console.`);
} }
} }
} }
+30 -4
View File
@@ -2,13 +2,43 @@
color: var(--text-error); color: var(--text-error);
} }
.fflow-error:empty {
display: none;
}
.fflow-symbol { .fflow-symbol {
width: 3em; width: 3em;
text-align: center; text-align: center;
font-family: var(--font-monospace); font-family: var(--font-monospace);
} }
.fflow-badge {
font-family: var(--font-monospace);
background: var(--background-modifier-hover);
border-radius: var(--radius-s);
padding: 0 0.4em;
margin-right: 0.5em;
}
.fflow-step .setting-item-control input[type="text"] { .fflow-step .setting-item-control input[type="text"] {
width: 14em;
}
/* Properties set by a step: indented, no separator line, so they read as part of the step above. */
.setting-items > .setting-item.fflow-effect {
padding-top: 0;
padding-left: 2.5em;
}
.setting-items > .setting-item.fflow-effect::before {
display: none;
}
.fflow-effect .setting-item-description {
color: var(--text-faint);
}
.fflow-effect .setting-item-control input[type="text"] {
width: 11em; width: 11em;
} }
@@ -27,7 +57,3 @@
.fflow-new { .fflow-new {
color: var(--text-muted); color: var(--text-muted);
} }
.fflow-error:empty {
display: none;
}