Oscar Plaisant 5b65eb2b2a update
2024-10-01 11:38:50 +02:00

1080 lines
42 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:
https://github.com/zhaoshenzhai/obsidian-mathlinks
*/
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
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);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => MathLinks
});
module.exports = __toCommonJS(main_exports);
var import_obsidian8 = require("obsidian");
var import_state2 = require("@codemirror/state");
// src/links/preview.ts
var import_obsidian4 = require("obsidian");
var import_state = require("@codemirror/state");
var import_view = require("@codemirror/view");
var import_language = require("@codemirror/language");
// src/api/provider.ts
var import_obsidian = require("obsidian");
var Provider = class extends import_obsidian.Component {
constructor(mathLinks) {
super();
this.mathLinks = mathLinks;
this._enableInSourceMode = false;
}
get enableInSourceMode() {
return this._enableInSourceMode;
}
set enableInSourceMode(enable) {
this._enableInSourceMode = enable;
this.mathLinks.update();
}
onunload() {
const providers = this.mathLinks.providers;
let index = providers.findIndex(({ provider }) => provider === this);
providers.splice(index, 1);
this.mathLinks.update();
}
};
var NativeProvider = class extends Provider {
get enableInSourceMode() {
return this.mathLinks.settings.enableInSourceMode;
}
set enableInSourceMode(enable) {
this.mathLinks.settings.enableInSourceMode = enable;
this.mathLinks.update();
this.mathLinks.saveSettings();
}
provide(parsedLinktext, targetFile, targetSubpathResult) {
var _a, _b;
const { mathLinks } = this;
const { app } = mathLinks;
if (!targetFile)
return null;
let cache = app.metadataCache.getFileCache(targetFile);
if (!cache)
return null;
let mathLink = null;
if (targetSubpathResult) {
mathLink = getMathLinkFromSubpath(parsedLinktext.path, targetSubpathResult, cache.frontmatter, mathLinks.settings.blockPrefix, mathLinks.settings.enableFileNameBlockLinks ? null : "");
} else if (parsedLinktext.path) {
mathLink = (_b = (_a = cache.frontmatter) == null ? void 0 : _a.mathLink) != null ? _b : null;
if (mathLink == "auto") {
mathLink = getMathLinkFromTemplates(mathLinks, targetFile);
}
}
return mathLink;
}
};
var DeprecatedAPIProvider = class extends Provider {
constructor(account) {
super(account.plugin);
this.account = account;
}
provide(parsedLinktext, targetFile, targetSubpathResult, sourceFile) {
var _a;
if (targetFile === null || sourceFile === null) {
return null;
}
let mathLink = null;
const metadata = this.account.metadataSet.get(targetFile);
if (metadata) {
if (targetSubpathResult) {
mathLink = getMathLinkFromSubpath(parsedLinktext.path, targetSubpathResult, metadata, this.account.blockPrefix, this.account.prefixer(sourceFile, targetFile, targetSubpathResult));
} else {
mathLink = (_a = metadata["mathLink"]) != null ? _a : null;
}
}
return mathLink;
}
};
// src/links/helper.ts
var import_obsidian2 = require("obsidian");
function setMathLink(source, mathLinkEl) {
mathLinkEl.replaceChildren();
const mathPattern = /\$(.*?[^\s])\$/g;
let textFrom = 0, textTo = 0;
let result;
while ((result = mathPattern.exec(source)) !== null) {
const mathString = result[1];
textTo = result.index;
if (textTo > textFrom)
mathLinkEl.createSpan().replaceWith(source.slice(textFrom, textTo));
const mathEl = (0, import_obsidian2.renderMath)(mathString, false);
mathLinkEl.createSpan({ cls: ["math", "math-inline", "is-loaded"] }).replaceWith(mathEl);
textFrom = mathPattern.lastIndex;
}
if (textFrom < source.length)
mathLinkEl.createSpan().replaceWith(source.slice(textFrom));
}
function getMathLink(plugin, targetLink, sourcePath, isSourceMode) {
let { path, subpath } = (0, import_obsidian2.parseLinktext)(targetLink);
let file = plugin.app.metadataCache.getFirstLinkpathDest(path, sourcePath);
if (!file)
return "";
let cache = plugin.app.metadataCache.getFileCache(file);
if (!cache)
return "";
let subpathResult = (0, import_obsidian2.resolveSubpath)(cache, subpath);
const sourceFile = plugin.app.vault.getAbstractFileByPath(sourcePath);
if (!(sourceFile === null || sourceFile instanceof import_obsidian2.TFile)) {
return "";
}
let mathLink = "";
plugin.iterateProviders((provider) => {
if (isSourceMode && !provider.enableInSourceMode)
return;
const provided = provider.provide({ path, subpath }, file, subpathResult, sourceFile);
if (provided) {
if (provider instanceof NativeProvider && (subpathResult == null ? void 0 : subpathResult.type) == "heading") {
if (mathLink && provided == (path ? path + " > " : "") + subpathResult.current.heading) {
return;
}
}
mathLink = provided;
}
});
return mathLink;
}
function getMathLinkFromSubpath(linkpath, subpathResult, metadata, blockPrefix, prefix) {
var _a, _b;
let subMathLink = "";
if (subpathResult.type == "heading") {
subMathLink = subpathResult.current.heading;
} else if (subpathResult.type == "block" && ((_a = metadata == null ? void 0 : metadata["mathLink-blocks"]) == null ? void 0 : _a[subpathResult.block.id])) {
subMathLink = blockPrefix + metadata["mathLink-blocks"][subpathResult.block.id];
}
if (subMathLink) {
if (prefix === null) {
if (linkpath) {
return ((_b = metadata == null ? void 0 : metadata["mathLink"]) != null ? _b : linkpath) + " > " + subMathLink;
} else {
return subMathLink;
}
} else {
return prefix + subMathLink;
}
} else {
return "";
}
}
function getMathLinkFromTemplates(plugin, file) {
let templates = plugin.settings.templates;
let mathLink = file.name.replace(/\.md$/, "");
for (let i = 0; i < templates.length; i++) {
let replaced = new RegExp(templates[i].replaced);
let replacement = templates[i].replacement;
let flags = "";
if (templates[i].globalMatch)
flags += "g";
if (!templates[i].sensitive)
flags += "i";
if (templates[i].word)
replaced = RegExp(replaced.source.replace(/^/, "\\b").replace(/$/, "\\b"), flags);
else
replaced = RegExp(replaced.source, flags);
mathLink = mathLink.replace(replaced, replacement);
}
return mathLink;
}
// src/links/supercharged.ts
function addSuperCharged(plugin, span, outLinkFile) {
if (outLinkFile && plugin.app.plugins.enabledPlugins.has("supercharged-links-obsidian")) {
let superCharged = getSuperCharged(plugin, outLinkFile);
span.classList.add("data-link-icon");
span.classList.add("data-link-icon-after");
span.classList.add("data-link-text");
span.setAttribute("data-link-path", outLinkFile.path);
span.setAttribute("data-link-tags", superCharged[0]);
for (let i = 0; i < superCharged[1].length; i++)
span.setAttribute("data-link-" + superCharged[1][i][0], superCharged[1][i][1]);
}
}
function getSuperCharged(plugin, file) {
var _a, _b, _c;
const data = (_a = plugin.app.plugins.plugins["supercharged-links-obsidian"]) == null ? void 0 : _a.settings;
let tagArr = (_b = plugin.app.metadataCache.getFileCache(file)) == null ? void 0 : _b.tags;
let tags = "";
if (tagArr) {
for (let i = 0; i < tagArr.length; i++)
tags += tagArr[i].tag.replace(/#/, "") + " ";
tags = tags.trimEnd();
}
let attributes = [];
let frontmatter = (_c = plugin.app.metadataCache.getFileCache(file)) == null ? void 0 : _c.frontmatter;
if (data) {
for (let attr in frontmatter) {
if (attr != "mathLink" && attr != "position") {
let selectors = data.selectors;
for (let i = 0; i < selectors.length; i++) {
if (selectors[i].name == attr && selectors[i].value == frontmatter[attr]) {
attributes.push([attr, frontmatter[attr]]);
} else if (selectors[i].type == "tag" && selectors[i].value == frontmatter[attr] && data.targetTags) {
attributes.push([attr, frontmatter[attr]]);
}
}
}
}
}
return [tags, attributes];
}
// src/utils.ts
var import_obsidian3 = require("obsidian");
function isExcluded(plugin, file) {
for (let i = 0; i < plugin.settings.excludedPaths.length; i++) {
let excluded = plugin.app.vault.getAbstractFileByPath(plugin.settings.excludedPaths[i]);
if (excluded && isEqualToOrChildOf(file, excluded))
return true;
}
return false;
}
function translateLink(targetLink) {
var _a;
function translateLinkImpl(targetLink2, pattern) {
let result = pattern.exec(targetLink2);
if (result)
return (result[1] ? `${result[1]} > ` : "") + `${result[2]}`;
}
let headingPattern = /(^.*)#([^\^].*)/;
let blockPattern = /(^.*)#(\^[a-zA-Z0-9\-]+)/;
let translatedAsHeading = translateLinkImpl(targetLink, headingPattern);
let translatedAsBlock = translateLinkImpl(targetLink, blockPattern);
return (_a = translatedAsHeading != null ? translatedAsHeading : translatedAsBlock) != null ? _a : "";
}
function isEqualToOrChildOf(file1, file2) {
if (file2 instanceof import_obsidian3.TFile)
return file1.path === file2.path;
if (file2 instanceof import_obsidian3.TFolder) {
return file1.path.startsWith(file2.path + "/");
}
return false;
}
// src/links/preview.ts
function selectionAndRangeOverlap(selection, rangeFrom, rangeTo) {
for (const range of selection.ranges) {
if (range.from <= rangeTo && range.to >= rangeFrom) {
return true;
}
}
return false;
}
function hasEffect(tr, effectType) {
return tr.effects.some((effect) => effect.is(effectType));
}
var createEditorExtensions = (plugin) => {
const { app, forceUpdateEffect } = plugin;
class MathWidget extends import_view.WidgetType {
constructor(outLinkText, outLinkMathLink, isSourceMode, sourcePath) {
super();
this.outLinkText = outLinkText;
this.outLinkMathLink = outLinkMathLink;
this.isSourceMode = isSourceMode;
this.sourcePath = sourcePath;
}
eq(other) {
return this.outLinkText === other.outLinkText && this.outLinkMathLink === other.outLinkMathLink && this.isSourceMode == other.isSourceMode && this.sourcePath === other.sourcePath;
}
toDOM() {
const mathLinkEl = createSpan();
setMathLink(this.outLinkMathLink, mathLinkEl);
if (!this.isSourceMode)
mathLinkEl.addClass("cm-underline");
mathLinkEl.setAttribute("draggable", "true");
const linkpath = (0, import_obsidian4.getLinkpath)(this.outLinkText);
const targetFile = app.metadataCache.getFirstLinkpathDest(linkpath, this.sourcePath);
if (targetFile)
addSuperCharged(plugin, mathLinkEl, targetFile);
const mathLinkWrapper = createSpan();
mathLinkWrapper.addClass("cm-hmd-internal-link");
mathLinkWrapper.appendChild(mathLinkEl);
mathLinkWrapper.onclick = (evt) => {
evt.preventDefault();
if (targetFile) {
app.workspace.openLinkText(this.outLinkText, this.sourcePath, import_obsidian4.Keymap.isModEvent(evt));
} else {
self.open(this.outLinkText, "_blank", "noreferrer");
}
};
mathLinkWrapper.onmousedown = (evt) => {
if (evt.button == 1) {
evt.preventDefault();
}
};
mathLinkWrapper.onauxclick = (evt) => {
if (evt.button == 1) {
if (targetFile) {
app.workspace.openLinkText(this.outLinkText, this.sourcePath, true);
} else {
self.open(this.outLinkText, "_blank", "noreferrer");
}
}
};
return mathLinkWrapper;
}
}
const viewPlugin = import_view.ViewPlugin.fromClass(class {
constructor(view) {
this.tryBuildingDecorations(view);
}
update(update) {
const forceUpdate = update.transactions.some((tr) => hasEffect(tr, forceUpdateEffect));
if (forceUpdate || update.docChanged || update.viewportChanged || update.selectionSet) {
this.tryBuildingDecorations(update.view);
}
}
tryBuildingDecorations(view) {
const isSourceMode = !view.state.field(import_obsidian4.editorLivePreviewField);
if (isSourceMode && !plugin.enableInSourceMode()) {
this.decorations = import_view.Decoration.none;
}
const file = view.state.field(import_obsidian4.editorInfoField).file;
if (!file || !isExcluded(plugin, file)) {
this.decorations = this.buildDecorations(view);
(0, import_obsidian4.finishRenderMath)();
} else {
this.decorations = import_view.Decoration.none;
}
}
buildDecorations(view) {
var _a;
const { state } = view;
const isSourceMode = !state.field(import_obsidian4.editorLivePreviewField);
const file = state.field(import_obsidian4.editorInfoField).file;
const sourcePath = (_a = file == null ? void 0 : file.path) != null ? _a : "";
const tree = (0, import_language.syntaxTree)(state);
const builder = new import_state.RangeSetBuilder();
for (let { from, to } of view.visibleRanges) {
let start = -1, end = -1, outLinkText = "", outLinkMathLink = "";
tree.iterate({
from,
to,
enter(node) {
const name = node.type.name;
if (name.contains("formatting-link_formatting-link-start")) {
if (isSourceMode) {
if (state.sliceDoc(node.from, node.to) == "[[" && node.node.nextSibling) {
start = node.node.nextSibling.from;
} else {
return;
}
} else {
start = node.from;
}
} else if (name.contains("formatting_formatting-link_link")) {
if (start == -1) {
start = node.from;
}
} else if (name.contains("has-alias")) {
outLinkText += state.doc.sliceString(node.from, node.to);
if (file && outLinkMathLink == outLinkText.replace(/\.md/, "")) {
outLinkMathLink = getMathLink(plugin, outLinkText, sourcePath, isSourceMode);
}
} else if (/string_url$/.test(name) && !name.contains("format")) {
outLinkText += decodeURI(state.doc.sliceString(node.from, node.to));
if (file && outLinkMathLink == outLinkText.replace(/\.md/, "")) {
outLinkMathLink = getMathLink(plugin, outLinkText, sourcePath, isSourceMode);
}
} else if (name.contains("hmd-internal-link") && !name.contains("alias")) {
outLinkText += state.doc.sliceString(node.from, node.to);
outLinkMathLink = getMathLink(plugin, outLinkText, sourcePath, isSourceMode);
} else if (name.contains("formatting-link-end") || name.contains("formatting-link-string")) {
if (!name.contains("end") && end == -1) {
end = -2;
} else {
if (isSourceMode) {
if (node.node.prevSibling && state.sliceDoc(node.from, node.to) == "]]") {
end = node.node.prevSibling.to;
} else {
return;
}
} else {
end = node.to;
}
if (!selectionAndRangeOverlap(state.selection, start, end) && outLinkText && outLinkMathLink) {
builder.add(start, end, import_view.Decoration.widget({
widget: new MathWidget(outLinkText, outLinkMathLink.replace(/\\\$/, "$"), isSourceMode, sourcePath)
}));
}
start = -1;
end = -1;
outLinkText = "";
outLinkMathLink = "";
}
} else if (!name.contains("pipe") && (name.contains("hmd-internal-link") && name.contains("alias") || name.contains("hmd-escape") && name.contains("link") || /^link/.test(name))) {
outLinkMathLink += state.doc.sliceString(node.from, node.to);
if (file && outLinkMathLink == outLinkText.replace(/\.md/, "")) {
outLinkMathLink = getMathLink(plugin, outLinkText, file.path, isSourceMode);
}
}
}
});
}
return builder.finish();
}
}, { decorations: (v) => v.decorations });
return viewPlugin;
};
// src/settings/settings.ts
var DEFAULT_SETTINGS = {
templates: [],
excludedPaths: [],
blockPrefix: "^",
enableFileNameBlockLinks: true,
enableInSourceMode: false,
renderOutline: true
};
// src/settings/tab.ts
var import_obsidian6 = require("obsidian");
// src/settings/modals.ts
var import_obsidian5 = require("obsidian");
var TemplatesModal = class extends import_obsidian5.Modal {
constructor(app, plugin) {
super(app);
this.plugin = plugin;
}
onOpen() {
this.display();
}
display() {
return __async(this, null, function* () {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h4", { text: "Add/Edit Templates" });
new import_obsidian5.Setting(contentEl).setName(createFragment((e) => {
e.createSpan({ text: "The templates in the list below are sorted by precedence, with the top being replaced first. Note that " });
e.createEl("code", { text: "a" });
e.createSpan({ text: " > " });
e.createEl("code", { text: "b" });
e.createSpan({ text: " followed by " });
e.createEl("code", { text: "b" });
e.createSpan({ text: " > " });
e.createEl("code", { text: "c" });
e.createSpan({ text: " together is equivalent to " });
e.createEl("code", { text: "a" });
e.createSpan({ text: " > " });
e.createEl("code", { text: "c" });
e.createSpan({ text: ", but not the other way around." });
})).addButton((btn) => {
btn.setTooltip("Add").setIcon("plus").onClick((event) => {
let newTemplate = { replaced: "", replacement: "", globalMatch: true, sensitive: true, word: true };
new TemplateSettingsModal(this.app, this.plugin, this, newTemplate, true).open();
});
});
if (this.plugin.settings.templates.length) {
let list = contentEl.createEl("ul");
for (let i = 0; i < this.plugin.settings.templates.length; i++) {
let template = this.plugin.settings.templates[i];
let item = list.createEl("li").createDiv();
new import_obsidian5.Setting(item).setName(createFragment((e) => {
e.createEl("code", { text: template.replaced });
e.createSpan({ text: " > " });
e.createEl("code", { text: template.replacement });
})).addExtraButton((button) => {
return button.setTooltip("Move up").setIcon("up-arrow-with-tail").onClick(() => __async(this, null, function* () {
if (i != 0) {
let down = __spreadValues({}, template);
let up = this.plugin.settings.templates[i - 1];
this.plugin.settings.templates[i] = up;
this.plugin.settings.templates[i - 1] = down;
yield this.plugin.saveSettings().then(() => {
this.display();
});
}
}));
}).addExtraButton((button) => {
return button.setTooltip("Move down").setIcon("down-arrow-with-tail").onClick(() => __async(this, null, function* () {
if (i != this.plugin.settings.templates.length - 1) {
let up = __spreadValues({}, template);
let down = this.plugin.settings.templates[i + 1];
this.plugin.settings.templates[i] = down;
this.plugin.settings.templates[i + 1] = up;
yield this.plugin.saveSettings().then(() => {
this.display();
});
}
}));
}).addExtraButton((button) => {
return button.setTooltip("Edit").setIcon("edit").onClick(() => __async(this, null, function* () {
let modal = new TemplateSettingsModal(this.app, this.plugin, this, template, false);
modal.open();
modal.onClose = () => __async(this, null, function* () {
yield this.plugin.saveSettings().then(() => {
this.display();
});
});
}));
}).addExtraButton((button) => {
return button.setTooltip("Remove").setIcon("x").onClick(() => __async(this, null, function* () {
this.plugin.settings.templates.remove(template);
yield this.plugin.saveSettings().then(() => {
this.display();
});
}));
});
}
}
});
}
};
var TemplateSettingsModal = class extends import_obsidian5.Modal {
constructor(app, plugin, modal, template, create) {
super(app);
this.plugin = plugin;
this.modal = modal;
this.template = template;
this.create = create;
}
onOpen() {
this.display();
}
display() {
return __async(this, null, function* () {
const { contentEl } = this;
contentEl.empty();
let replacedText;
new import_obsidian5.Setting(contentEl).setName("Match for...").setDesc("String to be matched and replaced. Do not include regex.").addText((text) => {
replacedText = text;
replacedText.setValue(this.template.replaced).onChange((current) => {
this.template.replaced = current;
});
});
let replacementText;
new import_obsidian5.Setting(contentEl).setName("Replace with...").setDesc("String to replace matches. Do not escape backslashes.").addText((text) => {
replacementText = text;
replacementText.setValue(this.template.replacement).onChange((current) => {
this.template.replacement = current;
});
});
new import_obsidian5.Setting(contentEl).setName("Global match").setDesc("Match all instances (instead of just the first).").addToggle((toggle) => {
toggle.setValue(this.template.globalMatch).onChange((current) => this.template.globalMatch = current);
});
new import_obsidian5.Setting(contentEl).setName("Case sensitive").setDesc("Matches will be case sensitive.").addToggle((toggle) => {
toggle.setValue(this.template.sensitive).onChange((current) => this.template.sensitive = current);
});
new import_obsidian5.Setting(contentEl).setName("Match whole words").setDesc("Only match whole words.").addToggle((toggle) => {
toggle.setValue(this.template.word).onChange((current) => this.template.word = current);
});
new import_obsidian5.Setting(contentEl).addButton((b) => {
b.setTooltip(this.create ? "Add" : "Save").setIcon("checkmark").onClick(() => __async(this, null, function* () {
if (this.template.replaced == "") {
new import_obsidian5.Notice("MathLinks: Please enter a non-empty string to be replaced");
} else {
if (this.create)
this.plugin.settings.templates.push(this.template);
yield this.plugin.saveSettings().then(() => {
this.close();
this.modal.display();
});
}
}));
}).addExtraButton((b) => {
b.setTooltip("Cancel").setIcon("cross").onClick(() => __async(this, null, function* () {
this.close();
}));
});
});
}
};
var ExcludeModal = class extends import_obsidian5.Modal {
constructor(app, plugin) {
super(app);
this.plugin = plugin;
}
onOpen() {
this.display();
}
display() {
return __async(this, null, function* () {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h4", { text: "Excluded files" });
new import_obsidian5.Setting(contentEl).setName("The files/folders in this list will be ignored by MathLinks.").addButton((btn) => {
btn.setTooltip("Add").setIcon("plus").onClick((event) => {
new FileExcludeSuggestModal(this.app, this.plugin, this).open();
});
});
if (this.plugin.settings.excludedPaths.length) {
let list = contentEl.createEl("ul");
for (let path of this.plugin.settings.excludedPaths) {
let item = list.createEl("li").createDiv();
new import_obsidian5.Setting(item).setName(path).addExtraButton((button) => {
return button.setTooltip("Remove").setIcon("x").onClick(() => __async(this, null, function* () {
this.plugin.settings.excludedPaths.remove(path);
yield this.plugin.saveSettings().then(() => {
this.display();
});
}));
});
}
}
});
}
};
var FileSuggestModal = class extends import_obsidian5.FuzzySuggestModal {
constructor(app, plugin) {
super(app);
this.plugin = plugin;
}
getItems() {
return this.app.vault.getAllLoadedFiles().filter(this.filterCallback.bind(this));
}
getItemText(file) {
return file.path;
}
filterCallback(abstractFile) {
if (abstractFile instanceof import_obsidian5.TFile && abstractFile.extension != "md")
return false;
if (abstractFile instanceof import_obsidian5.TFolder && abstractFile.isRoot())
return false;
for (const path of this.plugin.settings.excludedPaths) {
const file = this.app.vault.getAbstractFileByPath(path);
if (file && isEqualToOrChildOf(abstractFile, file)) {
return false;
}
}
return true;
}
};
var FileExcludeSuggestModal = class extends FileSuggestModal {
constructor(app, plugin, modal) {
super(app, plugin);
this.modal = modal;
}
onChooseItem(file, evt) {
return __async(this, null, function* () {
this.plugin.settings.excludedPaths.push(file.path);
yield this.plugin.saveSettings().then(() => {
this.modal.display();
});
});
}
};
// src/settings/tab.ts
var MathLinksSettingTab = class extends import_obsidian6.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
return __async(this, null, function* () {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "MathLinks Settings" });
new import_obsidian6.Setting(containerEl).setName("Templates").setDesc(createFragment((e) => {
e.createSpan({ text: "Generate mathLinks with a template. Use " });
e.createEl("code", { text: "mathLink: auto" });
e.createSpan({ text: " to use templates in a file." });
})).addButton((button) => {
return button.setButtonText("Manage").onClick(() => __async(this, null, function* () {
let modal = new TemplatesModal(this.app, this.plugin);
modal.open();
modal.onClose = () => __async(this, null, function* () {
yield this.plugin.saveSettings().then(() => {
this.display();
});
});
}));
});
new import_obsidian6.Setting(containerEl).setName("Excluded files").setDesc("Manage files/paths that MathLinks will ignore.").addButton((button) => {
return button.setButtonText("Manage").onClick(() => __async(this, null, function* () {
let modal = new ExcludeModal(this.app, this.plugin);
modal.open();
modal.onClose = () => __async(this, null, function* () {
yield this.plugin.saveSettings().then(() => {
this.display();
});
});
}));
});
let prefix;
new import_obsidian6.Setting(containerEl).setName("Edit prefix for block links").setDesc(createFragment((e) => {
e.createSpan({ text: "Links like " });
e.createEl("code", { text: "note#^block-id" });
e.createSpan({ text: " will be rendered as" });
if (this.plugin.settings.enableFileNameBlockLinks) {
e.createEl("code", { text: "note > " + this.plugin.settings.blockPrefix + "block-id" });
} else {
e.createEl("code", { text: this.plugin.settings.blockPrefix + "block-id" });
}
e.createSpan({ text: "." });
})).addText((text) => {
prefix = text;
prefix.setValue(this.plugin.settings.blockPrefix).onChange((current) => __async(this, null, function* () {
this.plugin.settings.blockPrefix = current;
yield this.plugin.saveSettings();
}));
prefix.setPlaceholder("No prefix (default: ^)");
}).addToggle((toggle) => {
toggle.setValue(this.plugin.settings.enableFileNameBlockLinks).onChange((value) => __async(this, null, function* () {
this.plugin.settings.enableFileNameBlockLinks = value;
yield this.plugin.saveSettings().then(() => {
this.display();
});
}));
toggle.setTooltip("Disable to ignore note name.");
});
new import_obsidian6.Setting(containerEl).setName("Enable in Source mode").setDesc("Currently, only wikilinks are supported in Source mode.").addToggle((toggle) => {
toggle.setValue(this.plugin.nativeProvider.enableInSourceMode).onChange((value) => {
this.plugin.nativeProvider.enableInSourceMode = value;
});
});
new import_obsidian6.Setting(containerEl).setName("Render MathJax in Outline").setDesc("Render headings with MathJax in the core Outline view. You need to reload the app for this option to take effect.").addToggle((toggle) => {
toggle.setValue(this.plugin.settings.renderOutline).onChange((value) => __async(this, null, function* () {
this.plugin.settings.renderOutline = value;
yield this.plugin.saveSettings();
}));
});
});
}
};
// src/api/deprecated.ts
var MathLinksAPIAccount = class {
constructor(plugin, manifest, blockPrefix, prefixer) {
this.plugin = plugin;
this.manifest = manifest;
this.blockPrefix = blockPrefix;
this.prefixer = prefixer;
this.metadataSet = /* @__PURE__ */ new Map();
}
get(file, blockID) {
let metadata = this.metadataSet.get(file);
if (metadata) {
if (blockID === void 0) {
return metadata["mathLink"];
}
let blocks = metadata["mathLink-blocks"];
if (blocks) {
return blocks[blockID];
}
}
}
update(file, newMetadata) {
if (file.extension == "md") {
this.metadataSet.set(file, Object.assign({}, this.metadataSet.get(file), newMetadata));
this.plugin.update(file);
} else {
throw Error(`MathLinks API: ${this.manifest.name} passed a non-markdown file ${file.path} to update().`);
}
}
delete(file, which) {
let metadata = this.metadataSet.get(file);
if (metadata) {
if (which === void 0) {
this.metadataSet.delete(file);
} else if (which == "mathLink" || which == "mathLink-blocks") {
if (metadata[which] !== void 0) {
delete metadata[which];
} else {
throw Error(`MathLinks API: ${this.manifest.name} attempted to delete ${which} of ${file.path}, but it does not exist.`);
}
} else {
let blocks = metadata["mathLink-blocks"];
if (blocks && blocks[which] !== void 0) {
delete blocks[which];
} else {
throw Error(`MathLinks API: ${this.manifest.name} attempted to delete mathLink-blocks for ${file.path}#^${which}", but it does not exist`);
}
}
} else {
throw Error(`MathLinks API: ${this.manifest.name} attempted to delete the MathLinks metadata of ${file.path}, but it does not exist.`);
}
this.plugin.update(file);
}
};
// src/links/reading.ts
var import_obsidian7 = require("obsidian");
var MathLinksRenderChild = class extends import_obsidian7.MarkdownRenderChild {
constructor(containerEl, plugin, sourcePath, targetLink, displayText) {
var _a;
super(containerEl);
this.plugin = plugin;
this.sourcePath = sourcePath;
this.targetLink = targetLink;
this.displayText = displayText;
this.targetFile = this.plugin.app.metadataCache.getFirstLinkpathDest((0, import_obsidian7.getLinkpath)(this.targetLink), this.sourcePath);
this.mathLinkEl = this.containerEl.cloneNode(true);
this.mathLinkEl.textContent = "";
(_a = this.containerEl.parentNode) == null ? void 0 : _a.insertBefore(this.mathLinkEl, this.containerEl.nextSibling);
this.mathLinkEl.classList.add("mathLink-internal-link");
this.containerEl.classList.add("original-internal-link");
this.containerEl.classList.remove("internal-link");
this.containerEl.style.display = "none";
this.getMathLink = this.setMathLinkGetter();
}
onload() {
this.update();
this.registerEvent(this.plugin.app.metadataCache.on("mathlinks:update", (changedFile) => {
if (!this.targetFile || this.targetFile == changedFile) {
this.update();
}
}));
this.registerEvent(this.plugin.app.metadataCache.on("mathlinks:update-all", () => {
this.update();
}));
}
setMathLinkGetter() {
var _a, _b;
let getter = () => "";
if (this.displayText != this.targetLink && this.displayText != translateLink(this.targetLink)) {
getter = () => this.displayText;
} else {
if (this.displayText == ((_a = this.targetFile) == null ? void 0 : _a.name) || this.displayText == ((_b = this.targetFile) == null ? void 0 : _b.basename) || this.displayText == translateLink(this.targetLink)) {
getter = () => getMathLink(this.plugin, this.targetLink, this.sourcePath);
}
}
return getter;
}
update() {
const mathLink = this.getMathLink();
if (mathLink) {
setMathLink(mathLink, this.mathLinkEl);
} else {
setMathLink(this.displayText, this.mathLinkEl);
}
(0, import_obsidian7.finishRenderMath)();
}
};
function generateMathLinks(plugin, element, context) {
var _a, _b;
for (let targetEl of element.querySelectorAll(".internal-link")) {
if (targetEl.classList.contains("mathLink-internal-link")) {
targetEl.remove();
let queryResult = element.querySelector(".original-internal-link");
if (queryResult) {
targetEl = queryResult;
targetEl.classList.remove("original-internal-link");
targetEl.style.display = "";
}
}
const targetDisplay = (_a = targetEl.textContent) == null ? void 0 : _a.trim().replace(/\.md/, "");
if (targetDisplay != "" && !/math-inline is-loaded/.test(targetEl.innerHTML)) {
const targetLink = (_b = targetEl.getAttribute("data-href")) == null ? void 0 : _b.replace(/\.md/, "");
if (targetLink) {
const targetFile = plugin.app.metadataCache.getFirstLinkpathDest((0, import_obsidian7.getLinkpath)(targetLink), context.sourcePath);
if (targetDisplay && targetFile) {
const child = new MathLinksRenderChild(targetEl, plugin, context.sourcePath, targetLink, targetDisplay);
context.addChild(child);
}
}
}
}
}
// node_modules/monkey-around/mjs/index.js
function around(obj, factories) {
const removers = Object.keys(factories).map((key) => around1(obj, key, factories[key]));
return removers.length === 1 ? removers[0] : function() {
removers.forEach((r) => r());
};
}
function around1(obj, method, createWrapper) {
const original = obj[method], hadOwn = obj.hasOwnProperty(method);
let current = createWrapper(original);
if (original)
Object.setPrototypeOf(current, original);
Object.setPrototypeOf(wrapper, current);
obj[method] = wrapper;
return remove;
function wrapper(...args) {
if (current === original && obj[method] === wrapper)
remove();
return current.apply(this, args);
}
function remove() {
if (obj[method] === wrapper) {
if (hadOwn)
obj[method] = original;
else
delete obj[method];
}
if (current === original)
return;
current = original;
Object.setPrototypeOf(wrapper, original || Function);
}
}
// src/outline.ts
var patchOutline = (plugin) => {
var _a;
const outlineView = (_a = plugin.app.workspace.getLeavesOfType("outline")[0]) == null ? void 0 : _a.view;
if (!outlineView)
return false;
plugin.register(around(outlineView.constructor.prototype, {
getItemDom(old) {
return function(arg) {
const ret = old.call(this, arg);
setTimeout(() => setMathLink(ret.heading.heading, ret.innerEl));
return ret;
};
}
}));
return true;
};
// src/main.ts
var MathLinks = class extends import_obsidian8.Plugin {
constructor() {
super(...arguments);
this.providers = [];
this.forceUpdateEffect = import_state2.StateEffect.define();
}
onload() {
return __async(this, null, function* () {
yield this.loadSettings();
yield (0, import_obsidian8.loadMathJax)();
this.nativeProvider = new NativeProvider(this);
this.addChild(this.nativeProvider);
this.registerProvider(this.nativeProvider, Infinity);
this.registerMarkdownPostProcessor((element, context) => {
let file = this.app.vault.getAbstractFileByPath(context.sourcePath);
if (!file || !isExcluded(this, file)) {
generateMathLinks(this, element, context);
}
});
this.registerEditorExtension(createEditorExtensions(this));
this.registerEvent(this.app.metadataCache.on("changed", (file) => this.update(file)));
this.registerEvent(this.app.workspace.on("layout-change", () => this.update()));
this.apiAccounts = [];
this.app.workspace.onLayoutReady(() => {
if (this.settings.renderOutline && this.app.internalPlugins.plugins.outline.enabled) {
const success = patchOutline(this);
if (!success) {
const eventRef = this.app.workspace.on("layout-change", () => {
const success2 = patchOutline(this);
if (success2)
this.app.workspace.offref(eventRef);
});
this.registerEvent(eventRef);
}
}
});
});
}
getAPIAccount(userPlugin) {
let account = this.apiAccounts.find((account2) => account2.manifest.id == userPlugin.manifest.id);
if (account)
return account;
account = new MathLinksAPIAccount(this, userPlugin.manifest, DEFAULT_SETTINGS.blockPrefix, () => null);
this.apiAccounts.push(account);
const provider = new DeprecatedAPIProvider(account);
userPlugin.addChild(provider);
this.registerProvider(provider);
return account;
}
loadSettings() {
return __async(this, null, function* () {
this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData());
this.addSettingTab(new MathLinksSettingTab(this.app, this));
});
}
saveSettings() {
return __async(this, null, function* () {
yield this.saveData(this.settings);
});
}
registerProvider(provider, sortOrder) {
var _a;
(_a = this.providers.find((another) => another.provider === provider)) != null ? _a : this.providers.push({ provider, sortOrder: sortOrder != null ? sortOrder : 0 });
}
iterateProviders(callback) {
this.providers.sort((p1, p2) => p1.sortOrder - p2.sortOrder).forEach(({ provider }) => callback(provider));
}
enableInSourceMode() {
return this.providers.some(({ provider }) => provider.enableInSourceMode);
}
update(file) {
if (file) {
this._update("mathlinks:update", file);
} else {
this._update("mathlinks:update-all");
}
}
_update(...args) {
const [eventName, file] = args;
this.app.metadataCache.trigger(eventName, file);
this.app.workspace.iterateAllLeaves((leaf) => {
if (leaf.view instanceof import_obsidian8.MarkdownView && leaf.view.getMode() === "source") {
const editorView = leaf.view.editor.cm;
if (!editorView)
return;
let shouldDispatch = !file;
shouldDispatch || (shouldDispatch = !this.app.metadataCache.resolvedLinks);
if (file && leaf.view.file && this.app.metadataCache.resolvedLinks[leaf.view.file.path]) {
shouldDispatch || (shouldDispatch = file.path in this.app.metadataCache.resolvedLinks[leaf.view.file.path]);
}
if (shouldDispatch) {
editorView.dispatch({ effects: this.forceUpdateEffect.of(null) });
}
}
});
}
};