Compare commits

1 Commits
11 changed files with 291 additions and 40 deletions

No files matched your search

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