README starting the real plugin v0.2
This commit is contained in:
192
src/main.ts
192
src/main.ts
@@ -1,114 +1,110 @@
|
||||
import {
|
||||
Editor,
|
||||
MarkdownView,
|
||||
MarkdownFileInfo,
|
||||
Modal,
|
||||
Notice,
|
||||
Plugin,
|
||||
} from 'obsidian';
|
||||
import {
|
||||
DEFAULT_SETTINGS,
|
||||
MyPluginSettings,
|
||||
SampleSettingTab,
|
||||
} from './settings';
|
||||
import { Plugin, TFile, TAbstractFile, Menu, moment } from 'obsidian';
|
||||
import { extractTimeId, generateSlug, buildFilename } from './slug';
|
||||
|
||||
// Remember to rename these classes and interfaces!
|
||||
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 MyPlugin extends Plugin {
|
||||
settings!: MyPluginSettings;
|
||||
export default class ZettelcleanPlugin extends Plugin {
|
||||
private renameTimers = new Map<string, number>();
|
||||
private lastRenamedAt = new Map<string, number>();
|
||||
private isRenameInProgress = false;
|
||||
|
||||
async onload() {
|
||||
await this.loadSettings();
|
||||
|
||||
// This creates an icon in the left ribbon.
|
||||
this.addRibbonIcon('dice', 'Sample', (_evt: MouseEvent) => {
|
||||
// Called when the user clicks the icon.
|
||||
new Notice('This is a notice!');
|
||||
});
|
||||
|
||||
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
|
||||
const statusBarItemEl = this.addStatusBarItem();
|
||||
statusBarItemEl.setText('Status bar text');
|
||||
|
||||
// This adds a simple command that can be triggered anywhere
|
||||
this.addCommand({
|
||||
id: 'open-modal-simple',
|
||||
name: 'Open modal (simple)',
|
||||
callback: () => {
|
||||
new SampleModal(this.app).open();
|
||||
},
|
||||
});
|
||||
// This adds an editor command that can perform some operation on the current editor instance
|
||||
this.addCommand({
|
||||
id: 'replace-selected',
|
||||
name: 'Replace selected content',
|
||||
editorCallback: (
|
||||
editor: Editor,
|
||||
_ctx: MarkdownView | MarkdownFileInfo,
|
||||
) => {
|
||||
editor.replaceSelection('Sample editor command');
|
||||
},
|
||||
});
|
||||
// This adds a complex command that can check whether the current state of the app allows execution of the command
|
||||
this.addCommand({
|
||||
id: 'open-modal-complex',
|
||||
name: 'Open modal (complex)',
|
||||
checkCallback: (checking: boolean) => {
|
||||
// Conditions to check
|
||||
const markdownView =
|
||||
this.app.workspace.getActiveViewOfType(MarkdownView);
|
||||
if (markdownView) {
|
||||
// If checking is true, we're simply "checking" if the command can be run.
|
||||
// If checking is false, then we want to actually perform the operation.
|
||||
if (!checking) {
|
||||
new SampleModal(this.app).open();
|
||||
}
|
||||
|
||||
// This command will only show up in Command Palette when the check function returns true
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
|
||||
// This adds a settings tab so the user can configure various aspects of the plugin
|
||||
this.addSettingTab(new SampleSettingTab(this.app, this));
|
||||
|
||||
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
|
||||
// Using this function will automatically remove the event listener when this plugin is disabled.
|
||||
this.registerDomEvent(activeDocument, 'click', (_evt: MouseEvent) => {
|
||||
new Notice('Click');
|
||||
});
|
||||
|
||||
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
|
||||
this.registerInterval(
|
||||
window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000),
|
||||
// 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() {}
|
||||
onunload() {
|
||||
for (const t of this.renameTimers.values()) window.clearTimeout(t);
|
||||
this.renameTimers.clear();
|
||||
}
|
||||
|
||||
async loadSettings() {
|
||||
this.settings = Object.assign(
|
||||
{},
|
||||
DEFAULT_SETTINGS,
|
||||
(await this.loadData()) as Partial<MyPluginSettings>,
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
async saveSettings() {
|
||||
await this.saveData(this.settings);
|
||||
}
|
||||
}
|
||||
// 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
|
||||
|
||||
class SampleModal extends Modal {
|
||||
onOpen() {
|
||||
const { contentEl } = this;
|
||||
contentEl.setText('Woah!');
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
onClose() {
|
||||
const { contentEl } = this;
|
||||
contentEl.empty();
|
||||
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)),
|
||||
);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user