Files
WorkNote/.obsidian/plugins/update-relative-links/main.js

174 lines
6.3 KiB
JavaScript
Raw Normal View History

2025-01-13 11:22:31 +08:00
/*
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: () => UpdateRelativeLinksPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian = require("obsidian");
// lib/path.ts
var SEP = "/";
function dirname(path) {
return stackToPath(pathToStack(path).slice(0, -1));
}
function relative(from, to) {
if (!from) {
return to;
}
const fromStack = pathToStack(from);
const toStack = pathToStack(to);
const firstDiffIdx = fromStack.findIndex((value, idx) => value != toStack[idx]);
const resultStack = [];
for (let i = firstDiffIdx; i < fromStack.length - 1; i++) {
resultStack.push("..");
}
for (let i = firstDiffIdx; i < toStack.length; i++) {
resultStack.push(toStack[i]);
}
return stackToPath(resultStack);
}
function pathToStack(path) {
return path.split(SEP);
}
function stackToPath(stack) {
return stack.join(SEP);
}
// main.ts
var ConfirmModal = class extends import_obsidian.Modal {
constructor(app, content, onConfirm) {
super(app);
this.content = content;
this.onConfirm = onConfirm;
}
onOpen() {
const { contentEl } = this;
contentEl.createEl("h1", { text: "Update Releate Links Plugin" });
contentEl.createEl("p", { text: this.content });
new import_obsidian.Setting(contentEl).addButton((btn) => btn.setButtonText("Yes").setCta().onClick(() => {
this.close();
this.onConfirm();
})).addButton((btn) => btn.setButtonText("No").onClick(() => {
this.close();
}));
}
onClose() {
this.contentEl.empty();
}
};
var UpdateRelativeLinksPlugin = class extends import_obsidian.Plugin {
async onload() {
const { app } = this;
const { metadataCache, vault } = app;
const message = "This command will modify all links in the entire vault (not just the current file) to relative paths, and this action cannot be undone. It is recommended that you back up the vault in advance. Please confirm whether you want to execute the command.";
this.addCommand({
id: "update-all-relative-links",
name: "Update all relative links",
callback() {
new ConfirmModal(app, message, () => {
const promises = vault.getMarkdownFiles().map((file) => replace(file, false));
Promise.all(promises).then((linkCounts) => {
const updatedLinkCounts = linkCounts.filter((count) => count > 0);
const linkCount = updatedLinkCounts.reduce((sum, count) => sum + count, 0);
const fileCount = updatedLinkCounts.length;
new import_obsidian.Notice(`Update ${linkCount} links in ${fileCount} file${fileCount > 1 ? "s" : ""}.`);
}).catch((err) => {
new import_obsidian.Notice("Update links error, see console.");
console.error(err);
});
}).open();
}
});
this.registerEvent(vault.on("rename", (file, oldPath) => {
var _a;
if (!oldPath || !file.path.toLocaleLowerCase().endsWith(".md") || ((_a = file.parent) == null ? void 0 : _a.path) === dirname(oldPath)) {
return;
}
if (file instanceof import_obsidian.TFile) {
setTimeout(() => replace(file, true), 100);
}
}));
async function replace(file, notice) {
var _a, _b;
const metadata = metadataCache.getFileCache(file);
const links = [...(_a = metadata == null ? void 0 : metadata.links) != null ? _a : [], ...(_b = metadata == null ? void 0 : metadata.embeds) != null ? _b : []];
const replacePairs = links.map(({ link, original }) => {
var _a2;
const linkPath = link.replace(/#.*$/, "");
if (!linkPath) {
return null;
}
const linkFile = metadataCache.getFirstLinkpathDest(linkPath, file.path);
if (!linkFile) {
return null;
}
const newLinkPath = ((_a2 = file.parent) == null ? void 0 : _a2.path) === "/" ? linkFile.path : relative(file.path, linkFile.path);
if (linkPath === newLinkPath) {
return null;
}
const newOriginal = replaceOriginal(original, linkPath, newLinkPath);
return [original, newOriginal];
}).filter((pair) => pair);
if (!(replacePairs == null ? void 0 : replacePairs.length)) {
return 0;
}
try {
const content = await vault.read(file);
const replacedContent = replacePairs.reduce((tmpContent, pair) => {
return (pair == null ? void 0 : pair.length) === 2 ? tmpContent.replace(pair[0], pair[1]) : tmpContent;
}, content);
await vault.modify(file, replacedContent);
const msg = `Update ${replacePairs.length} links in ${file.path}.`;
console.log(msg);
if (notice) {
new import_obsidian.Notice(msg);
}
return replacePairs.length;
} catch (e) {
console.error(e);
if (notice) {
new import_obsidian.Notice("Update links error, see console.");
}
throw e;
}
}
function replaceOriginal(original, link, newLink) {
let newOriginal = replaceWithFormat(original, link, newLink, (s) => s.replace(/ /g, "%20"));
if (original === newOriginal) {
newOriginal = replaceWithFormat(original, link, newLink, encodeURI);
}
if (original === newOriginal) {
newOriginal = original.replace(/^(!?\[.*?\]).*$/, `$1(${encodeURI(newLink)})`);
}
return newOriginal;
}
function replaceWithFormat(str, from, to, format) {
return str.replace(format(from), format(to));
}
}
};
/* nosourcemap */