FFLOW 0.3.0: everything is a flow; steps set any properties, symbol and hotkeys share them
This commit is contained in:
1 parent
68e390fb37
commit
8553b7c75a
12 files changed
+423
-335
No files matched your search
+6
-5
@@ -1,11 +1,11 @@
|
||||
import { Notice, TFile } from "obsidian";
|
||||
import { setFlowStep, updateFrontmatter } from "./frontmatter";
|
||||
import type FflowPlugin from "./main";
|
||||
import { Flow, flowSteps } from "./settings";
|
||||
import type { Flow } 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. */
|
||||
/** Re-registers the next/previous commands of every ordered flow. Ids derive from the flow id, so hotkeys survive renames. */
|
||||
export class FlowCommands {
|
||||
private registered: string[] = [];
|
||||
|
||||
@@ -15,6 +15,7 @@ export class FlowCommands {
|
||||
for (const id of this.registered) this.plugin.removeCommand(id);
|
||||
this.registered = [];
|
||||
for (const flow of this.plugin.settings.flows) {
|
||||
if (flow.kind !== "ordered") continue;
|
||||
this.add(flow, 1, "next", "next step");
|
||||
this.add(flow, -1, "previous", "previous step");
|
||||
}
|
||||
@@ -28,7 +29,7 @@ export class FlowCommands {
|
||||
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 (!file || file.extension !== "md" || !flow.property || !flow.steps.some((s) => s.value)) return false;
|
||||
if (!checking) void moveStep(this.plugin, file, flow, direction);
|
||||
return true;
|
||||
},
|
||||
@@ -37,7 +38,7 @@ export class FlowCommands {
|
||||
}
|
||||
|
||||
async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction: Direction): Promise<void> {
|
||||
const steps = flowSteps(flow);
|
||||
const steps = flow.steps.filter((s) => s.value);
|
||||
let message = "";
|
||||
try {
|
||||
// Read the current value inside the update: the metadata cache can lag behind the editor.
|
||||
@@ -52,7 +53,7 @@ async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction:
|
||||
}
|
||||
target = (target + steps.length) % steps.length;
|
||||
}
|
||||
setFlowStep(fm, flow, steps[target].value);
|
||||
setFlowStep(plugin.app, fm, flow, steps[target].value);
|
||||
message = `${flow.property}: ${steps[target].value}`;
|
||||
});
|
||||
new Notice(message);
|
||||
|
||||
+84
-14
@@ -1,5 +1,5 @@
|
||||
import { App, MarkdownView, TFile } from "obsidian";
|
||||
import type { Flow } from "./settings";
|
||||
import type { Flow, FlowEffect } from "./settings";
|
||||
|
||||
export type Frontmatter = Record<string, unknown>;
|
||||
|
||||
@@ -10,22 +10,92 @@ export async function updateFrontmatter(app: App, file: TFile, fn: (fm: Frontmat
|
||||
await app.fileManager.processFrontMatter(file, fn);
|
||||
}
|
||||
|
||||
/** Sets `value` on a single-value property, or appends it to a list property without duplicates. */
|
||||
export function setOpenValue(fm: Frontmatter, property: string, value: string, asList: boolean): void {
|
||||
if (!asList) {
|
||||
fm[property] = value;
|
||||
return;
|
||||
}
|
||||
const list = toList(fm[property], property);
|
||||
if (!list.includes(value)) list.push(value);
|
||||
fm[property] = list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Puts the note on step `value` of an ordered flow:
|
||||
* 1. sets the flow's property;
|
||||
* 2. undoes the effects of every other step (list items removed, scalars removed only if unchanged since the flow wrote them);
|
||||
* 3. applies the new step's effects (list items added, scalars replaced).
|
||||
*/
|
||||
export function setFlowStep(fm: Frontmatter, flow: Flow, value: string): void {
|
||||
export function setFlowStep(app: App, fm: Frontmatter, flow: Flow, value: string): void {
|
||||
fm[flow.property] = value;
|
||||
const target = flow.steps.find((s) => s.value === value);
|
||||
|
||||
// Decide list vs scalar before any edit: deleting a property would hide its array shape.
|
||||
const listness = new Map<string, boolean>();
|
||||
const isList = (p: string) => {
|
||||
let result = listness.get(p);
|
||||
if (result === undefined) listness.set(p, (result = isListProperty(app, fm, p)));
|
||||
return result;
|
||||
};
|
||||
const usable = (e: FlowEffect) => e.property !== "" && e.property !== flow.property;
|
||||
|
||||
for (const step of flow.steps) {
|
||||
if (step === target) continue;
|
||||
for (const effect of step.effects.filter(usable)) {
|
||||
const p = effect.property;
|
||||
if (isList(p)) {
|
||||
const remove = new Set(listItems(effect.value));
|
||||
const kept = toList(fm[p], p).filter((item) => !remove.has(item));
|
||||
if (kept.length) fm[p] = kept;
|
||||
else delete fm[p];
|
||||
} else if (p in fm && String(fm[p]) === String(parseScalar(effect.value))) {
|
||||
delete fm[p];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const effect of target?.effects.filter(usable) ?? []) {
|
||||
const p = effect.property;
|
||||
if (isList(p)) {
|
||||
const list = toList(fm[p], p);
|
||||
for (const item of listItems(effect.value)) if (!list.includes(item)) list.push(item);
|
||||
if (list.length) fm[p] = list;
|
||||
} else {
|
||||
fm[p] = parseScalar(effect.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Known list properties, current array values, and properties Obsidian types as lists (internal API, probed). */
|
||||
function isListProperty(app: App, fm: Frontmatter, property: string): boolean {
|
||||
if (["cssclasses", "tags", "aliases"].includes(property) || Array.isArray(fm[property])) return true;
|
||||
const types: unknown = Reflect.get(app, "metadataTypeManager");
|
||||
if (!types || typeof types !== "object" || !("getPropertyInfo" in types) || typeof types.getPropertyInfo !== "function") return false;
|
||||
const info: unknown = types.getPropertyInfo(property);
|
||||
const widget = info && typeof info === "object" && "widget" in info ? info.widget : null;
|
||||
return widget === "multitext" || widget === "tags" || widget === "aliases";
|
||||
}
|
||||
|
||||
function toList(raw: unknown, property: string): string[] {
|
||||
if (Array.isArray(raw)) return raw.map(String);
|
||||
if (raw == null || raw === "") return [];
|
||||
// Obsidian also accepts `cssclasses: a b` as a space-separated string.
|
||||
return property === "cssclasses" ? String(raw).split(/[\s,]+/).filter(Boolean) : [String(raw)];
|
||||
}
|
||||
|
||||
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);
|
||||
function listItems(value: string): string[] {
|
||||
return value
|
||||
.split(",")
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
if (next.length) fm.cssclasses = next;
|
||||
else if (current !== undefined) delete fm.cssclasses;
|
||||
/** "true"/"false" become booleans and plain numbers become numbers, so checkbox and number properties stay typed. */
|
||||
function parseScalar(value: string): string | number | boolean | null {
|
||||
const v = value.trim();
|
||||
if (v === "") return null;
|
||||
if (v === "true" || v === "false") return v === "true";
|
||||
if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v);
|
||||
return v;
|
||||
}
|
||||
+5
-11
@@ -1,6 +1,6 @@
|
||||
import { Plugin } from "obsidian";
|
||||
import { FlowCommands } from "./flows";
|
||||
import { DEFAULT_SETTINGS, FflowSettings, NEW_RULE } from "./settings";
|
||||
import { FflowSettings, loadSettings } from "./settings";
|
||||
import { FflowSettingTab } from "./settings-tab";
|
||||
import { TriggerSuggest, ValueIndex } from "./suggest";
|
||||
|
||||
@@ -9,7 +9,10 @@ export default class FflowPlugin extends Plugin {
|
||||
private flowCommands = new FlowCommands(this);
|
||||
|
||||
async onload(): Promise<void> {
|
||||
await this.loadSettings();
|
||||
const saved: unknown = await this.loadData();
|
||||
this.settings = loadSettings(saved);
|
||||
// Persist a migration from the old trigger/flow format right away.
|
||||
if (saved && typeof saved === "object" && "rules" in saved) await this.saveData(this.settings);
|
||||
|
||||
const index = new ValueIndex(this.app);
|
||||
this.registerEvent(this.app.metadataCache.on("changed", () => index.invalidate()));
|
||||
@@ -20,15 +23,6 @@ export default class FflowPlugin extends Plugin {
|
||||
this.addSettingTab(new FflowSettingTab(this.app, this));
|
||||
}
|
||||
|
||||
async loadSettings(): Promise<void> {
|
||||
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();
|
||||
|
||||
+161
-204
@@ -1,6 +1,6 @@
|
||||
import { App, PluginSettingTab, SearchComponent, Setting, SettingGroup } from "obsidian";
|
||||
import type FflowPlugin from "./main";
|
||||
import { BLOCKED_SYMBOLS, Flow, NEW_RULE, symbolError, TriggerRule, ValueMode } from "./settings";
|
||||
import { BLOCKED_SYMBOLS, Flow, FlowKind, FlowStep, newFlow, symbolError, ValueMode } from "./settings";
|
||||
|
||||
export class FflowSettingTab extends PluginSettingTab {
|
||||
constructor(app: App, private plugin: FflowPlugin) {
|
||||
@@ -9,164 +9,45 @@ export class FflowSettingTab extends PluginSettingTab {
|
||||
|
||||
private save = () => this.plugin.saveSettings();
|
||||
|
||||
/** Saves, then redraws: for edits that add, remove or reorder rows. */
|
||||
private async saveAndRedraw(): Promise<void> {
|
||||
await this.save();
|
||||
this.display();
|
||||
}
|
||||
|
||||
display(): void {
|
||||
const { containerEl } = this;
|
||||
const settings = this.plugin.settings;
|
||||
const flows = this.plugin.settings.flows;
|
||||
containerEl.empty();
|
||||
|
||||
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.")
|
||||
.setDesc(
|
||||
`Type a flow's symbol at the start of a word and pick a value: the text disappears, the property is set, and the step's other properties are applied. Ordered flows get “next step” and “previous step” commands for hotkeys. Reserved symbols: ${BLOCKED_SYMBOLS.join(" ")}`,
|
||||
)
|
||||
.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();
|
||||
flows.push(newFlow({ steps: [{ value: "", effects: [] }] }));
|
||||
await this.saveAndRedraw();
|
||||
}),
|
||||
);
|
||||
settings.flows.forEach((flow, index) => this.renderFlow(flow, index));
|
||||
}
|
||||
|
||||
private renderRule(rule: TriggerRule, index: number): void {
|
||||
const settings = this.plugin.settings;
|
||||
const flow = rule.source === "flow" ? settings.flows.find((f) => f.id === rule.flowId) : undefined;
|
||||
|
||||
const title = createFragment();
|
||||
const titleEl = title.createSpan();
|
||||
const updateTitle = () => {
|
||||
const property = flow ? flow.property : rule.property;
|
||||
titleEl.setText(`${rule.symbol || "?"} → ${property || "?"}`);
|
||||
};
|
||||
updateTitle();
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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") {
|
||||
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;
|
||||
}),
|
||||
);
|
||||
}
|
||||
flows.forEach((flow, index) => this.renderFlow(flow, index));
|
||||
}
|
||||
|
||||
private renderFlow(flow: Flow, index: number): void {
|
||||
const settings = this.plugin.settings;
|
||||
const flows = this.plugin.settings.flows;
|
||||
|
||||
const title = createFragment();
|
||||
const titleEl = title.createSpan();
|
||||
const updateTitle = () => titleEl.setText(flow.name || flow.property || "New flow");
|
||||
const badge = title.createSpan({ cls: "fflow-badge" });
|
||||
const name = title.createSpan();
|
||||
const updateTitle = () => {
|
||||
badge.setText(flow.symbol);
|
||||
badge.toggle(flow.symbol !== "");
|
||||
name.setText(flow.name || flow.property || "New flow");
|
||||
};
|
||||
updateTitle();
|
||||
|
||||
const group = new SettingGroup(this.containerEl).setHeading(title).addClass("fflow-group");
|
||||
@@ -175,23 +56,15 @@ export class FflowSettingTab extends PluginSettingTab {
|
||||
.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();
|
||||
flows.splice(index, 1);
|
||||
await this.saveAndRedraw();
|
||||
}),
|
||||
);
|
||||
|
||||
group.addSetting((s) =>
|
||||
s
|
||||
.setName("Name and property")
|
||||
.setDesc("The name labels the hotkey commands.")
|
||||
.setName("Name")
|
||||
.setDesc(flow.kind === "ordered" ? "Labels the hotkey commands." : "For your reference.")
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder("Status")
|
||||
@@ -201,6 +74,34 @@ export class FflowSettingTab extends PluginSettingTab {
|
||||
updateTitle();
|
||||
await this.save();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
group.addSetting((s) => {
|
||||
s.setName("Symbol").setDesc("Optional. One character, not a letter or digit.");
|
||||
const error = s.descEl.createDiv({ cls: "fflow-error" });
|
||||
error.setText(symbolError(flow.symbol, flows, index) ?? "");
|
||||
s.addText((t) => {
|
||||
t.setPlaceholder("@").setValue(flow.symbol);
|
||||
t.inputEl.addClass("fflow-symbol");
|
||||
t.onChange(async (value) => {
|
||||
const problem = symbolError(value, flows, index);
|
||||
error.setText(problem ?? "");
|
||||
// Invalid input stays in the field but is never saved.
|
||||
if (problem) return;
|
||||
flow.symbol = value;
|
||||
updateTitle();
|
||||
await this.save();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
group.addSetting((s) => {
|
||||
s.setName("Property")
|
||||
.setDesc(
|
||||
flow.kind === "ordered"
|
||||
? "Ordered: the steps below, in order. Each step can set other properties."
|
||||
: "Open: every value already used in the vault; new values allowed. No steps or hotkeys.",
|
||||
)
|
||||
.addText((t) =>
|
||||
t
|
||||
@@ -211,8 +112,30 @@ export class FflowSettingTab extends PluginSettingTab {
|
||||
updateTitle();
|
||||
await this.save();
|
||||
}),
|
||||
),
|
||||
);
|
||||
)
|
||||
.addDropdown((d) =>
|
||||
d
|
||||
.addOptions({ ordered: "Ordered list", open: "Open (vault)" })
|
||||
.setValue(flow.kind)
|
||||
.onChange(async (value) => {
|
||||
flow.kind = value as FlowKind;
|
||||
await this.saveAndRedraw();
|
||||
}),
|
||||
);
|
||||
if (flow.kind === "open") {
|
||||
s.addDropdown((d) =>
|
||||
d
|
||||
.addOptions({ single: "Single value", list: "List" })
|
||||
.setValue(flow.valueMode)
|
||||
.onChange(async (value) => {
|
||||
flow.valueMode = value as ValueMode;
|
||||
await this.save();
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (flow.kind === "open") return;
|
||||
|
||||
group.addSetting((s) =>
|
||||
s
|
||||
@@ -226,64 +149,98 @@ export class FflowSettingTab extends PluginSettingTab {
|
||||
),
|
||||
);
|
||||
|
||||
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();
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
flow.steps.forEach((step, i) => this.renderStep(group, flow, step, i));
|
||||
|
||||
group.addSetting((s) =>
|
||||
s.addButton((b) =>
|
||||
b.setButtonText("Add step").onClick(async () => {
|
||||
flow.steps.push({ value: "", cssclass: "" });
|
||||
await this.save();
|
||||
this.display();
|
||||
flow.steps.push({ value: "", effects: [] });
|
||||
await this.saveAndRedraw();
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private renderStep(group: SettingGroup, flow: Flow, step: FlowStep, i: number): void {
|
||||
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.addExtraButton((b) =>
|
||||
b
|
||||
.setIcon("list-plus")
|
||||
.setTooltip("Also set a property")
|
||||
.onClick(async () => {
|
||||
step.effects.push({ property: "", value: "" });
|
||||
await this.saveAndRedraw();
|
||||
}),
|
||||
);
|
||||
const move = async (to: number) => {
|
||||
flow.steps.splice(to, 0, ...flow.steps.splice(i, 1));
|
||||
await this.saveAndRedraw();
|
||||
};
|
||||
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.saveAndRedraw();
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
step.effects.forEach((effect, j) =>
|
||||
group.addSetting((s) =>
|
||||
s
|
||||
.setClass("fflow-effect")
|
||||
.setDesc(j === 0 ? "Also sets" : "")
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder("property")
|
||||
.setValue(effect.property)
|
||||
.onChange(async (value) => {
|
||||
effect.property = value.trim();
|
||||
await this.save();
|
||||
}),
|
||||
)
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder("value (lists: a, b)")
|
||||
.setValue(effect.value)
|
||||
.onChange(async (value) => {
|
||||
effect.value = value;
|
||||
await this.save();
|
||||
}),
|
||||
)
|
||||
.addExtraButton((b) =>
|
||||
b
|
||||
.setIcon("x")
|
||||
.setTooltip("Remove property")
|
||||
.onClick(async () => {
|
||||
step.effects.splice(j, 1);
|
||||
await this.saveAndRedraw();
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** 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");
|
||||
|
||||
+78
-34
@@ -1,71 +1,115 @@
|
||||
/** ordered: a fixed list of steps with effects and next/previous commands. open: any value already used in the vault. */
|
||||
export type FlowKind = "ordered" | "open";
|
||||
/** single: replace the value. list: append to a list, no duplicates. Ordered flows are always single. */
|
||||
export type ValueMode = "single" | "list";
|
||||
export type SourceMode = "open" | "finite" | "flow";
|
||||
|
||||
export interface TriggerRule {
|
||||
/** One non-alphanumeric character that opens the suggestions. */
|
||||
symbol: string;
|
||||
/** Frontmatter property written on selection. Ignored for flow sources: the flow owns it. */
|
||||
/** Another property written when the note reaches a step. */
|
||||
export interface FlowEffect {
|
||||
property: string;
|
||||
/** 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`. flow: the steps of `flowId`. */
|
||||
source: SourceMode;
|
||||
values: string[];
|
||||
flowId: string;
|
||||
/** Scalars: true/false and numbers are typed. List properties: comma-separated items. */
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface FlowStep {
|
||||
value: string;
|
||||
/** Space-separated classes added to `cssclasses` while the note is on this step. */
|
||||
cssclass: string;
|
||||
effects: FlowEffect[];
|
||||
}
|
||||
|
||||
export interface Flow {
|
||||
/** Stable id: command ids derive from it, so hotkeys survive renames. */
|
||||
id: string;
|
||||
name: string;
|
||||
/** Optional trigger: one non-alphanumeric character typed at the start of a word. */
|
||||
symbol: string;
|
||||
property: string;
|
||||
kind: FlowKind;
|
||||
valueMode: ValueMode;
|
||||
/** 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 function newFlow(fields: Partial<Flow>): Flow {
|
||||
return {
|
||||
id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
|
||||
name: "",
|
||||
symbol: "",
|
||||
property: "",
|
||||
kind: "ordered",
|
||||
valueMode: "single",
|
||||
loop: false,
|
||||
steps: [],
|
||||
...fields,
|
||||
};
|
||||
}
|
||||
|
||||
export const DEFAULT_SETTINGS: FflowSettings = {
|
||||
rules: [{ ...NEW_RULE, symbol: "@", property: "type" }],
|
||||
flows: [],
|
||||
};
|
||||
export function defaultSettings(): FflowSettings {
|
||||
return { flows: [newFlow({ name: "Type", symbol: "@", property: "type", kind: "open" })] };
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
/** Returns an error message, or null when `symbol` is usable by flow `index`. Empty means "no trigger" and is valid. */
|
||||
export function symbolError(symbol: string, flows: Flow[], index: number): string | null {
|
||||
if (symbol === "") return 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 trigger.`;
|
||||
if (flows.some((f, i) => i !== index && f.symbol === symbol)) return `"${symbol}" is already used by another flow.`;
|
||||
return 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;
|
||||
/** 0.1–0.2 stored separate triggers and flows; the shapes below are only read during migration. */
|
||||
interface LegacyRule {
|
||||
symbol: string;
|
||||
property: string;
|
||||
valueMode: ValueMode;
|
||||
source: "open" | "finite" | "flow";
|
||||
values: string[];
|
||||
flowId?: string;
|
||||
}
|
||||
interface LegacyFlow {
|
||||
id: string;
|
||||
name: string;
|
||||
property: string;
|
||||
loop: boolean;
|
||||
steps: { value: string; cssclass: string }[];
|
||||
}
|
||||
|
||||
/** Steps usable at runtime: blank values are skipped. */
|
||||
export function flowSteps(flow: Flow): FlowStep[] {
|
||||
return flow.steps.filter((s) => s.value.trim() !== "");
|
||||
/** Builds settings from saved data, converting the 0.1–0.2 trigger/flow split into flows. */
|
||||
export function loadSettings(saved: unknown): FflowSettings {
|
||||
if (!saved || typeof saved !== "object") return defaultSettings();
|
||||
if ("flows" in saved && !("rules" in saved) && Array.isArray(saved.flows)) {
|
||||
// Current format: fill fields added since the flow was saved.
|
||||
return { flows: saved.flows.map((f: Partial<Flow>) => newFlow(f)) };
|
||||
}
|
||||
|
||||
// Own persisted blob from an older version of this plugin; fields were always written together.
|
||||
const legacy = saved as { rules?: LegacyRule[]; flows?: LegacyFlow[] };
|
||||
const rules = legacy.rules ?? [];
|
||||
const flows: Flow[] = (legacy.flows ?? []).map((f) =>
|
||||
newFlow({
|
||||
id: f.id,
|
||||
name: f.name,
|
||||
property: f.property,
|
||||
loop: f.loop,
|
||||
symbol: rules.find((r) => r.source === "flow" && r.flowId === f.id)?.symbol ?? "",
|
||||
steps: f.steps.map((s) => ({
|
||||
value: s.value,
|
||||
effects: s.cssclass.trim() ? [{ property: "cssclasses", value: s.cssclass.trim().split(/\s+/).join(", ") }] : [],
|
||||
})),
|
||||
}),
|
||||
);
|
||||
for (const r of rules) {
|
||||
if (r.source === "open") flows.push(newFlow({ name: r.property, symbol: r.symbol, property: r.property, kind: "open", valueMode: r.valueMode }));
|
||||
if (r.source === "finite") {
|
||||
flows.push(newFlow({ name: r.property, symbol: r.symbol, property: r.property, steps: r.values.map((value) => ({ value, effects: [] })) }));
|
||||
}
|
||||
}
|
||||
return { flows };
|
||||
}
|
||||
+23
-40
@@ -1,13 +1,7 @@
|
||||
import { App, Editor, EditorPosition, EditorSuggest, EditorSuggestContext, EditorSuggestTriggerInfo, Notice, TFile } from "obsidian";
|
||||
import { setFlowStep, updateFrontmatter } from "./frontmatter";
|
||||
import { setFlowStep, setOpenValue, updateFrontmatter } from "./frontmatter";
|
||||
import type FflowPlugin from "./main";
|
||||
import { Flow, flowSteps, resolveRule, TriggerRule } from "./settings";
|
||||
|
||||
interface ActiveTrigger {
|
||||
rule: TriggerRule;
|
||||
property: string;
|
||||
flow: Flow | null;
|
||||
}
|
||||
import { Flow, symbolError } from "./settings";
|
||||
|
||||
interface Suggestion {
|
||||
value: string;
|
||||
@@ -49,7 +43,7 @@ function flatten(raw: unknown): string[] {
|
||||
const isSpace = (ch: string | undefined) => ch !== undefined && /\s/.test(ch);
|
||||
|
||||
export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
private active: ActiveTrigger | null = null;
|
||||
private flow: Flow | null = null;
|
||||
|
||||
constructor(app: App, private plugin: FflowPlugin, private index: ValueIndex) {
|
||||
super(app);
|
||||
@@ -63,33 +57,32 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
const word = before.slice(start);
|
||||
if (!word) 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;
|
||||
const flows = this.plugin.settings.flows;
|
||||
const index = flows.findIndex((f) => f.symbol !== "" && f.symbol === word[0]);
|
||||
const flow = flows[index];
|
||||
if (!flow || !flow.property || symbolError(flow.symbol, flows, index)) return null;
|
||||
if (inFrontmatter(editor, cursor.line) || inCode(editor, cursor.line, before.slice(0, start))) return null;
|
||||
|
||||
this.active = { rule: settings.rules[index], ...target };
|
||||
this.flow = flow;
|
||||
return { start: { line: cursor.line, ch: start }, end: cursor, query: word.slice(1) };
|
||||
}
|
||||
|
||||
getSuggestions(context: EditorSuggestContext): Suggestion[] {
|
||||
const active = this.active;
|
||||
if (!active) return [];
|
||||
const { rule, flow } = active;
|
||||
const flow = this.flow;
|
||||
if (!flow) return [];
|
||||
const query = context.query.toLowerCase();
|
||||
|
||||
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(active.property)]
|
||||
const pool: Suggestion[] =
|
||||
flow.kind === "ordered"
|
||||
? flow.steps.filter((s) => s.value).map((s) => ({ value: s.value, isNew: false }))
|
||||
: [...this.index.get(flow.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)) {
|
||||
if (flow.kind === "open" && query && !pool.some((s) => s.value.toLowerCase() === query)) {
|
||||
matches.push({ value: context.query, isNew: true });
|
||||
}
|
||||
return matches;
|
||||
@@ -108,12 +101,12 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
|
||||
selectSuggestion(s: Suggestion, _evt: MouseEvent | KeyboardEvent): void {
|
||||
const context = this.context;
|
||||
const active = this.active;
|
||||
if (!context || !active) return;
|
||||
void this.apply(context, active, s.value);
|
||||
const flow = this.flow;
|
||||
if (!context || !flow) return;
|
||||
void this.apply(context, flow, s.value);
|
||||
}
|
||||
|
||||
private async apply(context: EditorSuggestContext, { rule, property, flow }: ActiveTrigger, value: string): Promise<void> {
|
||||
private async apply(context: EditorSuggestContext, flow: Flow, value: string): Promise<void> {
|
||||
const { editor, file, start } = context;
|
||||
const line = editor.getLine(start.line);
|
||||
|
||||
@@ -126,22 +119,12 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
|
||||
try {
|
||||
await updateFrontmatter(this.app, file, (fm) => {
|
||||
if (flow) {
|
||||
setFlowStep(fm, flow, value);
|
||||
return;
|
||||
}
|
||||
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[property] = list;
|
||||
if (flow.kind === "ordered") setFlowStep(this.app, fm, flow, value);
|
||||
else setOpenValue(fm, flow.property, value, flow.valueMode === "list");
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("FFLOW: could not update frontmatter", err);
|
||||
new Notice(`FFLOW: could not set "${property}". See console.`);
|
||||
new Notice(`FFLOW: could not set "${flow.property}". See console.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user