FFLOW 0.5.0: conditional flows share symbols; per-flow and per-symbol step commands; popup header shows set/replace/add
This commit is contained in:
1 parent
f5992e4539
commit
60582bcb03
11 files changed
+291
-40
No files matched your search
+37
-15
@@ -1,11 +1,15 @@
|
||||
import { Notice, TFile } from "obsidian";
|
||||
import { setFlowStep, updateFrontmatter } from "./frontmatter";
|
||||
import type FflowPlugin from "./main";
|
||||
import type { Flow } from "./settings";
|
||||
import { Flow, pickFlow } from "./settings";
|
||||
|
||||
type Direction = 1 | -1;
|
||||
|
||||
/** Re-registers the next/previous commands of every ordered flow. Ids derive from the flow id, so hotkeys survive renames. */
|
||||
/**
|
||||
* Re-registers the next/previous commands of ordered flows. Every flow gets its own pair, available only on notes its
|
||||
* condition matches; ids derive from the flow id, so hotkeys and toolbar buttons survive renames. Flows sharing a symbol
|
||||
* also get a shared pair that runs whichever of them matches the note, so one hotkey moves a project's or a client's status.
|
||||
*/
|
||||
export class FlowCommands {
|
||||
private registered: string[] = [];
|
||||
|
||||
@@ -14,35 +18,53 @@ export class FlowCommands {
|
||||
sync(): void {
|
||||
for (const id of this.registered) this.plugin.removeCommand(id);
|
||||
this.registered = [];
|
||||
|
||||
const bySymbol = new Map<string, Flow[]>();
|
||||
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");
|
||||
const name = flow.name || flow.property || "Unnamed flow";
|
||||
this.add([flow], `flow-${flow.id}-next`, `${name}: next step`, 1);
|
||||
this.add([flow], `flow-${flow.id}-previous`, `${name}: previous step`, -1);
|
||||
if (flow.symbol) bySymbol.set(flow.symbol, [...(bySymbol.get(flow.symbol) ?? []), flow]);
|
||||
}
|
||||
for (const [symbol, flows] of bySymbol) {
|
||||
if (flows.length < 2) continue;
|
||||
const id = `symbol-${symbol.codePointAt(0)?.toString(16)}`;
|
||||
const label = `${symbol} ${flows.map((f) => f.name || f.property || "Unnamed flow").join(" / ")}`;
|
||||
this.add(flows, `${id}-next`, `${label}: next step`, 1);
|
||||
this.add(flows, `${id}-previous`, `${label}: previous step`, -1);
|
||||
}
|
||||
}
|
||||
|
||||
private add(flow: Flow, direction: Direction, suffix: string, label: string): void {
|
||||
const id = `flow-${flow.id}-${suffix}`;
|
||||
private add(flows: Flow[], id: string, name: string, direction: Direction): void {
|
||||
this.registered.push(id);
|
||||
this.plugin.addCommand({
|
||||
id,
|
||||
name: `${flow.name || flow.property || "Unnamed flow"}: ${label}`,
|
||||
name,
|
||||
checkCallback: (checking) => {
|
||||
const file = this.plugin.app.workspace.getActiveFile();
|
||||
if (!file || file.extension !== "md" || !flow.property || !flow.steps.some((s) => s.value)) return false;
|
||||
if (!checking) void moveStep(this.plugin, file, flow, direction);
|
||||
const app = this.plugin.app;
|
||||
const file = app.workspace.getActiveFile();
|
||||
if (!file || file.extension !== "md") return false;
|
||||
const flow = pickFlow(flows, app.metadataCache.getFileCache(file)?.frontmatter ?? null);
|
||||
if (!flow?.property || !flow.steps.some((s) => s.value)) return false;
|
||||
if (!checking) void moveStep(this.plugin, file, flows, direction);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction: Direction): Promise<void> {
|
||||
const steps = flow.steps.filter((s) => s.value);
|
||||
async function moveStep(plugin: FflowPlugin, file: TFile, flows: Flow[], direction: Direction): Promise<void> {
|
||||
let message = "";
|
||||
let property = "";
|
||||
try {
|
||||
// Read the current value inside the update: the metadata cache can lag behind the editor.
|
||||
// Read the current values inside the update: the metadata cache can lag behind the editor.
|
||||
await updateFrontmatter(plugin.app, file, (fm) => {
|
||||
const flow = pickFlow(flows, fm);
|
||||
if (!flow?.property) return;
|
||||
property = flow.property;
|
||||
const steps = flow.steps.filter((s) => s.value);
|
||||
if (steps.length === 0) return;
|
||||
const index = steps.findIndex((s) => s.value === String(fm[flow.property]));
|
||||
// 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;
|
||||
@@ -56,9 +78,9 @@ async function moveStep(plugin: FflowPlugin, file: TFile, flow: Flow, direction:
|
||||
setFlowStep(plugin.app, fm, flow, steps[target].value);
|
||||
message = `${flow.property}: ${steps[target].value}`;
|
||||
});
|
||||
new Notice(message);
|
||||
if (message) new Notice(message);
|
||||
} catch (err) {
|
||||
console.error("FFLOW: could not move flow step", err);
|
||||
new Notice(`FFLOW: could not set "${flow.property}". See console.`);
|
||||
new Notice(`FFLOW: could not set "${property}". See console.`);
|
||||
}
|
||||
}
|
||||
+58
-7
@@ -11,11 +11,13 @@ import {
|
||||
ToggleComponent,
|
||||
} from "obsidian";
|
||||
import type FflowPlugin from "./main";
|
||||
import { BLOCKED_SYMBOLS, Flow, FlowKind, FlowStep, newFlow, symbolError, ValueMode } from "./settings";
|
||||
import { BLOCKED_SYMBOLS, Flow, FlowKind, FlowStep, newFlow, shadowingFlow, symbolError, ValueMode } from "./settings";
|
||||
|
||||
export class FflowSettingTab extends PluginSettingTab {
|
||||
/** Flows shown open. Kept across redraws, not saved: every visit starts with compact cards. */
|
||||
private expanded = new Set<string>();
|
||||
/** Re-check every card's symbol message: a symbol or condition change in one flow can shadow another. */
|
||||
private refreshers: (() => void)[] = [];
|
||||
|
||||
constructor(app: App, private plugin: FflowPlugin) {
|
||||
super(app, plugin);
|
||||
@@ -33,6 +35,7 @@ export class FflowSettingTab extends PluginSettingTab {
|
||||
const { containerEl } = this;
|
||||
const flows = this.plugin.settings.flows;
|
||||
containerEl.empty();
|
||||
this.refreshers = [];
|
||||
|
||||
new Setting(containerEl)
|
||||
.setHeading()
|
||||
@@ -72,8 +75,15 @@ export class FflowSettingTab extends PluginSettingTab {
|
||||
badge.toggle(flow.symbol !== "");
|
||||
title.setText(flow.name || flow.property || "New flow");
|
||||
const values = flow.steps.map((s) => s.value).filter(Boolean);
|
||||
const { property, values: when } = flow.condition;
|
||||
summary.setText(
|
||||
[flow.property, flow.kind === "open" ? "open list" : values.join(" → ") || "no steps"].filter(Boolean).join(" · "),
|
||||
[
|
||||
flow.property,
|
||||
property && `when ${property}${when.trim() ? ` = ${when.trim()}` : ""}`,
|
||||
flow.kind === "open" ? "open list" : values.join(" → ") || "no steps",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · "),
|
||||
);
|
||||
};
|
||||
updateHeader();
|
||||
@@ -116,15 +126,56 @@ export class FflowSettingTab extends PluginSettingTab {
|
||||
const symbol = new TextComponent(symbolField).setPlaceholder("—").setValue(flow.symbol);
|
||||
symbol.inputEl.addClass("fflow-symbol");
|
||||
setTooltip(symbol.inputEl, `Optional. One character, not a letter or digit. Reserved: ${BLOCKED_SYMBOLS.join(" ")}`);
|
||||
const error = body.createDiv({ cls: "fflow-error", text: symbolError(flow.symbol, flows, index) ?? "" });
|
||||
symbol.onChange(async (value) => {
|
||||
const problem = symbolError(value, flows, index);
|
||||
error.setText(problem ?? "");
|
||||
|
||||
// Condition: lets several flows share a symbol, each on its own notes.
|
||||
const when = body.createDiv({ cls: "fflow-fields fflow-when" });
|
||||
when.createDiv({ cls: "fflow-label", text: "Only on notes where" });
|
||||
const onCondition = async () => {
|
||||
updateHeader();
|
||||
this.refreshers.forEach((refresh) => refresh());
|
||||
await this.save();
|
||||
};
|
||||
new TextComponent(when)
|
||||
.setPlaceholder("type")
|
||||
.setValue(flow.condition.property)
|
||||
.onChange(async (value) => {
|
||||
flow.condition.property = value.trim();
|
||||
await onCondition();
|
||||
});
|
||||
when.createSpan({ cls: "fflow-equals", text: "=" });
|
||||
const whenValues = new TextComponent(when)
|
||||
.setPlaceholder("project, area (empty: any value)")
|
||||
.setValue(flow.condition.values)
|
||||
.onChange(async (value) => {
|
||||
flow.condition.values = value;
|
||||
await onCondition();
|
||||
});
|
||||
whenValues.inputEl.addClass("fflow-when-values");
|
||||
setTooltip(
|
||||
when,
|
||||
"Leave the property empty to use this flow on every note. Flows sharing a symbol: a matching condition wins over a flow without one.",
|
||||
);
|
||||
|
||||
const error = body.createDiv({ cls: "fflow-error" });
|
||||
const refresh = () => {
|
||||
const problem = symbolError(symbol.getValue());
|
||||
const other = problem ? null : shadowingFlow(flows, index);
|
||||
error.setText(
|
||||
problem ?? (other ? `Never runs: “${other.name || other.property}” takes ${flow.symbol} on the same notes first.` : ""),
|
||||
);
|
||||
symbol.inputEl.toggleClass("is-invalid", problem !== null);
|
||||
};
|
||||
this.refreshers.push(refresh);
|
||||
refresh();
|
||||
symbol.onChange(async (value) => {
|
||||
// Invalid input stays in the field but is never saved.
|
||||
if (problem) return;
|
||||
if (symbolError(value)) {
|
||||
refresh();
|
||||
return;
|
||||
}
|
||||
flow.symbol = value;
|
||||
updateHeader();
|
||||
this.refreshers.forEach((r) => r());
|
||||
await this.save();
|
||||
});
|
||||
|
||||
|
||||
+56
-5
@@ -15,6 +15,15 @@ export interface FlowStep {
|
||||
effects: FlowEffect[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Limits a flow to notes whose `property` holds one of `values` (comma-separated, case-insensitive; list properties match
|
||||
* if any item matches). No property: every note. No values: any note where the property has a value.
|
||||
*/
|
||||
export interface FlowCondition {
|
||||
property: string;
|
||||
values: string;
|
||||
}
|
||||
|
||||
export interface Flow {
|
||||
/** Stable id: command ids derive from it, so hotkeys survive renames. */
|
||||
id: string;
|
||||
@@ -27,6 +36,8 @@ export interface Flow {
|
||||
/** After the last step, "next" goes back to the first (and "previous" the other way). */
|
||||
loop: boolean;
|
||||
steps: FlowStep[];
|
||||
/** Several flows can share a symbol: the note's frontmatter decides which one runs. */
|
||||
condition: FlowCondition;
|
||||
}
|
||||
|
||||
export interface FflowSettings {
|
||||
@@ -43,24 +54,64 @@ export function newFlow(fields: Partial<Flow>): Flow {
|
||||
valueMode: "single",
|
||||
loop: false,
|
||||
steps: [],
|
||||
condition: { property: "", values: "" },
|
||||
...fields,
|
||||
};
|
||||
}
|
||||
|
||||
export function defaultSettings(): FflowSettings {
|
||||
return { flows: [newFlow({ name: "Type", symbol: "@", property: "type", kind: "open" })] };
|
||||
return { flows: [newFlow({ name: "Type", symbol: "&", property: "type", kind: "open" })] };
|
||||
}
|
||||
|
||||
const conditionValues = (c: FlowCondition) =>
|
||||
c.values
|
||||
.split(",")
|
||||
.map((v) => v.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
|
||||
const isConditional = (flow: Flow) => flow.condition.property !== "";
|
||||
|
||||
function matches(flow: Flow, fm: Record<string, unknown> | null): boolean {
|
||||
if (!isConditional(flow)) return true;
|
||||
const raw = fm?.[flow.condition.property];
|
||||
const actual = (Array.isArray(raw) ? raw : [raw])
|
||||
.filter((v) => v !== null && v !== undefined && String(v).trim() !== "")
|
||||
.map((v) => String(v).trim().toLowerCase());
|
||||
const wanted = conditionValues(flow.condition);
|
||||
return wanted.length === 0 ? actual.length > 0 : actual.some((v) => wanted.includes(v));
|
||||
}
|
||||
|
||||
/** The flow that runs on a note: the first matching flow with a condition, else the first one without. */
|
||||
export function pickFlow(candidates: Flow[], fm: Record<string, unknown> | null): Flow | null {
|
||||
return candidates.find((f) => isConditional(f) && matches(f, fm)) ?? candidates.find((f) => !isConditional(f)) ?? null;
|
||||
}
|
||||
|
||||
/** An earlier flow with the same symbol that always wins over flow `index`, so `index` never runs; null if none. */
|
||||
export function shadowingFlow(flows: Flow[], index: number): Flow | null {
|
||||
const flow = flows[index];
|
||||
if (!flow.symbol) return null;
|
||||
const wanted = conditionValues(flow.condition);
|
||||
return (
|
||||
flows.slice(0, index).find((other) => {
|
||||
if (other.symbol !== flow.symbol) return false;
|
||||
if (!isConditional(flow)) return !isConditional(other);
|
||||
if (other.condition.property !== flow.condition.property) return false;
|
||||
const otherValues = conditionValues(other.condition);
|
||||
// Empty values match any value, so they cover every value list.
|
||||
return otherValues.length === 0 || (wanted.length > 0 && wanted.every((v) => otherValues.includes(v)));
|
||||
}) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/** Reserved by Obsidian or common plugins: tags, links, slash commands, emoji shortcodes. */
|
||||
export const BLOCKED_SYMBOLS = ["#", "[", "/", ":"];
|
||||
|
||||
/** 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 {
|
||||
/** Returns an error message, or null when `symbol` is a usable trigger. Empty means "no trigger" and is valid. */
|
||||
export function symbolError(symbol: string): 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 (flows.some((f, i) => i !== index && f.symbol === symbol)) return `"${symbol}" is already used by another flow.`;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -86,7 +137,7 @@ 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)) };
|
||||
return { flows: saved.flows.map((f: Partial<Flow>) => newFlow({ ...f, condition: { property: "", values: "", ...f.condition } })) };
|
||||
}
|
||||
|
||||
// Own persisted blob from an older version of this plugin; fields were always written together.
|
||||
|
||||
+58
-6
@@ -1,7 +1,19 @@
|
||||
import { App, Editor, EditorPosition, EditorSuggest, EditorSuggestContext, EditorSuggestTriggerInfo, Notice, TFile } from "obsidian";
|
||||
import {
|
||||
App,
|
||||
Editor,
|
||||
EditorPosition,
|
||||
EditorSuggest,
|
||||
EditorSuggestContext,
|
||||
EditorSuggestTriggerInfo,
|
||||
getFrontMatterInfo,
|
||||
Notice,
|
||||
parseYaml,
|
||||
setIcon,
|
||||
TFile,
|
||||
} from "obsidian";
|
||||
import { setFlowStep, setOpenValue, updateFrontmatter } from "./frontmatter";
|
||||
import type FflowPlugin from "./main";
|
||||
import { Flow, symbolError } from "./settings";
|
||||
import { Flow, pickFlow, symbolError } from "./settings";
|
||||
|
||||
interface Suggestion {
|
||||
value: string;
|
||||
@@ -44,9 +56,17 @@ const isSpace = (ch: string | undefined) => ch !== undefined && /\s/.test(ch);
|
||||
|
||||
export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
private flow: Flow | null = null;
|
||||
/** "Replace status (active)" / "Add to participants", above the suggestions. */
|
||||
private header: HTMLElement | null = null;
|
||||
|
||||
constructor(app: App, private plugin: FflowPlugin, private index: ValueIndex) {
|
||||
super(app);
|
||||
// `suggestEl` (the popup container) is internal API: probe it, and go without a header if it changes.
|
||||
const container: unknown = Reflect.get(this, "suggestEl");
|
||||
if (container instanceof HTMLElement) {
|
||||
this.header = container.createDiv({ cls: "fflow-header" });
|
||||
container.prepend(this.header);
|
||||
}
|
||||
}
|
||||
|
||||
onTrigger(cursor: EditorPosition, editor: Editor, _file: TFile | null): EditorSuggestTriggerInfo | null {
|
||||
@@ -57,16 +77,35 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
const word = before.slice(start);
|
||||
if (!word) 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;
|
||||
const symbol = word[0];
|
||||
if (symbolError(symbol)) return null;
|
||||
const candidates = this.plugin.settings.flows.filter((f) => f.symbol === symbol && f.property);
|
||||
if (candidates.length === 0) return null;
|
||||
if (inFrontmatter(editor, cursor.line) || inCode(editor, cursor.line, before.slice(0, start))) return null;
|
||||
|
||||
const fm = readFrontmatter(editor);
|
||||
const flow = pickFlow(candidates, fm);
|
||||
if (!flow) return null;
|
||||
|
||||
this.flow = flow;
|
||||
this.renderHeader(flow, fm);
|
||||
return { start: { line: cursor.line, ch: start }, end: cursor, query: word.slice(1) };
|
||||
}
|
||||
|
||||
private renderHeader(flow: Flow, fm: Record<string, unknown> | null): void {
|
||||
const header = this.header;
|
||||
if (!header) return;
|
||||
header.empty();
|
||||
const raw = fm?.[flow.property];
|
||||
const current = (Array.isArray(raw) ? raw : [raw]).filter((v) => v !== null && v !== undefined && String(v) !== "");
|
||||
const adds = flow.kind === "open" && flow.valueMode === "list";
|
||||
const replaces = !adds && current.length > 0;
|
||||
setIcon(header.createSpan({ cls: "fflow-header-icon" }), replaces ? "replace" : "plus");
|
||||
header.createSpan({ cls: "fflow-header-action", text: adds ? "Add to" : replaces ? "Replace" : "Set" });
|
||||
header.createSpan({ cls: "fflow-header-property", text: flow.property });
|
||||
if (replaces) header.createSpan({ cls: "fflow-header-current", text: current.map(String).join(", ") });
|
||||
}
|
||||
|
||||
getSuggestions(context: EditorSuggestContext): Suggestion[] {
|
||||
const flow = this.flow;
|
||||
if (!flow) return [];
|
||||
@@ -129,6 +168,19 @@ export class TriggerSuggest extends EditorSuggest<Suggestion> {
|
||||
}
|
||||
}
|
||||
|
||||
/** The note's frontmatter as typed in the editor: the metadata cache lags behind, e.g. right after `&` set the type. */
|
||||
function readFrontmatter(editor: Editor): Record<string, unknown> | null {
|
||||
const info = getFrontMatterInfo(editor.getValue());
|
||||
if (!info.exists) return null;
|
||||
try {
|
||||
const fm: unknown = parseYaml(info.frontmatter);
|
||||
return fm && typeof fm === "object" ? (fm as Record<string, unknown>) : null;
|
||||
} catch {
|
||||
// Half-typed YAML: behave as if the note had no properties.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when `line` lies inside a closed `---` frontmatter block at the top of the note. */
|
||||
function inFrontmatter(editor: Editor, line: number): boolean {
|
||||
if (editor.getLine(0) !== "---") return false;
|
||||
|
||||
Reference in new issue
Block a user