Files
zettelclean/src/main.ts

111 lines
3.8 KiB
TypeScript
Raw Normal View History

2026-07-28 16:52:19 -03:00
import { Plugin, TFile, TAbstractFile, Menu, moment } from 'obsidian';
import { extractTimeId, generateSlug, buildFilename } from './slug';
2026-07-28 16:52:19 -03:00
const SETTLE_MS = 5000; // rename ~5s after the H1 stops changing
const COOLDOWN_MS = 10000; // do not rename the same path again within 10s
2026-07-28 16:52:19 -03:00
export default class ZettelcleanPlugin extends Plugin {
private renameTimers = new Map<string, number>();
private lastRenamedAt = new Map<string, number>();
private isRenameInProgress = false;
async onload() {
2026-07-28 16:52:19 -03:00
// Fires after the metadata cache reparses a note, so headings[] is fresh.
this.registerEvent(
this.app.metadataCache.on('changed', (file) =>
this.scheduleSync(file),
),
);
// Retrofit entry in the file-explorer right-click menu, near "Rename".
this.registerEvent(
this.app.workspace.on('file-menu', (menu, file) =>
this.addTimeIdMenu(menu, file),
),
);
}
2026-07-28 16:52:19 -03:00
onunload() {
for (const t of this.renameTimers.values()) window.clearTimeout(t);
this.renameTimers.clear();
}
2026-07-28 16:52:19 -03:00
private pathFor(file: TFile, base: string): string {
const dir =
file.parent && file.parent.path !== '/' ? `${file.parent.path}/` : '';
return `${dir}${base}.md`;
}
2026-07-28 16:52:19 -03:00
// Guard layer: only the actively edited zettel, honoring the 10s cooldown,
// (re)arming the 5s settle timer on every cache change.
private scheduleSync(file: TAbstractFile) {
if (this.isRenameInProgress) return; // our own rename, ignore
if (!(file instanceof TFile) || file.extension !== 'md') return;
if (extractTimeId(file.basename) === null) return; // opt-in gate: no TIMEID
if (this.app.workspace.getActiveFile() !== file) return; // only the edited note
2026-07-28 16:52:19 -03:00
const last = this.lastRenamedAt.get(file.path);
if (last && Date.now() - last < COOLDOWN_MS) return; // 10s cooldown
2026-07-28 16:52:19 -03:00
const existing = this.renameTimers.get(file.path);
if (existing) window.clearTimeout(existing);
this.renameTimers.set(
file.path,
window.setTimeout(() => {
this.renameTimers.delete(file.path);
void this.syncNow(file);
}, SETTLE_MS),
);
}
2026-07-28 16:52:19 -03:00
// Compute the target basename, bail if unchanged, otherwise rename.
private async syncNow(file: TFile) {
const id = extractTimeId(file.basename);
if (id === null) return; // prefix removed meanwhile
2026-07-28 16:52:19 -03:00
const first = this.app.metadataCache.getFileCache(file)?.headings?.[0];
const h1 = first && first.level === 1 ? first.heading : '';
const newBase = buildFilename(id, generateSlug(h1));
if (newBase === file.basename) return; // nothing to do
2026-07-28 16:52:19 -03:00
const newPath = this.pathFor(file, newBase);
this.isRenameInProgress = true;
try {
await this.app.fileManager.renameFile(file, newPath);
this.lastRenamedAt.set(newPath, Date.now());
} catch (e) {
console.error('zettelclean: rename failed', e);
} finally {
this.isRenameInProgress = false;
}
}
2026-07-28 16:52:19 -03:00
private addTimeIdMenu(menu: Menu, file: TAbstractFile) {
if (!(file instanceof TFile) || file.extension !== 'md') return;
if (extractTimeId(file.basename) !== null) return; // already a zettel
menu.addItem((item) =>
item
.setTitle('Add zettel TIMEID to filename')
.setIcon('clock')
.onClick(() => void this.addTimeId(file)),
);
}
2026-07-28 16:52:19 -03:00
// Retrofit: mint a fresh timestamp for a note that has no TIMEID yet.
private async addTimeId(file: TFile) {
let id = moment().format('YYYYMMDDHHmmss'); // core Unique-note format
const first = this.app.metadataCache.getFileCache(file)?.headings?.[0];
const h1 =
first && first.level === 1 ? first.heading : file.basename;
const slug = generateSlug(h1);
let target = this.pathFor(file, buildFilename(id, slug));
// Rare same-second + same-title collision: extend the id (up to 18 digits).
while (this.app.vault.getAbstractFileByPath(target) && id.length < 18) {
id += String(Math.floor(Date.now() % 10));
target = this.pathFor(file, buildFilename(id, slug));
}
await this.app.fileManager.renameFile(file, target);
}
}