Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80dc13cfe8 | ||
|
|
60582bcb03 |
No files matched your search
@@ -2,18 +2,36 @@
|
|||||||
|
|
||||||
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
|
||||||
|
|
||||||
Everything is a flow (Settings → FFLOW). A flow has:
|
Everything is a flow (Settings → FFLOW). Each card's header has **Duplicate** (copies the flow right below it, named "… (copy)", with its own hotkey commands) and **Delete**. A flow has:
|
||||||
|
|
||||||
- **Name**: labels its hotkey commands.
|
- **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.
|
- **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
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ Nothing planned.
|
|||||||
|
|
||||||
## Done
|
## Done
|
||||||
|
|
||||||
|
- 0.6.0 — Duplicate a flow from its card header: an independent deep copy inserted right below, with a unique name and id and its own next/previous commands. Keeps the original symbol and conditions.
|
||||||
|
- 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.
|
||||||
|
|||||||
@@ -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 pe=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var fe=(o,s)=>{for(var t in s)I(o,t,{get:s[t],enumerable:!0})},ge=(o,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of ue(s))!de.call(o,n)&&n!==t&&I(o,n,{get:()=>s[n],enumerable:!(e=pe(s,n))||e.enumerable});return o};var we=o=>ge(I({},"__esModule",{value:!0}),o);var Ce={};fe(Ce,{default:()=>R});module.exports=we(Ce);var ie=require("obsidian");var Y=require("obsidian");var X=require("obsidian");var N=require("obsidian"),U=String.raw`\{\{(date|time)(?::([^}]*))?\}\}`,he={date:"YYYY-MM-DD",time:"HH:mm"},z=(o,s)=>(s==null?void 0:s.trim())||he[o];function B(o){let s=(0,N.moment)();return o.replace(new RegExp(U,"g"),(t,e,n)=>s.format(z(e,n)))}function G(o,s){let t=new RegExp(U,"g"),e=[],n="^",r=0;for(let i=t.exec(o);i;i=t.exec(o))n+=W(o.slice(r,i.index))+"(.+?)",e.push(z(i[1],i[2])),r=i.index+i[0].length;if(e.length===0)return o===s;let a=new RegExp(n+W(o.slice(r))+"$").exec(s);return a!==null&&e.every((i,l)=>(0,N.moment)(a[l+1],i,!0).isValid())}function W(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function T(o,s,t){let e=o.workspace.getActiveViewOfType(X.MarkdownView);(e==null?void 0:e.file)===s&&await e.save(),await o.fileManager.processFrontMatter(s,t)}function Z(o,s,t,e){if(!e){o[s]=t;return}let n=H(o[s],s);n.includes(t)||n.push(t),o[s]=n}function M(o,s,t,e){var l;s[t.property]=e;let n=t.steps.find(c=>c.value===e),r=new Map,a=c=>{let d=r.get(c);return d===void 0&&r.set(c,d=me(o,s,c)),d},i=c=>c.property!==""&&c.property!==t.property;for(let c of t.steps)if(c!==n)for(let d of c.effects.filter(i)){let p=d.property;if(a(p)){let w=J(d.value),g=H(s[p],p).filter(F=>!w.some(y=>Q(y,F)));g.length?s[p]=g:delete s[p]}else p in s&&Q(d.value,s[p])&&delete s[p]}for(let c of(l=n==null?void 0:n.effects.filter(i))!=null?l:[]){let d=c.property;if(a(d)){let p=H(s[d],d);for(let w of J(c.value).map(B))p.includes(w)||p.push(w);p.length&&(s[d]=p)}else s[d]=ee(B(c.value))}}function me(o,s,t){if(["cssclasses","tags","aliases"].includes(t)||Array.isArray(s[t]))return!0;let e=Reflect.get(o,"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(o,s){return Array.isArray(o)?o.map(String):o==null||o===""?[]:s==="cssclasses"?String(o).split(/[\s,]+/).filter(Boolean):[String(o)]}function J(o){return o.split(/,(?![^{]*\}\})/).map(s=>s.trim()).filter(Boolean)}function Q(o,s){let t=o.trim();return String(ee(t))===String(s)||G(t,String(s))}function ee(o){let s=o.trim();return s===""?null:s==="true"||s==="false"?s==="true":/^-?\d+(\.\d+)?$/.test(s)?Number(s):s}function v(o){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:""},...o}}function te(o,s){let t=o.name||o.property||"New flow",e=new Set(s.map(i=>i.name)),n=`${t} (copy)`;for(let i=2;e.has(n);i++)n=`${t} (copy ${i})`;let{id:r,...a}=structuredClone(o);return v({...a,name:n})}function ye(){return{flows:[v({name:"Type",symbol:"&",property:"type",kind:"open"})]}}var j=o=>o.values.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),C=o=>o.condition.property!=="";function ve(o,s){if(!C(o))return!0;let t=s==null?void 0:s[o.condition.property],e=(Array.isArray(t)?t:[t]).filter(r=>r!=null&&String(r).trim()!=="").map(r=>String(r).trim().toLowerCase()),n=j(o.condition);return n.length===0?e.length>0:e.some(r=>n.includes(r))}function k(o,s){var t,e;return(e=(t=o.find(n=>C(n)&&ve(n,s)))!=null?t:o.find(n=>!C(n)))!=null?e:null}function ne(o,s){var n;let t=o[s];if(!t.symbol)return null;let e=j(t.condition);return(n=o.slice(0,s).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 D=["#","[","/",":"];function E(o){return o===""?null:[...o].length!==1?"Use exactly one character.":/[\p{L}\p{N}\s]/u.test(o)?"Letters, digits and spaces are not allowed.":D.includes(o)?`"${o}" is reserved (${D.join(" ")}).`:null}function oe(o){var n,r;if(!o||typeof o!="object")return ye();if("flows"in o&&!("rules"in o)&&Array.isArray(o.flows))return{flows:o.flows.map(a=>v({...a,condition:{property:"",values:"",...a.condition}}))};let s=o,t=(n=s.rules)!=null?n:[],e=((r=s.flows)!=null?r:[]).map(a=>{var i,l;return v({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(v({name:a.properLine truncated
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"id": "fflow",
|
"id": "fflow",
|
||||||
"name": "FFLOW",
|
"name": "FFLOW",
|
||||||
"version": "0.4.0",
|
"version": "0.6.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",
|
||||||
|
|||||||
Generated
+2
-2
@@ -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
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "fflow",
|
"name": "fflow",
|
||||||
"version": "0.4.0",
|
"version": "0.6.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
@@ -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.`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+80
-9
@@ -11,11 +11,23 @@ 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,
|
||||||
|
duplicateFlow,
|
||||||
|
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 +45,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 +85,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();
|
||||||
@@ -83,7 +103,18 @@ export class FflowSettingTab extends PluginSettingTab {
|
|||||||
else this.expanded.delete(flow.id);
|
else this.expanded.delete(flow.id);
|
||||||
card.toggleClass("is-collapsed", !open);
|
card.toggleClass("is-collapsed", !open);
|
||||||
});
|
});
|
||||||
const remove = new ExtraButtonComponent(header.createDiv({ cls: "fflow-header-actions" }))
|
const actions = header.createDiv({ cls: "fflow-header-actions" });
|
||||||
|
actions.addEventListener("click", (e) => e.stopPropagation());
|
||||||
|
new ExtraButtonComponent(actions)
|
||||||
|
.setIcon("copy")
|
||||||
|
.setTooltip("Duplicate flow")
|
||||||
|
.onClick(async () => {
|
||||||
|
const copy = duplicateFlow(flow, flows);
|
||||||
|
flows.splice(index + 1, 0, copy);
|
||||||
|
this.expanded.add(copy.id);
|
||||||
|
await this.saveAndRedraw();
|
||||||
|
});
|
||||||
|
new ExtraButtonComponent(actions)
|
||||||
.setIcon("trash-2")
|
.setIcon("trash-2")
|
||||||
.setTooltip("Delete flow")
|
.setTooltip("Delete flow")
|
||||||
.onClick(async () => {
|
.onClick(async () => {
|
||||||
@@ -91,7 +122,6 @@ export class FflowSettingTab extends PluginSettingTab {
|
|||||||
this.expanded.delete(flow.id);
|
this.expanded.delete(flow.id);
|
||||||
await this.saveAndRedraw();
|
await this.saveAndRedraw();
|
||||||
});
|
});
|
||||||
remove.extraSettingsEl.addEventListener("click", (e) => e.stopPropagation());
|
|
||||||
|
|
||||||
const body = card.createDiv({ cls: "fflow-card-body" });
|
const body = card.createDiv({ cls: "fflow-card-body" });
|
||||||
|
|
||||||
@@ -116,15 +146,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();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+66
-5
@@ -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,74 @@ export function newFlow(fields: Partial<Flow>): Flow {
|
|||||||
valueMode: "single",
|
valueMode: "single",
|
||||||
loop: false,
|
loop: false,
|
||||||
steps: [],
|
steps: [],
|
||||||
|
condition: { property: "", values: "" },
|
||||||
...fields,
|
...fields,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A deep copy of `flow` with a fresh id (so its own commands) and a name no other flow uses: "Status (copy)", "Status (copy 2)"… */
|
||||||
|
export function duplicateFlow(flow: Flow, flows: Flow[]): Flow {
|
||||||
|
const base = flow.name || flow.property || "New flow";
|
||||||
|
const taken = new Set(flows.map((f) => f.name));
|
||||||
|
let name = `${base} (copy)`;
|
||||||
|
for (let n = 2; taken.has(name); n++) name = `${base} (copy ${n})`;
|
||||||
|
const { id: _id, ...fields } = structuredClone(flow);
|
||||||
|
return newFlow({ ...fields, name });
|
||||||
|
}
|
||||||
|
|
||||||
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 +147,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
@@ -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
@@ -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);
|
||||||
|
|||||||
Reference in new issue
Block a user