FFLOW 0.2.0: flows with next/previous commands and per-step cssclasses; grouped settings page

This commit is contained in:
olivier committed 2026-10-25 17:54:31 -04:00
1 parent 021777203b
commit 68e390fb37
12 files changed
+450 -129

No files matched your search

+12 -3
View File
@@ -9,12 +9,21 @@ Type `@mee`, pick `meeting`: the text `@mee` disappears and the note gets `type:
Each trigger (Settings → FFLOW) has: Each trigger (Settings → FFLOW) has:
- **Symbol**: one character that is not a letter, digit or space. `# [ / :` are reserved (tags, links, slash commands, emoji). Default: `@`. - **Symbol**: one character that is not a letter, digit or space. `# [ / :` are reserved (tags, links, slash commands, emoji). Default: `@`.
- **Property**: the frontmatter key to write. Default: `type`. - **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).
- **Value mode**: *Single value* replaces the value; *List* appends without duplicates. - **Property** and **value mode** (open and fixed lists): the frontmatter key to write (default `type`); *Single value* replaces the value, *List* appends without duplicates.
- **Suggestions**: *Open* lists every value already used for that property in the vault, ranked by use, and accepts new values. *Finite* only offers the values listed in the settings.
A trigger fires only at the start of a word (line start or after a space), and never inside frontmatter or code. A trigger fires only at the start of a word (line start or after a space), and never inside frontmatter or code.
## Flows
A flow is an ordered list of values for one property, e.g. `status`: `todo` → `started` → `in-progress` → `done`.
- 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).
- 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.
- 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.
- A trigger whose values come from a flow applies the same cssclasses, so `!done` and the hotkey give the same result.
- cssclasses change only through FFLOW (hotkeys or triggers), not when the property is edited by hand.
## Development ## Development
``` ```
+7 -4
View File
@@ -1,7 +1,10 @@
# FFLOW roadmap # FFLOW roadmap
## Next version ## Next
- **Property cycle hotkeys.** Assign a hotkey that moves a property to the next value in an ordered list, e.g. `status: started` → `status: in-progress` → … . - **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).
- **cssclasses with the cycle.** Each step of a cycle can also set the note's `cssclasses` (replace the previous step's class, keep other classes).
- **Finite list from a note.** Setting per trigger: take the finite list from the plugin settings (current) or from a note in the vault (one value per line or list items). ## 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.1.0 — Triggers: symbol → property, open (vault) or fixed list, single value or list.
+2 -2
View File
@@ -2,6 +2,6 @@
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
*/ */
var x=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var D=(n,s)=>{for(var e in s)x(n,e,{get:s[e],enumerable:!0})},P=(n,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of R(s))!A.call(n,i)&&i!==e&&x(n,i,{get:()=>s[i],enumerable:!(t=N(s,i))||t.enumerable});return n};var V=n=>P(x({},"__esModule",{value:!0}),n);var B={};D(B,{default:()=>S});module.exports=V(B);var F=require("obsidian");var T={rules:[{symbol:"@",property:"type",valueMode:"single",source:"open",values:[]}]},h=["#","[","/",":"];function m(n,s,e){return[...n].length!==1?"Use exactly one character.":/[\p{L}\p{N}\s]/u.test(n)?"Letters, digits and spaces are not allowed.":h.includes(n)?`"${n}" is reserved (${h.join(" ")}).`:s.some((t,i)=>i!==e&&t.symbol===n)?`"${n}" is already used by another rule.`:null}function C(n,s,e){return n.property.trim()!==""&&m(n.symbol,s,e)===null}var c=require("obsidian");var y=class extends c.PluginSettingTab{constructor(e,t){super(e,t);this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("p",{cls:"setting-item-description",text:`Type a trigger symbol at the start of a word to pick a value. The typed text is removed and the value is written to the note's frontmatter. Reserved symbols: ${h.join(" ")}`}),this.plugin.settings.rules.forEach((t,i)=>this.renderRule(t,i)),new c.Setting(e).addButton(t=>t.setButtonText("Add trigger").setCta().onClick(async()=>{this.plugin.settings.rules.push({symbol:"",property:"",valueMode:"single",source:"open",values:[]}),await this.plugin.saveSettings(),this.display()}))}renderRule(e,t){let i=this.plugin.settings.rules,r=()=>this.plugin.saveSettings(),o=this.containerEl.createDiv({cls:"fflow-rule"});new c.Setting(o).setHeading().setName(e.symbol&&e.property?`${e.symbol} \u2192 ${e.property}`:"New trigger").addExtraButton(l=>l.setIcon("trash").setTooltip("Delete trigger").onClick(async()=>{i.splice(t,1),await r(),this.display()}));let a=new c.Setting(o).setName("Symbol").setDesc("One character, not a letter or digit."),g=a.descEl.createDiv({cls:"fflow-error"}),p=l=>{var u;return g.setText((u=m(l,i,t))!=null?u:"")};a.addText(l=>{l.setPlaceholder("@").setValue(e.symbol),l.inputEl.addClass("fflow-symbol"),l.onChange(async u=>{p(u),!m(u,i,t)&&(e.symbol=u,await r())})}),e.symbol&&p(e.symbol),new c.Setting(o).setName("Property").setDesc("Frontmatter property to set.").addText(l=>l.setPlaceholder("type").setValue(e.property).onChange(async u=>{e.property=u.trim(),await r()})),new c.Setting(o).setName("Value mode").setDesc("Single replaces the current value. List adds to the existing values.").addDropdown(l=>l.addOptions({single:"Single value",list:"List"}).setValue(e.valueMode).onChange(async u=>{e.valueMode=u,await r()})),new c.Setting(o).setName("Suggestions").setDesc("Open: every value already used in the vault; new values are allowed. Finite: only the values listed below.").addDropdown(l=>l.addOptions({open:"Open (from vault)",finite:"Finite list"}).setValue(e.source).onChange(async u=>{e.source=u,await r(),this.display()})),e.source==="finite"&&new c.Setting(o).setName("Values").setDesc("One value per line, in the order they should appear.").addTextArea(l=>{l.setValue(e.values.join(` 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
`)).onChange(async u=>{e.values=u.split(` `)).onChange(async u=>{e.values=u.split(`
`).map(d=>d.trim()).filter(Boolean),await r()}),l.inputEl.rows=6})}};var f=require("obsidian");var v=class{constructor(s){this.app=s;this.cache=new Map}invalidate(){this.cache.clear()}get(s){var t,i,r;let e=this.cache.get(s);if(e)return e;e=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=(i=(t=this.app.metadataCache.getFileCache(o))==null?void 0:t.frontmatter)==null?void 0:i[s];for(let g of new Set(M(a)))e.set(g,((r=e.get(g))!=null?r:0)+1)}return this.cache.set(s,e),e}};function M(n){return Array.isArray(n)?n.flatMap(M):typeof n=="string"?n.trim()?[n.trim()]:[]:typeof n=="number"||typeof n=="boolean"?[String(n)]:[]}var E=n=>n!==void 0&&/\s/.test(n),w=class extends f.EditorSuggest{constructor(e,t,i){super(e);this.plugin=t;this.index=i;this.rule=null}onTrigger(e,t,i){let r=t.getLine(e.line).slice(0,e.ch),o=r.length;for(;o>0&&!E(r[o-1]);)o--;let a=r.slice(o);if(!a)return null;let g=this.plugin.settings.rules,p=g.find((l,u)=>l.symbol===a[0]&&C(l,g,u));return!p||O(t,e.line)||k(t,e.line,r.slice(0,o))?null:(this.rule=p,{start:{line:e.line,ch:o},end:e,query:a.slice(1)})}getSuggestions(e){let t=this.rule;if(!t)return[];let i=e.query.toLowerCase(),r=t.source==="finite"?t.values.map(a=>({value:a,isNew:!1})):[...this.index.get(t.property)].sort((a,g)=>g[1]-a[1]||a[0].localeCompare(g[0])).map(([a,g])=>({value:a,count:g,isNew:!1})),o=r.filter(a=>a.value.toLowerCase().includes(i));return o.sort((a,g)=>+!a.value.toLowerCase().startsWith(i)-+!g.value.toLowerCase().startsWith(i)),t.source==="open"&&i&&!r.some(a=>a.value.toLowerCase()===i)&&o.push({value:e.query,isNew:!0}),o}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 i=this.context,r=this.rule;!i||!r||this.apply(i,r,e.value)}async apply(e,t,i){let{editor:r,file:o,start:a}=e,g=r.getLine(a.line),p=e.end.ch;for(;p<g.length&&!E(g[p]);)p++;E(g[p])&&p++,r.replaceRange("",a,{line:a.line,ch:p}),r.setCursor(a);try{let l=this.app.workspace.getActiveViewOfType(f.MarkdownView);(l==null?void 0:l.file)===o&&await l.save(),await this.app.fileManager.processFrontMatter(o,u=>{if(t.valueMode==="single"){u[t.property]=i;return}let d=u[t.property],b=d==null?[]:Array.isArray(d)?d:[d];b.some(L=>String(L)===i)||b.push(i),u[t.property]=b})}catch(l){console.error("FFLOW: could not update frontmatter",l),new f.Notice(`FFLOW: could not set "${t.property}". See console.`)}}};function O(n,s){if(n.getLine(0)!=="---")return!1;for(let e=1;e<n.lineCount();e++)if(n.getLine(e)==="---")return s<=e;return!1}function k(n,s,e){var i,r;let t=0;for(let o=0;o<s;o++)/^\s*(```|~~~)/.test(n.getLine(o))&&t++;return t%2===1?!0:((r=(i=e.match(/`/g))==null?void 0:i.length)!=null?r:0)%2===1}var S=class extends F.Plugin{async onload(){await this.loadSettings();let s=new v(this.app);this.registerEvent(this.app.metadataCache.on("changed",()=>s.invalidate())),this.registerEvent(this.app.metadataCache.on("deleted",()=>s.invalidate())),this.registerEditorSuggest(new w(this.app,this,s)),this.addSettingTab(new y(this.app,this))}async loadSettings(){let s=await this.loadData();this.settings={...T,...s}}async saveSettings(){await this.saveData(this.settings)}}; `).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
+2 -2
View File
@@ -1,8 +1,8 @@
{ {
"id": "fflow", "id": "fflow",
"name": "FFLOW", "name": "FFLOW",
"version": "0.1.0", "version": "0.2.0",
"minAppVersion": "1.4.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",
"isDesktopOnly": false "isDesktopOnly": false
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "fflow", "name": "fflow",
"version": "0.1.0", "version": "0.2.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": {
+63
View File
@@ -0,0 +1,63 @@
import { Notice, TFile } from "obsidian";
import { setFlowStep, updateFrontmatter } from "./frontmatter";
import type FflowPlugin from "./main";
import { Flow, flowSteps } from "./settings";
type Direction = 1 | -1;
/** Re-registers the next/previous commands of every flow. Ids derive from the flow id, so hotkeys survive renames. */
export class FlowCommands {
private registered: string[] = [];
constructor(private plugin: FflowPlugin) {}
sync(): void {
for (const id of this.registered) this.plugin.removeCommand(id);
this.registered = [];
for (const flow of this.plugin.settings.flows) {
this.add(flow, 1, "next", "next step");
this.add(flow, -1, "previous", "previous step");
}
}
private add(flow: Flow, direction: Direction, suffix: string, label: string): void {
const id = `flow-${flow.id}-${suffix}`;
this.registered.push(id);
this.plugin.addCommand({
id,
name: `${flow.name || flow.property || "Unnamed flow"}: ${label}`,
checkCallback: (checking) => {
const file = this.plugin.app.workspace.getActiveFile();
if (!file || file.extension !== "md" || !flow.property || flowSteps(flow).length === 0) return false;
if (!checking) void moveStep(this.plugin, file, flow, direction);
return true;
},
});
}
}
async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction: Direction): Promise<void> {
const steps = flowSteps(flow);
let message = "";
try {
// Read the current value inside the update: the metadata cache can lag behind the editor.
await updateFrontmatter(plugin.app, file, (fm) => {
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;
if (target < 0 || target >= steps.length) {
if (!flow.loop) {
message = `${flow.property}: already at the ${direction === 1 ? "last" : "first"} step`;
return;
}
target = (target + steps.length) % steps.length;
}
setFlowStep(fm, flow, steps[target].value);
message = `${flow.property}: ${steps[target].value}`;
});
new Notice(message);
} catch (err) {
console.error("FFLOW: could not move flow step", err);
new Notice(`FFLOW: could not set "${flow.property}". See console.`);
}
}
+31
View File
@@ -0,0 +1,31 @@
import { App, MarkdownView, TFile } from "obsidian";
import type { Flow } from "./settings";
export type Frontmatter = Record<string, unknown>;
/** processFrontMatter rewrites the file on disk, so flush the open editor first or unsaved typing is lost. */
export async function updateFrontmatter(app: App, file: TFile, fn: (fm: Frontmatter) => void): Promise<void> {
const view = app.workspace.getActiveViewOfType(MarkdownView);
if (view?.file === file) await view.save();
await app.fileManager.processFrontMatter(file, fn);
}
/**
* Put the note on `value` of `flow`: set the property, drop the classes of every
* step of this flow from `cssclasses`, then add the classes of the new step.
* Classes that don't belong to the flow are kept.
*/
export function setFlowStep(fm: Frontmatter, flow: Flow, value: string): void {
fm[flow.property] = value;
const split = (s: string) => s.split(/\s+/).filter(Boolean);
const flowClasses = new Set(flow.steps.flatMap((s) => split(s.cssclass)));
const current = fm.cssclasses;
const existing = (Array.isArray(current) ? current : typeof current === "string" ? split(current) : []).map(String);
const step = flow.steps.find((s) => s.value === value);
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;
else if (current !== undefined) delete fm.cssclasses;
}
+11 -3
View File
@@ -1,10 +1,12 @@
import { Plugin } from "obsidian"; import { Plugin } from "obsidian";
import { DEFAULT_SETTINGS, FflowSettings } from "./settings"; import { FlowCommands } from "./flows";
import { DEFAULT_SETTINGS, FflowSettings, NEW_RULE } from "./settings";
import { FflowSettingTab } from "./settings-tab"; import { FflowSettingTab } from "./settings-tab";
import { TriggerSuggest, ValueIndex } from "./suggest"; import { TriggerSuggest, ValueIndex } from "./suggest";
export default class FflowPlugin extends Plugin { export default class FflowPlugin extends Plugin {
settings!: FflowSettings; settings!: FflowSettings;
private flowCommands = new FlowCommands(this);
async onload(): Promise<void> { async onload(): Promise<void> {
await this.loadSettings(); await this.loadSettings();
@@ -14,15 +16,21 @@ export default class FflowPlugin extends Plugin {
this.registerEvent(this.app.metadataCache.on("deleted", () => index.invalidate())); this.registerEvent(this.app.metadataCache.on("deleted", () => index.invalidate()));
this.registerEditorSuggest(new TriggerSuggest(this.app, this, index)); this.registerEditorSuggest(new TriggerSuggest(this.app, this, index));
this.flowCommands.sync();
this.addSettingTab(new FflowSettingTab(this.app, this)); this.addSettingTab(new FflowSettingTab(this.app, this));
} }
async loadSettings(): Promise<void> { async loadSettings(): Promise<void> {
const saved = (await this.loadData()) as Partial<FflowSettings> | null; const saved = ((await this.loadData()) ?? {}) as Partial<FflowSettings>;
this.settings = { ...DEFAULT_SETTINGS, ...saved }; 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();
} }
} }
+234 -62
View File
@@ -1,125 +1,297 @@
import { App, PluginSettingTab, Setting } from "obsidian"; import { App, PluginSettingTab, SearchComponent, Setting, SettingGroup } from "obsidian";
import type FflowPlugin from "./main"; import type FflowPlugin from "./main";
import { BLOCKED_SYMBOLS, SourceMode, symbolError, TriggerRule, ValueMode } from "./settings"; import { BLOCKED_SYMBOLS, Flow, NEW_RULE, symbolError, TriggerRule, 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) {
super(app, plugin); super(app, plugin);
} }
private save = () => this.plugin.saveSettings();
display(): void { display(): void {
const { containerEl } = this; const { containerEl } = this;
const settings = this.plugin.settings;
containerEl.empty(); containerEl.empty();
containerEl.createEl("p", {
cls: "setting-item-description",
text:
"Type a trigger symbol at the start of a word to pick a value. The typed text is removed and the value is written to the note's frontmatter. " +
`Reserved symbols: ${BLOCKED_SYMBOLS.join(" ")}`,
});
this.plugin.settings.rules.forEach((rule, index) => this.renderRule(rule, index)); new Setting(containerEl)
.setHeading()
new Setting(containerEl).addButton((b) => .setName("Triggers")
b .setDesc(
.setButtonText("Add trigger") `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(" ")}`,
.setCta() )
.onClick(async () => { .addButton((b) =>
this.plugin.settings.rules.push({ symbol: "", property: "", valueMode: "single", source: "open", values: [] }); b.setButtonText("Add trigger").onClick(async () => {
await this.plugin.saveSettings(); settings.rules.push({ ...NEW_RULE, values: [] });
await this.save();
this.display(); this.display();
}), }),
); );
settings.rules.forEach((rule, index) => this.renderRule(rule, index));
new Setting(containerEl)
.setHeading()
.setName("Flows")
.setDesc("Ordered values for a property. Each step can add cssclasses. Every flow gets “next step” and “previous step” commands for hotkeys.")
.addButton((b) => b.setButtonText("Hotkeys").onClick(() => this.openHotkeys()))
.addButton((b) =>
b.setButtonText("Add flow").onClick(async () => {
settings.flows.push({ id: Date.now().toString(36), name: "", property: "", loop: false, steps: [{ value: "", cssclass: "" }] });
await this.save();
this.display();
}),
);
settings.flows.forEach((flow, index) => this.renderFlow(flow, index));
} }
private renderRule(rule: TriggerRule, index: number): void { private renderRule(rule: TriggerRule, index: number): void {
const rules = this.plugin.settings.rules; const settings = this.plugin.settings;
const save = () => this.plugin.saveSettings(); const flow = rule.source === "flow" ? settings.flows.find((f) => f.id === rule.flowId) : undefined;
const box = this.containerEl.createDiv({ cls: "fflow-rule" });
new Setting(box) const title = createFragment();
.setHeading() const titleEl = title.createSpan();
.setName(rule.symbol && rule.property ? `${rule.symbol} → ${rule.property}` : "New trigger") const updateTitle = () => {
.addExtraButton((b) => 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 b
.setIcon("trash") .setIcon("trash")
.setTooltip("Delete trigger") .setTooltip("Delete trigger")
.onClick(async () => { .onClick(async () => {
rules.splice(index, 1); settings.rules.splice(index, 1);
await save(); await this.save();
this.display(); this.display();
}), }),
); );
const symbolSetting = new Setting(box).setName("Symbol").setDesc("One character, not a letter or digit."); group.addSetting((s) => {
const error = symbolSetting.descEl.createDiv({ cls: "fflow-error" }); s.setName("Symbol");
const showError = (value: string) => error.setText(symbolError(value, rules, index) ?? ""); const error = s.descEl.createDiv({ cls: "fflow-error" });
symbolSetting.addText((t) => { 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.setPlaceholder("@").setValue(rule.symbol);
t.inputEl.addClass("fflow-symbol"); t.inputEl.addClass("fflow-symbol");
t.onChange(async (value) => { t.onChange(async (value) => {
showError(value); check(value);
// Invalid input stays in the field but is never saved. // Invalid input stays in the field but is never saved.
if (symbolError(value, rules, index)) return; if (symbolError(value, settings.rules, index)) return;
rule.symbol = value; rule.symbol = value;
await save(); updateTitle();
await this.save();
});
}); });
}); });
if (rule.symbol) showError(rule.symbol);
new Setting(box) 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") .setName("Property")
.setDesc("Frontmatter property to set.")
.addText((t) => .addText((t) =>
t t
.setPlaceholder("type") .setPlaceholder("type")
.setValue(rule.property) .setValue(rule.property)
.onChange(async (value) => { .onChange(async (value) => {
rule.property = value.trim(); rule.property = value.trim();
await save(); updateTitle();
await this.save();
}), }),
); )
new Setting(box)
.setName("Value mode")
.setDesc("Single replaces the current value. List adds to the existing values.")
.addDropdown((d) => .addDropdown((d) =>
d d
.addOptions({ single: "Single value", list: "List" }) .addOptions({ single: "Single value", list: "List" })
.setValue(rule.valueMode) .setValue(rule.valueMode)
.onChange(async (value) => { .onChange(async (value) => {
rule.valueMode = value as ValueMode; rule.valueMode = value as ValueMode;
await save(); await this.save();
}),
);
new Setting(box)
.setName("Suggestions")
.setDesc("Open: every value already used in the vault; new values are allowed. Finite: only the values listed below.")
.addDropdown((d) =>
d
.addOptions({ open: "Open (from vault)", finite: "Finite list" })
.setValue(rule.source)
.onChange(async (value) => {
rule.source = value as SourceMode;
await save();
this.display();
}), }),
),
); );
if (rule.source === "finite") { if (rule.source === "finite") {
new Setting(box) group.addSetting((s) =>
s
.setName("Values") .setName("Values")
.setDesc("One value per line, in the order they should appear.") .setDesc("One per line, in display order.")
.addTextArea((t) => { .addTextArea((t) => {
t.setValue(rule.values.join("\n")).onChange(async (value) => { t.setValue(rule.values.join("\n")).onChange(async (value) => {
rule.values = value rule.values = value
.split("\n") .split("\n")
.map((v) => v.trim()) .map((v) => v.trim())
.filter(Boolean); .filter(Boolean);
await save(); await this.save();
});
t.inputEl.rows = 6;
}); });
t.inputEl.rows = 5;
}),
);
} }
} }
private renderFlow(flow: Flow, index: number): void {
const settings = this.plugin.settings;
const title = createFragment();
const titleEl = title.createSpan();
const updateTitle = () => titleEl.setText(flow.name || flow.property || "New flow");
updateTitle();
const group = new SettingGroup(this.containerEl).setHeading(title).addClass("fflow-group");
group.addExtraButton((b) =>
b
.setIcon("trash")
.setTooltip("Delete flow")
.onClick(async () => {
settings.flows.splice(index, 1);
// Triggers that used this flow keep writing the same property, from the vault's values.
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) =>
s
.setName("Name and property")
.setDesc("The name labels the hotkey commands.")
.addText((t) =>
t
.setPlaceholder("Status")
.setValue(flow.name)
.onChange(async (value) => {
flow.name = value;
updateTitle();
await this.save();
}),
)
.addText((t) =>
t
.setPlaceholder("status")
.setValue(flow.property)
.onChange(async (value) => {
flow.property = value.trim();
updateTitle();
await this.save();
}),
),
);
group.addSetting((s) =>
s
.setName("Loop")
.setDesc("After the last step, “next” goes back to the first.")
.addToggle((t) =>
t.setValue(flow.loop).onChange(async (value) => {
flow.loop = value;
await this.save();
}),
),
);
flow.steps.forEach((step, i) => {
group.addSetting((s) => {
s.setName(`Step ${i + 1}`).setClass("fflow-step");
s.addText((t) =>
t
.setPlaceholder("value")
.setValue(step.value)
.onChange(async (value) => {
step.value = value.trim();
await this.save();
}),
);
s.addText((t) =>
t
.setPlaceholder("cssclasses (optional)")
.setValue(step.cssclass)
.onChange(async (value) => {
step.cssclass = value.trim();
await this.save();
}),
);
const move = async (to: number) => {
flow.steps.splice(to, 0, ...flow.steps.splice(i, 1));
await this.save();
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-down")
.setTooltip("Move down")
.setDisabled(i === flow.steps.length - 1)
.onClick(() => move(i + 1)),
);
s.addExtraButton((b) =>
b
.setIcon("x")
.setTooltip("Remove step")
.onClick(async () => {
flow.steps.splice(i, 1);
await this.save();
this.display();
}),
);
});
});
group.addSetting((s) =>
s.addButton((b) =>
b.setButtonText("Add step").onClick(async () => {
flow.steps.push({ value: "", cssclass: "" });
await this.save();
this.display();
}),
),
);
}
/** Opens Settings → Hotkeys filtered on this plugin. `app.setting` and the tab's search box are internal API: probe before use. */
private openHotkeys(): void {
const setting: unknown = Reflect.get(this.app, "setting");
if (!setting || typeof setting !== "object" || !("openTabById" in setting) || typeof setting.openTabById !== "function") return;
const tab: unknown = setting.openTabById("hotkeys");
const search = tab && typeof tab === "object" && "searchComponent" in tab ? tab.searchComponent : null;
if (!(search instanceof SearchComponent)) return;
search.setValue(this.plugin.manifest.name);
search.inputEl.dispatchEvent(new Event("input"));
}
} }
+41 -8
View File
@@ -1,24 +1,45 @@
export type ValueMode = "single" | "list"; export type ValueMode = "single" | "list";
export type SourceMode = "open" | "finite"; export type SourceMode = "open" | "finite" | "flow";
export interface TriggerRule { export interface TriggerRule {
/** One non-alphanumeric character that opens the suggestions. */ /** One non-alphanumeric character that opens the suggestions. */
symbol: string; symbol: string;
/** Frontmatter property written on selection. */ /** 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. */ /** single: replace the value. list: append to a list, no duplicates. Flows are always single. */
valueMode: ValueMode; valueMode: ValueMode;
/** open: values already used in the vault. finite: `values` below. */ /** open: values already used in the vault. finite: `values`. flow: the steps of `flowId`. */
source: SourceMode; source: SourceMode;
values: string[]; values: string[];
flowId: string;
}
export interface FlowStep {
value: string;
/** Space-separated classes added to `cssclasses` while the note is on this step. */
cssclass: string;
}
export interface Flow {
/** Stable id: command ids derive from it, so hotkeys survive renames. */
id: string;
name: string;
property: string;
/** After the last step, "next" goes back to the first (and "previous" the other way). */
loop: boolean;
steps: FlowStep[];
} }
export interface FflowSettings { export interface FflowSettings {
rules: TriggerRule[]; rules: TriggerRule[];
flows: Flow[];
} }
export const NEW_RULE: TriggerRule = { symbol: "", property: "", valueMode: "single", source: "open", values: [], flowId: "" };
export const DEFAULT_SETTINGS: FflowSettings = { export const DEFAULT_SETTINGS: FflowSettings = {
rules: [{ symbol: "@", property: "type", valueMode: "single", source: "open", values: [] }], rules: [{ ...NEW_RULE, symbol: "@", property: "type" }],
flows: [],
}; };
/** Reserved by Obsidian or common plugins: tags, links, slash commands, emoji shortcodes. */ /** Reserved by Obsidian or common plugins: tags, links, slash commands, emoji shortcodes. */
@@ -29,10 +50,22 @@ export function symbolError(symbol: string, rules: TriggerRule[], index: number)
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 rule.`; if (rules.some((r, i) => i !== index && r.symbol === symbol)) return `"${symbol}" is already used by another trigger.`;
return null; return null;
} }
export function isRuleActive(rule: TriggerRule, rules: TriggerRule[], index: number): boolean { /** What a usable trigger writes to; null when the rule is incomplete or points to a missing flow. */
return rule.property.trim() !== "" && symbolError(rule.symbol, rules, index) === null; export function resolveRule(settings: FflowSettings, index: number): { property: string; flow: Flow | null } | null {
const rule = settings.rules[index];
if (symbolError(rule.symbol, settings.rules, index)) return null;
if (rule.source === "flow") {
const flow = settings.flows.find((f) => f.id === rule.flowId);
return flow && flow.property ? { property: flow.property, flow } : null;
}
return rule.property ? { property: rule.property, flow: null } : null;
}
/** Steps usable at runtime: blank values are skipped. */
export function flowSteps(flow: Flow): FlowStep[] {
return flow.steps.filter((s) => s.value.trim() !== "");
} }
+36 -36
View File
@@ -1,16 +1,13 @@
import { import { App, Editor, EditorPosition, EditorSuggest, EditorSuggestContext, EditorSuggestTriggerInfo, Notice, TFile } from "obsidian";
App, import { setFlowStep, updateFrontmatter } from "./frontmatter";
Editor,
EditorPosition,
EditorSuggest,
EditorSuggestContext,
EditorSuggestTriggerInfo,
MarkdownView,
Notice,
TFile,
} from "obsidian";
import type FflowPlugin from "./main"; import type FflowPlugin from "./main";
import { isRuleActive, TriggerRule } from "./settings"; import { Flow, flowSteps, resolveRule, TriggerRule } from "./settings";
interface ActiveTrigger {
rule: TriggerRule;
property: string;
flow: Flow | null;
}
interface Suggestion { interface Suggestion {
value: string; value: string;
@@ -52,7 +49,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 rule: TriggerRule | null = null; private active: ActiveTrigger | null = null;
constructor(app: App, private plugin: FflowPlugin, private index: ValueIndex) { constructor(app: App, private plugin: FflowPlugin, private index: ValueIndex) {
super(app); super(app);
@@ -66,26 +63,28 @@ 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 rules = this.plugin.settings.rules; const settings = this.plugin.settings;
const rule = rules.find((r, i) => r.symbol === word[0] && isRuleActive(r, rules, i)); const index = settings.rules.findIndex((r) => r.symbol === word[0]);
if (!rule || inFrontmatter(editor, cursor.line) || inCode(editor, cursor.line, before.slice(0, start))) return null; const target = index === -1 ? null : resolveRule(settings, index);
if (!target || inFrontmatter(editor, cursor.line) || inCode(editor, cursor.line, before.slice(0, start))) return null;
this.rule = rule; this.active = { rule: settings.rules[index], ...target };
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 rule = this.rule; const active = this.active;
if (!rule) return []; if (!active) return [];
const { rule, flow } = active;
const query = context.query.toLowerCase(); const query = context.query.toLowerCase();
const pool: Suggestion[] = const pool: Suggestion[] = flow
rule.source === "finite" ? flowSteps(flow).map((s) => ({ value: s.value, isNew: false }))
: rule.source === "finite"
? rule.values.map((value) => ({ value, isNew: false })) ? rule.values.map((value) => ({ value, isNew: false }))
: [...this.index.get(rule.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)));
@@ -109,12 +108,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 rule = this.rule; const active = this.active;
if (!context || !rule) return; if (!context || !active) return;
void this.apply(context, rule, s.value); void this.apply(context, active, s.value);
} }
private async apply(context: EditorSuggestContext, rule: TriggerRule, value: string): Promise<void> { private async apply(context: EditorSuggestContext, { rule, property, flow }: ActiveTrigger, 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 +125,23 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
editor.setCursor(start); editor.setCursor(start);
try { try {
// Flush the editor first: processFrontMatter rewrites the file on disk. await updateFrontmatter(this.app, file, (fm) => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView); if (flow) {
if (view?.file === file) await view.save(); setFlowStep(fm, flow, value);
await this.app.fileManager.processFrontMatter(file, (fm: Record<string, unknown>) => {
if (rule.valueMode === "single") {
fm[rule.property] = value;
return; return;
} }
const current = fm[rule.property]; if (rule.valueMode === "single") {
fm[property] = value;
return;
}
const current = fm[property];
const list: unknown[] = current == null ? [] : Array.isArray(current) ? current : [current]; const list: unknown[] = current == null ? [] : Array.isArray(current) ? current : [current];
if (!list.some((v) => String(v) === value)) list.push(value); if (!list.some((v) => String(v) === value)) list.push(value);
fm[rule.property] = list; 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 "${rule.property}". See console.`); new Notice(`FFLOW: could not set "${property}". See console.`);
} }
} }
} }
+10 -8
View File
@@ -1,17 +1,15 @@
.fflow-rule {
border: 1px solid var(--background-modifier-border);
border-radius: var(--radius-m);
padding: 0 var(--size-4-3);
margin-bottom: var(--size-4-3);
}
.fflow-error { .fflow-error {
color: var(--text-error); color: var(--text-error);
} }
.fflow-symbol { .fflow-symbol {
width: 4em; width: 3em;
text-align: center; text-align: center;
font-family: var(--font-monospace);
}
.fflow-step .setting-item-control input[type="text"] {
width: 11em;
} }
.fflow-suggestion { .fflow-suggestion {
@@ -29,3 +27,7 @@
.fflow-new { .fflow-new {
color: var(--text-muted); color: var(--text-muted);
} }
.fflow-error:empty {
display: none;
}