Files
monster-menus/main.js
T

287 lines
11 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// main.ts
var main_exports = {};
__export(main_exports, {
default: () => MenuPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian = require("obsidian");
var LAYOUTS = ["default", "minimal", "slate"];
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 {
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 == null ? void 0 : data.defaultLayout;
this.settings = {
defaultLayout: LAYOUTS.includes(saved) ? saved : DEFAULT_SETTINGS.defaultLayout
};
}
async saveSettings() {
await this.saveData(this.settings);
}
processMenuBlock(source, el, ctx) {
let layoutOrClass = "";
const options = {};
const links = [];
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;
} 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;
}
}
const tokens = layoutOrClass.split(/\s+/).filter(Boolean);
let layout = tokens.find((t) => LAYOUTS.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 = { 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 != null ? alias : target).trim(), sourcePath, hoverParent);
continue;
}
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", {
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);
}
}
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 component = new import_obsidian.MarkdownRenderChild(dvContainer);
ctx.addChild(component);
import_obsidian.MarkdownRenderer.render(this.app, `\`\`\`dataview
${query}
\`\`\``, dvContainer, ctx.sourcePath, component);
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();
}
};
var MenuPluginSettingTab = class extends import_obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
new import_obsidian.Setting(containerEl).setName("Default layout").setDesc("Layout used when a menu block has no layout: line, or only modifiers (small, grid).").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;
await this.plugin.saveSettings();
});
});
new import_obsidian.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. To edit a menu in Live Preview, click the thin strip on its left edge."
});
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, description) => {
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; Ctrl-hover: preview)");
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)");
addRow("[Text](<file:///path with spaces>)", "File path containing spaces");
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; the rest of the block is the query (needs Dataview)");
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {});