2 Commits
Author SHA1 Message Date
olivier 9a1a1dd150 chore: bump to v2.0.0 2026-10-12 21:58:45 -04:00
olivier 0f257cbace 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
2026-10-12 21:58:39 -04:00
7 changed files with 627 additions and 993 deletions

No files matched your search

+58 -58
View File
@@ -15,36 +15,69 @@ layout: default
``` ```
The plugin supports three link types: The plugin supports three link types:
- Internal: `[[Note]]` or `[[Note|Alias]]` opens notes in Obsidian - Internal: `[[Note]]` or `[[Note|Alias]]` opens notes in Obsidian. Ctrl-click or middle-click opens a new tab; Ctrl-hover shows the page preview.
- Web: `[Text](https://example.com)` opens in your browser - Web: `[Text](https://example.com)` opens in your browser
- File: `[Text](file:///C:/path/to/file)` opens local files or folders - File: `[Text](file:///C:/path/to/file)` opens local files or folders (desktop only). Use `[Text](<file:///C:/path with spaces>)` for paths with spaces.
## Built-in Templates ## Layouts
Choose from five pre-styled layouts: Three built-in layouts, all following your theme's colors:
- `default` — balanced, general-purpose design - `default` — outlined buttons
- `minimal` — clean and understated - `minimal` — plain text links
- `slate` — darker theme with subtle borders - `slate` — filled chips
- `horizon` — horizontal emphasis with gradients
- `aether` — light and airy aesthetic
Add extra classes after the layout name: Add modifiers after the layout name:
- `small` — smaller text and padding
- `grid` — equal-width tiles that fill the row
```code ```code
layout: horizon wide layout: slate small
[[Dashboard]] [[Dashboard]]
[Resources](https://example.com) [Resources](https://example.com)
``` ```
Without a `layout:` line, the menu uses the default layout chosen in the plugin settings.
## Options
Customize any menu with `key: value` lines before the links:
| Option | Effect |
|---|---|
| `text`, `bg`, `border` | Link colors |
| `hover-text`, `hover-bg`, `hover-border` | Hover colors |
| `font` | Font family (quote names with spaces: `"Work Sans"`) |
| `size` | Font size (`0.8em`, `14px`) |
| `gap` | Space between links |
| `radius` | Corner rounding (`99px` for pills) |
| `padding` | Space inside each link (`0.3em 1em`) |
Prefix a color or font option with `internal-`, `external-`, or `file-` to target one link type:
```code
layout: minimal
internal-text: var(--text-accent)
external-text: #ff6600
file-text: #0066ff
[[Internal Link]]
[External Link](https://example.com)
[File Link](file:///C:/Documents)
```
Values are plain CSS: hex, rgb, hsl, gradients, or theme variables like `var(--text-accent)`.
Aliases: `background` = `bg`, `accent` = `hover-text`, `text-hover` = `hover-text`, `bg-hover` = `hover-bg`, `border-hover` = `hover-border`.
## Custom Styling ## Custom Styling
Use your own CSS class to bypass the built-in templates entirely. The plugin only renders the HTML structure and inline CSS variables—no default styles apply. Use `class:` with your own class name instead of a layout. The plugin then applies no built-in styles; it renders the links and sets the options as CSS variables on the container.
Each link also exposes resolved variables (`--mm-text`, `--mm-bg`, `--mm-border`, `--mm-font`, `--mm-hover-text`, `--mm-hover-bg`, `--mm-hover-border`) that already apply the per-link-type options.
```code ```code
class: my-menu class: my-menu
bg: #111
text: #eee text: #eee
hover-text: #0af hover-text: #0af
@@ -52,8 +85,6 @@ hover-text: #0af
[Web](https://example.com) [Web](https://example.com)
``` ```
Then create your own CSS snippet:
```css ```css
.menu-container.my-menu { .menu-container.my-menu {
display: flex; display: flex;
@@ -64,47 +95,16 @@ Then create your own CSS snippet:
.menu-container.my-menu a { .menu-container.my-menu a {
padding: 0.5rem 0.8rem; padding: 0.5rem 0.8rem;
border-radius: 6px; border-radius: 6px;
color: var(--text, var(--text-normal)); text-decoration: none;
background: var(--bg, transparent); color: var(--mm-text, var(--text-normal));
background: var(--mm-bg, transparent);
} }
.menu-container.my-menu a:hover { .menu-container.my-menu a:hover {
color: var(--hover-text, var(--text-accent)); color: var(--mm-hover-text, var(--text-accent));
background: var(--hover-bg, transparent);
} }
``` ```
## Style Variables
Override colors and fonts using YAML-like variables inside the code block. Only these whitelisted properties are supported:
**Global variables:**
- `bg` — background color for buttons
- `text` — text color
- `border` — border color
- `font` — font family
- `hover-text`, `hover-bg`, `hover-border`, `hover-font` — hover state styles
**Per-link-type variables:**
Prefix any global variable with `internal-`, `external-`, or `file-` to target specific link types:
```code
layout: minimal
internal-text: #00ff00
external-text: #ff6600
file-text: #0066ff
[[Internal Link]]
[External Link](https://example.com)
[File Link](file:///C:/Documents)
```
**Accepted formats:**
- Colors: hex (`#1a1a1a`), rgb, hsl, CSS variables (`var(--text-accent)`), gradients
- Fonts: plain names or quoted for spaces (`font: "Work Sans"`)
## Dataview Integration ## Dataview Integration
Generate links dynamically from Dataview queries. Prefix your query with `dataview:` or `dv:`: Generate links dynamically from Dataview queries. Prefix your query with `dataview:` or `dv:`:
@@ -119,10 +119,11 @@ The plugin unwraps Dataview results so links blend seamlessly into your menu lay
## Examples ## Examples
Template with gradient background: Pill buttons with a gradient:
```code ```code
layout: horizon layout: default
radius: 99px
bg: linear-gradient(45deg, #667eea, #764ba2) bg: linear-gradient(45deg, #667eea, #764ba2)
text: white text: white
hover-text: #ffd700 hover-text: #ffd700
@@ -131,13 +132,12 @@ hover-text: #ffd700
[Projects](https://github.com) [Projects](https://github.com)
``` ```
Custom class with theme variables: Compact tile grid:
```code ```code
class: my-toolbar layout: slate small grid
text: var(--text-normal)
hover-text: var(--text-accent)
[[Inbox]] [[Inbox]]
[Wiki](https://example.com) [[Projects]]
[[Areas]]
[[Resources]]
``` ```
+182 -236
View File
@@ -28,271 +28,194 @@ __export(main_exports, {
}); });
module.exports = __toCommonJS(main_exports); module.exports = __toCommonJS(main_exports);
var import_obsidian = require("obsidian"); var import_obsidian = require("obsidian");
var DEFAULT_SETTINGS = { var LAYOUTS = ["default", "minimal", "slate"];
mySetting: "default" var MODIFIERS = /* @__PURE__ */ new Set(["small", "grid"]);
var LINK_KEYS = /* @__PURE__ */ new Set(["text", "bg", "border", "font", "hover-text", "hover-bg", "hover-border"]);
var MENU_KEYS = /* @__PURE__ */ new Set(["size", "gap", "radius", "padding"]);
var KEY_ALIASES = {
"background": "bg",
"accent": "hover-text",
"text-hover": "hover-text",
"bg-hover": "hover-bg",
"border-hover": "hover-border"
}; };
var HOVER_SOURCE = "monster-menus";
var DEFAULT_SETTINGS = {
defaultLayout: "default"
};
function normalizeKey(raw) {
var _a;
const match = raw.trim().toLowerCase().match(/^(?:(internal|external|file)-)?(.+)$/);
if (!match)
return null;
const prefix = match[1] ? `${match[1]}-` : "";
const key = (_a = KEY_ALIASES[match[2]]) != null ? _a : match[2];
if (LINK_KEYS.has(key))
return prefix + key;
if (!prefix && MENU_KEYS.has(key))
return key;
return null;
}
var MenuPlugin = class extends import_obsidian.Plugin { var MenuPlugin = class extends import_obsidian.Plugin {
async onload() { async onload() {
try {
await this.loadSettings(); await this.loadSettings();
this.addSettingTab(new MenuPluginSettingTab(this.app, this)); this.addSettingTab(new MenuPluginSettingTab(this.app, this));
this.registerHoverLinkSource(HOVER_SOURCE, { display: "Monster Menus", defaultMod: true });
this.registerMarkdownCodeBlockProcessor("menu", (source, el, ctx) => { this.registerMarkdownCodeBlockProcessor("menu", (source, el, ctx) => {
this.processMenuBlock(source, el, ctx); this.processMenuBlock(source, el, ctx);
}); });
} catch (error) {
console.error("[obsidian-menus] Failed to load plugin:", error);
throw error;
}
}
onunload() {
} }
async loadSettings() { async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); const data = await this.loadData();
const saved = data == null ? void 0 : data.defaultLayout;
this.settings = {
defaultLayout: LAYOUTS.includes(saved) ? saved : DEFAULT_SETTINGS.defaultLayout
};
} }
async saveSettings() { async saveSettings() {
await this.saveData(this.settings); await this.saveData(this.settings);
} }
processMenuBlock(source, el, ctx) { processMenuBlock(source, el, ctx) {
const lines = source.trim().split("\n");
let layoutOrClass = ""; let layoutOrClass = "";
let colors = {}; const options = {};
const links = []; const links = [];
let dataviewQuery = ""; let dataviewQuery = "";
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) {
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) {
dataviewQuery += "\n" + line;
}
}
layoutOrClass = "";
colors = {};
links.length = 0;
dataviewQuery = "";
let isDataviewBlock = false; let isDataviewBlock = false;
for (const line of lines) { for (const line of source.trim().split("\n")) {
const trimmed = line.trim(); const trimmed = line.trim();
if (isDataviewBlock) { if (isDataviewBlock) {
dataviewQuery += "\n" + line; dataviewQuery += "\n" + line;
continue; continue;
} }
if (trimmed.startsWith("layout:") || trimmed.startsWith("class:")) { if (trimmed.startsWith("layout:") || trimmed.startsWith("class:")) {
const colonIndex = trimmed.indexOf(":"); layoutOrClass = trimmed.substring(trimmed.indexOf(":") + 1).trim();
layoutOrClass = trimmed.substring(colonIndex + 1).trim();
} else if (trimmed.startsWith("dataview:") || trimmed.startsWith("dv:")) { } else if (trimmed.startsWith("dataview:") || trimmed.startsWith("dv:")) {
const colonIndex = trimmed.indexOf(":"); dataviewQuery = trimmed.substring(trimmed.indexOf(":") + 1).trim();
dataviewQuery = trimmed.substring(colonIndex + 1).trim();
isDataviewBlock = true; isDataviewBlock = true;
} else if (trimmed.includes(":") && !trimmed.startsWith("[") && !trimmed.startsWith("[[")) { } else if (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) {
links.push(trimmed); 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;
} }
} }
const builtInLayouts = /* @__PURE__ */ new Set(["default", "minimal", "slate", "horizon", "aether"]);
const container = el.createEl("div", { cls: "menu-container" });
let selectedLayout = "";
let extraClasses = [];
if (layoutOrClass) {
const tokens = layoutOrClass.split(/\s+/).filter(Boolean); const tokens = layoutOrClass.split(/\s+/).filter(Boolean);
if (tokens.length) { let layout = tokens.find((t) => LAYOUTS.includes(t));
const builtInIndex = tokens.findIndex((t) => builtInLayouts.has(t)); if (!layout && tokens.every((t) => MODIFIERS.has(t))) {
if (builtInIndex !== -1) { layout = this.settings.defaultLayout;
selectedLayout = tokens[builtInIndex];
extraClasses = tokens.filter((_, i) => i !== builtInIndex);
} else {
extraClasses = tokens;
} }
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);
} }
} else { for (const [key, value] of Object.entries(options)) {
selectedLayout = "default";
}
if (selectedLayout) {
container.setAttr("data-layout", selectedLayout);
}
for (const cls of extraClasses) {
container.addClass(cls);
}
if (Object.keys(colors).length > 0) {
const baseKeys = /* @__PURE__ */ new Set([
"bg",
"text",
"border",
"font",
"hover-text",
"hover-bg",
"hover-border",
"hover-font"
]);
const normalizeKey = (raw) => {
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) => {
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); container.style.setProperty(`--${key}`, value);
} }
} const sourcePath = ctx.sourcePath;
const applyInlineBaseStyles = (a, variant) => { const hoverParent = { hoverPopover: null };
const prefix = variant === "generic" ? "" : `${variant}-`;
const get = (k) => {
var _a;
return (_a = colors[`${prefix}${k}`]) != null ? _a : colors[k];
};
const bgVal = get("bg");
if (bgVal)
a.style.background = bgVal;
const textVal = get("text");
if (textVal)
a.style.color = textVal;
const borderVal = get("border");
if (borderVal)
a.style.borderColor = borderVal;
const fontVal = get("font");
if (fontVal)
a.style.fontFamily = fontVal;
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);
}
};
for (const link of links) { for (const link of links) {
if (link.startsWith("[[") && link.endsWith("]]")) { const wiki = link.match(/^\[\[(.+)\]\]$/);
const linkContent = link.slice(2, -2); if (wiki) {
let href = linkContent; const [target, alias] = wiki[1].split("|");
let text = linkContent; this.createInternalLink(container, target.trim(), (alias != null ? alias : target).trim(), sourcePath, hoverParent);
if (linkContent.includes("|")) { continue;
[href, text] = linkContent.split("|");
} }
const markdown = link.match(/^\[(.*)\]\((.*)\)$/);
if (!markdown)
continue;
const text = markdown[1];
const url = markdown[2].trim().replace(/^<(.*)>$/, "$1").trim();
if (url.startsWith("file://")) {
this.createFileLink(container, text, url);
} else {
const a = container.createEl("a", { const a = container.createEl("a", {
text, text,
attr: { "data-href": href } 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) => { a.addEventListener("click", (e) => {
e.preventDefault(); e.preventDefault();
let sourcePath = ctx == null ? void 0 : 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);
}
});
} else if (link.match(/^\[.*\]\(.*\)$/)) {
const match = link.match(/^\[(.*)\]\((.*)\)$/);
if (match) {
const text = match[1];
const url = match[2];
const a = container.createEl("a", {
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 (import_obsidian.Platform.isDesktop) {
try {
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"); window.open(url, "_blank", "noopener,noreferrer");
}
}); });
} }
} }
}
if (dataviewQuery) { if (dataviewQuery) {
this.renderDataview(container, dataviewQuery, ctx);
}
}
createInternalLink(container, target, text, sourcePath, hoverParent) {
const a = container.createEl("a", {
text,
cls: "menu-internal-link",
attr: { href: target, "data-href": target }
});
const open = (newLeaf) => {
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(import_obsidian.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
});
});
}
createFileLink(container, text, url) {
const a = container.createEl("a", { text, cls: "menu-file-link", attr: { href: url } });
a.addEventListener("click", (e) => {
e.preventDefault();
if (!import_obsidian.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);
}
const { shell } = require("electron");
shell.openPath(filePath).then((error) => {
if (error)
console.error("[monster-menus] Failed to open file:", filePath, error);
});
});
}
renderDataview(container, query, ctx) {
const dvContainer = container.createDiv({ cls: "menu-dataview-container" }); const dvContainer = container.createDiv({ cls: "menu-dataview-container" });
import_obsidian.MarkdownRenderer.render( const component = new import_obsidian.MarkdownRenderChild(dvContainer);
this.app, ctx.addChild(component);
`\`\`\`dataview import_obsidian.MarkdownRenderer.render(this.app, `\`\`\`dataview
${dataviewQuery} ${query}
\`\`\``, \`\`\``, dvContainer, ctx.sourcePath, component);
dvContainer, const tagLinks = () => {
ctx.sourcePath, dvContainer.querySelectorAll("a:not(.menu-internal-link, .menu-external-link)").forEach((link) => {
this link.addClass(link.hasClass("internal-link") ? "menu-internal-link" : "menu-external-link");
);
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === "childList") {
const links2 = dvContainer.querySelectorAll("a");
links2.forEach((link) => {
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");
}
});
}
}
}); });
};
const observer = new MutationObserver(tagLinks);
observer.observe(dvContainer, { childList: true, subtree: true }); observer.observe(dvContainer, { childList: true, subtree: true });
} component.register(() => observer.disconnect());
tagLinks();
} }
}; };
var MenuPluginSettingTab = class extends import_obsidian.PluginSettingTab { var MenuPluginSettingTab = class extends import_obsidian.PluginSettingTab {
@@ -303,36 +226,59 @@ var MenuPluginSettingTab = class extends import_obsidian.PluginSettingTab {
display() { display() {
const { containerEl } = this; const { containerEl } = this;
containerEl.empty(); containerEl.empty();
containerEl.createEl("h2", { text: "Menu Plugin Settings" }); new import_obsidian.Setting(containerEl).setName("Default layout").setDesc("Layout used when a menu block has no layout: line.").addDropdown((dropdown) => {
new import_obsidian.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) => { for (const layout of LAYOUTS) {
this.plugin.settings.mySetting = value; dropdown.addOption(layout, layout.charAt(0).toUpperCase() + layout.slice(1));
}
dropdown.setValue(this.plugin.settings.defaultLayout).onChange(async (value) => {
this.plugin.settings.defaultLayout = value;
await this.plugin.saveSettings(); await this.plugin.saveSettings();
})); });
containerEl.createEl("hr"); });
containerEl.createEl("h3", { text: "Usage Guide" }); new import_obsidian.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" }); doc.createEl("h4", { text: "Example" });
const pre = doc.createEl("pre"); const pre = doc.createEl("pre");
pre.createEl("code", { pre.createEl("code", {
text: `\`\`\`menu text: `\`\`\`menu
layout: slate layout: slate small
bg: #333 hover-text: #0af
text: white radius: 99px
[[Internal Link]] [[Internal Link]]
[External Link](https://example.com) [External Link](https://example.com)
[File Link](file:///C:/Documents)
\`\`\`` \`\`\``
}); });
doc.createEl("h4", { text: "Supported Properties" }); doc.createEl("h4", { text: "Link types" });
const ul = doc.createEl("ul"); const linkTable = doc.createEl("table", { cls: "menu-settings-table" });
ul.createEl("li", { text: "layout: default, minimal, slate, horizon, aether" }); const addRow = (syntax, description) => {
ul.createEl("li", { text: "class: custom CSS classes" }); const tr = linkTable.createEl("tr");
ul.createEl("li", { text: "colors: bg, text, border, font (supports hover- prefix)" }); tr.createEl("td", { text: syntax, cls: "menu-settings-syntax" });
doc.createEl("h4", { text: "Link Types" }); tr.createEl("td", { text: description });
const ul2 = doc.createEl("ul"); };
ul2.createEl("li", { text: "[[Internal Link]] - Opens Obsidian note" }); addRow("[[Note]]", "Opens an Obsidian note (Ctrl-click or middle-click: new tab)");
ul2.createEl("li", { text: "[External Link](https://...) - Opens in browser" }); addRow("[[Note|Alias]]", "Obsidian note with custom display text");
ul2.createEl("li", { text: "[File Link](file://...) - Opens local file/folder" }); 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, values, description) => {
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)");
} }
}; };
// Annotate the CommonJS export names for ESM import in node: // Annotate the CommonJS export names for ESM import in node:
+193 -266
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 { interface MenuPluginSettings {
mySetting: string; defaultLayout: Layout;
} }
const DEFAULT_SETTINGS: MenuPluginSettings = { 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 { export default class MenuPlugin extends Plugin {
settings: MenuPluginSettings; settings: MenuPluginSettings;
async onload() { async onload() {
try {
await this.loadSettings(); 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.addSettingTab(new MenuPluginSettingTab(this.app, this));
this.registerHoverLinkSource(HOVER_SOURCE, { display: 'Monster Menus', defaultMod: true });
this.registerMarkdownCodeBlockProcessor('menu', (source, el, ctx) => { this.registerMarkdownCodeBlockProcessor('menu', (source, el, ctx) => {
this.processMenuBlock(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
} }
async loadSettings() { 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() { async saveSettings() {
@@ -40,53 +62,13 @@ export default class MenuPlugin extends Plugin {
} }
private processMenuBlock(source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) { private processMenuBlock(source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) {
const lines = source.trim().split('\n');
let layoutOrClass = ''; let layoutOrClass = '';
let colors: Record<string, string> = {}; const options: Record<string, string> = {};
const links: string[] = []; const links: string[] = [];
let dataviewQuery = ''; 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; let isDataviewBlock = false;
for (const line of lines) { for (const line of source.trim().split('\n')) {
const trimmed = line.trim(); const trimmed = line.trim();
if (isDataviewBlock) { if (isDataviewBlock) {
dataviewQuery += '\n' + line; dataviewQuery += '\n' + line;
@@ -94,217 +76,142 @@ export default class MenuPlugin extends Plugin {
} }
if (trimmed.startsWith('layout:') || trimmed.startsWith('class:')) { if (trimmed.startsWith('layout:') || trimmed.startsWith('class:')) {
const colonIndex = trimmed.indexOf(':'); layoutOrClass = trimmed.substring(trimmed.indexOf(':') + 1).trim();
layoutOrClass = trimmed.substring(colonIndex + 1).trim();
} else if (trimmed.startsWith('dataview:') || trimmed.startsWith('dv:')) { } else if (trimmed.startsWith('dataview:') || trimmed.startsWith('dv:')) {
const colonIndex = trimmed.indexOf(':'); dataviewQuery = trimmed.substring(trimmed.indexOf(':') + 1).trim();
dataviewQuery = trimmed.substring(colonIndex + 1).trim(); isDataviewBlock = true; // The rest of the block is the query
isDataviewBlock = true; // Assume rest of block is the query } else if (trimmed.startsWith('[')) {
} 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) {
links.push(trimmed); 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 // A built-in layout name selects the layout; other tokens become CSS classes.
const builtInLayouts = new Set(['default', 'minimal', 'slate', 'horizon', 'aether']); // Without a built-in layout, the menu is unstyled (custom class mode),
const container = el.createEl('div', { cls: 'menu-container' }); // unless the only tokens are modifiers such as `small` or `grid`.
let selectedLayout = '';
let extraClasses: string[] = [];
if (layoutOrClass) {
const tokens = layoutOrClass.split(/\s+/).filter(Boolean); const tokens = layoutOrClass.split(/\s+/).filter(Boolean);
if (tokens.length) { let layout = tokens.find((t): t is Layout => (LAYOUTS as readonly string[]).includes(t));
const builtInIndex = tokens.findIndex(t => builtInLayouts.has(t)); if (!layout && tokens.every(t => MODIFIERS.has(t))) {
if (builtInIndex !== -1) { layout = this.settings.defaultLayout;
selectedLayout = tokens[builtInIndex];
extraClasses = tokens.filter((_, i) => i !== builtInIndex);
} else {
extraClasses = tokens;
}
}
} else {
selectedLayout = 'default';
} }
if (selectedLayout) { const container = el.createDiv({ cls: 'menu-container' });
container.setAttr('data-layout', selectedLayout); 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)) {
for (const cls of extraClasses) {
container.addClass(cls);
}
// 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); container.style.setProperty(`--${key}`, value);
} }
}
const applyInlineBaseStyles = (a: HTMLElement, variant: 'internal' | 'external' | 'file' | 'generic') => { const sourcePath = ctx.sourcePath;
const prefix = variant === 'generic' ? '' : `${variant}-`; const hoverParent: HoverParent = { hoverPopover: null as HoverPopover | null };
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) { for (const link of links) {
if (link.startsWith('[[') && link.endsWith(']]')) { const wiki = link.match(/^\[\[(.+)\]\]$/);
const linkContent = link.slice(2, -2); if (wiki) {
let href = linkContent; const [target, alias] = wiki[1].split('|');
let text = linkContent; this.createInternalLink(container, target.trim(), (alias ?? target).trim(), sourcePath, hoverParent);
if (linkContent.includes('|')) { continue;
[href, text] = linkContent.split('|');
} }
const a = container.createEl('a', {
text: text,
attr: { 'data-href': href }
});
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);
}
});
} 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';
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://')) { if (url.startsWith('file://')) {
a.addClass('menu-file-link'); this.createFileLink(container, text, url);
if (!selectedLayout) applyInlineBaseStyles(a, 'file');
} else { } else {
a.addClass('menu-external-link'); const a = container.createEl('a', {
if (!selectedLayout) applyInlineBaseStyles(a, 'external'); text,
} cls: 'menu-external-link',
attr: { href: url, target: '_blank', rel: 'noopener noreferrer' }
});
a.addEventListener('click', (e) => { a.addEventListener('click', (e) => {
e.preventDefault(); e.preventDefault();
if (url.startsWith('file://')) { window.open(url, '_blank', 'noopener,noreferrer');
if (Platform.isDesktop) { });
try { }
// Use dynamic import with proper error handling }
const electronPath = 'electron';
const { shell } = require(electronPath); if (dataviewQuery) {
let filePath = decodeURIComponent(url.substring(7)); 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) === ':') { if (filePath.startsWith('/') && filePath.charAt(2) === ':') {
filePath = filePath.substring(1); filePath = filePath.substring(1);
} }
shell.openPath(filePath); // eslint-disable-next-line @typescript-eslint/no-var-requires
} catch (error) { const { shell } = require('electron');
console.error('Failed to open file:', error); shell.openPath(filePath).then((error: string) => {
} if (error) console.error('[monster-menus] Failed to open file:', filePath, error);
} else { });
console.warn('File links are not supported on mobile.');
}
} else {
window.open(url, '_blank', 'noopener,noreferrer');
}
}); });
} }
}
}
// Process Dataview Query private renderDataview(container: HTMLElement, query: string, ctx: MarkdownPostProcessorContext) {
if (dataviewQuery) {
const dvContainer = container.createDiv({ cls: 'menu-dataview-container' }); const dvContainer = container.createDiv({ cls: 'menu-dataview-container' });
// Render the dataview query const component = new MarkdownRenderChild(dvContainer);
// We wrap it in ```dataview ... ``` so Obsidian's renderer handles it ctx.addChild(component);
MarkdownRenderer.render( MarkdownRenderer.render(this.app, `\`\`\`dataview\n${query}\n\`\`\``, dvContainer, ctx.sourcePath, component);
this.app,
`\`\`\`dataview\n${dataviewQuery}\n\`\`\``,
dvContainer,
ctx.sourcePath,
this
);
// MutationObserver to style links once they render // Dataview renders asynchronously; tag its links so per-link-type options apply.
const observer = new MutationObserver((mutations) => { const tagLinks = () => {
for (const mutation of mutations) { dvContainer.querySelectorAll('a:not(.menu-internal-link, .menu-external-link)').forEach((link) => {
if (mutation.type === 'childList') { link.addClass(link.hasClass('internal-link') ? 'menu-internal-link' : 'menu-external-link');
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');
}
}); });
} };
} const observer = new MutationObserver(tagLinks);
});
observer.observe(dvContainer, { childList: true, subtree: true }); observer.observe(dvContainer, { childList: true, subtree: true });
} component.register(() => observer.disconnect());
tagLinks();
} }
} }
@@ -321,48 +228,68 @@ class MenuPluginSettingTab extends PluginSettingTab {
containerEl.empty(); containerEl.empty();
containerEl.createEl('h2', { text: 'Menu Plugin Settings' });
new Setting(containerEl) new Setting(containerEl)
.setName('Setting #1') .setName('Default layout')
.setDesc('It\'s a secret') .setDesc('Layout used when a menu block has no layout: line.')
.addText(text => text .addDropdown(dropdown => {
.setPlaceholder('Enter your secret') for (const layout of LAYOUTS) {
.setValue(this.plugin.settings.mySetting) dropdown.addOption(layout, layout.charAt(0).toUpperCase() + layout.slice(1));
}
dropdown
.setValue(this.plugin.settings.defaultLayout)
.onChange(async (value) => { .onChange(async (value) => {
this.plugin.settings.mySetting = value; this.plugin.settings.defaultLayout = value as Layout;
await this.plugin.saveSettings(); await this.plugin.saveSettings();
})); });
});
// --- Documentation Section --- new Setting(containerEl).setName('Usage guide').setHeading();
containerEl.createEl('hr');
containerEl.createEl('h3', { text: 'Usage Guide' });
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' }); doc.createEl('h4', { text: 'Example' });
const pre = doc.createEl('pre'); const pre = doc.createEl('pre');
pre.createEl('code', { pre.createEl('code', {
text: `\`\`\`menu text: `\`\`\`menu
layout: slate layout: slate small
bg: #333 hover-text: #0af
text: white radius: 99px
[[Internal Link]] [[Internal Link]]
[External Link](https://example.com) [External Link](https://example.com)
[File Link](file:///C:/Documents)
\`\`\``}); \`\`\``});
doc.createEl('h4', { text: 'Supported Properties' }); doc.createEl('h4', { text: 'Link types' });
const ul = doc.createEl('ul'); const linkTable = doc.createEl('table', { cls: 'menu-settings-table' });
ul.createEl('li', { text: 'layout: default, minimal, slate, horizon, aether' }); const addRow = (syntax: string, description: string) => {
ul.createEl('li', { text: 'class: custom CSS classes' }); const tr = linkTable.createEl('tr');
ul.createEl('li', { text: 'colors: bg, text, border, font (supports hover- prefix)' }); 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' }); doc.createEl('h4', { text: 'Options' });
const ul2 = doc.createEl('ul'); const propTable = doc.createEl('table', { cls: 'menu-settings-table' });
ul2.createEl('li', { text: '[[Internal Link]] - Opens Obsidian note' }); const addProp = (prop: string, values: string, description: string) => {
ul2.createEl('li', { text: '[External Link](https://...) - Opens in browser' }); const tr = propTable.createEl('tr');
ul2.createEl('li', { text: '[File Link](file://...) - Opens local file/folder' }); 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)');
} }
} }
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"id": "monster-menus", "id": "monster-menus",
"name": "Monster Menus", "name": "Monster Menus",
"version": "1.4.1", "version": "2.0.0",
"minAppVersion": "0.15.0", "minAppVersion": "0.15.0",
"description": "Create custom menus using code blocks with links and CSS styling.", "description": "Create custom menus using code blocks with links and CSS styling.",
"author": "Olivier Legendre", "author": "Olivier Legendre",
-73
View File
@@ -1,73 +0,0 @@
import { Plugin, MarkdownPostProcessorContext, TFile, Vault } from 'obsidian';
// Node.js shell module for opening files/folders
const { shell } = require('electron');
export default class MenuPlugin extends Plugin {
async onload() {
this.registerMarkdownCodeBlockProcessor('menu', this.menuProcessor.bind(this));
}
async menuProcessor(source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) {
// Parse optional class from first line
let lines = source.split('\n').map(l => l.trim()).filter(Boolean);
let menuClass = 'menu-container';
if (lines[0]?.startsWith('class:')) {
menuClass += ' ' + lines[0].replace('class:', '').trim();
lines = lines.slice(1);
}
const container = el.createDiv({ cls: menuClass });
for (const line of lines) {
let match;
// Internal Obsidian link: [[file|alias]]
if ((match = line.match(/^\[\[(.+?)(\|(.+?))?]]$/))) {
const fileName = match[1];
const alias = match[3] || match[1];
const a = container.createEl('a', { text: alias, cls: 'internal-link' });
a.setAttr('data-href', fileName);
a.addEventListener('click', (e) => {
e.preventDefault();
this.app.workspace.openLinkText(fileName, ctx.sourcePath);
});
continue;
}
// Markdown link: [text](url)
if ((match = line.match(/^\[(.+?)]\((.+?)\)$/))) {
const text = match[1];
const url = match[2];
// Local file/folder (file:/// or absolute path)
if (url.startsWith('file:///') || url.match(/^([a-zA-Z]:\\|\\\\)/)) {
const a = container.createEl('a', { text });
a.style.cursor = 'pointer';
a.addEventListener('click', (e) => {
e.preventDefault();
// Remove file:/// if present
let path = url.replace('file:///', '');
// Decode URI
path = decodeURIComponent(path);
shell.openPath(path);
});
} else if (url.startsWith('http')) {
// Web link
const a = container.createEl('a', { text });
a.href = url;
a.target = '_blank';
a.rel = 'noopener noreferrer';
a.style.cursor = 'pointer';
} else {
// Try to open as vault file
const a = container.createEl('a', { text });
a.style.cursor = 'pointer';
a.addEventListener('click', (e) => {
e.preventDefault();
this.app.workspace.openLinkText(url, ctx.sourcePath);
});
}
continue;
}
// Plain text fallback
container.createEl('span', { text: line });
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "menu-plugin", "name": "menu-plugin",
"version": "1.0.0", "version": "2.0.0",
"description": "Create custom menus using code blocks with links and CSS styling.", "description": "Create custom menus using code blocks with links and CSS styling.",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
+192 -358
View File
@@ -1,19 +1,37 @@
/* Special styles to hide the border and </> icon on hover */ /* Editor: hide the code-block border and </> button.
The block's 0.5rem left edge stays clickable to enter edit mode.
Newer Obsidian (seen in 1.14.4) wraps the button in .embed-actions (absolute, top-right);
older versions position .edit-block-button itself. Both are handled.
Button placement applies outside :hover too: Obsidian fades .embed-actions out
after hover ends, and the icon must not reappear at its default spot meanwhile. */
.markdown-source-view.mod-cm6 .cm-embed-block:not(.cm-table-widget, .cm-lang-base):has(.menu-container[data-layout]):hover { .markdown-source-view.mod-cm6 .cm-embed-block:not(.cm-table-widget, .cm-lang-base):has(.menu-container) {
&:hover {
border-width: 0; border-width: 0;
outline: 0;
box-shadow: var(--background-primary) 0 0 0 1px inset !important; box-shadow: var(--background-primary) 0 0 0 1px inset !important;
background-color: transparent !important; background-color: transparent !important;
outline: 1px solid transparent; outline: 1px solid transparent;
}
.embed-actions {
top: 0;
bottom: 0;
left: 0;
right: auto;
width: 0.5rem;
gap: 0;
.edit-block-button { .edit-block-button {
top: 0em; height: 100%;
}
}
.edit-block-button {
top: 0;
bottom: 0; bottom: 0;
left: 0; left: 0;
width: 0.5rem; width: 0.5rem;
padding: 0; padding: 0;
cursor: help; cursor: help;
svg { svg {
@@ -22,397 +40,213 @@
} }
} }
.menu-container[data-layout], /*
.menu-container[data-layout] a { •·················•·················•
transition: 125ms; | Variable resolution |
•·················•·················•
Every menu link resolves its final values into --mm-* variables:
per-link-type option (internal-text) → global option (text) → layout default (--d-text).
Built-in layouts consume --mm-*; custom `class:` menus may use them too.
*/
.menu-container a.menu-internal-link {
--_text: var(--internal-text);
--_bg: var(--internal-bg);
--_border: var(--internal-border);
--_font: var(--internal-font);
--_hover-text: var(--internal-hover-text);
--_hover-bg: var(--internal-hover-bg);
--_hover-border: var(--internal-hover-border);
}
.menu-container a.menu-external-link {
--_text: var(--external-text);
--_bg: var(--external-bg);
--_border: var(--external-border);
--_font: var(--external-font);
--_hover-text: var(--external-hover-text);
--_hover-bg: var(--external-hover-bg);
--_hover-border: var(--external-hover-border);
}
.menu-container a.menu-file-link {
--_text: var(--file-text);
--_bg: var(--file-bg);
--_border: var(--file-border);
--_font: var(--file-font);
--_hover-text: var(--file-hover-text);
--_hover-bg: var(--file-hover-bg);
--_hover-border: var(--file-hover-border);
}
.menu-container a {
--mm-text: var(--_text, var(--text, var(--d-text)));
--mm-bg: var(--_bg, var(--bg, var(--d-bg)));
--mm-border: var(--_border, var(--border, var(--d-border)));
--mm-font: var(--_font, var(--font, inherit));
--mm-hover-text: var(--_hover-text, var(--hover-text, var(--d-hover-text, var(--mm-text))));
--mm-hover-bg: var(--_hover-bg, var(--hover-bg, var(--d-hover-bg, var(--mm-bg))));
--mm-hover-border: var(--_hover-border, var(--hover-border, var(--d-hover-border, var(--mm-border))));
} }
/* /*
•·················•·················• •·················•·················•
| Menu Container Styles | | Built-in layouts |
•·················•·················• •·················•·················•
*/ */
/* Default style variant */ .menu-container[data-layout] {
.menu-container[data-layout='default']:has(:not(.menu-dataview-container)),
.menu-container[data-layout='default'] .menu-dataview-container {
display: flex; display: flex;
--gap: 0.7em;
gap: var(--gap);
flex-wrap: wrap; flex-wrap: wrap;
border-radius: 6px; gap: var(--gap, var(--d-gap));
font-family: var(--font, inherit); font-size: var(--size, var(--d-size));
/* ul.list-view-ul {
gap: 2em !important;
} */
a { a {
padding: 0.6em 1em; padding: var(--padding, var(--d-padding));
border-radius: var(--radius, var(--d-radius));
border: 1px solid var(--mm-border);
color: var(--mm-text);
background: var(--mm-bg);
font-family: var(--mm-font);
font-weight: var(--d-weight);
line-height: 1.3;
text-decoration: none; text-decoration: none;
border-radius: 4px; cursor: pointer;
transition: all 0.2s ease; transition: color 120ms ease, background-color 120ms ease, border-color 120ms ease;
font-weight: 500;
border: 1px solid var(--border, var(--background-modifier-border));
color: var(--text, var(--text-normal));
background: var(--bg, var(--background-primary));
font-family: var(--font, inherit);
&:hover { &:hover {
color: var(--hover-text, var(--accent, var(--text-accent))); color: var(--mm-hover-text);
border-color: var(--hover-border, var(--accent, var(--text-accent))); background: var(--mm-hover-bg);
background: var(--hover-bg, transparent); border-color: var(--mm-hover-border);
}
&.menu-internal-link {
color: var(--internal-text, var(--text, var(--text-normal)));
border-color: var(--internal-border, var(--border, var(--background-modifier-border)));
background: var(--internal-bg, var(--bg, var(--background-primary)));
font-family: var(--internal-font, var(--font, inherit));
&:hover {
color: var(--internal-hover-text, var(--internal-accent, var(--hover-text, var(--accent, var(--text-accent)))));
border-color: var(--internal-hover-border, var(--hover-border, var(--accent, var(--text-accent))));
background: var(--internal-hover-bg, var(--hover-bg, transparent));
}
}
&.menu-external-link {
color: var(--external-text, var(--text, var(--text-normal)));
border-color: var(--external-border, var(--border, var(--background-modifier-border)));
background: var(--external-bg, var(--bg, var(--background-primary)));
font-family: var(--external-font, var(--font, inherit));
&:hover {
color: var(--external-hover-text, var(--external-accent, var(--hover-text, var(--accent, var(--text-accent)))));
border-color: var(--external-hover-border, var(--hover-border, var(--accent, var(--text-accent))));
background: var(--external-hover-bg, var(--hover-bg, transparent));
}
}
&.menu-file-link {
color: var(--file-text, var(--text, var(--text-normal)));
border-color: var(--file-border, var(--border, var(--background-modifier-border)));
background: var(--file-bg, var(--bg, var(--background-primary)));
font-family: var(--file-font, var(--font, inherit));
&:hover {
color: var(--file-hover-text, var(--file-accent, var(--hover-text, var(--accent, var(--text-accent)))));
border-color: var(--file-hover-border, var(--hover-border, var(--accent, var(--text-accent))));
background: var(--file-hover-bg, var(--hover-bg, transparent));
}
}
}
&.wide a {
flex-grow: 1;
flex-basis: 150px;
text-align: center;
}
}
/* .menu-file-link
.menu-external-link
.menu-internal-link */
/* Minimal style variant */
.menu-container[data-layout='minimal']:has(:not(.menu-dataview-container)),
.menu-container[data-layout='minimal'] .menu-dataview-container {
display: flex;
--gap: 0.2em;
gap: var(--gap);
flex-wrap: wrap;
transition: 125ms;
font-family: var(--font, inherit);
a {
padding: 0.4em 0.8em;
text-decoration: none; text-decoration: none;
border-radius: 3px;
transition: color 0.15s ease;
font-size: 0.9em;
font-weight: normal;
color: var(--text, var(--text-normal));
background: var(--bg, transparent);
font-family: var(--font, inherit);
&:hover {
background: var(--hover-bg, var(--background-secondary));
color: var(--hover-text, var(--accent, var(--text-accent)));
} }
&.menu-internal-link { &:focus-visible {
color: var(--internal-text, var(--internal, var(--text-accent))); outline: 2px solid var(--interactive-accent);
font-family: var(--internal-font, var(--font, inherit)); outline-offset: 2px;
&:hover {
color: var(--internal-hover-text, var(--internal-accent, var(--hover-text, var(--internal-hover, var(--text-accent-hover)))));
background: var(--internal-hover-bg, var(--hover-bg, var(--background-secondary)));
}
}
&.menu-external-link {
color: var(--external-text, var(--external, var(--text-faint)));
font-family: var(--external-font, var(--font, inherit));
&:hover {
color: var(--external-hover-text, var(--external-accent, var(--hover-text, var(--external-hover, var(--text-normal)))));
background: var(--external-hover-bg, var(--hover-bg, var(--background-secondary)));
}
}
&.menu-file-link {
color: var(--file-text, var(--file, var(--text-faint)));
font-family: var(--file-font, var(--font, inherit));
&:hover {
color: var(--file-hover-text, var(--file-accent, var(--hover-text, var(--file-hover, var(--text-normal)))));
background: var(--file-hover-bg, var(--hover-bg, var(--background-secondary)));
}
} }
} }
} }
/* Minimal style variant */ /* default — outlined buttons */
.menu-container[data-layout='slate']:has(:not(.menu-dataview-container)), .menu-container[data-layout='default'] {
.menu-container[data-layout='slate'] .menu-dataview-container { --d-text: var(--text-normal);
display: flex; --d-bg: var(--background-primary);
--gap: 0.2em; --d-border: var(--background-modifier-border);
gap: var(--gap); --d-hover-text: var(--text-accent);
flex-wrap: wrap; --d-hover-border: var(--text-accent);
font-family: var(--font, inherit); --d-gap: 0.5em;
--d-size: 1em;
a { --d-padding: 0.5em 1em;
padding: 0.4em 0.8em; --d-radius: var(--radius-s, 4px);
text-decoration: none; --d-weight: 500;
border-radius: 3px;
transition: color 0.15s ease;
font-size: 0.9em;
font-weight: normal;
background: var(--bg, var(--background-secondary));
border: 1px solid var(--border, var(--background-secondary));
color: var(--text, var(--text-faint));
font-family: var(--font, inherit);
&:hover {
background: var(--hover-bg, var(--background-secondary));
color: var(--hover-text, var(--accent, var(--text-accent)));
border: 1px solid var(--hover-border, var(--accent, var(--text-accent)));
}
&.menu-internal-link {
color: var(--internal-text, var(--text, var(--text-faint)));
border-color: var(--internal-border, var(--border, var(--background-secondary)));
background: var(--internal-bg, var(--bg, var(--background-secondary)));
font-family: var(--internal-font, var(--font, inherit));
&:hover {
color: var(--internal-hover-text, var(--internal-accent, var(--hover-text, var(--accent, var(--text-accent)))));
border-color: var(--internal-hover-border, var(--hover-border, var(--accent, var(--text-accent))));
background: var(--internal-hover-bg, var(--hover-bg, var(--background-secondary)));
}
}
&.menu-external-link {
color: var(--external-text, var(--text, var(--text-faint)));
border-color: var(--external-border, var(--border, var(--background-secondary)));
background: var(--external-bg, var(--bg, var(--background-secondary)));
font-family: var(--external-font, var(--font, inherit));
&:hover {
color: var(--external-hover-text, var(--external-accent, var(--hover-text, var(--accent, var(--text-accent)))));
border-color: var(--external-hover-border, var(--hover-border, var(--accent, var(--text-accent))));
background: var(--external-hover-bg, var(--hover-bg, var(--background-secondary)));
}
}
&.menu-file-link {
color: var(--file-text, var(--text, var(--text-faint)));
border-color: var(--file-border, var(--border, var(--background-secondary)));
background: var(--file-bg, var(--bg, var(--background-secondary)));
font-family: var(--file-font, var(--font, inherit));
&:hover {
color: var(--file-hover-text, var(--file-accent, var(--hover-text, var(--accent, var(--text-accent)))));
border-color: var(--file-hover-border, var(--hover-border, var(--accent, var(--text-accent))));
background: var(--file-hover-bg, var(--hover-bg, var(--background-secondary)));
}
}
}
} }
/* minimal — plain text links */
.menu-container[data-layout='horizon'] { .menu-container[data-layout='minimal'] {
display: flex; --d-text: var(--text-muted);
--gap: 0.5em; --d-bg: transparent;
gap: var(--gap); --d-border: transparent;
flex-wrap: wrap; --d-hover-text: var(--text-normal);
border-radius: 8px; --d-hover-bg: var(--background-modifier-hover);
font-family: var(--font, 'Space Grotesk', Inter, sans-serif); --d-gap: 0.25em;
--d-size: 0.95em;
a { --d-padding: 0.3em 0.6em;
font-family: var(--font, 'Space Grotesk', Inter, sans-serif); --d-radius: var(--radius-s, 4px);
font-size: var(--fs, 0.9rem); --d-weight: normal;
white-space: nowrap;
color: var(--text, var(--cyan-500, darkcyan));
text-align: center;
text-decoration: none;
border: 1px solid var(--border, var(--cyan-500, darkcyan));
border-radius: 3px;
padding-block: var(--size-2, 0.5em);
padding-inline: var(--size-3, 2em);
background: var(--bg, transparent);
transition: 250ms;
&:hover {
color: var(--hover-text, var(--accent, var(--orange-500, darkorange)));
border: 1px solid var(--hover-border, var(--accent, var(--orange-500, darkorange)));
background: var(--hover-bg, transparent);
}
&.menu-internal-link {
color: var(--internal-text, var(--text, var(--cyan-500, darkcyan)));
border-color: var(--internal-border, var(--border, var(--cyan-500, darkcyan)));
background: var(--internal-bg, var(--bg, transparent));
font-family: var(--internal-font, var(--font, 'Space Grotesk', Inter, sans-serif));
&:hover {
color: var(--internal-hover-text, var(--internal-accent, var(--hover-text, var(--accent, var(--orange-500, darkorange)))));
border-color: var(--internal-hover-border, var(--hover-border, var(--accent, var(--orange-500, darkorange))));
background: var(--internal-hover-bg, var(--hover-bg, transparent));
}
}
&.menu-external-link {
color: var(--external-text, var(--text, var(--cyan-500, darkcyan)));
border-color: var(--external-border, var(--border, var(--cyan-500, darkcyan)));
background: var(--external-bg, var(--bg, transparent));
font-family: var(--external-font, var(--font, 'Space Grotesk', Inter, sans-serif));
&:hover {
color: var(--external-hover-text, var(--external-accent, var(--hover-text, var(--accent, var(--orange-500, darkorange)))));
border-color: var(--external-hover-border, var(--hover-border, var(--accent, var(--orange-500, darkorange))));
background: var(--external-hover-bg, var(--hover-bg, transparent));
}
}
&.menu-file-link {
color: var(--file-text, var(--text, var(--cyan-500, darkcyan)));
border-color: var(--file-border, var(--border, var(--cyan-500, darkcyan)));
background: var(--file-bg, var(--bg, transparent));
font-family: var(--file-font, var(--font, 'Space Grotesk', Inter, sans-serif));
&:hover {
color: var(--file-hover-text, var(--file-accent, var(--hover-text, var(--accent, var(--orange-500, darkorange)))));
border-color: var(--file-hover-border, var(--hover-border, var(--accent, var(--orange-500, darkorange))));
background: var(--file-hover-bg, var(--hover-bg, transparent));
}
}
}
&.wide a {
flex-grow: 1;
flex-basis: 150px;
text-align: center;
}
} }
.menu-container[data-layout='aether'] { /* slate — filled chips */
.menu-container[data-layout='slate'] {
--d-text: var(--text-muted);
--d-bg: var(--background-secondary);
--d-border: var(--background-modifier-border);
--d-hover-text: var(--text-accent);
--d-hover-border: var(--text-accent);
--d-gap: 0.35em;
--d-size: 0.9em;
--d-padding: 0.4em 0.8em;
--d-radius: var(--radius-s, 4px);
--d-weight: 500;
}
/* Modifiers (combine with any layout) */
.menu-container[data-layout].small {
--d-size: 0.8em;
--d-padding: 0.25em 0.6em;
--d-gap: 0.25em;
}
.menu-container[data-layout].grid {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); grid-template-columns: repeat(auto-fill, minmax(min(10em, 100%), 1fr));
gap: 0.5em;
font-family: var(--font, inherit);
a { a {
text-align: center; text-align: center;
text-decoration: none;
font-weight: 600;
padding: 0.5em 1em;
border-radius: 8px;
color: var(--text, var(--text-normal));
border: 1px solid var(--border, var(--background-modifier-border));
background: var(--bg, transparent);
font-family: var(--font, inherit);
&:hover {
color: var(--hover-text, var(--accent, var(--text-accent)));
border-color: var(--hover-border, var(--accent, var(--text-accent)));
background: var(--hover-bg, var(--background-modifier-hover));
}
&.menu-internal-link {
color: var(--internal-text, var(--text, var(--text-normal)));
border-color: var(--internal-border, var(--border, var(--background-modifier-border)));
background: var(--internal-bg, var(--bg, transparent));
font-family: var(--internal-font, var(--font, inherit));
&:hover {
color: var(--internal-hover-text, var(--internal-accent, var(--hover-text, var(--accent, var(--text-accent)))));
border-color: var(--internal-hover-border, var(--hover-border, var(--accent, var(--text-accent))));
background: var(--internal-hover-bg, var(--hover-bg, var(--background-modifier-hover)));
}
}
&.menu-external-link {
color: var(--external-text, var(--text, var(--text-normal)));
border-color: var(--external-border, var(--border, var(--background-modifier-border)));
background: var(--external-bg, var(--bg, transparent));
font-family: var(--external-font, var(--font, inherit));
&:hover {
color: var(--external-hover-text, var(--external-accent, var(--hover-text, var(--accent, var(--text-accent)))));
border-color: var(--external-hover-border, var(--hover-border, var(--accent, var(--text-accent))));
background: var(--external-hover-bg, var(--hover-bg, var(--background-modifier-hover)));
}
}
&.menu-file-link {
color: var(--file-text, var(--text, var(--text-normal)));
border-color: var(--file-border, var(--border, var(--background-modifier-border)));
background: var(--file-bg, var(--bg, transparent));
font-family: var(--file-font, var(--font, inherit));
&:hover {
color: var(--file-hover-text, var(--file-accent, var(--hover-text, var(--accent, var(--text-accent)))));
border-color: var(--file-hover-border, var(--hover-border, var(--accent, var(--text-accent))));
background: var(--file-hover-bg, var(--hover-bg, var(--background-modifier-hover)));
}
}
} }
} }
/* /*
•·················•·················• •·················•·················•
| Dataview | | Dataview |
•·················•·················• •·················•·················•
Flatten Dataview's list markup so its links become direct items of the menu.
*/ */
.menu-dataview-container { .menu-dataview-container,
.menu-dataview-container *:not(a) {
display: contents; display: contents;
}
ul { /*
margin-left: 0; •·················•·················•
padding-left: 0; | Settings Page Styles |
flex-wrap: wrap; •·················•·················•
display: flex; */
gap: var(--gap);
.menu-settings-docs {
li { margin-top: 1em;
display: block; }
margin-left: 0;
list-style-type: none; .menu-settings-docs h4 {
margin-top: 1.5em;
span { margin-bottom: 0.5em;
display: contents; }
a { .menu-settings-table {
display: block; width: 100%;
} border-collapse: collapse;
} margin-bottom: 1em;
} }
}
.menu-settings-table td {
padding: 0.4em 0.8em;
border: 1px solid var(--background-modifier-border);
vertical-align: top;
}
.menu-settings-table tr:first-child td {
border-top: none;
}
.menu-settings-table tr td:first-child {
border-left: none;
}
.menu-settings-table tr td:last-child {
border-right: none;
}
.menu-settings-table tr:last-child td {
border-bottom: none;
}
.menu-settings-syntax {
font-family: var(--font-monospace);
font-size: 0.9em;
white-space: nowrap;
color: var(--text-accent);
} }