FFLOW 0.2.0: flows with next/previous commands and per-step cssclasses; grouped settings page
This commit is contained in:
1 parent
021777203b
commit
68e390fb37
12 files changed
+486
-165
No files matched your search
@@ -0,0 +1,63 @@
|
||||
import { Notice, TFile } from "obsidian";
|
||||
import { setFlowStep, updateFrontmatter } from "./frontmatter";
|
||||
import type FflowPlugin from "./main";
|
||||
import { Flow, flowSteps } from "./settings";
|
||||
|
||||
type Direction = 1 | -1;
|
||||
|
||||
/** Re-registers the next/previous commands of every flow. Ids derive from the flow id, so hotkeys survive renames. */
|
||||
export class FlowCommands {
|
||||
private registered: string[] = [];
|
||||
|
||||
constructor(private plugin: FflowPlugin) {}
|
||||
|
||||
sync(): void {
|
||||
for (const id of this.registered) this.plugin.removeCommand(id);
|
||||
this.registered = [];
|
||||
for (const flow of this.plugin.settings.flows) {
|
||||
this.add(flow, 1, "next", "next step");
|
||||
this.add(flow, -1, "previous", "previous step");
|
||||
}
|
||||
}
|
||||
|
||||
private add(flow: Flow, direction: Direction, suffix: string, label: string): void {
|
||||
const id = `flow-${flow.id}-${suffix}`;
|
||||
this.registered.push(id);
|
||||
this.plugin.addCommand({
|
||||
id,
|
||||
name: `${flow.name || flow.property || "Unnamed flow"}: ${label}`,
|
||||
checkCallback: (checking) => {
|
||||
const file = this.plugin.app.workspace.getActiveFile();
|
||||
if (!file || file.extension !== "md" || !flow.property || flowSteps(flow).length === 0) return false;
|
||||
if (!checking) void moveStep(this.plugin, file, flow, direction);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction: Direction): Promise<void> {
|
||||
const steps = flowSteps(flow);
|
||||
let message = "";
|
||||
try {
|
||||
// Read the current value inside the update: the metadata cache can lag behind the editor.
|
||||
await updateFrontmatter(plugin.app, file, (fm) => {
|
||||
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.
|
||||
let target = index === -1 ? 0 : index + direction;
|
||||
if (target < 0 || target >= steps.length) {
|
||||
if (!flow.loop) {
|
||||
message = `${flow.property}: already at the ${direction === 1 ? "last" : "first"} step`;
|
||||
return;
|
||||
}
|
||||
target = (target + steps.length) % steps.length;
|
||||
}
|
||||
setFlowStep(fm, flow, steps[target].value);
|
||||
message = `${flow.property}: ${steps[target].value}`;
|
||||
});
|
||||
new Notice(message);
|
||||
} catch (err) {
|
||||
console.error("FFLOW: could not move flow step", err);
|
||||
new Notice(`FFLOW: could not set "${flow.property}". See console.`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { App, MarkdownView, TFile } from "obsidian";
|
||||
import type { Flow } from "./settings";
|
||||
|
||||
export type Frontmatter = Record<string, unknown>;
|
||||
|
||||
/** processFrontMatter rewrites the file on disk, so flush the open editor first or unsaved typing is lost. */
|
||||
export async function updateFrontmatter(app: App, file: TFile, fn: (fm: Frontmatter) => void): Promise<void> {
|
||||
const view = app.workspace.getActiveViewOfType(MarkdownView);
|
||||
if (view?.file === file) await view.save();
|
||||
await app.fileManager.processFrontMatter(file, fn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the note on `value` of `flow`: set the property, drop the classes of every
|
||||
* step of this flow from `cssclasses`, then add the classes of the new step.
|
||||
* Classes that don't belong to the flow are kept.
|
||||
*/
|
||||
export function setFlowStep(fm: Frontmatter, flow: Flow, value: string): void {
|
||||
fm[flow.property] = value;
|
||||
|
||||
const split = (s: string) => s.split(/\s+/).filter(Boolean);
|
||||
const flowClasses = new Set(flow.steps.flatMap((s) => split(s.cssclass)));
|
||||
const current = fm.cssclasses;
|
||||
const existing = (Array.isArray(current) ? current : typeof current === "string" ? split(current) : []).map(String);
|
||||
const step = flow.steps.find((s) => s.value === value);
|
||||
const next = existing.filter((c) => !flowClasses.has(c));
|
||||
for (const c of split(step?.cssclass ?? "")) if (!next.includes(c)) next.push(c);
|
||||
|
||||
if (next.length) fm.cssclasses = next;
|
||||
else if (current !== undefined) delete fm.cssclasses;
|
||||
}
|
||||
+11
-3
@@ -1,10 +1,12 @@
|
||||
import { Plugin } from "obsidian";
|
||||
import { DEFAULT_SETTINGS, FflowSettings } from "./settings";
|
||||
import { FlowCommands } from "./flows";
|
||||
import { DEFAULT_SETTINGS, FflowSettings, NEW_RULE } from "./settings";
|
||||
import { FflowSettingTab } from "./settings-tab";
|
||||
import { TriggerSuggest, ValueIndex } from "./suggest";
|
||||
|
||||
export default class FflowPlugin extends Plugin {
|
||||
settings!: FflowSettings;
|
||||
private flowCommands = new FlowCommands(this);
|
||||
|
||||
async onload(): Promise<void> {
|
||||
await this.loadSettings();
|
||||
@@ -14,15 +16,21 @@ export default class FflowPlugin extends Plugin {
|
||||
this.registerEvent(this.app.metadataCache.on("deleted", () => index.invalidate()));
|
||||
|
||||
this.registerEditorSuggest(new TriggerSuggest(this.app, this, index));
|
||||
this.flowCommands.sync();
|
||||
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 };
|
||||
const saved = ((await this.loadData()) ?? {}) as Partial<FflowSettings>;
|
||||
this.settings = {
|
||||
// Fill fields added after a rule was saved (e.g. flowId in 0.2.0).
|
||||
rules: (saved.rules ?? DEFAULT_SETTINGS.rules).map((r) => ({ ...NEW_RULE, ...r })),
|
||||
flows: saved.flows ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
async saveSettings(): Promise<void> {
|
||||
await this.saveData(this.settings);
|
||||
this.flowCommands.sync();
|
||||
}
|
||||
}
|
||||
+270
-98
@@ -1,125 +1,297 @@
|
||||
import { App, PluginSettingTab, Setting } from "obsidian";
|
||||
import { App, PluginSettingTab, SearchComponent, Setting, SettingGroup } from "obsidian";
|
||||
import type FflowPlugin from "./main";
|
||||
import { BLOCKED_SYMBOLS, SourceMode, symbolError, TriggerRule, ValueMode } from "./settings";
|
||||
import { BLOCKED_SYMBOLS, Flow, NEW_RULE, symbolError, TriggerRule, ValueMode } from "./settings";
|
||||
|
||||
export class FflowSettingTab extends PluginSettingTab {
|
||||
constructor(app: App, private plugin: FflowPlugin) {
|
||||
super(app, plugin);
|
||||
}
|
||||
|
||||
private save = () => this.plugin.saveSettings();
|
||||
|
||||
display(): void {
|
||||
const { containerEl } = this;
|
||||
const settings = this.plugin.settings;
|
||||
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();
|
||||
new Setting(containerEl)
|
||||
.setHeading()
|
||||
.setName("Triggers")
|
||||
.setDesc(
|
||||
`Type a symbol at the start of a word, pick a value: the typed text disappears and the value goes to the frontmatter. Reserved: ${BLOCKED_SYMBOLS.join(" ")}`,
|
||||
)
|
||||
.addButton((b) =>
|
||||
b.setButtonText("Add trigger").onClick(async () => {
|
||||
settings.rules.push({ ...NEW_RULE, values: [] });
|
||||
await this.save();
|
||||
this.display();
|
||||
}),
|
||||
);
|
||||
);
|
||||
settings.rules.forEach((rule, index) => this.renderRule(rule, index));
|
||||
|
||||
new Setting(containerEl)
|
||||
.setHeading()
|
||||
.setName("Flows")
|
||||
.setDesc("Ordered values for a property. Each step can add cssclasses. Every flow gets “next step” and “previous step” commands for hotkeys.")
|
||||
.addButton((b) => b.setButtonText("Hotkeys").onClick(() => this.openHotkeys()))
|
||||
.addButton((b) =>
|
||||
b.setButtonText("Add flow").onClick(async () => {
|
||||
settings.flows.push({ id: Date.now().toString(36), name: "", property: "", loop: false, steps: [{ value: "", cssclass: "" }] });
|
||||
await this.save();
|
||||
this.display();
|
||||
}),
|
||||
);
|
||||
settings.flows.forEach((flow, index) => this.renderFlow(flow, index));
|
||||
}
|
||||
|
||||
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" });
|
||||
const settings = this.plugin.settings;
|
||||
const flow = rule.source === "flow" ? settings.flows.find((f) => f.id === rule.flowId) : undefined;
|
||||
|
||||
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 title = createFragment();
|
||||
const titleEl = title.createSpan();
|
||||
const updateTitle = () => {
|
||||
const property = flow ? flow.property : rule.property;
|
||||
titleEl.setText(`${rule.symbol || "?"} → ${property || "?"}`);
|
||||
};
|
||||
updateTitle();
|
||||
|
||||
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();
|
||||
const group = new SettingGroup(this.containerEl).setHeading(title).addClass("fflow-group");
|
||||
group.addExtraButton((b) =>
|
||||
b
|
||||
.setIcon("trash")
|
||||
.setTooltip("Delete trigger")
|
||||
.onClick(async () => {
|
||||
settings.rules.splice(index, 1);
|
||||
await this.save();
|
||||
this.display();
|
||||
}),
|
||||
);
|
||||
|
||||
group.addSetting((s) => {
|
||||
s.setName("Symbol");
|
||||
const error = s.descEl.createDiv({ cls: "fflow-error" });
|
||||
const check = (value: string) => error.setText(value ? (symbolError(value, settings.rules, index) ?? "") : "Pick a symbol.");
|
||||
check(rule.symbol);
|
||||
s.addText((t) => {
|
||||
t.setPlaceholder("@").setValue(rule.symbol);
|
||||
t.inputEl.addClass("fflow-symbol");
|
||||
t.onChange(async (value) => {
|
||||
check(value);
|
||||
// Invalid input stays in the field but is never saved.
|
||||
if (symbolError(value, settings.rules, index)) return;
|
||||
rule.symbol = value;
|
||||
updateTitle();
|
||||
await this.save();
|
||||
});
|
||||
});
|
||||
});
|
||||
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();
|
||||
group.addSetting((s) =>
|
||||
s
|
||||
.setName("Values from")
|
||||
.setDesc(
|
||||
rule.source === "open"
|
||||
? "Every value already used for the property in the vault. New values are allowed."
|
||||
: rule.source === "finite"
|
||||
? "Only the values listed below."
|
||||
: "The steps of the flow. Picking one also applies its cssclasses.",
|
||||
)
|
||||
.addDropdown((d) => {
|
||||
d.addOption("open", "Vault (open list)").addOption("finite", "Fixed list");
|
||||
for (const f of settings.flows) d.addOption(`flow:${f.id}`, `Flow: ${f.name || f.property || "unnamed"}`);
|
||||
d.setValue(rule.source === "flow" ? `flow:${rule.flowId}` : rule.source).onChange(async (value) => {
|
||||
if (value.startsWith("flow:")) {
|
||||
rule.source = "flow";
|
||||
rule.flowId = value.slice("flow:".length);
|
||||
} else {
|
||||
rule.source = value as "open" | "finite";
|
||||
}
|
||||
await this.save();
|
||||
this.display();
|
||||
}),
|
||||
);
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
if (rule.source === "flow") {
|
||||
if (!flow) group.addSetting((s) => s.setName("Flow deleted").setDesc("Pick another source.").descEl.addClass("fflow-error"));
|
||||
return;
|
||||
}
|
||||
|
||||
group.addSetting((s) =>
|
||||
s
|
||||
.setName("Property")
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder("type")
|
||||
.setValue(rule.property)
|
||||
.onChange(async (value) => {
|
||||
rule.property = value.trim();
|
||||
updateTitle();
|
||||
await this.save();
|
||||
}),
|
||||
)
|
||||
.addDropdown((d) =>
|
||||
d
|
||||
.addOptions({ single: "Single value", list: "List" })
|
||||
.setValue(rule.valueMode)
|
||||
.onChange(async (value) => {
|
||||
rule.valueMode = value as ValueMode;
|
||||
await this.save();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (rule.source === "finite") {
|
||||
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;
|
||||
});
|
||||
group.addSetting((s) =>
|
||||
s
|
||||
.setName("Values")
|
||||
.setDesc("One per line, in display order.")
|
||||
.addTextArea((t) => {
|
||||
t.setValue(rule.values.join("\n")).onChange(async (value) => {
|
||||
rule.values = value
|
||||
.split("\n")
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean);
|
||||
await this.save();
|
||||
});
|
||||
t.inputEl.rows = 5;
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private renderFlow(flow: Flow, index: number): void {
|
||||
const settings = this.plugin.settings;
|
||||
|
||||
const title = createFragment();
|
||||
const titleEl = title.createSpan();
|
||||
const updateTitle = () => titleEl.setText(flow.name || flow.property || "New flow");
|
||||
updateTitle();
|
||||
|
||||
const group = new SettingGroup(this.containerEl).setHeading(title).addClass("fflow-group");
|
||||
group.addExtraButton((b) =>
|
||||
b
|
||||
.setIcon("trash")
|
||||
.setTooltip("Delete flow")
|
||||
.onClick(async () => {
|
||||
settings.flows.splice(index, 1);
|
||||
// Triggers that used this flow keep writing the same property, from the vault's values.
|
||||
for (const rule of settings.rules) {
|
||||
if (rule.source === "flow" && rule.flowId === flow.id) {
|
||||
rule.source = "open";
|
||||
rule.property = flow.property;
|
||||
}
|
||||
}
|
||||
await this.save();
|
||||
this.display();
|
||||
}),
|
||||
);
|
||||
|
||||
group.addSetting((s) =>
|
||||
s
|
||||
.setName("Name and property")
|
||||
.setDesc("The name labels the hotkey commands.")
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder("Status")
|
||||
.setValue(flow.name)
|
||||
.onChange(async (value) => {
|
||||
flow.name = value;
|
||||
updateTitle();
|
||||
await this.save();
|
||||
}),
|
||||
)
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder("status")
|
||||
.setValue(flow.property)
|
||||
.onChange(async (value) => {
|
||||
flow.property = value.trim();
|
||||
updateTitle();
|
||||
await this.save();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
group.addSetting((s) =>
|
||||
s
|
||||
.setName("Loop")
|
||||
.setDesc("After the last step, “next” goes back to the first.")
|
||||
.addToggle((t) =>
|
||||
t.setValue(flow.loop).onChange(async (value) => {
|
||||
flow.loop = value;
|
||||
await this.save();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
flow.steps.forEach((step, i) => {
|
||||
group.addSetting((s) => {
|
||||
s.setName(`Step ${i + 1}`).setClass("fflow-step");
|
||||
s.addText((t) =>
|
||||
t
|
||||
.setPlaceholder("value")
|
||||
.setValue(step.value)
|
||||
.onChange(async (value) => {
|
||||
step.value = value.trim();
|
||||
await this.save();
|
||||
}),
|
||||
);
|
||||
s.addText((t) =>
|
||||
t
|
||||
.setPlaceholder("cssclasses (optional)")
|
||||
.setValue(step.cssclass)
|
||||
.onChange(async (value) => {
|
||||
step.cssclass = value.trim();
|
||||
await this.save();
|
||||
}),
|
||||
);
|
||||
const move = async (to: number) => {
|
||||
flow.steps.splice(to, 0, ...flow.steps.splice(i, 1));
|
||||
await this.save();
|
||||
this.display();
|
||||
};
|
||||
s.addExtraButton((b) => b.setIcon("arrow-up").setTooltip("Move up").setDisabled(i === 0).onClick(() => move(i - 1)));
|
||||
s.addExtraButton((b) =>
|
||||
b
|
||||
.setIcon("arrow-down")
|
||||
.setTooltip("Move down")
|
||||
.setDisabled(i === flow.steps.length - 1)
|
||||
.onClick(() => move(i + 1)),
|
||||
);
|
||||
s.addExtraButton((b) =>
|
||||
b
|
||||
.setIcon("x")
|
||||
.setTooltip("Remove step")
|
||||
.onClick(async () => {
|
||||
flow.steps.splice(i, 1);
|
||||
await this.save();
|
||||
this.display();
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group.addSetting((s) =>
|
||||
s.addButton((b) =>
|
||||
b.setButtonText("Add step").onClick(async () => {
|
||||
flow.steps.push({ value: "", cssclass: "" });
|
||||
await this.save();
|
||||
this.display();
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Opens Settings → Hotkeys filtered on this plugin. `app.setting` and the tab's search box are internal API: probe before use. */
|
||||
private openHotkeys(): void {
|
||||
const setting: unknown = Reflect.get(this.app, "setting");
|
||||
if (!setting || typeof setting !== "object" || !("openTabById" in setting) || typeof setting.openTabById !== "function") return;
|
||||
const tab: unknown = setting.openTabById("hotkeys");
|
||||
const search = tab && typeof tab === "object" && "searchComponent" in tab ? tab.searchComponent : null;
|
||||
if (!(search instanceof SearchComponent)) return;
|
||||
search.setValue(this.plugin.manifest.name);
|
||||
search.inputEl.dispatchEvent(new Event("input"));
|
||||
}
|
||||
}
|
||||
+41
-8
@@ -1,24 +1,45 @@
|
||||
export type ValueMode = "single" | "list";
|
||||
export type SourceMode = "open" | "finite";
|
||||
export type SourceMode = "open" | "finite" | "flow";
|
||||
|
||||
export interface TriggerRule {
|
||||
/** One non-alphanumeric character that opens the suggestions. */
|
||||
symbol: string;
|
||||
/** Frontmatter property written on selection. */
|
||||
/** Frontmatter property written on selection. Ignored for flow sources: the flow owns it. */
|
||||
property: string;
|
||||
/** single: replace the value. list: append to a list, no duplicates. */
|
||||
/** single: replace the value. list: append to a list, no duplicates. Flows are always single. */
|
||||
valueMode: ValueMode;
|
||||
/** open: values already used in the vault. finite: `values` below. */
|
||||
/** open: values already used in the vault. finite: `values`. flow: the steps of `flowId`. */
|
||||
source: SourceMode;
|
||||
values: string[];
|
||||
flowId: string;
|
||||
}
|
||||
|
||||
export interface FlowStep {
|
||||
value: string;
|
||||
/** Space-separated classes added to `cssclasses` while the note is on this step. */
|
||||
cssclass: string;
|
||||
}
|
||||
|
||||
export interface Flow {
|
||||
/** Stable id: command ids derive from it, so hotkeys survive renames. */
|
||||
id: string;
|
||||
name: string;
|
||||
property: string;
|
||||
/** After the last step, "next" goes back to the first (and "previous" the other way). */
|
||||
loop: boolean;
|
||||
steps: FlowStep[];
|
||||
}
|
||||
|
||||
export interface FflowSettings {
|
||||
rules: TriggerRule[];
|
||||
flows: Flow[];
|
||||
}
|
||||
|
||||
export const NEW_RULE: TriggerRule = { symbol: "", property: "", valueMode: "single", source: "open", values: [], flowId: "" };
|
||||
|
||||
export const DEFAULT_SETTINGS: FflowSettings = {
|
||||
rules: [{ symbol: "@", property: "type", valueMode: "single", source: "open", values: [] }],
|
||||
rules: [{ ...NEW_RULE, symbol: "@", property: "type" }],
|
||||
flows: [],
|
||||
};
|
||||
|
||||
/** Reserved by Obsidian or common plugins: tags, links, slash commands, emoji shortcodes. */
|
||||
@@ -29,10 +50,22 @@ export function symbolError(symbol: string, rules: TriggerRule[], index: number)
|
||||
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.`;
|
||||
if (rules.some((r, i) => i !== index && r.symbol === symbol)) return `"${symbol}" is already used by another trigger.`;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isRuleActive(rule: TriggerRule, rules: TriggerRule[], index: number): boolean {
|
||||
return rule.property.trim() !== "" && symbolError(rule.symbol, rules, index) === null;
|
||||
/** What a usable trigger writes to; null when the rule is incomplete or points to a missing flow. */
|
||||
export function resolveRule(settings: FflowSettings, index: number): { property: string; flow: Flow | null } | null {
|
||||
const rule = settings.rules[index];
|
||||
if (symbolError(rule.symbol, settings.rules, index)) return null;
|
||||
if (rule.source === "flow") {
|
||||
const flow = settings.flows.find((f) => f.id === rule.flowId);
|
||||
return flow && flow.property ? { property: flow.property, flow } : null;
|
||||
}
|
||||
return rule.property ? { property: rule.property, flow: null } : null;
|
||||
}
|
||||
|
||||
/** Steps usable at runtime: blank values are skipped. */
|
||||
export function flowSteps(flow: Flow): FlowStep[] {
|
||||
return flow.steps.filter((s) => s.value.trim() !== "");
|
||||
}
|
||||
+36
-36
@@ -1,16 +1,13 @@
|
||||
import {
|
||||
App,
|
||||
Editor,
|
||||
EditorPosition,
|
||||
EditorSuggest,
|
||||
EditorSuggestContext,
|
||||
EditorSuggestTriggerInfo,
|
||||
MarkdownView,
|
||||
Notice,
|
||||
TFile,
|
||||
} from "obsidian";
|
||||
import { App, Editor, EditorPosition, EditorSuggest, EditorSuggestContext, EditorSuggestTriggerInfo, Notice, TFile } from "obsidian";
|
||||
import { setFlowStep, updateFrontmatter } from "./frontmatter";
|
||||
import type FflowPlugin from "./main";
|
||||
import { isRuleActive, TriggerRule } from "./settings";
|
||||
import { Flow, flowSteps, resolveRule, TriggerRule } from "./settings";
|
||||
|
||||
interface ActiveTrigger {
|
||||
rule: TriggerRule;
|
||||
property: string;
|
||||
flow: Flow | null;
|
||||
}
|
||||
|
||||
interface Suggestion {
|
||||
value: string;
|
||||
@@ -52,7 +49,7 @@ function flatten(raw: unknown): string[] {
|
||||
const isSpace = (ch: string | undefined) => ch !== undefined && /\s/.test(ch);
|
||||
|
||||
export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
private rule: TriggerRule | null = null;
|
||||
private active: ActiveTrigger | null = null;
|
||||
|
||||
constructor(app: App, private plugin: FflowPlugin, private index: ValueIndex) {
|
||||
super(app);
|
||||
@@ -66,26 +63,28 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
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;
|
||||
const settings = this.plugin.settings;
|
||||
const index = settings.rules.findIndex((r) => r.symbol === word[0]);
|
||||
const target = index === -1 ? null : resolveRule(settings, index);
|
||||
if (!target || inFrontmatter(editor, cursor.line) || inCode(editor, cursor.line, before.slice(0, start))) return null;
|
||||
|
||||
this.rule = rule;
|
||||
this.active = { rule: settings.rules[index], ...target };
|
||||
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 active = this.active;
|
||||
if (!active) return [];
|
||||
const { rule, flow } = active;
|
||||
const query = context.query.toLowerCase();
|
||||
|
||||
const pool: Suggestion[] =
|
||||
rule.source === "finite"
|
||||
const pool: Suggestion[] = flow
|
||||
? flowSteps(flow).map((s) => ({ value: s.value, isNew: false }))
|
||||
: rule.source === "finite"
|
||||
? rule.values.map((value) => ({ value, isNew: false }))
|
||||
: [...this.index.get(rule.property)]
|
||||
: [...this.index.get(active.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)));
|
||||
@@ -109,12 +108,12 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
|
||||
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);
|
||||
const active = this.active;
|
||||
if (!context || !active) return;
|
||||
void this.apply(context, active, s.value);
|
||||
}
|
||||
|
||||
private async apply(context: EditorSuggestContext, rule: TriggerRule, value: string): Promise<void> {
|
||||
private async apply(context: EditorSuggestContext, { rule, property, flow }: ActiveTrigger, value: string): Promise<void> {
|
||||
const { editor, file, start } = context;
|
||||
const line = editor.getLine(start.line);
|
||||
|
||||
@@ -126,22 +125,23 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
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;
|
||||
await updateFrontmatter(this.app, file, (fm) => {
|
||||
if (flow) {
|
||||
setFlowStep(fm, flow, value);
|
||||
return;
|
||||
}
|
||||
const current = fm[rule.property];
|
||||
if (rule.valueMode === "single") {
|
||||
fm[property] = value;
|
||||
return;
|
||||
}
|
||||
const current = fm[property];
|
||||
const list: unknown[] = current == null ? [] : Array.isArray(current) ? current : [current];
|
||||
if (!list.some((v) => String(v) === value)) list.push(value);
|
||||
fm[rule.property] = list;
|
||||
fm[property] = list;
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("FFLOW: could not update frontmatter", err);
|
||||
new Notice(`FFLOW: could not set "${rule.property}". See console.`);
|
||||
new Notice(`FFLOW: could not set "${property}". See console.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user