import type { MarkdownIt, Token } from "markdown-it"; const SUFFIX_SIZE_RE = /\|(\d+)(?:x(\d+))?$/; const BARE_SIZE_RE = /^(\d+)(?:x(\d+))?$/; function applySize(token: Token, width: string, height?: string): void { if (token.attrIndex("width") < 0) token.attrPush(["width", width]); if (height && token.attrIndex("height") < 0) token.attrPush(["height", height]); } // Obsidian sizes an image with `![alt|300](…)`, `![alt|300x200](…)`, or — when there is no // alt to hang the suffix on — a wholly numeric alt, `![300](…)`. Either way the number is a // dimension, not a description: the alt is built from the token's children, so it has to // come off there too, or a screen reader announces the number as the image. function applySizeFromAlt(token: Token): void { const bare = BARE_SIZE_RE.exec(token.content); if (bare) { token.children = []; token.content = ""; applySize(token, bare[1] as string, bare[2]); return; } const match = SUFFIX_SIZE_RE.exec(token.content); if (!match) return; const last = token.children?.at(-1); if (last?.type !== "text" || !SUFFIX_SIZE_RE.test(last.content)) return; last.content = last.content.replace(SUFFIX_SIZE_RE, ""); token.content = token.content.replace(SUFFIX_SIZE_RE, ""); applySize(token, match[1] as string, match[2]); } // Content images (`![](…)`) render eager by default, so a note with many embedded // blob images fetches and decodes them all on first paint. Default them to lazy // loading + async decode so only in-viewport images load up front; an explicit // author-set attribute still wins. Attrs are whitelisted in sanitize.ts. export function imagePlugin(mdi: MarkdownIt): void { const defaultImage = mdi.renderer.rules["image"] ?? ((tokens, idx, options, _env, slf) => slf.renderToken(tokens, idx, options)); mdi.renderer.rules["image"] = (tokens, idx, options, env, slf) => { const token = tokens[idx]; if (token) { applySizeFromAlt(token); if (token.attrIndex("loading") < 0) token.attrPush(["loading", "lazy"]); if (token.attrIndex("decoding") < 0) token.attrPush(["decoding", "async"]); } return defaultImage(tokens, idx, options, env, slf); }; }