export const IMAGE_EXT = new Set([ "png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", ]); function fileExt(relPath: string): string { const base = relPath.split("/").pop() ?? relPath; const dot = base.lastIndexOf("."); if (dot <= 0) { return ""; } return base.slice(dot + 1).toLowerCase(); } export function isImagePath(relPath: string): boolean { return IMAGE_EXT.has(fileExt(relPath)); } export function isMarkdownPath(relPath: string): boolean { const ext = fileExt(relPath); return ext === "md" || ext === "markdown" || ext === "mdown"; } export function markdownTitle(relPath: string): string { return (relPath.replaceAll("\\", "/").split("/").pop() || "Untitled").replace(/\.(?:md|markdown|mdown)$/i, ""); } export function dirnameOf(relPath: string): string { const idx = relPath.replaceAll("\\", "/").lastIndexOf("/"); if (idx <= 0) { return ""; } return relPath.slice(0, idx); } export function resolveImageRel(noteRel: string, raw: string): string { let path = raw.trim().replaceAll("\\", "/").replace(/^<|>$/g, ""); path = path.replace(/^\.\//, ""); if (path.startsWith("/")) { return path.replace(/^\/+/, ""); } const noteDir = dirnameOf(noteRel.replaceAll("\\", "/")); if (path.startsWith("../")) { const parts = [...noteDir.split("/").filter(Boolean), ...path.split("/")]; const out: string[] = []; for (const part of parts) { if (part === "..") { out.pop(); } else if (part !== "." && part) { out.push(part); } } return out.join("/"); } if (noteDir) { return `${noteDir}/${path}`; } return path; } export function isRemoteImage(raw: string): boolean { return /^https?:\/\//i.test(raw.trim()); } export type MarkdownImage = { alt: string; src: string; kind: "md" | "wiki"; }; export function findMarkdownImages(line: string): MarkdownImage[] { const found: MarkdownImage[] = []; const md = /!\[([^\]]*)\]\(([^)]+)\)/g; const wiki = /!\[\[([^\]|#]+)(?:\|([^\]]+))?\]\]/g; let match: RegExpExecArray | null; while ((match = md.exec(line))) { found.push({ alt: match[1], src: match[2].trim(), kind: "md" }); } while ((match = wiki.exec(line))) { found.push({ alt: match[2] ?? match[1], src: match[1].trim(), kind: "wiki" }); } return found; } export function attachmentRel(fileName: string): string { const raw = fileName || "image.png"; const safe = raw.replace(/[^\w.\-]+/g, "-"); const stamp = new Date().toISOString().replace(/[:.]/g, "").replace("T", "-").slice(0, 15); return `attachments/${stamp}-${crypto.randomUUID()}-${safe}`; } const ENTITIES: Record = { amp: "&", quot: '"', apos: "'", "#39": "'", lt: "<", gt: ">" }; /** * The web address of a copied image. A browser puts only the first frame on the clipboard, * with HTML that names the original file. */ export function pastedImageSource(html: string): string | undefined { const images = [...html.matchAll(/]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi)]; if (images.length !== 1) return undefined; const [, double, single, bare] = images[0]; const source = (double ?? single ?? bare).trim().replace(/&(amp|quot|apos|#39|lt|gt);/g, (_, name: string) => ENTITIES[name]); try { const url = new URL(source); return /^https?:$/.test(url.protocol) ? url.href : undefined; } catch { return undefined; } } /** A GIF, WebP, or AVIF address. These formats can have more frames, so the original is worth a download. */ export function mayAnimate(source: string): boolean { return /\.(?:gif|webp|avif)$/i.test(new URL(source).pathname); } const EXTENSIONS: Record = { "image/gif": "gif", "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/avif": "avif", "image/bmp": "bmp", }; /** The file extension of an image data URL, or undefined for another type. */ export function dataUrlExtension(data: string): string | undefined { return EXTENSIONS[/^data:([^;,]+)[;,]/.exec(data)?.[1] ?? ""]; } export function imageFiles(data: DataTransfer | null): File[] { return [...(data?.files ?? [])].filter(file => isImagePath(file.name)); } // File contents and names are protected during dragover; files is usually empty. export function hasFileDrag(data: DataTransfer | null): boolean { return !!data && [...data.types].includes("Files"); } export function imageInsertion(source: string, from: number, to: number, snippets: string[]): string { const before = source.slice(0, from), after = source.slice(to); const prefix = !before || /(?:\r?\n){2}$/.test(before) ? "" : before.endsWith("\n") ? "\n" : "\n\n"; const suffix = /^(?:\r?\n){2}/.test(after) ? "" : /^\r?\n/.test(after) ? "\n" : "\n\n"; return prefix + snippets.join("\n\n") + suffix; } export function workspaceImageLink(notePath: string, imagePath: string): string { const from = notePath.replaceAll("\\", "/").split("/").slice(0, -1); const to = imagePath.replaceAll("\\", "/").split("/"); while (from.length && to.length && from[0] === to[0]) { from.shift(); to.shift(); } const relative = [...from.map(() => ".."), ...to].map(part => encodeURIComponent(part).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)).join("/"); return `![](${relative})`; }