Files
fflow/src/flows.ts
T

65 lines
2.4 KiB
TypeScript

import { Notice, TFile } from "obsidian";
import { setFlowStep, updateFrontmatter } from "./frontmatter";
import type FflowPlugin from "./main";
import type { Flow } 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. */
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) {
if (flow.kind !== "ordered") continue;
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 || !flow.steps.some((s) => s.value)) 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 = flow.steps.filter((s) => s.value);
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(plugin.app, 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.`);
}
}