diff --git a/README.md b/README.md index 5cfd596..5dd0908 100644 --- a/README.md +++ b/README.md @@ -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`. -## 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 -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: : 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. +- **Name**: labels its hotkey commands. +- **Symbol** (optional): one character that is not a letter, digit or space. `# [ / :` are reserved (tags, links, slash commands, emoji). It fires only at the start of a word (line start or after a space), never inside frontmatter or code. +- **Property**: the frontmatter key the flow sets. +- **Kind**: + - **Ordered list**: fixed steps, in order. Each step can also set other properties (**Also sets**). Gets **FFLOW: : next step** / **previous step** commands for hotkeys; **Loop** wraps around at the ends. + - **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 @@ -33,4 +44,6 @@ npm run build Copy `main.js`, `manifest.json` and `styles.css` to `/.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. diff --git a/ROADMAP.md b/ROADMAP.md index 57b80cd..a45f280 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,9 +2,11 @@ ## 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 -- 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. diff --git a/main.js b/main.js index 8e89e1c..2db428b 100644 --- a/main.js +++ b/main.js @@ -2,6 +2,4 @@ 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 of the flow. Picking one also applies its cssclasses.").addDropdown(c=>{c.addOption("open","Vault (open list)").addOption("finite","Fixed list");for(let u of s.flows)c.addOption(`flow:${u.id}`,`Flow: ${u.name||u.property||"unnamed"}`);c.setValue(e.source==="flow"?`flow:${e.flowId}`:e.source).onChange(async u=>{u.startsWith("flow:")?(e.source="flow",e.flowId=u.slice(5)):e.source=u,await this.save(),this.display()})})),e.source==="flow"){a||r.addSetting(o=>o.setName("Flow deleted").setDesc("Pick another source.").descEl.addClass("fflow-error"));return}r.addSetting(o=>o.setName("Property").addText(c=>c.setPlaceholder("type").setValue(e.property).onChange(async u=>{e.property=u.trim(),p(),await this.save()})).addDropdown(c=>c.addOptions({single:"Single value",list:"List"}).setValue(e.valueMode).onChange(async u=>{e.valueMode=u,await this.save()}))),e.source==="finite"&&r.addSetting(o=>o.setName("Values").setDesc("One per line, in display order.").addTextArea(c=>{c.setValue(e.values.join(` -`)).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{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;ee.invalidate())),this.registerEvent(this.app.metadataCache.on("deleted",()=>e.invalidate())),this.registerEditorSuggest(new C(this.app,this,e)),this.flowCommands.sync(),this.addSettingTab(new T(this.app,this))}async loadSettings(){var t,s,a;let e=(t=await this.loadData())!=null?t:{};this.settings={rules:((s=e.rules)!=null?s:A.rules).map(l=>({...m,...l})),flows:(a=e.flows)!=null?a:[]}}async saveSettings(){await this.saveData(this.settings),this.flowCommands.sync()}}; +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, the property is set, and the step's other properties are applied. Ordered flows get \u201Cnext step\u201D and \u201Cprevious step\u201D commands for hotkeys. Reserved symbols: ${b.join(" ")}`).addButton(o=>o.setButtonText("Hotkeys").onClick(()=>this.openHotkeys())).addButton(o=>o.setButtonText("Add flow").onClick(async()=>{t.push(f({steps:[{value:"",effects:[]}]})),await this.saveAndRedraw()})),t.forEach((o,i)=>this.renderFlow(o,i))}renderFlow(e,t){let o=this.plugin.settings.flows,i=createFragment(),r=i.createSpan({cls:"fflow-badge"}),p=i.createSpan(),a=()=>{r.setText(e.symbol),r.toggle(e.symbol!==""),p.setText(e.name||e.property||"New flow")};a();let l=new g.SettingGroup(this.containerEl).setHeading(i).addClass("fflow-group");l.addExtraButton(d=>d.setIcon("trash").setTooltip("Delete flow").onClick(async()=>{o.splice(t,1),await this.saveAndRedraw()})),l.addSetting(d=>d.setName("Name").setDesc(e.kind==="ordered"?"Labels the hotkey commands.":"For your reference.").addText(u=>u.setPlaceholder("Status").setValue(e.name).onChange(async c=>{e.name=c,a(),await this.save()}))),l.addSetting(d=>{var c;d.setName("Symbol").setDesc("Optional. One character, not a letter or digit.");let u=d.descEl.createDiv({cls:"fflow-error"});u.setText((c=h(e.symbol,o,t))!=null?c:""),d.addText(m=>{m.setPlaceholder("@").setValue(e.symbol),m.inputEl.addClass("fflow-symbol"),m.onChange(async y=>{let w=h(y,o,t);u.setText(w!=null?w:""),!w&&(e.symbol=y,a(),await this.save())})})}),l.addSetting(d=>{d.setName("Property").setDesc(e.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(u=>u.setPlaceholder("status").setValue(e.property).onChange(async c=>{e.property=c.trim(),a(),await this.save()})).addDropdown(u=>u.addOptions({ordered:"Ordered list",open:"Open (vault)"}).setValue(e.kind).onChange(async c=>{e.kind=c,await this.saveAndRedraw()})),e.kind==="open"&&d.addDropdown(u=>u.addOptions({single:"Single value",list:"List"}).setValue(e.valueMode).onChange(async c=>{e.valueMode=c,await this.save()}))}),e.kind!=="open"&&(l.addSetting(d=>d.setName("Loop").setDesc("After the last step, \u201Cnext\u201D goes back to the first.").addToggle(u=>u.setValue(e.loop).onChange(async c=>{e.loop=c,await this.save()}))),e.steps.forEach((d,u)=>this.renderStep(l,e,d,u)),l.addSetting(d=>d.addButton(u=>u.setButtonText("Add step").onClick(async()=>{e.steps.push({value:"",effects:[]}),await this.saveAndRedraw()}))))}renderStep(e,t,o,i){e.addSetting(r=>{r.setName(`Step ${i+1}`).setClass("fflow-step"),r.addText(a=>a.setPlaceholder("value").setValue(o.value).onChange(async l=>{o.value=l.trim(),await this.save()})),r.addExtraButton(a=>a.setIcon("list-plus").setTooltip("Also set a property").onClick(async()=>{o.effects.push({property:"",value:""}),await this.saveAndRedraw()}));let p=async a=>{t.steps.splice(a,0,...t.steps.splice(i,1)),await this.saveAndRedraw()};r.addExtraButton(a=>a.setIcon("arrow-up").setTooltip("Move up").setDisabled(i===0).onClick(()=>p(i-1))),r.addExtraButton(a=>a.setIcon("arrow-down").setTooltip("Move down").setDisabled(i===t.steps.length-1).onClick(()=>p(i+1))),r.addExtraButton(a=>a.setIcon("x").setTooltip("Remove step").onClick(async()=>{t.steps.splice(i,1),await this.saveAndRedraw()}))}),o.effects.forEach((r,p)=>e.addSetting(a=>a.setClass("fflow-effect").setDesc(p===0?"Also sets":"").addText(l=>l.setPlaceholder("property").setValue(r.property).onChange(async d=>{r.property=d.trim(),await this.save()})).addText(l=>l.setPlaceholder("value (lists: a, b)").setValue(r.value).onChange(async d=>{r.value=d,await this.save()})).addExtraButton(l=>l.setIcon("x").setTooltip("Remove property").onClick(async()=>{o.effects.splice(p,1),await this.saveAndRedraw()}))))}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"),o=t&&typeof t=="object"&&"searchComponent"in t?t.searchComponent:null;o instanceof g.SearchComponent&&(o.setValue(this.plugin.manifest.name),o.inputEl.dispatchEvent(new Event("input")))}};var E=require("obsidian");var C=class{constructor(s){this.app=s;this.cache=new Map}invalidate(){this.cache.clear()}get(s){var t,o,i;let e=this.cache.get(s);if(e)return e;e=new Map;for(let r of this.app.vault.getMarkdownFiles()){let p=(o=(t=this.app.metadataCache.getFileCache(r))==null?void 0:t.frontmatter)==null?void 0:o[s];for(let a of new Set(V(p)))e.set(a,((i=e.get(a))!=null?i:0)+1)}return this.cache.set(s,e),e}};function V(n){return Array.isArray(n)?n.flatMap(V):typeof n=="string"?n.trim()?[n.trim()]:[]:typeof n=="number"||typeof n=="boolean"?[String(n)]:[]}var P=n=>n!==void 0&&/\s/.test(n),k=class extends E.EditorSuggest{constructor(e,t,o){super(e);this.plugin=t;this.index=o;this.flow=null}onTrigger(e,t,o){let i=t.getLine(e.line).slice(0,e.ch),r=i.length;for(;r>0&&!P(i[r-1]);)r--;let p=i.slice(r);if(!p)return null;let a=this.plugin.settings.flows,l=a.findIndex(u=>u.symbol!==""&&u.symbol===p[0]),d=a[l];return!d||!d.property||h(d.symbol,a,l)||Y(t,e.line)||z(t,e.line,i.slice(0,r))?null:(this.flow=d,{start:{line:e.line,ch:r},end:e,query:p.slice(1)})}getSuggestions(e){let t=this.flow;if(!t)return[];let o=e.query.toLowerCase(),i=t.kind==="ordered"?t.steps.filter(p=>p.value).map(p=>({value:p.value,isNew:!1})):[...this.index.get(t.property)].sort((p,a)=>a[1]-p[1]||p[0].localeCompare(a[0])).map(([p,a])=>({value:p,count:a,isNew:!1})),r=i.filter(p=>p.value.toLowerCase().includes(o));return r.sort((p,a)=>+!p.value.toLowerCase().startsWith(o)-+!a.value.toLowerCase().startsWith(o)),t.kind==="open"&&o&&!i.some(p=>p.value.toLowerCase()===o)&&r.push({value:e.query,isNew:!0}),r}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 o=this.context,i=this.flow;!o||!i||this.apply(o,i,e.value)}async apply(e,t,o){let{editor:i,file:r,start:p}=e,a=i.getLine(p.line),l=e.end.ch;for(;l{t.kind==="ordered"?F(this.app,d,t,o):I(d,t.property,o,t.valueMode==="list")})}catch(d){console.error("FFLOW: could not update frontmatter",d),new E.Notice(`FFLOW: could not set "${t.property}". See console.`)}}};function Y(n,s){if(n.getLine(0)!=="---")return!1;for(let e=1;et.invalidate())),this.registerEvent(this.app.metadataCache.on("deleted",()=>t.invalidate())),this.registerEditorSuggest(new k(this.app,this,t)),this.flowCommands.sync(),this.addSettingTab(new x(this.app,this))}async saveSettings(){await this.saveData(this.settings),this.flowCommands.sync()}}; diff --git a/manifest.json b/manifest.json index 91909cf..f83ac24 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "fflow", "name": "FFLOW", - "version": "0.2.0", + "version": "0.3.0", "minAppVersion": "1.11.0", "description": "Frontmatter Flow: type a trigger symbol (like @) to autocomplete and set a frontmatter property.", "author": "Olivier Legendre", diff --git a/package.json b/package.json index f5a23bb..d6316f9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fflow", - "version": "0.2.0", + "version": "0.3.0", "description": "Frontmatter Flow: set properties from the editor with trigger symbols.", "main": "main.js", "scripts": { diff --git a/src/flows.ts b/src/flows.ts index 52f63fe..64db862 100644 --- a/src/flows.ts +++ b/src/flows.ts @@ -1,11 +1,11 @@ import { Notice, TFile } from "obsidian"; import { setFlowStep, updateFrontmatter } from "./frontmatter"; import type FflowPlugin from "./main"; -import { Flow, flowSteps } from "./settings"; +import type { Flow } 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. */ +/** Re-registers the next/previous commands of every ordered flow. Ids derive from the flow id, so hotkeys survive renames. */ export class FlowCommands { private registered: string[] = []; @@ -15,6 +15,7 @@ export class FlowCommands { for (const id of this.registered) this.plugin.removeCommand(id); this.registered = []; for (const flow of this.plugin.settings.flows) { + if (flow.kind !== "ordered") continue; this.add(flow, 1, "next", "next step"); this.add(flow, -1, "previous", "previous step"); } @@ -28,7 +29,7 @@ export class FlowCommands { 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 (!file || file.extension !== "md" || !flow.property || !flow.steps.some((s) => s.value)) return false; if (!checking) void moveStep(this.plugin, file, flow, direction); return true; }, @@ -37,7 +38,7 @@ export class FlowCommands { } async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction: Direction): Promise { - const steps = flowSteps(flow); + const steps = flow.steps.filter((s) => s.value); let message = ""; try { // 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; } - setFlowStep(fm, flow, steps[target].value); + setFlowStep(plugin.app, fm, flow, steps[target].value); message = `${flow.property}: ${steps[target].value}`; }); new Notice(message); diff --git a/src/frontmatter.ts b/src/frontmatter.ts index 177f68b..df6cfaa 100644 --- a/src/frontmatter.ts +++ b/src/frontmatter.ts @@ -1,5 +1,5 @@ import { App, MarkdownView, TFile } from "obsidian"; -import type { Flow } from "./settings"; +import type { Flow, FlowEffect } from "./settings"; export type Frontmatter = Record; @@ -10,22 +10,92 @@ export async function updateFrontmatter(app: App, file: TFile, fn: (fm: Frontmat 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 - * step of this flow from `cssclasses`, then add the classes of the new step. - * Classes that don't belong to the flow are kept. + * Puts the note on step `value` of an ordered flow: + * 1. sets the flow's property; + * 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; + 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(); + 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); - 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); +function listItems(value: string): string[] { + return value + .split(",") + .map((v) => v.trim()) + .filter(Boolean); +} - if (next.length) fm.cssclasses = next; - else if (current !== undefined) delete fm.cssclasses; +/** "true"/"false" become booleans and plain numbers become numbers, so checkbox and number properties stay typed. */ +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; } diff --git a/src/main.ts b/src/main.ts index 15e357e..4a20e80 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,6 +1,6 @@ import { Plugin } from "obsidian"; import { FlowCommands } from "./flows"; -import { DEFAULT_SETTINGS, FflowSettings, NEW_RULE } from "./settings"; +import { FflowSettings, loadSettings } from "./settings"; import { FflowSettingTab } from "./settings-tab"; import { TriggerSuggest, ValueIndex } from "./suggest"; @@ -9,7 +9,10 @@ export default class FflowPlugin extends Plugin { private flowCommands = new FlowCommands(this); async onload(): Promise { - 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); 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)); } - async loadSettings(): Promise { - const saved = ((await this.loadData()) ?? {}) as Partial; - 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 { await this.saveData(this.settings); this.flowCommands.sync(); diff --git a/src/settings-tab.ts b/src/settings-tab.ts index b3726cf..bcd0523 100644 --- a/src/settings-tab.ts +++ b/src/settings-tab.ts @@ -1,6 +1,6 @@ import { App, PluginSettingTab, SearchComponent, Setting, SettingGroup } from "obsidian"; 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 { constructor(app: App, private plugin: FflowPlugin) { @@ -9,164 +9,45 @@ export class FflowSettingTab extends PluginSettingTab { private save = () => this.plugin.saveSettings(); + /** Saves, then redraws: for edits that add, remove or reorder rows. */ + private async saveAndRedraw(): Promise { + await this.save(); + this.display(); + } + display(): void { const { containerEl } = this; - const settings = this.plugin.settings; + const flows = this.plugin.settings.flows; 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) .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.") + .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("Add flow").onClick(async () => { - settings.flows.push({ id: Date.now().toString(36), name: "", property: "", loop: false, steps: [{ value: "", cssclass: "" }] }); - await this.save(); - this.display(); + flows.push(newFlow({ steps: [{ value: "", effects: [] }] })); + await this.saveAndRedraw(); }), ); - 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) => { - 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; - }), - ); - } + flows.forEach((flow, index) => this.renderFlow(flow, index)); } private renderFlow(flow: Flow, index: number): void { - const settings = this.plugin.settings; + const flows = this.plugin.settings.flows; const title = createFragment(); - const titleEl = title.createSpan(); - const updateTitle = () => titleEl.setText(flow.name || flow.property || "New flow"); + const badge = title.createSpan({ cls: "fflow-badge" }); + const name = title.createSpan(); + const updateTitle = () => { + badge.setText(flow.symbol); + badge.toggle(flow.symbol !== ""); + name.setText(flow.name || flow.property || "New flow"); + }; updateTitle(); const group = new SettingGroup(this.containerEl).setHeading(title).addClass("fflow-group"); @@ -175,23 +56,15 @@ export class FflowSettingTab extends PluginSettingTab { .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(); + flows.splice(index, 1); + await this.saveAndRedraw(); }), ); group.addSetting((s) => s - .setName("Name and property") - .setDesc("The name labels the hotkey commands.") + .setName("Name") + .setDesc(flow.kind === "ordered" ? "Labels the hotkey commands." : "For your reference.") .addText((t) => t .setPlaceholder("Status") @@ -201,6 +74,34 @@ export class FflowSettingTab extends PluginSettingTab { updateTitle(); 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) => t @@ -211,8 +112,30 @@ export class FflowSettingTab extends PluginSettingTab { updateTitle(); 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) => s @@ -226,64 +149,98 @@ export class FflowSettingTab extends PluginSettingTab { ), ); - 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(); - }), - ); - }); - }); + 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: "", cssclass: "" }); - await this.save(); - this.display(); + flow.steps.push({ value: "", effects: [] }); + await this.saveAndRedraw(); }), ), ); } + private renderStep(group: SettingGroup, flow: Flow, step: FlowStep, i: number): void { + 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.addExtraButton((b) => + b + .setIcon("list-plus") + .setTooltip("Also set a property") + .onClick(async () => { + step.effects.push({ property: "", value: "" }); + await this.saveAndRedraw(); + }), + ); + const move = async (to: number) => { + flow.steps.splice(to, 0, ...flow.steps.splice(i, 1)); + await this.saveAndRedraw(); + }; + 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.saveAndRedraw(); + }), + ); + }); + + step.effects.forEach((effect, j) => + group.addSetting((s) => + s + .setClass("fflow-effect") + .setDesc(j === 0 ? "Also sets" : "") + .addText((t) => + t + .setPlaceholder("property") + .setValue(effect.property) + .onChange(async (value) => { + effect.property = value.trim(); + await this.save(); + }), + ) + .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(); + }), + ), + ), + ); + } + /** 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"); diff --git a/src/settings.ts b/src/settings.ts index e08207b..dc6a160 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -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 SourceMode = "open" | "finite" | "flow"; -export interface TriggerRule { - /** One non-alphanumeric character that opens the suggestions. */ - symbol: string; - /** Frontmatter property written on selection. Ignored for flow sources: the flow owns it. */ +/** Another property written when the note reaches a step. */ +export interface FlowEffect { property: string; - /** single: replace the value. list: append to a list, no duplicates. Flows are always single. */ - valueMode: ValueMode; - /** open: values already used in the vault. finite: `values`. flow: the steps of `flowId`. */ - source: SourceMode; - values: string[]; - flowId: string; + /** Scalars: true/false and numbers are typed. List properties: comma-separated items. */ + value: string; } export interface FlowStep { value: string; - /** Space-separated classes added to `cssclasses` while the note is on this step. */ - cssclass: string; + effects: FlowEffect[]; } export interface Flow { /** Stable id: command ids derive from it, so hotkeys survive renames. */ id: string; name: string; + /** Optional trigger: one non-alphanumeric character typed at the start of a word. */ + symbol: string; property: string; + kind: FlowKind; + valueMode: ValueMode; /** After the last step, "next" goes back to the first (and "previous" the other way). */ loop: boolean; steps: FlowStep[]; } export interface FflowSettings { - rules: TriggerRule[]; flows: Flow[]; } -export const NEW_RULE: TriggerRule = { symbol: "", property: "", valueMode: "single", source: "open", values: [], flowId: "" }; +export function newFlow(fields: Partial): Flow { + return { + id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6), + name: "", + symbol: "", + property: "", + kind: "ordered", + valueMode: "single", + loop: false, + steps: [], + ...fields, + }; +} -export const DEFAULT_SETTINGS: FflowSettings = { - rules: [{ ...NEW_RULE, symbol: "@", property: "type" }], - flows: [], -}; +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. */ export const BLOCKED_SYMBOLS = ["#", "[", "/", ":"]; -/** Returns an error message, or null when `symbol` is usable by rule `index`. */ -export function symbolError(symbol: string, rules: TriggerRule[], index: number): string | null { +/** Returns an error message, or null when `symbol` is usable by flow `index`. Empty means "no trigger" and is valid. */ +export function symbolError(symbol: string, flows: Flow[], index: number): string | null { + if (symbol === "") return null; if ([...symbol].length !== 1) return "Use exactly one character."; if (/[\p{L}\p{N}\s]/u.test(symbol)) return "Letters, digits and spaces are not allowed."; if (BLOCKED_SYMBOLS.includes(symbol)) return `"${symbol}" is reserved (${BLOCKED_SYMBOLS.join(" ")}).`; - if (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; } -/** What a usable trigger writes to; null when the rule is incomplete or points to a missing flow. */ -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; +/** 0.1–0.2 stored separate triggers and flows; the shapes below are only read during migration. */ +interface LegacyRule { + symbol: string; + property: string; + valueMode: ValueMode; + source: "open" | "finite" | "flow"; + values: string[]; + flowId?: string; +} +interface LegacyFlow { + id: string; + name: string; + property: string; + loop: boolean; + steps: { value: string; cssclass: string }[]; } -/** Steps usable at runtime: blank values are skipped. */ -export function flowSteps(flow: Flow): FlowStep[] { - return flow.steps.filter((s) => s.value.trim() !== ""); +/** Builds settings from saved data, converting the 0.1–0.2 trigger/flow split into flows. */ +export function loadSettings(saved: unknown): FflowSettings { + if (!saved || typeof saved !== "object") return defaultSettings(); + if ("flows" in saved && !("rules" in saved) && Array.isArray(saved.flows)) { + // Current format: fill fields added since the flow was saved. + return { flows: saved.flows.map((f: Partial) => newFlow(f)) }; + } + + // 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 }; } diff --git a/src/suggest.ts b/src/suggest.ts index c66912d..544300e 100644 --- a/src/suggest.ts +++ b/src/suggest.ts @@ -1,13 +1,7 @@ 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 { Flow, flowSteps, resolveRule, TriggerRule } from "./settings"; - -interface ActiveTrigger { - rule: TriggerRule; - property: string; - flow: Flow | null; -} +import { Flow, symbolError } from "./settings"; interface Suggestion { value: string; @@ -49,7 +43,7 @@ function flatten(raw: unknown): string[] { const isSpace = (ch: string | undefined) => ch !== undefined && /\s/.test(ch); export class TriggerSuggest extends EditorSuggest { - private active: ActiveTrigger | null = null; + private flow: Flow | null = null; constructor(app: App, private plugin: FflowPlugin, private index: ValueIndex) { super(app); @@ -63,33 +57,32 @@ export class TriggerSuggest extends EditorSuggest { const word = before.slice(start); if (!word) return null; - const settings = this.plugin.settings; - const index = settings.rules.findIndex((r) => r.symbol === word[0]); - const target = index === -1 ? null : resolveRule(settings, index); - if (!target || inFrontmatter(editor, cursor.line) || inCode(editor, cursor.line, before.slice(0, start))) return null; + const flows = this.plugin.settings.flows; + const index = flows.findIndex((f) => f.symbol !== "" && f.symbol === word[0]); + const flow = flows[index]; + if (!flow || !flow.property || symbolError(flow.symbol, flows, index)) return null; + 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) }; } getSuggestions(context: EditorSuggestContext): Suggestion[] { - const active = this.active; - if (!active) return []; - const { rule, flow } = active; + const flow = this.flow; + if (!flow) return []; const query = context.query.toLowerCase(); - const pool: Suggestion[] = flow - ? flowSteps(flow).map((s) => ({ value: s.value, isNew: false })) - : rule.source === "finite" - ? rule.values.map((value) => ({ value, isNew: false })) - : [...this.index.get(active.property)] + const pool: Suggestion[] = + flow.kind === "ordered" + ? flow.steps.filter((s) => s.value).map((s) => ({ value: s.value, isNew: false })) + : [...this.index.get(flow.property)] .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) .map(([value, count]) => ({ value, count, isNew: false })); const matches = pool.filter((s) => s.value.toLowerCase().includes(query)); // 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))); - 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 }); } return matches; @@ -108,12 +101,12 @@ export class TriggerSuggest extends EditorSuggest { selectSuggestion(s: Suggestion, _evt: MouseEvent | KeyboardEvent): void { const context = this.context; - const active = this.active; - if (!context || !active) return; - void this.apply(context, active, s.value); + const flow = this.flow; + if (!context || !flow) return; + void this.apply(context, flow, s.value); } - private async apply(context: EditorSuggestContext, { rule, property, flow }: ActiveTrigger, value: string): Promise { + private async apply(context: EditorSuggestContext, flow: Flow, value: string): Promise { const { editor, file, start } = context; const line = editor.getLine(start.line); @@ -126,22 +119,12 @@ export class TriggerSuggest extends EditorSuggest { try { await updateFrontmatter(this.app, file, (fm) => { - if (flow) { - setFlowStep(fm, flow, value); - 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; + if (flow.kind === "ordered") setFlowStep(this.app, fm, flow, value); + else setOpenValue(fm, flow.property, value, flow.valueMode === "list"); }); } catch (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.`); } } } diff --git a/styles.css b/styles.css index 38e2a0d..ef4de9f 100644 --- a/styles.css +++ b/styles.css @@ -2,13 +2,43 @@ color: var(--text-error); } +.fflow-error:empty { + display: none; +} + .fflow-symbol { width: 3em; text-align: center; 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"] { + 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; } @@ -27,7 +57,3 @@ .fflow-new { color: var(--text-muted); } - -.fflow-error:empty { - display: none; -}