feat!: simplify menu layouts and options

- 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
This commit is contained in:
olivier committed 2026-10-12 21:58:39 -04:00
1 parent 46dea4e8ed
commit 0f257cbace
5 files changed
+658 -1024

No files matched your search

+209 -282
View File
@@ -1,38 +1,60 @@
import { App, Plugin, PluginSettingTab, Setting, MarkdownRenderer, Platform, MarkdownPostProcessorContext } from 'obsidian';
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 {
mySetting: string;
defaultLayout: Layout;
}
const DEFAULT_SETTINGS: MenuPluginSettings = {
mySetting: 'default'
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() {
try {
await this.loadSettings();
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new MenuPluginSettingTab(this.app, this));
this.registerMarkdownCodeBlockProcessor('menu', (source, el, ctx) => {
this.processMenuBlock(source, el, ctx);
});
} catch (error) {
console.error('[obsidian-menus] Failed to load plugin:', error);
throw error;
}
}
onunload() {
// Cleanup if needed
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() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
const data = await this.loadData();
const saved = data?.defaultLayout;
this.settings = {
defaultLayout: (LAYOUTS as readonly string[]).includes(saved) ? saved : DEFAULT_SETTINGS.defaultLayout,
};
}
async saveSettings() {
@@ -40,53 +62,13 @@ export default class MenuPlugin extends Plugin {
}
private processMenuBlock(source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) {
const lines = source.trim().split('\n');
let layoutOrClass = '';
let colors: Record<string, string> = {};
const options: Record<string, string> = {};
const links: string[] = [];
let dataviewQuery = '';
// Parse YAML-like properties and links
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('layout:') || trimmed.startsWith('class:')) {
const colonIndex = trimmed.indexOf(':');
layoutOrClass = trimmed.substring(colonIndex + 1).trim();
} else if (trimmed.startsWith('dataview:') || trimmed.startsWith('dv:')) {
const colonIndex = trimmed.indexOf(':');
dataviewQuery = trimmed.substring(colonIndex + 1).trim();
} else if (trimmed.includes(':') && !trimmed.startsWith('[') && !trimmed.startsWith('[[') && !dataviewQuery) {
// Parse color properties
const [key, ...valueParts] = trimmed.split(':');
const value = valueParts.join(':').trim();
if (key && value && !key.includes('//') && !key.includes('http')) {
colors[key.trim()] = value;
}
} else if (trimmed && !trimmed.includes(':') && !dataviewQuery) {
links.push(trimmed);
} else if (trimmed.startsWith('[') && !dataviewQuery) {
links.push(trimmed);
} else if (dataviewQuery) {
// If we already found a dataview start, append subsequent lines to it
// This handles multi-line queries if the user didn't put it all on one line
// But actually, the simple parsing above assumes one line per property.
// For complex queries, we might need a better parser.
// For now, let's assume the query might be multi-line if it started with dv:
// But the loop iterates lines.
// Let's adjust: if we are in "dataview mode", just add to query.
dataviewQuery += '\n' + line;
}
}
// Re-parsing to handle multi-line dataview queries correctly
// The previous loop was a bit naive for multi-line. Let's do a cleaner pass.
layoutOrClass = '';
colors = {};
links.length = 0;
dataviewQuery = '';
let isDataviewBlock = false;
for (const line of lines) {
for (const line of source.trim().split('\n')) {
const trimmed = line.trim();
if (isDataviewBlock) {
dataviewQuery += '\n' + line;
@@ -94,218 +76,143 @@ export default class MenuPlugin extends Plugin {
}
if (trimmed.startsWith('layout:') || trimmed.startsWith('class:')) {
const colonIndex = trimmed.indexOf(':');
layoutOrClass = trimmed.substring(colonIndex + 1).trim();
layoutOrClass = trimmed.substring(trimmed.indexOf(':') + 1).trim();
} else if (trimmed.startsWith('dataview:') || trimmed.startsWith('dv:')) {
const colonIndex = trimmed.indexOf(':');
dataviewQuery = trimmed.substring(colonIndex + 1).trim();
isDataviewBlock = true; // Assume rest of block is the query
} else if (trimmed.includes(':') && !trimmed.startsWith('[') && !trimmed.startsWith('[[')) {
const [key, ...valueParts] = trimmed.split(':');
const value = valueParts.join(':').trim();
if (key && value && !key.includes('//') && !key.includes('http')) {
colors[key.trim()] = value;
}
} else if (trimmed) {
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;
}
}
// Determine layout and classes
const builtInLayouts = new Set(['default', 'minimal', 'slate', 'horizon', 'aether']);
const container = el.createEl('div', { cls: 'menu-container' });
let selectedLayout = '';
let extraClasses: string[] = [];
if (layoutOrClass) {
const tokens = layoutOrClass.split(/\s+/).filter(Boolean);
if (tokens.length) {
const builtInIndex = tokens.findIndex(t => builtInLayouts.has(t));
if (builtInIndex !== -1) {
selectedLayout = tokens[builtInIndex];
extraClasses = tokens.filter((_, i) => i !== builtInIndex);
} else {
extraClasses = tokens;
}
}
} else {
selectedLayout = 'default';
// 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;
}
if (selectedLayout) {
container.setAttr('data-layout', selectedLayout);
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);
}
for (const cls of extraClasses) {
container.addClass(cls);
}
const sourcePath = ctx.sourcePath;
const hoverParent: HoverParent = { hoverPopover: null as HoverPopover | null };
// Apply custom properties
if (Object.keys(colors).length > 0) {
const baseKeys = new Set([
'bg', 'text', 'border', 'font',
'hover-text', 'hover-bg', 'hover-border', 'hover-font',
]);
const normalizeKey = (raw: string) => {
let s = raw.trim().toLowerCase();
s = s
.replace(/\btext-hover\b/g, 'hover-text')
.replace(/\bbg-hover\b/g, 'hover-bg')
.replace(/\bborder-hover\b/g, 'hover-border')
.replace(/\binternal-text-hover\b/g, 'internal-hover-text')
.replace(/\binternal-bg-hover\b/g, 'internal-hover-bg')
.replace(/\binternal-border-hover\b/g, 'internal-hover-border')
.replace(/\bexternal-text-hover\b/g, 'external-hover-text')
.replace(/\bexternal-bg-hover\b/g, 'external-hover-bg')
.replace(/\bexternal-border-hover\b/g, 'external-hover-border')
.replace(/\bfile-text-hover\b/g, 'file-hover-text')
.replace(/\bfile-bg-hover\b/g, 'file-hover-bg')
.replace(/\bfile-border-hover\b/g, 'file-hover-border')
.replace(/\baccent\b/g, 'hover-text')
.replace(/\binternal-accent\b/g, 'internal-hover-text')
.replace(/\bexternal-accent\b/g, 'external-hover-text')
.replace(/\bfile-accent\b/g, 'file-hover-text')
.replace(/\bbackground\b/g, 'bg');
return s;
};
const isAllowed = (key: string) => {
if (baseKeys.has(key)) return true;
const m = key.match(/^(internal|external|file)-(.*)$/);
return !!(m && baseKeys.has(m[2]));
};
for (const [rawKey, value] of Object.entries(colors)) {
const key = normalizeKey(rawKey);
if (!isAllowed(key)) continue;
container.style.setProperty(`--${key}`, value);
}
}
const applyInlineBaseStyles = (a: HTMLElement, variant: 'internal' | 'external' | 'file' | 'generic') => {
const prefix = variant === 'generic' ? '' : `${variant}-`;
const get = (k: string) => (colors[`${prefix}${k}`] ?? colors[k]);
const bgVal = get('bg'); if (bgVal) a.style.background = bgVal as string;
const textVal = get('text'); if (textVal) a.style.color = textVal as string;
const borderVal = get('border'); if (borderVal) a.style.borderColor = borderVal as string;
const fontVal = get('font'); if (fontVal) a.style.fontFamily = fontVal as string;
const hoverKeys = ['hover-bg', 'hover-text', 'hover-border', 'hover-font'];
for (const hk of hoverKeys) {
const v = get(hk);
if (v) a.style.setProperty(`--${hk}`, v as string);
}
};
// Process regular links
for (const link of links) {
if (link.startsWith('[[') && link.endsWith(']]')) {
const linkContent = link.slice(2, -2);
let href = linkContent;
let text = linkContent;
if (linkContent.includes('|')) {
[href, text] = linkContent.split('|');
}
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: text,
attr: { 'data-href': href }
text,
cls: 'menu-external-link',
attr: { href: url, target: '_blank', rel: 'noopener noreferrer' }
});
a.addClass('menu-internal-link');
if (!selectedLayout) applyInlineBaseStyles(a, 'internal');
a.style.cursor = 'pointer';
a.addEventListener('click', (e) => {
e.preventDefault();
let sourcePath = ctx?.sourcePath;
if (!sourcePath) {
const activeFile = this.app.workspace.getActiveFile();
sourcePath = activeFile ? activeFile.path : '';
if (!sourcePath) {
console.error('[obsidian-menus] Could not determine sourcePath for internal link:', href);
}
}
try {
this.app.workspace.openLinkText(href, sourcePath, false);
} catch (err) {
console.error('[obsidian-menus] Failed to open internal link:', href, err);
}
window.open(url, '_blank', 'noopener,noreferrer');
});
} else if (link.match(/^\[.*\]\(.*\)$/)) {
const match = link.match(/^\[(.*)\]\((.*)\)$/);
if (match) {
const text = match[1];
const url = match[2];
const a = container.createEl('a', {
text: text,
attr: url.startsWith('file://') ? {} : { href: url, target: '_blank', rel: 'noopener noreferrer' }
});
a.style.cursor = 'pointer';
if (url.startsWith('file://')) {
a.addClass('menu-file-link');
if (!selectedLayout) applyInlineBaseStyles(a, 'file');
} else {
a.addClass('menu-external-link');
if (!selectedLayout) applyInlineBaseStyles(a, 'external');
}
a.addEventListener('click', (e) => {
e.preventDefault();
if (url.startsWith('file://')) {
if (Platform.isDesktop) {
try {
// Use dynamic import with proper error handling
const electronPath = 'electron';
const { shell } = require(electronPath);
let filePath = decodeURIComponent(url.substring(7));
if (filePath.startsWith('/') && filePath.charAt(2) === ':') {
filePath = filePath.substring(1);
}
shell.openPath(filePath);
} catch (error) {
console.error('Failed to open file:', error);
}
} else {
console.warn('File links are not supported on mobile.');
}
} else {
window.open(url, '_blank', 'noopener,noreferrer');
}
});
}
}
}
// Process Dataview Query
if (dataviewQuery) {
const dvContainer = container.createDiv({ cls: 'menu-dataview-container' });
// Render the dataview query
// We wrap it in ```dataview ... ``` so Obsidian's renderer handles it
MarkdownRenderer.render(
this.app,
`\`\`\`dataview\n${dataviewQuery}\n\`\`\``,
dvContainer,
ctx.sourcePath,
this
);
// MutationObserver to style links once they render
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'childList') {
const links = dvContainer.querySelectorAll('a');
links.forEach((link: HTMLElement) => {
if (link.hasClass('internal-link')) {
link.addClass('menu-internal-link');
if (!selectedLayout) applyInlineBaseStyles(link, 'internal');
} else {
link.addClass('menu-external-link');
if (!selectedLayout) applyInlineBaseStyles(link, 'external');
}
});
}
}
});
observer.observe(dvContainer, { childList: true, subtree: true });
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 {
@@ -321,48 +228,68 @@ class MenuPluginSettingTab extends PluginSettingTab {
containerEl.empty();
containerEl.createEl('h2', { text: 'Menu Plugin Settings' });
new Setting(containerEl)
.setName('Setting #1')
.setDesc('It\'s a secret')
.addText(text => text
.setPlaceholder('Enter your secret')
.setValue(this.plugin.settings.mySetting)
.onChange(async (value) => {
this.plugin.settings.mySetting = value;
await this.plugin.saveSettings();
}));
.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();
});
});
// --- Documentation Section ---
containerEl.createEl('hr');
containerEl.createEl('h3', { text: 'Usage Guide' });
new Setting(containerEl).setName('Usage guide').setHeading();
const doc = containerEl.createEl('div');
const doc = containerEl.createEl('div', { cls: 'menu-settings-docs' });
doc.createEl('p', { text: 'Create a custom menu using the `menu` code block.' });
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
bg: #333
text: white
layout: slate small
hover-text: #0af
radius: 99px
[[Internal Link]]
[External Link](https://example.com)
[File Link](file:///C:/Documents)
\`\`\``});
doc.createEl('h4', { text: 'Supported Properties' });
const ul = doc.createEl('ul');
ul.createEl('li', { text: 'layout: default, minimal, slate, horizon, aether' });
ul.createEl('li', { text: 'class: custom CSS classes' });
ul.createEl('li', { text: 'colors: bg, text, border, font (supports hover- prefix)' });
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: 'Link Types' });
const ul2 = doc.createEl('ul');
ul2.createEl('li', { text: '[[Internal Link]] - Opens Obsidian note' });
ul2.createEl('li', { text: '[External Link](https://...) - Opens in browser' });
ul2.createEl('li', { text: '[File Link](file://...) - Opens local file/folder' });
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)');
}
}