- Three theme-aware layouts (default, minimal, slate) plus small/grid modifiers - New options: size, gap, radius, padding; per-link-type colors resolve via --mm-* variables - Remove horizon and aether layouts, wide modifier and hover-font - Fix class: menus ignoring hover colors (inline styles removed) - Fix Dataview links not joining the menu row - Wire up default layout setting - Parse <angle-bracketed> file link destinations - Internal links: Ctrl/middle-click new tab, hover preview, keyboard focus - Keep 0.5rem edit strip working with Obsidian's .embed-actions wrapper, no icon flicker
296 lines
12 KiB
TypeScript
296 lines
12 KiB
TypeScript
import { App, Plugin, PluginSettingTab, Setting, MarkdownRenderer, Platform, MarkdownPostProcessorContext, MarkdownRenderChild, Keymap, HoverParent, HoverPopover, PaneType } from 'obsidian';
|
|
|
|
const LAYOUTS = ['default', 'minimal', 'slate'] as const;
|
|
type Layout = typeof LAYOUTS[number];
|
|
const MODIFIERS = new Set(['small', 'grid']);
|
|
|
|
/** Options that can be prefixed with internal-/external-/file- to target one link type. */
|
|
const LINK_KEYS = new Set(['text', 'bg', 'border', 'font', 'hover-text', 'hover-bg', 'hover-border']);
|
|
/** Options that apply to the whole menu. */
|
|
const MENU_KEYS = new Set(['size', 'gap', 'radius', 'padding']);
|
|
const KEY_ALIASES: Record<string, string> = {
|
|
'background': 'bg',
|
|
'accent': 'hover-text',
|
|
'text-hover': 'hover-text',
|
|
'bg-hover': 'hover-bg',
|
|
'border-hover': 'hover-border',
|
|
};
|
|
|
|
const HOVER_SOURCE = 'monster-menus';
|
|
|
|
interface MenuPluginSettings {
|
|
defaultLayout: Layout;
|
|
}
|
|
|
|
const DEFAULT_SETTINGS: MenuPluginSettings = {
|
|
defaultLayout: 'default'
|
|
}
|
|
|
|
/** Maps a user-written option key to its CSS variable name, or null if unsupported. */
|
|
function normalizeKey(raw: string): string | null {
|
|
const match = raw.trim().toLowerCase().match(/^(?:(internal|external|file)-)?(.+)$/);
|
|
if (!match) return null;
|
|
const prefix = match[1] ? `${match[1]}-` : '';
|
|
const key = KEY_ALIASES[match[2]] ?? match[2];
|
|
if (LINK_KEYS.has(key)) return prefix + key;
|
|
if (!prefix && MENU_KEYS.has(key)) return key;
|
|
return null;
|
|
}
|
|
|
|
export default class MenuPlugin extends Plugin {
|
|
settings: MenuPluginSettings;
|
|
|
|
async onload() {
|
|
await this.loadSettings();
|
|
this.addSettingTab(new MenuPluginSettingTab(this.app, this));
|
|
this.registerHoverLinkSource(HOVER_SOURCE, { display: 'Monster Menus', defaultMod: true });
|
|
this.registerMarkdownCodeBlockProcessor('menu', (source, el, ctx) => {
|
|
this.processMenuBlock(source, el, ctx);
|
|
});
|
|
}
|
|
|
|
async loadSettings() {
|
|
const data = await this.loadData();
|
|
const saved = data?.defaultLayout;
|
|
this.settings = {
|
|
defaultLayout: (LAYOUTS as readonly string[]).includes(saved) ? saved : DEFAULT_SETTINGS.defaultLayout,
|
|
};
|
|
}
|
|
|
|
async saveSettings() {
|
|
await this.saveData(this.settings);
|
|
}
|
|
|
|
private processMenuBlock(source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) {
|
|
let layoutOrClass = '';
|
|
const options: Record<string, string> = {};
|
|
const links: string[] = [];
|
|
let dataviewQuery = '';
|
|
let isDataviewBlock = false;
|
|
|
|
for (const line of source.trim().split('\n')) {
|
|
const trimmed = line.trim();
|
|
if (isDataviewBlock) {
|
|
dataviewQuery += '\n' + line;
|
|
continue;
|
|
}
|
|
|
|
if (trimmed.startsWith('layout:') || trimmed.startsWith('class:')) {
|
|
layoutOrClass = trimmed.substring(trimmed.indexOf(':') + 1).trim();
|
|
} else if (trimmed.startsWith('dataview:') || trimmed.startsWith('dv:')) {
|
|
dataviewQuery = trimmed.substring(trimmed.indexOf(':') + 1).trim();
|
|
isDataviewBlock = true; // The rest of the block is the query
|
|
} else if (trimmed.startsWith('[')) {
|
|
links.push(trimmed);
|
|
} else if (trimmed.includes(':')) {
|
|
const colonIndex = trimmed.indexOf(':');
|
|
const key = normalizeKey(trimmed.substring(0, colonIndex));
|
|
const value = trimmed.substring(colonIndex + 1).trim();
|
|
if (key && value) options[key] = value;
|
|
}
|
|
}
|
|
|
|
// A built-in layout name selects the layout; other tokens become CSS classes.
|
|
// Without a built-in layout, the menu is unstyled (custom class mode),
|
|
// unless the only tokens are modifiers such as `small` or `grid`.
|
|
const tokens = layoutOrClass.split(/\s+/).filter(Boolean);
|
|
let layout = tokens.find((t): t is Layout => (LAYOUTS as readonly string[]).includes(t));
|
|
if (!layout && tokens.every(t => MODIFIERS.has(t))) {
|
|
layout = this.settings.defaultLayout;
|
|
}
|
|
|
|
const container = el.createDiv({ cls: 'menu-container' });
|
|
if (layout) container.setAttr('data-layout', layout);
|
|
for (const token of tokens) {
|
|
if (token !== layout) container.addClass(token);
|
|
}
|
|
for (const [key, value] of Object.entries(options)) {
|
|
container.style.setProperty(`--${key}`, value);
|
|
}
|
|
|
|
const sourcePath = ctx.sourcePath;
|
|
const hoverParent: HoverParent = { hoverPopover: null as HoverPopover | null };
|
|
|
|
for (const link of links) {
|
|
const wiki = link.match(/^\[\[(.+)\]\]$/);
|
|
if (wiki) {
|
|
const [target, alias] = wiki[1].split('|');
|
|
this.createInternalLink(container, target.trim(), (alias ?? target).trim(), sourcePath, hoverParent);
|
|
continue;
|
|
}
|
|
|
|
const markdown = link.match(/^\[(.*)\]\((.*)\)$/);
|
|
if (!markdown) continue;
|
|
const text = markdown[1];
|
|
// Markdown allows <angle-bracketed> destinations, needed for paths with spaces
|
|
const url = markdown[2].trim().replace(/^<(.*)>$/, '$1').trim();
|
|
if (url.startsWith('file://')) {
|
|
this.createFileLink(container, text, url);
|
|
} else {
|
|
const a = container.createEl('a', {
|
|
text,
|
|
cls: 'menu-external-link',
|
|
attr: { href: url, target: '_blank', rel: 'noopener noreferrer' }
|
|
});
|
|
a.addEventListener('click', (e) => {
|
|
e.preventDefault();
|
|
window.open(url, '_blank', 'noopener,noreferrer');
|
|
});
|
|
}
|
|
}
|
|
|
|
if (dataviewQuery) {
|
|
this.renderDataview(container, dataviewQuery, ctx);
|
|
}
|
|
}
|
|
|
|
private createInternalLink(container: HTMLElement, target: string, text: string, sourcePath: string, hoverParent: HoverParent) {
|
|
const a = container.createEl('a', {
|
|
text,
|
|
cls: 'menu-internal-link',
|
|
attr: { href: target, 'data-href': target }
|
|
});
|
|
const open = (newLeaf: PaneType | boolean) => {
|
|
this.app.workspace.openLinkText(target, sourcePath, newLeaf).catch((err) => {
|
|
console.error('[monster-menus] Failed to open internal link:', target, err);
|
|
});
|
|
};
|
|
a.addEventListener('click', (e) => {
|
|
e.preventDefault();
|
|
open(Keymap.isModEvent(e));
|
|
});
|
|
a.addEventListener('auxclick', (e) => {
|
|
if (e.button !== 1) return;
|
|
e.preventDefault();
|
|
open('tab');
|
|
});
|
|
a.addEventListener('mouseover', (event) => {
|
|
this.app.workspace.trigger('hover-link', {
|
|
event,
|
|
source: HOVER_SOURCE,
|
|
hoverParent,
|
|
targetEl: a,
|
|
linktext: target,
|
|
sourcePath,
|
|
});
|
|
});
|
|
}
|
|
|
|
private createFileLink(container: HTMLElement, text: string, url: string) {
|
|
const a = container.createEl('a', { text, cls: 'menu-file-link', attr: { href: url } });
|
|
a.addEventListener('click', (e) => {
|
|
e.preventDefault();
|
|
if (!Platform.isDesktop) {
|
|
console.warn('[monster-menus] File links are not supported on mobile.');
|
|
return;
|
|
}
|
|
let filePath = decodeURIComponent(url.substring('file://'.length));
|
|
if (filePath.startsWith('/') && filePath.charAt(2) === ':') {
|
|
filePath = filePath.substring(1);
|
|
}
|
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
const { shell } = require('electron');
|
|
shell.openPath(filePath).then((error: string) => {
|
|
if (error) console.error('[monster-menus] Failed to open file:', filePath, error);
|
|
});
|
|
});
|
|
}
|
|
|
|
private renderDataview(container: HTMLElement, query: string, ctx: MarkdownPostProcessorContext) {
|
|
const dvContainer = container.createDiv({ cls: 'menu-dataview-container' });
|
|
const component = new MarkdownRenderChild(dvContainer);
|
|
ctx.addChild(component);
|
|
MarkdownRenderer.render(this.app, `\`\`\`dataview\n${query}\n\`\`\``, dvContainer, ctx.sourcePath, component);
|
|
|
|
// Dataview renders asynchronously; tag its links so per-link-type options apply.
|
|
const tagLinks = () => {
|
|
dvContainer.querySelectorAll('a:not(.menu-internal-link, .menu-external-link)').forEach((link) => {
|
|
link.addClass(link.hasClass('internal-link') ? 'menu-internal-link' : 'menu-external-link');
|
|
});
|
|
};
|
|
const observer = new MutationObserver(tagLinks);
|
|
observer.observe(dvContainer, { childList: true, subtree: true });
|
|
component.register(() => observer.disconnect());
|
|
tagLinks();
|
|
}
|
|
}
|
|
|
|
class MenuPluginSettingTab extends PluginSettingTab {
|
|
plugin: MenuPlugin;
|
|
|
|
constructor(app: App, plugin: MenuPlugin) {
|
|
super(app, plugin);
|
|
this.plugin = plugin;
|
|
}
|
|
|
|
display(): void {
|
|
const { containerEl } = this;
|
|
|
|
containerEl.empty();
|
|
|
|
new Setting(containerEl)
|
|
.setName('Default layout')
|
|
.setDesc('Layout used when a menu block has no layout: line.')
|
|
.addDropdown(dropdown => {
|
|
for (const layout of LAYOUTS) {
|
|
dropdown.addOption(layout, layout.charAt(0).toUpperCase() + layout.slice(1));
|
|
}
|
|
dropdown
|
|
.setValue(this.plugin.settings.defaultLayout)
|
|
.onChange(async (value) => {
|
|
this.plugin.settings.defaultLayout = value as Layout;
|
|
await this.plugin.saveSettings();
|
|
});
|
|
});
|
|
|
|
new Setting(containerEl).setName('Usage guide').setHeading();
|
|
|
|
const doc = containerEl.createEl('div', { cls: 'menu-settings-docs' });
|
|
|
|
doc.createEl('p', {
|
|
text: 'Put one link per line in a `menu` code block. Options go before the links.'
|
|
});
|
|
|
|
doc.createEl('h4', { text: 'Example' });
|
|
const pre = doc.createEl('pre');
|
|
pre.createEl('code', {
|
|
text: `\`\`\`menu
|
|
layout: slate small
|
|
hover-text: #0af
|
|
radius: 99px
|
|
|
|
[[Internal Link]]
|
|
[External Link](https://example.com)
|
|
[File Link](file:///C:/Documents)
|
|
\`\`\``});
|
|
|
|
doc.createEl('h4', { text: 'Link types' });
|
|
const linkTable = doc.createEl('table', { cls: 'menu-settings-table' });
|
|
const addRow = (syntax: string, description: string) => {
|
|
const tr = linkTable.createEl('tr');
|
|
tr.createEl('td', { text: syntax, cls: 'menu-settings-syntax' });
|
|
tr.createEl('td', { text: description });
|
|
};
|
|
addRow('[[Note]]', 'Opens an Obsidian note (Ctrl-click or middle-click: new tab)');
|
|
addRow('[[Note|Alias]]', 'Obsidian note with custom display text');
|
|
addRow('[Text](https://...)', 'Opens URL in your browser');
|
|
addRow('[Text](file:///path)', 'Opens a local file or folder (desktop only)');
|
|
|
|
doc.createEl('h4', { text: 'Options' });
|
|
const propTable = doc.createEl('table', { cls: 'menu-settings-table' });
|
|
const addProp = (prop: string, values: string, description: string) => {
|
|
const tr = propTable.createEl('tr');
|
|
tr.createEl('td', { text: prop, cls: 'menu-settings-syntax' });
|
|
tr.createEl('td', { text: values });
|
|
tr.createEl('td', { text: description });
|
|
};
|
|
addProp('layout:', `${LAYOUTS.join(', ')} + small, grid`, 'Built-in style and modifiers');
|
|
addProp('class:', 'any CSS class name', 'Custom CSS class (no built-in style)');
|
|
addProp('text / bg / border / font', 'any CSS value', 'Link colors and font');
|
|
addProp('hover-text / hover-bg / hover-border', 'any CSS value', 'Hover colors');
|
|
addProp('size / gap / radius / padding', 'any CSS length', 'Font size, spacing, corner rounding');
|
|
addProp('internal-* / external-* / file-*', 'any CSS value', 'Color or font for one link type');
|
|
addProp('dataview: / dv:', 'Dataview query', 'Add links from Dataview (rest of block)');
|
|
}
|
|
}
|