FFLOW 0.1.0: trigger symbols set frontmatter properties
This commit is contained in:
commit
021777203b
15 files changed
+1189
No files matched your search
+28
@@ -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<void> {
|
||||
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<void> {
|
||||
const saved = (await this.loadData()) as Partial<FflowSettings> | null;
|
||||
this.settings = { ...DEFAULT_SETTINGS, ...saved };
|
||||
}
|
||||
|
||||
async saveSettings(): Promise<void> {
|
||||
await this.saveData(this.settings);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+163
@@ -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<string, Map<string, number>>();
|
||||
|
||||
constructor(private app: App) {}
|
||||
|
||||
invalidate(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
|
||||
get(property: string): Map<string, number> {
|
||||
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<Suggestion> {
|
||||
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<void> {
|
||||
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<string, unknown>) => {
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user