132 lines
5.3 KiB
TypeScript
132 lines
5.3 KiB
TypeScript
// *************************************************************************
|
|
// * (C)opyright 2026 by Ruben Carlo Benante *
|
|
// * *
|
|
// * This program is free software; you can redistribute it and/or modify *
|
|
// * it under the terms of the GNU General Public License as published by *
|
|
// * the Free Software Foundation, either version 3 of the License, or *
|
|
// * (at your option) any later version. *
|
|
// * *
|
|
// * This program is distributed in the hope that it will be useful, *
|
|
// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
|
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
|
// * GNU General Public License for more details. *
|
|
// * *
|
|
// * You should have received a copy of the GNU General Public License *
|
|
// * along with this program. If not, see http://www.gnu.org/licenses/. *
|
|
// * *
|
|
// * Contact author at: *
|
|
// * Ruben Carlo Benante *
|
|
// * rcb@beco.cc *
|
|
// *************************************************************************
|
|
|
|
import { Plugin, TFile, TAbstractFile, Menu, moment } from 'obsidian';
|
|
import { extractTimeId, generateSlug, buildFilename } from './slug';
|
|
|
|
const SETTLE_MS = 5000; // rename ~5s after the H1 stops changing
|
|
const COOLDOWN_MS = 10000; // do not rename the same path again within 10s
|
|
|
|
export default class ZettelcleanPlugin extends Plugin {
|
|
private renameTimers = new Map<string, number>();
|
|
private lastRenamedAt = new Map<string, number>();
|
|
private isRenameInProgress = false;
|
|
|
|
async onload() {
|
|
// 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),
|
|
),
|
|
);
|
|
}
|
|
|
|
onunload() {
|
|
for (const t of this.renameTimers.values()) window.clearTimeout(t);
|
|
this.renameTimers.clear();
|
|
}
|
|
|
|
private pathFor(file: TFile, base: string): string {
|
|
const dir =
|
|
file.parent && file.parent.path !== '/' ? `${file.parent.path}/` : '';
|
|
return `${dir}${base}.md`;
|
|
}
|
|
|
|
// 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
|
|
|
|
const last = this.lastRenamedAt.get(file.path);
|
|
if (last && Date.now() - last < COOLDOWN_MS) return; // 10s cooldown
|
|
|
|
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),
|
|
);
|
|
}
|
|
|
|
// 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
|
|
|
|
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
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
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('Prefix timestamp to filename')
|
|
.setIcon('clock')
|
|
.onClick(() => void this.addTimeId(file)),
|
|
);
|
|
}
|
|
|
|
// 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);
|
|
}
|
|
}
|