Files
waypoint/src/settings-tab.ts
T

616 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Setting, PluginSettingTab, App, setIcon, AbstractInputSuggest, TFile } from 'obsidian';
import type WaypointPlugin from 'src/main';
import { WaypointSettings, DEFAULT_SETTINGS, DEFAULT_DATE_SYSTEM, PeriodNoteSettings } from 'src/settings';
import { formatHasDateToken } from 'src/utils/date-systems';
import { IconSuggestModal } from 'src/views/waypoint-view';
/**
* Vault-wide Markdown-file suggester for template-path fields, matching
* Obsidian's native suggest popup (same base class Templater's own template
* pickers use) rather than the browser's unstyled `<datalist>` dropdown.
*/
class TemplateFileSuggest extends AbstractInputSuggest<TFile> {
constructor(app: App, private inputEl: HTMLInputElement) {
super(app, inputEl);
}
getSuggestions(query: string): TFile[] {
const q = query.toLowerCase();
return this.app.vault.getMarkdownFiles()
.filter(file => file.path.toLowerCase().includes(q))
.slice(0, 200);
}
renderSuggestion(file: TFile, el: HTMLElement): void {
el.setText(file.path.replace(/\.md$/, ''));
}
selectSuggestion(file: TFile): void {
this.setValue(file.path.replace(/\.md$/, ''));
this.inputEl.trigger('input');
this.close();
}
}
export class WaypointSettingTab extends PluginSettingTab {
private plugin: WaypointPlugin;
private settings: WaypointSettings;
private onSettingsChange: () => void;
private activeTab: 'calendar' | 'periodic' | 'systems' | 'recent' | 'display' | 'about' = 'calendar';
constructor(app: App, plugin: WaypointPlugin, settings: WaypointSettings, onSettingsChange: () => void) {
super(app, plugin);
this.plugin = plugin;
this.settings = settings;
this.onSettingsChange = onSettingsChange;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
// ── Tab bar ──
const tabBar = containerEl.createDiv({ cls: 'waypoint-settings-tabs' });
const tabs = [
{ key: 'calendar' as const, label: 'Calendar' },
{ key: 'periodic' as const, label: 'Periodic Notes' },
{ key: 'systems' as const, label: 'Date systems' },
{ key: 'recent' as const, label: 'Recent Files' },
{ key: 'display' as const, label: 'Display' },
{ key: 'about' as const, label: 'About' },
];
for (const tab of tabs) {
const btn = tabBar.createEl('button', {
cls: `waypoint-settings-tab${this.activeTab === tab.key ? ' is-active' : ''}`,
text: tab.label,
});
btn.addEventListener('click', () => {
this.activeTab = tab.key;
this.display();
});
}
const tabContent = containerEl.createDiv({ cls: 'waypoint-settings-content' });
switch (this.activeTab) {
case 'calendar':
this.renderCalendarTab(tabContent);
break;
case 'periodic':
this.renderPeriodicTab(tabContent);
break;
case 'systems':
this.renderSystemsTab(tabContent);
break;
case 'recent':
this.renderRecentTab(tabContent);
break;
case 'display':
this.renderDisplayTab(tabContent);
break;
case 'about':
this.renderAboutTab(tabContent);
break;
}
}
// ═══════════════════════════════
// Calendar tab
// ═══════════════════════════════
private renderCalendarTab(container: HTMLElement): void {
new Setting(container)
.setName('First day of week')
.setDesc('Which day the calendar week starts on.')
.addDropdown((dropdown) => {
dropdown
.addOption('0', 'Sunday')
.addOption('1', 'Monday')
.setValue(String(this.settings.calendar.firstDayOfWeek))
.onChange((value) => {
this.settings.calendar.firstDayOfWeek = parseInt(value, 10);
this.saveAndRefresh();
});
});
new Setting(container)
.setName('Show note indicators')
.setDesc('Show a dot on days that have existing notes.')
.addToggle((toggle) => {
toggle
.setValue(this.settings.calendar.showNoteIndicators)
.onChange((value) => {
this.settings.calendar.showNoteIndicators = value;
this.saveAndRefresh();
});
});
new Setting(container)
.setName('Indicator style')
.setDesc('Show one neutral dot for any dated note, or one coloured dot for each configured date system.')
.addDropdown((dropdown) => {
dropdown
.addOption('any', 'Single dot')
.addOption('systems', 'Colour by note system')
.setValue(this.settings.calendar.indicatorMode)
.onChange((value: 'any' | 'systems') => {
this.settings.calendar.indicatorMode = value;
this.saveAndRefresh();
});
});
new Setting(container)
.setName('Daily indicator colour')
.setDesc('Colour for daily-note dots when using “Colour by note system”.')
.addColorPicker((color) => {
color
.setValue(this.settings.calendar.dailyIndicatorColor)
.onChange((value) => {
this.settings.calendar.dailyIndicatorColor = value;
this.saveAndRefresh();
});
});
}
// ═══════════════════════════════
// Periodic Notes tab
// ═══════════════════════════════
private renderPeriodicTab(container: HTMLElement): void {
new Setting(container)
.setName('Use existing tabs')
.setDesc('If a periodic note is already open, switch to its tab instead of opening it again.')
.addToggle((toggle) => {
toggle
.setValue(this.settings.reusePeriodicNoteTabs)
.onChange((value) => {
this.settings.reusePeriodicNoteTabs = value;
this.saveAndRefresh();
});
});
this.addPeriodNoteSettings(container, 'Daily', this.settings.daily);
this.addPeriodNoteSettings(container, 'Weekly', this.settings.weekly);
this.addPeriodNoteSettings(container, 'Monthly', this.settings.monthly);
this.addPeriodNoteSettings(container, 'Quarterly', this.settings.quarterly);
this.addPeriodNoteSettings(container, 'Yearly', this.settings.yearly);
}
private addPeriodNoteSettings(container: HTMLElement, label: string, period: PeriodNoteSettings): void {
new Setting(container).setHeading().setName(label);
new Setting(container)
.setName('Folder')
.setDesc(`Folder path for ${label.toLowerCase()} notes.`)
.addText((text) => {
text.setPlaceholder('periodic/daily');
text.setValue(period.folder);
text.onChange((value) => {
period.folder = value;
this.saveAndRefresh();
});
});
new Setting(container)
.setName('Name format')
.setDesc(`Date format for ${label.toLowerCase()} note filenames (moment.js format).`)
.addText((text) => {
text.setPlaceholder('yyyy-MM-dd');
text.setValue(period.nameFormat);
text.onChange((value) => {
period.nameFormat = value;
this.saveAndRefresh();
});
});
new Setting(container)
.setName('Template file')
.setDesc('Path to the template file. The .md extension is optional.')
.addText((text) => {
text.setPlaceholder('Templates/Daily note');
text.setValue(period.templateFile);
new TemplateFileSuggest(this.app, text.inputEl);
text.onChange((value) => {
period.templateFile = value;
this.saveAndRefresh();
});
});
new Setting(container)
.setName('Type property')
.setDesc(`Value for the 'type' frontmatter property.`)
.addText((text) => {
text.setPlaceholder('daily-note');
text.setValue(period.typeProperty);
text.onChange((value) => {
period.typeProperty = value;
this.saveAndRefresh();
});
});
}
// ═══════════════════════════════
// Date systems tab
// ═══════════════════════════════
private renderSystemsTab(container: HTMLElement): void {
const intro = new DocumentFragment();
intro.createDiv({ text: 'A date system is a folder of notes whose filenames start with a date. Each one appears in the calendar\'s right-click menu for that day.' });
intro.createDiv({ text: 'The daily note is configured under Periodic Notes and always comes first in that menu.' });
intro.createDiv({ text: 'Name format is a moment.js format. Literal words need bracket escaping, e.g. YYYY-MM-DD - [Journal].' });
intro.createDiv({ text: 'Include {title} for systems that hold many notes per date, such as meetings: the text before the token finds the existing notes, and the token marks where a typed title goes. Without it, a date has exactly one note.' });
new Setting(container)
.setHeading()
.setName('Date systems')
.setDesc(intro);
this.settings.dateSystems.forEach((system, i, arr) => {
new Setting(container)
.setHeading()
.setName(system.name || 'Untitled system')
.addExtraButton((btn) => {
btn
.setIcon('arrow-up')
.setTooltip('Move up')
.setDisabled(i === 0)
.onClick(async () => {
if (i === 0) return;
const above = arr[i - 1];
arr[i - 1] = arr[i];
arr[i] = above;
await this.saveAndRefresh();
this.display();
});
})
.addExtraButton((btn) => {
btn
.setIcon('arrow-down')
.setTooltip('Move down')
.setDisabled(i === arr.length - 1)
.onClick(async () => {
if (i === arr.length - 1) return;
const below = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = below;
await this.saveAndRefresh();
this.display();
});
})
.addExtraButton((btn) => {
btn
.setIcon('trash')
.setTooltip('Delete this date system')
.onClick(async () => {
arr.splice(i, 1);
await this.saveAndRefresh();
this.display();
});
});
this.addSystemTextSetting(container,
'Name', 'Label shown in the calendar right-click menu.',
system, 'name', 'Journal',
);
this.addSystemTextSetting(container,
'Folder', 'Folder these notes live in.',
system, 'folder', 'periodic/journal',
);
const formatSetting = this.addSystemTextSetting(container,
'Name format', 'Filename format (moment.js format). Include {title} for many notes per date.',
system, 'nameFormat', 'YYYY-MM-DD - {title}',
);
// A blank row is still being filled in, so only warn once something was typed.
if (system.nameFormat && !formatHasDateToken(system.nameFormat)) {
formatSetting.descEl.createDiv({
cls: 'waypoint-settings-warning',
text: 'This name format has no date placeholder, so it will never match or create dated notes.',
});
}
this.addSystemTextSetting(container,
'Template file', 'Path to the template file. The .md extension is optional.',
system, 'templateFile', 'resources/template/journal', true,
);
this.addSystemTextSetting(container,
'Type property', `Fallback value for the 'type' frontmatter property, used when no template is found.`,
system, 'typeProperty', 'journal-note',
);
this.addSystemTextSetting(container,
'Icon', 'Lucide icon name for the menu item. Browse names at lucide.dev.',
system, 'icon', 'book-open',
);
new Setting(container)
.setName('Indicator colour')
.setDesc('Colour for this system’s dot when using “Colour by note system”.')
.addColorPicker((color) => {
color
.setValue(system.indicatorColor)
.onChange((value) => {
system.indicatorColor = value;
this.saveAndRefresh();
});
});
});
new Setting(container)
.addButton((btn) =>
btn
.setButtonText('Add date system')
.setCta()
.onClick(async () => {
this.settings.dateSystems.push(Object.assign(
{ id: `ds-${Date.now()}-${Math.random().toString(36).slice(2, 6)}` },
DEFAULT_DATE_SYSTEM,
));
await this.saveAndRefresh();
this.display();
}),
);
}
/** Returns the Setting so callers can append validation notices to its description. */
private addSystemTextSetting<K extends string>(
container: HTMLElement,
name: string,
desc: string,
obj: Record<K, string>,
key: K,
placeholder: string,
suggestTemplates?: boolean,
): Setting {
return new Setting(container)
.setName(name)
.setDesc(desc)
.addText((text) => {
text.setPlaceholder(placeholder);
text.setValue(obj[key]);
if (suggestTemplates) new TemplateFileSuggest(this.app, text.inputEl);
text.onChange((value) => {
obj[key] = value;
this.saveAndRefresh();
});
});
}
// ═══════════════════════════════
// Recent Files tab
// ═══════════════════════════════
private renderRecentTab(container: HTMLElement): void {
new Setting(container)
.setName('Max items')
.setDesc('How many recently opened files, and separately how many recently changed files, to keep. A burst of synced changes cannot push out the files you opened.')
.addText((text) => {
text.inputEl.setAttr('type', 'number');
text.inputEl.setAttr('placeholder', '50');
text.setValue(String(this.settings.recentFiles.maxItems));
text.inputEl.onblur = () => {
const val = parseInt(text.getValue(), 10);
if (!isNaN(val) && val > 0) {
this.settings.recentFiles.maxItems = val;
this.saveAndRefresh();
}
};
});
const pathDesc = new DocumentFragment();
pathDesc.appendText('Regex patterns for paths to exclude. One per line.');
new Setting(container)
.setName('Omitted paths')
.setDesc(pathDesc)
.addTextArea((text) => {
text.inputEl.setAttr('rows', 4);
text.setPlaceholder('^archives/\n\\.png$');
text.setValue(this.settings.recentFiles.omittedPaths.join('\n'));
text.inputEl.onblur = () => {
this.settings.recentFiles.omittedPaths = text.getValue().split('\n').filter(p => p.trim());
this.saveAndRefresh();
};
});
const tagDesc = new DocumentFragment();
tagDesc.appendText('Regex patterns for frontmatter tags to exclude. One per line.');
new Setting(container)
.setName('Omitted tags')
.setDesc(tagDesc)
.addTextArea((text) => {
text.inputEl.setAttr('rows', 4);
text.setPlaceholder('ignore\narchive');
text.setValue(this.settings.recentFiles.omittedTags.join('\n'));
text.inputEl.onblur = () => {
this.settings.recentFiles.omittedTags = text.getValue().split('\n').filter(t => t.trim());
this.saveAndRefresh();
};
});
this.renderRecentTypes(container);
}
/** Frontmatter types with an icon each. */
private renderRecentTypes(container: HTMLElement): void {
const types = this.settings.recentFiles.types;
new Setting(container)
.setHeading()
.setName('File types')
.setDesc('Frontmatter `type` values. A type\'s icon shows beside matching recent files.');
types.forEach((entry, i) => {
new Setting(container)
.addText((text) => {
text.setPlaceholder('meeting');
text.setValue(entry.type);
text.inputEl.onblur = () => {
const value = text.getValue().trim();
if (value === entry.type) return;
entry.type = value;
this.saveAndRefresh();
};
})
.addExtraButton((btn) => {
btn
.setIcon(entry.icon || 'image-off')
.setTooltip(entry.icon ? `Icon: ${entry.icon}` : 'Choose icon')
.onClick(() => {
new IconSuggestModal(this.app, entry.icon, (icon) => {
entry.icon = icon;
this.saveAndRefresh();
this.display();
}).open();
});
})
.addExtraButton((btn) => {
btn
.setIcon('trash')
.setTooltip('Remove this type')
.onClick(() => {
types.splice(i, 1);
this.saveAndRefresh();
this.display();
});
});
});
new Setting(container)
.addButton((btn) => {
btn
.setButtonText('Add type')
.onClick(() => {
types.push({ type: '', icon: '' });
this.display();
});
});
}
// ═══════════════════════════════
// Display tab
// ═══════════════════════════════
private renderDisplayTab(container: HTMLElement): void {
new Setting(container).setHeading().setName('Bookmarks');
this.addSliderSetting(container,
'Row size', 'Height of bookmark items.',
this.settings.display, 'rowSize', 18, 40, 1, 'px',
);
this.addSliderSetting(container,
'Row spacing', 'Gap between bookmark items.',
this.settings.display, 'rowSpacing', 0, 12, 1, 'px',
);
this.addSliderSetting(container,
'Indent size', 'Indent per nesting depth.',
this.settings.display, 'indentSize', 8, 32, 2, 'px',
);
this.addSliderSetting(container,
'Font size', 'Label font size.',
this.settings.display, 'fontSize', 10, 18, 1, 'px',
);
this.addSliderSetting(container,
'Icon size', 'Bookmark icon size.',
this.settings.display, 'iconSize', 12, 24, 1, 'px',
);
new Setting(container).setHeading().setName('Calendar');
this.addSliderSetting(container,
'Cell size', 'Height of calendar day cells.',
this.settings.display, 'calendarCellSize', 20, 48, 2, 'px',
);
new Setting(container)
.addButton((btn) =>
btn
.setButtonText('Reset to defaults')
.onClick(() => {
this.settings.display = { ...DEFAULT_SETTINGS.display };
this.saveAndRefresh();
this.display();
}),
);
}
private addSliderSetting<K extends string>(
container: HTMLElement,
name: string,
desc: string,
obj: Record<K, number>,
key: K,
min: number,
max: number,
step: number,
unit: string,
): void {
const setting = new Setting(container)
.setName(name)
.setDesc(`${desc} (${obj[key]}${unit})`);
setting.addSlider((slider) => {
slider
.setLimits(min, max, step)
.setValue(obj[key])
.setDynamicTooltip()
.onChange((value) => {
obj[key] = value;
setting.setDesc(`${desc} (${value}${unit})`);
this.saveAndRefresh();
});
});
}
private async saveAndRefresh(): Promise<void> {
await this.plugin.saveSettings();
this.onSettingsChange();
}
// ═══════════════════════════════
// About tab
// ═══════════════════════════════
private renderAboutTab(container: HTMLElement): void {
const version = this.plugin.manifest.version;
const header = container.createDiv();
header.style.display = 'flex';
header.style.alignItems = 'center';
header.style.gap = '12px';
header.style.marginBottom = '16px';
const icon = header.createDiv();
icon.style.display = 'flex';
icon.style.alignItems = 'center';
icon.style.justifyContent = 'center';
icon.style.width = '48px';
icon.style.height = '48px';
icon.style.borderRadius = '12px';
icon.style.background = 'var(--interactive-accent)';
icon.style.color = 'var(--text-on-accent)';
icon.style.fontSize = '24px';
setIcon(icon, 'compass');
const titleGroup = header.createDiv();
const title = titleGroup.createEl('h2', { text: 'Waypoint Sidebar' });
title.style.margin = '0';
title.style.lineHeight = '1.2';
const subtitle = titleGroup.createDiv({ text: `v${version}` });
subtitle.style.color = 'var(--text-muted)';
subtitle.style.fontSize = 'var(--font-ui-small)';
const desc = container.createDiv();
desc.style.marginBottom = '20px';
desc.style.lineHeight = '1.6';
desc.style.color = 'var(--text-normal)';
desc.innerHTML = [
`<p><strong>Waypoint</strong> is a sidebar plugin that brings three essential panels into one view:</p>`,
`<ul style="padding-left: 20px; margin: 8px 0;">`,
`<li><strong>Calendar</strong> — a monthly grid for your periodic notes (daily, weekly, monthly, quarterly, yearly). Click any day, week, or month to open or create the corresponding note.</li>`,
`<li><strong>Recent Files</strong> — a list of recently opened and changed files with type icons, drag-and-drop, and right-click actions.</li>`,
`<li><strong>Bookmarks</strong> — custom bookmarks with icons, groups, nesting, and drag-and-drop reordering. Separate from Obsidian's native bookmarks.</li>`,
`</ul>`,
`<p style="color: var(--text-muted); font-size: var(--font-ui-small);">Made by Olivier. Licensed under MIT.</p>`,
].join('\n');
}
}