Add checkbox sync support for Reading View via vault.on('modify'), keep editor-change for real-time updates, #3

This commit is contained in:
Grol Grol 2025-03-10 11:07:25 +03:00
parent ec9cccd313
commit 2c8d353f15

View file

@ -1,7 +1,9 @@
import { Plugin, Editor } from "obsidian";
import { Plugin, TFile } from "obsidian";
import { syncCheckboxes } from "./checkboxUtils";
export default class CheckboxSyncPlugin extends Plugin {
private isProcessing = false;
async onload() {
this.registerEvent(
this.app.workspace.on("editor-change", (editor) => {
@ -14,5 +16,31 @@ export default class CheckboxSyncPlugin extends Plugin {
}
})
);
this.registerEvent(
this.app.vault.on("modify", async (file) => {
if (this.isProcessing || !(file instanceof TFile) || file.extension !== "md") return;
this.isProcessing = true;
try {
await this.syncFileCheckboxes(file);
} finally {
this.isProcessing = false;
}
})
);
}
}
async syncFileCheckboxes(file: TFile) {
const text = await this.app.vault.read(file);
const updates = syncCheckboxes(text);
if (updates.length === 0) return;
const lines = text.split("\n");
updates.forEach(({ line, ch, value }) => {
lines[line] = lines[line].substring(0, ch) + value + lines[line].substring(ch + 1);
});
const updatedText = lines.join("\n");
await this.app.vault.modify(file, updatedText);
}
}