commit 021777203b9b78143c7bfd86639b035750ba9094 Author: Olivier Date: Sun Oct 25 16:02:10 2026 -0400 FFLOW 0.1.0: trigger symbols set frontmatter properties diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c45938 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +*.log +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0e6c238 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Olivier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..352d567 --- /dev/null +++ b/README.md @@ -0,0 +1,27 @@ +# FFLOW — Frontmatter Flow + +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`. + +## 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: `@`. +- **Property**: the frontmatter key to write. Default: `type`. +- **Value mode**: *Single value* replaces the value; *List* appends without duplicates. +- **Suggestions**: *Open* lists every value already used for that property in the vault, ranked by use, and accepts new values. *Finite* only offers the values listed in the settings. + +A trigger fires only at the start of a word (line start or after a space), and never inside frontmatter or code. + +## Development + +``` +npm install +npm run build +``` + +Copy `main.js`, `manifest.json` and `styles.css` to `/.obsidian/plugins/fflow/`. + +See [ROADMAP.md](ROADMAP.md) for planned features. diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..6ef78ed --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,7 @@ +# FFLOW roadmap + +## Next version + +- **Property cycle hotkeys.** Assign a hotkey that moves a property to the next value in an ordered list, e.g. `status: started` → `status: in-progress` → … . +- **cssclasses with the cycle.** Each step of a cycle can also set the note's `cssclasses` (replace the previous step's class, keep other classes). +- **Finite list from a note.** Setting per trigger: take the finite list from the plugin settings (current) or from a note in the vault (one value per line or list items). diff --git a/esbuild.config.mjs b/esbuild.config.mjs new file mode 100644 index 0000000..40f7e53 --- /dev/null +++ b/esbuild.config.mjs @@ -0,0 +1,46 @@ +import esbuild from 'esbuild'; +import process from 'process'; +import builtins from 'builtin-modules'; + +const banner = `/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +*/ +`; + +const prod = process.argv[2] === 'production'; + +const context = await esbuild.context({ + banner: { js: banner }, + entryPoints: ['src/main.ts'], + bundle: true, + external: [ + 'obsidian', + 'electron', + '@codemirror/autocomplete', + '@codemirror/collab', + '@codemirror/commands', + '@codemirror/language', + '@codemirror/lint', + '@codemirror/search', + '@codemirror/state', + '@codemirror/view', + '@lezer/common', + '@lezer/highlight', + '@lezer/lr', + ...builtins, + ], + format: 'cjs', + target: 'es2018', + logLevel: 'info', + sourcemap: prod ? false : 'inline', + treeShaking: true, + outfile: 'main.js', + minify: prod, +}); + +if (prod) { + await context.rebuild(); + process.exit(0); +} else { + await context.watch(); +} \ No newline at end of file diff --git a/main.js b/main.js new file mode 100644 index 0000000..e9a4779 --- /dev/null +++ b/main.js @@ -0,0 +1,7 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +*/ + +var x=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var D=(n,s)=>{for(var e in s)x(n,e,{get:s[e],enumerable:!0})},P=(n,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of R(s))!A.call(n,i)&&i!==e&&x(n,i,{get:()=>s[i],enumerable:!(t=N(s,i))||t.enumerable});return n};var V=n=>P(x({},"__esModule",{value:!0}),n);var B={};D(B,{default:()=>S});module.exports=V(B);var F=require("obsidian");var T={rules:[{symbol:"@",property:"type",valueMode:"single",source:"open",values:[]}]},h=["#","[","/",":"];function m(n,s,e){return[...n].length!==1?"Use exactly one character.":/[\p{L}\p{N}\s]/u.test(n)?"Letters, digits and spaces are not allowed.":h.includes(n)?`"${n}" is reserved (${h.join(" ")}).`:s.some((t,i)=>i!==e&&t.symbol===n)?`"${n}" is already used by another rule.`:null}function C(n,s,e){return n.property.trim()!==""&&m(n.symbol,s,e)===null}var c=require("obsidian");var y=class extends c.PluginSettingTab{constructor(e,t){super(e,t);this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("p",{cls:"setting-item-description",text:`Type a trigger symbol at the start of a word to pick a value. The typed text is removed and the value is written to the note's frontmatter. Reserved symbols: ${h.join(" ")}`}),this.plugin.settings.rules.forEach((t,i)=>this.renderRule(t,i)),new c.Setting(e).addButton(t=>t.setButtonText("Add trigger").setCta().onClick(async()=>{this.plugin.settings.rules.push({symbol:"",property:"",valueMode:"single",source:"open",values:[]}),await this.plugin.saveSettings(),this.display()}))}renderRule(e,t){let i=this.plugin.settings.rules,r=()=>this.plugin.saveSettings(),o=this.containerEl.createDiv({cls:"fflow-rule"});new c.Setting(o).setHeading().setName(e.symbol&&e.property?`${e.symbol} \u2192 ${e.property}`:"New trigger").addExtraButton(l=>l.setIcon("trash").setTooltip("Delete trigger").onClick(async()=>{i.splice(t,1),await r(),this.display()}));let a=new c.Setting(o).setName("Symbol").setDesc("One character, not a letter or digit."),g=a.descEl.createDiv({cls:"fflow-error"}),p=l=>{var u;return g.setText((u=m(l,i,t))!=null?u:"")};a.addText(l=>{l.setPlaceholder("@").setValue(e.symbol),l.inputEl.addClass("fflow-symbol"),l.onChange(async u=>{p(u),!m(u,i,t)&&(e.symbol=u,await r())})}),e.symbol&&p(e.symbol),new c.Setting(o).setName("Property").setDesc("Frontmatter property to set.").addText(l=>l.setPlaceholder("type").setValue(e.property).onChange(async u=>{e.property=u.trim(),await r()})),new c.Setting(o).setName("Value mode").setDesc("Single replaces the current value. List adds to the existing values.").addDropdown(l=>l.addOptions({single:"Single value",list:"List"}).setValue(e.valueMode).onChange(async u=>{e.valueMode=u,await r()})),new c.Setting(o).setName("Suggestions").setDesc("Open: every value already used in the vault; new values are allowed. Finite: only the values listed below.").addDropdown(l=>l.addOptions({open:"Open (from vault)",finite:"Finite list"}).setValue(e.source).onChange(async u=>{e.source=u,await r(),this.display()})),e.source==="finite"&&new c.Setting(o).setName("Values").setDesc("One value per line, in the order they should appear.").addTextArea(l=>{l.setValue(e.values.join(` +`)).onChange(async u=>{e.values=u.split(` +`).map(d=>d.trim()).filter(Boolean),await r()}),l.inputEl.rows=6})}};var f=require("obsidian");var v=class{constructor(s){this.app=s;this.cache=new Map}invalidate(){this.cache.clear()}get(s){var t,i,r;let e=this.cache.get(s);if(e)return e;e=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=(i=(t=this.app.metadataCache.getFileCache(o))==null?void 0:t.frontmatter)==null?void 0:i[s];for(let g of new Set(M(a)))e.set(g,((r=e.get(g))!=null?r:0)+1)}return this.cache.set(s,e),e}};function M(n){return Array.isArray(n)?n.flatMap(M):typeof n=="string"?n.trim()?[n.trim()]:[]:typeof n=="number"||typeof n=="boolean"?[String(n)]:[]}var E=n=>n!==void 0&&/\s/.test(n),w=class extends f.EditorSuggest{constructor(e,t,i){super(e);this.plugin=t;this.index=i;this.rule=null}onTrigger(e,t,i){let r=t.getLine(e.line).slice(0,e.ch),o=r.length;for(;o>0&&!E(r[o-1]);)o--;let a=r.slice(o);if(!a)return null;let g=this.plugin.settings.rules,p=g.find((l,u)=>l.symbol===a[0]&&C(l,g,u));return!p||O(t,e.line)||k(t,e.line,r.slice(0,o))?null:(this.rule=p,{start:{line:e.line,ch:o},end:e,query:a.slice(1)})}getSuggestions(e){let t=this.rule;if(!t)return[];let i=e.query.toLowerCase(),r=t.source==="finite"?t.values.map(a=>({value:a,isNew:!1})):[...this.index.get(t.property)].sort((a,g)=>g[1]-a[1]||a[0].localeCompare(g[0])).map(([a,g])=>({value:a,count:g,isNew:!1})),o=r.filter(a=>a.value.toLowerCase().includes(i));return o.sort((a,g)=>+!a.value.toLowerCase().startsWith(i)-+!g.value.toLowerCase().startsWith(i)),t.source==="open"&&i&&!r.some(a=>a.value.toLowerCase()===i)&&o.push({value:e.query,isNew:!0}),o}renderSuggestion(e,t){if(t.addClass("fflow-suggestion"),e.isNew){t.createSpan({cls:"fflow-new",text:"New: "}),t.createSpan({text:e.value});return}t.createSpan({text:e.value}),e.count!==void 0&&t.createSpan({cls:"fflow-count",text:String(e.count)})}selectSuggestion(e,t){let i=this.context,r=this.rule;!i||!r||this.apply(i,r,e.value)}async apply(e,t,i){let{editor:r,file:o,start:a}=e,g=r.getLine(a.line),p=e.end.ch;for(;p{if(t.valueMode==="single"){u[t.property]=i;return}let d=u[t.property],b=d==null?[]:Array.isArray(d)?d:[d];b.some(L=>String(L)===i)||b.push(i),u[t.property]=b})}catch(l){console.error("FFLOW: could not update frontmatter",l),new f.Notice(`FFLOW: could not set "${t.property}". See console.`)}}};function O(n,s){if(n.getLine(0)!=="---")return!1;for(let e=1;es.invalidate())),this.registerEvent(this.app.metadataCache.on("deleted",()=>s.invalidate())),this.registerEditorSuggest(new w(this.app,this,s)),this.addSettingTab(new y(this.app,this))}async loadSettings(){let s=await this.loadData();this.settings={...T,...s}}async saveSettings(){await this.saveData(this.settings)}}; diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..7d4f838 --- /dev/null +++ b/manifest.json @@ -0,0 +1,9 @@ +{ + "id": "fflow", + "name": "FFLOW", + "version": "0.1.0", + "minAppVersion": "1.4.0", + "description": "Frontmatter Flow: type a trigger symbol (like @) to autocomplete and set a frontmatter property.", + "author": "Olivier Legendre", + "isDesktopOnly": false +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..53ab362 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,639 @@ +{ + "name": "fflow", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "fflow", + "version": "0.1.0", + "license": "MIT", + "devDependencies": { + "builtin-modules": "4.0.0", + "esbuild": "^0.25.0", + "obsidian": "latest", + "typescript": "^5.6.0" + } + }, + "node_modules/@codemirror/state": { + "version": "6.7.6", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz", + "integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@marijn/find-cluster-break": "^1.0.0" + } + }, + "node_modules/@codemirror/view": { + "version": "6.43.13", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.13.tgz", + "integrity": "sha512-sihaFrUzAsYBQsL9J2t69y8nfMQGwcYmggAZsk+kjPbjYZMyuf2hU8tUNTZ+P+isb6XRr8JE22TZlJxBoVdH1A==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@codemirror/state": "^6.7.0", + "crelt": "^1.0.6", + "style-mod": "^4.1.0", + "w3c-keyname": "^2.2.4" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@marijn/find-cluster-break": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", + "integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@types/codemirror": { + "version": "5.60.8", + "resolved": "https://registry.npmjs.org/@types/codemirror/-/codemirror-5.60.8.tgz", + "integrity": "sha512-VjFgDF/eB+Aklcy15TtOTLQeMjTo07k7KAjql8OK5Dirr7a6sJY4T1uVBDuTVG9VEmn1uUsohOpYnVfgC6/jyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/tern": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/tern": { + "version": "0.23.9", + "resolved": "https://registry.npmjs.org/@types/tern/-/tern-0.23.9.tgz", + "integrity": "sha512-ypzHFE/wBzh+BlH6rrBgS5I/Z7RD21pGhZ2rltb/+ZrVM1awdZwjx7hE5XfuYgHWk9uvV5HLZN3SloevCAp3Bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/builtin-modules": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-4.0.0.tgz", + "integrity": "sha512-p1n8zyCkt1BVrKNFymOHjcDSAl7oq/gUvfgULv2EblgpPVQlQr9yHnWjg9IJ2MhfwPqiYqMMrr01OY7yQoK2yA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/crelt": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz", + "integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/moment": { + "version": "2.31.0", + "resolved": "https://registry.npmjs.org/moment/-/moment-2.31.0.tgz", + "integrity": "sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/obsidian": { + "version": "1.14.4", + "resolved": "https://registry.npmjs.org/obsidian/-/obsidian-1.14.4.tgz", + "integrity": "sha512-Kyo+5t0wFW2On5irLOPrgtwWDnaJsvE9n/P1OVvdPytx+NqeHJXvxVqADNOqLp9bU1+I64B6i+dHb0fxR/ss3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/codemirror": "5.60.8", + "moment": "2.31.0" + }, + "peerDependencies": { + "@codemirror/state": "6.7.6", + "@codemirror/view": "6.43.13" + } + }, + "node_modules/style-mod": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz", + "integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/w3c-keyname": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", + "dev": true, + "license": "MIT", + "peer": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..1a46dae --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "name": "fflow", + "version": "0.1.0", + "description": "Frontmatter Flow: set properties from the editor with trigger symbols.", + "main": "main.js", + "scripts": { + "dev": "node esbuild.config.mjs", + "typecheck": "node node_modules/typescript/bin/tsc --noEmit", + "build": "npm run typecheck && node esbuild.config.mjs production" + }, + "keywords": [], + "author": "Olivier Legendre", + "license": "MIT", + "devDependencies": { + "builtin-modules": "4.0.0", + "esbuild": "^0.25.0", + "obsidian": "latest", + "typescript": "^5.6.0" + } +} diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..1c04883 --- /dev/null +++ b/src/main.ts @@ -0,0 +1,28 @@ +import { Plugin } from "obsidian"; +import { DEFAULT_SETTINGS, FflowSettings } from "./settings"; +import { FflowSettingTab } from "./settings-tab"; +import { TriggerSuggest, ValueIndex } from "./suggest"; + +export default class FflowPlugin extends Plugin { + settings!: FflowSettings; + + async onload(): Promise { + await this.loadSettings(); + + const index = new ValueIndex(this.app); + this.registerEvent(this.app.metadataCache.on("changed", () => index.invalidate())); + this.registerEvent(this.app.metadataCache.on("deleted", () => index.invalidate())); + + this.registerEditorSuggest(new TriggerSuggest(this.app, this, index)); + this.addSettingTab(new FflowSettingTab(this.app, this)); + } + + async loadSettings(): Promise { + const saved = (await this.loadData()) as Partial | null; + this.settings = { ...DEFAULT_SETTINGS, ...saved }; + } + + async saveSettings(): Promise { + await this.saveData(this.settings); + } +} diff --git a/src/settings-tab.ts b/src/settings-tab.ts new file mode 100644 index 0000000..600a18b --- /dev/null +++ b/src/settings-tab.ts @@ -0,0 +1,125 @@ +import { App, PluginSettingTab, Setting } from "obsidian"; +import type FflowPlugin from "./main"; +import { BLOCKED_SYMBOLS, SourceMode, symbolError, TriggerRule, ValueMode } from "./settings"; + +export class FflowSettingTab extends PluginSettingTab { + constructor(app: App, private plugin: FflowPlugin) { + super(app, plugin); + } + + display(): void { + const { containerEl } = this; + containerEl.empty(); + containerEl.createEl("p", { + cls: "setting-item-description", + text: + "Type a trigger symbol at the start of a word to pick a value. The typed text is removed and the value is written to the note's frontmatter. " + + `Reserved symbols: ${BLOCKED_SYMBOLS.join(" ")}`, + }); + + this.plugin.settings.rules.forEach((rule, index) => this.renderRule(rule, index)); + + new Setting(containerEl).addButton((b) => + b + .setButtonText("Add trigger") + .setCta() + .onClick(async () => { + this.plugin.settings.rules.push({ symbol: "", property: "", valueMode: "single", source: "open", values: [] }); + await this.plugin.saveSettings(); + this.display(); + }), + ); + } + + private renderRule(rule: TriggerRule, index: number): void { + const rules = this.plugin.settings.rules; + const save = () => this.plugin.saveSettings(); + const box = this.containerEl.createDiv({ cls: "fflow-rule" }); + + new Setting(box) + .setHeading() + .setName(rule.symbol && rule.property ? `${rule.symbol} → ${rule.property}` : "New trigger") + .addExtraButton((b) => + b + .setIcon("trash") + .setTooltip("Delete trigger") + .onClick(async () => { + rules.splice(index, 1); + await save(); + this.display(); + }), + ); + + const symbolSetting = new Setting(box).setName("Symbol").setDesc("One character, not a letter or digit."); + const error = symbolSetting.descEl.createDiv({ cls: "fflow-error" }); + const showError = (value: string) => error.setText(symbolError(value, rules, index) ?? ""); + symbolSetting.addText((t) => { + t.setPlaceholder("@").setValue(rule.symbol); + t.inputEl.addClass("fflow-symbol"); + t.onChange(async (value) => { + showError(value); + // Invalid input stays in the field but is never saved. + if (symbolError(value, rules, index)) return; + rule.symbol = value; + await save(); + }); + }); + if (rule.symbol) showError(rule.symbol); + + new Setting(box) + .setName("Property") + .setDesc("Frontmatter property to set.") + .addText((t) => + t + .setPlaceholder("type") + .setValue(rule.property) + .onChange(async (value) => { + rule.property = value.trim(); + await save(); + }), + ); + + new Setting(box) + .setName("Value mode") + .setDesc("Single replaces the current value. List adds to the existing values.") + .addDropdown((d) => + d + .addOptions({ single: "Single value", list: "List" }) + .setValue(rule.valueMode) + .onChange(async (value) => { + rule.valueMode = value as ValueMode; + await save(); + }), + ); + + new Setting(box) + .setName("Suggestions") + .setDesc("Open: every value already used in the vault; new values are allowed. Finite: only the values listed below.") + .addDropdown((d) => + d + .addOptions({ open: "Open (from vault)", finite: "Finite list" }) + .setValue(rule.source) + .onChange(async (value) => { + rule.source = value as SourceMode; + await save(); + this.display(); + }), + ); + + if (rule.source === "finite") { + new Setting(box) + .setName("Values") + .setDesc("One value per line, in the order they should appear.") + .addTextArea((t) => { + t.setValue(rule.values.join("\n")).onChange(async (value) => { + rule.values = value + .split("\n") + .map((v) => v.trim()) + .filter(Boolean); + await save(); + }); + t.inputEl.rows = 6; + }); + } + } +} diff --git a/src/settings.ts b/src/settings.ts new file mode 100644 index 0000000..049e9d5 --- /dev/null +++ b/src/settings.ts @@ -0,0 +1,38 @@ +export type ValueMode = "single" | "list"; +export type SourceMode = "open" | "finite"; + +export interface TriggerRule { + /** One non-alphanumeric character that opens the suggestions. */ + symbol: string; + /** Frontmatter property written on selection. */ + property: string; + /** single: replace the value. list: append to a list, no duplicates. */ + valueMode: ValueMode; + /** open: values already used in the vault. finite: `values` below. */ + source: SourceMode; + values: string[]; +} + +export interface FflowSettings { + rules: TriggerRule[]; +} + +export const DEFAULT_SETTINGS: FflowSettings = { + rules: [{ symbol: "@", property: "type", valueMode: "single", source: "open", values: [] }], +}; + +/** 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 { + 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 rule.`; + return null; +} + +export function isRuleActive(rule: TriggerRule, rules: TriggerRule[], index: number): boolean { + return rule.property.trim() !== "" && symbolError(rule.symbol, rules, index) === null; +} diff --git a/src/suggest.ts b/src/suggest.ts new file mode 100644 index 0000000..3fc8d96 --- /dev/null +++ b/src/suggest.ts @@ -0,0 +1,163 @@ +import { + App, + Editor, + EditorPosition, + EditorSuggest, + EditorSuggestContext, + EditorSuggestTriggerInfo, + MarkdownView, + Notice, + TFile, +} from "obsidian"; +import type FflowPlugin from "./main"; +import { isRuleActive, TriggerRule } from "./settings"; + +interface Suggestion { + value: string; + /** Number of notes using the value (open lists only). */ + count?: number; + isNew: boolean; +} + +/** Values already present in the vault, per property, ranked by use. Rebuilt lazily after metadata changes. */ +export class ValueIndex { + private cache = new Map>(); + + constructor(private app: App) {} + + invalidate(): void { + this.cache.clear(); + } + + get(property: string): Map { + let counts = this.cache.get(property); + if (counts) return counts; + counts = new Map(); + for (const file of this.app.vault.getMarkdownFiles()) { + const raw: unknown = this.app.metadataCache.getFileCache(file)?.frontmatter?.[property]; + for (const value of new Set(flatten(raw))) counts.set(value, (counts.get(value) ?? 0) + 1); + } + this.cache.set(property, counts); + return counts; + } +} + +function flatten(raw: unknown): string[] { + if (Array.isArray(raw)) return raw.flatMap(flatten); + if (typeof raw === "string") return raw.trim() ? [raw.trim()] : []; + if (typeof raw === "number" || typeof raw === "boolean") return [String(raw)]; + return []; +} + +const isSpace = (ch: string | undefined) => ch !== undefined && /\s/.test(ch); + +export class TriggerSuggest extends EditorSuggest { + private rule: TriggerRule | null = null; + + constructor(app: App, private plugin: FflowPlugin, private index: ValueIndex) { + super(app); + } + + onTrigger(cursor: EditorPosition, editor: Editor, _file: TFile | null): EditorSuggestTriggerInfo | null { + const before = editor.getLine(cursor.line).slice(0, cursor.ch); + // The trigger must start a word: line start or right after whitespace. + let start = before.length; + while (start > 0 && !isSpace(before[start - 1])) start--; + const word = before.slice(start); + if (!word) return null; + + const rules = this.plugin.settings.rules; + const rule = rules.find((r, i) => r.symbol === word[0] && isRuleActive(r, rules, i)); + if (!rule || inFrontmatter(editor, cursor.line) || inCode(editor, cursor.line, before.slice(0, start))) return null; + + this.rule = rule; + return { start: { line: cursor.line, ch: start }, end: cursor, query: word.slice(1) }; + } + + getSuggestions(context: EditorSuggestContext): Suggestion[] { + const rule = this.rule; + if (!rule) return []; + const query = context.query.toLowerCase(); + + const pool: Suggestion[] = + rule.source === "finite" + ? rule.values.map((value) => ({ value, isNew: false })) + : [...this.index.get(rule.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)) { + matches.push({ value: context.query, isNew: true }); + } + return matches; + } + + renderSuggestion(s: Suggestion, el: HTMLElement): void { + el.addClass("fflow-suggestion"); + if (s.isNew) { + el.createSpan({ cls: "fflow-new", text: "New: " }); + el.createSpan({ text: s.value }); + return; + } + el.createSpan({ text: s.value }); + if (s.count !== undefined) el.createSpan({ cls: "fflow-count", text: String(s.count) }); + } + + selectSuggestion(s: Suggestion, _evt: MouseEvent | KeyboardEvent): void { + const context = this.context; + const rule = this.rule; + if (!context || !rule) return; + void this.apply(context, rule, s.value); + } + + private async apply(context: EditorSuggestContext, rule: TriggerRule, value: string): Promise { + const { editor, file, start } = context; + const line = editor.getLine(start.line); + + // Remove the whole trigger word (the cursor may sit mid-word), plus one following space. + let end = context.end.ch; + while (end < line.length && !isSpace(line[end])) end++; + if (isSpace(line[end])) end++; + editor.replaceRange("", start, { line: start.line, ch: end }); + editor.setCursor(start); + + try { + // Flush the editor first: processFrontMatter rewrites the file on disk. + const view = this.app.workspace.getActiveViewOfType(MarkdownView); + if (view?.file === file) await view.save(); + await this.app.fileManager.processFrontMatter(file, (fm: Record) => { + if (rule.valueMode === "single") { + fm[rule.property] = value; + return; + } + const current = fm[rule.property]; + const list: unknown[] = current == null ? [] : Array.isArray(current) ? current : [current]; + if (!list.some((v) => String(v) === value)) list.push(value); + fm[rule.property] = list; + }); + } catch (err) { + console.error("FFLOW: could not update frontmatter", err); + new Notice(`FFLOW: could not set "${rule.property}". See console.`); + } + } +} + +/** True when `line` lies inside a closed `---` frontmatter block at the top of the note. */ +function inFrontmatter(editor: Editor, line: number): boolean { + if (editor.getLine(0) !== "---") return false; + for (let i = 1; i < editor.lineCount(); i++) { + if (editor.getLine(i) === "---") return line <= i; + } + return false; +} + +function inCode(editor: Editor, line: number, beforeWord: string): boolean { + let fences = 0; + for (let i = 0; i < line; i++) if (/^\s*(```|~~~)/.test(editor.getLine(i))) fences++; + if (fences % 2 === 1) return true; + return (beforeWord.match(/`/g)?.length ?? 0) % 2 === 1; +} diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..6a6bf18 --- /dev/null +++ b/styles.css @@ -0,0 +1,31 @@ +.fflow-rule { + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + padding: 0 var(--size-4-3); + margin-bottom: var(--size-4-3); +} + +.fflow-error { + color: var(--text-error); +} + +.fflow-symbol { + width: 4em; + text-align: center; +} + +.fflow-suggestion { + display: flex; + gap: var(--size-4-2); + align-items: baseline; +} + +.fflow-count { + margin-left: auto; + color: var(--text-faint); + font-size: var(--font-ui-smaller); +} + +.fflow-new { + color: var(--text-muted); +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..61937ca --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "baseUrl": ".", + "inlineSourceMap": true, + "inlineSources": true, + "module": "ESNext", + "target": "ES2018", + "allowJs": false, + "noImplicitAny": true, + "moduleResolution": "node", + "importHelpers": false, + "isolatedModules": true, + "strictNullChecks": true, + "lib": [ + "DOM", + "ES2019" + ], + "paths": { + "src/*": ["./src/*"] + } + }, + "include": [ + "**/*.ts" + ] +} \ No newline at end of file