diff --git a/web/cm_plugins/inline_content.ts b/web/cm_plugins/inline_content.ts index a084b179..9c22772c 100644 --- a/web/cm_plugins/inline_content.ts +++ b/web/cm_plugins/inline_content.ts @@ -8,204 +8,8 @@ import { shouldRenderWidgets, } from "./util.ts"; import type { Client } from "../client.ts"; -import { - isLocalURL, - resolveMarkdownLink, -} from "@silverbulletmd/silverbullet/lib/resolve"; -import { - getNameFromPath, - getPathExtension, - isMarkdownPath, - parseToRef, - type Ref, -} from "@silverbulletmd/silverbullet/lib/ref"; import { LuaWidget } from "./lua_widget.ts"; -import { mdLinkRegex, wikiLinkRegex } from "../markdown_parser/constants.ts"; -import { mime } from "mimetypes"; -import { extractTransclusion } from "../markdown.ts"; - -type ContentDimensions = { - width?: number; - height?: number; -}; - -async function inlineHtmlFromURL( - client: Client, - url: string, - alias: string, - dimensions: ContentDimensions | undefined, - allowExternal: boolean = true, -): Promise { - let mimeType: string | null | undefined; - if (!isLocalURL(url) && allowExternal) { - const response = await fetch(url, { method: "HEAD" }); - if (!response.ok) { - return `Failed to fetch resource, server responded with status code: ${response.status}`; - } - - mimeType = response.headers.get("Content-Type"); - } else { - const ref = parseToRef(url); - if (!ref) { - return `Failed to parse url`; - } - - mimeType = mime.getType(getPathExtension(ref.path)); - } - - if (!mimeType) { - return `Failed to determine mime type`; - } - - const setDimension = (element: HTMLElement, event: string) => { - const cachedContentHeight = client.getCachedWidgetHeight( - `content:${url}`, - ); - - element.addEventListener(event, () => { - if (element.clientHeight !== cachedContentHeight) { - client.setCachedWidgetHeight( - `content:${url}`, - element.clientHeight, - ); - } - }); - - element.style.maxWidth = "100%"; - - if (dimensions) { - if (dimensions.height) { - element.style.height = `${dimensions.height}px`; - } - if (dimensions.width) { - element.style.width = `${dimensions.width}px`; - } - } else if (cachedContentHeight > 0) { - element.style.height = cachedContentHeight.toString(); - } - }; - - // If the URL is a local, encode the : so that it's not interpreted as a protocol - const sanitizedURL = isLocalURL(url) ? url.replace(":", "%3A") : url; - - let result: HTMLElement | string; - if (mimeType.startsWith("image/")) { - const img = document.createElement("img"); - img.src = sanitizedURL; - img.alt = alias; - setDimension(img, "load"); - result = img; - } else if (mimeType.startsWith("video/")) { - const video = document.createElement("video"); - video.src = sanitizedURL; - video.title = alias; - video.controls = true; - video.autoplay = false; - setDimension(video, "loadeddata"); - result = video; - } else if (mimeType.startsWith("audio/")) { - const audio = document.createElement("audio"); - audio.src = sanitizedURL; - audio.title = alias; - audio.controls = true; - audio.autoplay = false; - setDimension(audio, "loadeddata"); - result = audio; - } else if (mimeType === "application/pdf") { - const embed = document.createElement("object"); - embed.type = mimeType; - embed.data = sanitizedURL; - embed.style.width = "100%"; - embed.style.height = "20em"; - setDimension(embed, "load"); - result = embed; - } else if (mimeType === "text/markdown") { - let details: Ref["details"], markdown: string; - - if (!isLocalURL(url) && allowExternal) { - const response = await fetch(url); - if (!response.ok) { - // This shouldn't really happen, but let's check anyways - return `Couldn't transclude markdown from external source. Server responded with: ${response.status}`; - } - - markdown = await response.text(); - - const parsedURL = new URL(url); - if (parsedURL.hash) { - details = { - type: "header", - header: parsedURL.hash, - }; - } - } else { - const ref = parseToRef(url); - - if (!ref || !isMarkdownPath(ref.path)) { - // We can be fairly sure this can't happen, but just be sure - return `Couldn't transclude markdown, invalid path`; - } - - details = ref.details; - - // Do a pre-check, because `readPage` is quiete heavy - if (!client.clientSystem.allKnownFiles.has(ref.path)) { - return `Couldn't transclude markdown, page doesn't exist`; - } - - // Don't try catch, we just checked the existence - ({ text: markdown } = await client.space.readPage( - getNameFromPath(ref.path), - )); - } - - const transclusion = extractTransclusion(markdown, details); - if (!transclusion) { - return `Couldn't extract translcusion from markdown, try removing any headers '\\#' or positions '@' from your link`; - } - - result = transclusion; - } else { - result = `Server responded with unsupported mimeType: ${mimeType}`; - } - - return result; -} - -// Parse an alias, possibly containing dimensions into an object -// Formats supported: "alias", "alias|100", "alias|100x200", "100", "100x200" -function parseAlias( - text: string, -): { alias: string; dim?: ContentDimensions } { - let alias: string; - let dim: ContentDimensions | undefined; - if (text.includes("|")) { - const [aliasPart, dimPart] = text.split("|"); - alias = aliasPart; - const [width, height] = dimPart.split("x"); - dim = {}; - if (width) { - dim.width = parseInt(width); - } - if (height) { - dim.height = parseInt(height); - } - } else if (/^[x\d]/.test(text)) { - const [width, height] = text.split("x"); - dim = {}; - if (width) { - dim.width = parseInt(width); - } - if (height) { - dim.height = parseInt(height); - } - alias = ""; - } else { - alias = text; - } - - return { alias, dim }; -} +import { inlineContentFromURL, parseTransclusion } from "../markdown/inline.ts"; export function inlineContentPlugin(client: Client) { return decoratorStateField((state: EditorState) => { @@ -223,36 +27,11 @@ export function inlineContentPlugin(client: Client) { const text = state.sliceDoc(from, to); - let url, alias = undefined; - let isWikilink = false; - - mdLinkRegex.lastIndex = 0; - wikiLinkRegex.lastIndex = 0; - let match: RegExpMatchArray | null = null; - if ((match = mdLinkRegex.exec(text)) && match.groups) { - ({ url, title: alias } = match.groups); - - if (isLocalURL(url)) { - url = resolveMarkdownLink( - client.currentName(), - decodeURI(url), - ); - } - } else if ((match = wikiLinkRegex.exec(text)) && match.groups) { - ({ stringRef: url, alias } = match.groups); - isWikilink = true; - } else { - // We found no match + const transclusion = parseTransclusion(text); + if (!transclusion) { return; } - let dimension: ContentDimensions | undefined; - if (alias) { - ({ alias, dim: dimension } = parseAlias(alias)); - } else { - alias = ""; - } - if (!isCursorInRange(state, [from, to])) { widgets.push(invisibleDecoration.range(from, to)); } @@ -264,12 +43,12 @@ export function inlineContentPlugin(client: Client) { `widget:${client.currentPath()}:${text}`, text, async () => { - const result = await inlineHtmlFromURL( + const result = await inlineContentFromURL( client, - url, - alias, - dimension, - !isWikilink, + transclusion.url, + transclusion.alias, + transclusion.dimension, + transclusion.linktype !== "wikilink", ); const content = typeof result === "string" ? { markdown: result } diff --git a/web/cm_plugins/lua_widget.ts b/web/cm_plugins/lua_widget.ts index a3f4a9dd..5deebb83 100644 --- a/web/cm_plugins/lua_widget.ts +++ b/web/cm_plugins/lua_widget.ts @@ -12,9 +12,9 @@ import { attachWidgetEventHandlers, moveCursorIntoText, } from "./widget_util.ts"; -import { expandMarkdown } from "../markdown.ts"; +import { expandMarkdown } from "../markdown/inline.ts"; import { LuaStackFrame, LuaTable } from "../../lib/space_lua/runtime.ts"; -import { isBlockMarkdown, jsonToMDTable } from "../markdown_util.ts"; +import { isBlockMarkdown, jsonToMDTable } from "../markdown/result_render.ts"; import { activeWidgets } from "./code_widget.ts"; export type LuaWidgetCallback = ( diff --git a/web/cm_plugins/table.ts b/web/cm_plugins/table.ts index aaf582c6..954c5cb2 100644 --- a/web/cm_plugins/table.ts +++ b/web/cm_plugins/table.ts @@ -15,7 +15,7 @@ import { isLocalURL, resolveMarkdownLink, } from "@silverbulletmd/silverbullet/lib/resolve"; -import { expandMarkdown } from "../markdown.ts"; +import { expandMarkdown } from "../markdown/inline.ts"; import { LuaStackFrame } from "../../lib/space_lua/runtime.ts"; import { attachWidgetEventHandlers } from "./widget_util.ts"; diff --git a/web/markdown.ts b/web/markdown.ts deleted file mode 100644 index 2107c303..00000000 --- a/web/markdown.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { - findNodeOfType, - type ParseTree, - renderToText, - replaceNodesMatchingAsync, - traverseTree, -} from "@silverbulletmd/silverbullet/lib/tree"; -import { - getNameFromPath, - isMarkdownPath, - parseToRef, - type Ref, -} from "@silverbulletmd/silverbullet/lib/ref"; -import { parseMarkdown } from "./markdown_parser/parser.ts"; -import type { LuaExpression } from "../lib/space_lua/ast.ts"; -import { evalExpression } from "../lib/space_lua/eval.ts"; -import type { LuaEnv, LuaStackFrame } from "../lib/space_lua/runtime.ts"; -import { parseExpressionString } from "../lib/space_lua/parse.ts"; -import { renderExpressionResult } from "./markdown_util.ts"; -import type { Client } from "./client.ts"; - -/** - * Expands custom markdown Lua directives and transclusions into plain markdown - * @param mdTree parsed markdown tree - * @returns modified mdTree - */ -export async function expandMarkdown( - client: Client, - mdTree: ParseTree, - env: LuaEnv, - sf: LuaStackFrame, -): Promise { - await replaceNodesMatchingAsync(mdTree, async (n) => { - if (n.type === "Image") { - // Let's scan for ![[embeds]] that are codified as Images, confusingly - const wikiLinkMark = findNodeOfType(n, "WikiLinkMark"); - if (!wikiLinkMark) { - return; - } - const wikiLinkPage = findNodeOfType(n, "WikiLinkPage"); - if (!wikiLinkPage) { - return; - } - - const page = wikiLinkPage.children![0].text!; - - const ref = parseToRef(page); - - if (!ref || !isMarkdownPath(ref.path)) { - return; - } - - // Read the page - const { text } = await client.space.readPage(getNameFromPath(ref.path)); - const parsedBody = parseMarkdown(text); - // Recursively process - return expandMarkdown( - client, - parsedBody, - env, - sf, - ); - } else if (n.type === "LuaDirective") { - const expr = findNodeOfType(n, "LuaExpressionDirective") as - | LuaExpression - | null; - if (!expr) { - return; - } - const exprText = renderToText(expr); - - try { - let result = await evalExpression( - parseExpressionString(exprText), - env, - sf, - ); - - if (result?.markdown) { - result = result.markdown; - } - const markdown = await renderExpressionResult(result); - return parseMarkdown(markdown); - } catch (e: any) { - // Reduce blast radius and give useful error message - console.error("Error evaluating Lua directive", exprText, e); - return parseMarkdown(`**Error:** ${e.message}`); - } - } - }); - return mdTree; -} - -/** - * Extracts the transclusion from a markdown tree. Right now this is only - * supported for headers, in which case the Function will extract the header - * plus all text till the next header - * @returns Returns null if the header isn't found - */ -export function extractTransclusion( - markdown: string, - details: Ref["details"], -): string | null { - if (!details) { - return markdown; - } else if (details.type !== "header") { - return null; - } - - const parseTree = parseMarkdown(markdown); - - let from: undefined | number = undefined, to: undefined | number = undefined; - traverseTree(parseTree, (subTree) => { - // We are done, but we can't properly cancel the traversal - if (from !== undefined && to !== undefined) { - return true; - } - - if (!subTree.type || !subTree.type.startsWith("ATXHeading")) { - return false; - } - - // We already found the first header - if (from !== undefined) { - to = subTree.from; - return true; - } - - const mark = findNodeOfType(subTree, "HeaderMark"); - if (!mark || mark.from === undefined || mark.to === undefined) { - return true; - } - - if ( - renderToText(subTree) - .slice(mark.to - mark.from) - .trimStart() === details.header.trim() - ) { - from = subTree.from; - } - - // No need to continue into a header - return true; - }); - - // Go till end of file if we can't find a second header - to ??= parseTree.to; - - if (from === undefined) { - return null; - } - - return markdown.slice(from, to); -} diff --git a/web/markdown/inline.ts b/web/markdown/inline.ts new file mode 100644 index 00000000..b466800d --- /dev/null +++ b/web/markdown/inline.ts @@ -0,0 +1,385 @@ +import { + findNodeOfType, + type ParseTree, + renderToText, + replaceNodesMatchingAsync, + traverseTree, +} from "@silverbulletmd/silverbullet/lib/tree"; +import { + getNameFromPath, + getPathExtension, + isMarkdownPath, + parseToRef, + type Ref, +} from "@silverbulletmd/silverbullet/lib/ref"; +import { + isLocalURL, + resolveMarkdownLink, +} from "@silverbulletmd/silverbullet/lib/resolve"; +import { mime } from "mimetypes"; +import type { Client } from "../client.ts"; +import type { LuaEnv, LuaStackFrame } from "../../lib/space_lua/runtime.ts"; +import { parseMarkdown } from "../markdown_parser/parser.ts"; +import { renderExpressionResult } from "./result_render.ts"; +import { parseExpressionString } from "../../lib/space_lua/parse.ts"; +import { evalExpression } from "../../lib/space_lua/eval.ts"; +import type { LuaExpression } from "../../lib/space_lua/ast.ts"; +import { mdLinkRegex, wikiLinkRegex } from "../markdown_parser/constants.ts"; + +/** + * Describes the dimensions of a transclusion, if provided through the alias. + * Can be parsed from the alias using {@link parseDimensionFromAlias} + */ +export type ContentDimensions = { + width?: number; + height?: number; +}; + +/** + * Expands custom markdown Lua directives and transclusions into plain markdown + * @param mdTree parsed markdown tree + * @returns modified mdTree + */ +export async function expandMarkdown( + client: Client, + mdTree: ParseTree, + env: LuaEnv, + sf: LuaStackFrame, + forbiddenPages: Set = new Set(), +): Promise { + await replaceNodesMatchingAsync(mdTree, async (n) => { + if (n.type === "Image") { + // Let's scan for ![[embeds]] that are codified as Images, confusingly + const text = renderToText(n); + + const transclusion = parseTransclusion(text); + if (!transclusion || forbiddenPages.has(transclusion.url)) { + return n; + } + + const result = await inlineContentFromURL( + client, + transclusion.url, + transclusion.alias, + transclusion.dimension, + transclusion.linktype !== "wikilink", + ); + + // We don't transclude anything that's not markdown + if (typeof result !== "string") { + return n; + } + + // We know it's a markdown page and we know we are transcluding it. "Mark" + // it so we won't touch it down the line and cause endless recursion + forbiddenPages.add(transclusion.url); + + const tree = parseMarkdown(result); + + // Recursively process + return expandMarkdown( + client, + tree, + env, + sf, + forbiddenPages, + ); + } else if (n.type === "LuaDirective") { + const expr = findNodeOfType(n, "LuaExpressionDirective") as + | LuaExpression + | null; + if (!expr) { + return; + } + const exprText = renderToText(expr); + + try { + let result = await evalExpression( + parseExpressionString(exprText), + env, + sf, + ); + + if (result?.markdown) { + result = result.markdown; + } + const markdown = await renderExpressionResult(result); + return parseMarkdown(markdown); + } catch (e: any) { + // Reduce blast radius and give useful error message + console.error("Error evaluating Lua directive", exprText, e); + return parseMarkdown(`**Error:** ${e.message}`); + } + } + }); + return mdTree; +} + +/** + * Extracts the transclusion from a markdown tree. Right now this is only + * supported for headers, in which case the Function will extract the header + * plus all text till the next header + * @returns Returns null if the header isn't found + */ +export function extractTransclusion( + markdown: string, + details: Ref["details"], +): string | null { + if (!details) { + return markdown; + } else if (details.type !== "header") { + return null; + } + + const parseTree = parseMarkdown(markdown); + + let from: undefined | number = undefined, to: undefined | number = undefined; + traverseTree(parseTree, (subTree) => { + // We are done, but we can't properly cancel the traversal + if (from !== undefined && to !== undefined) { + return true; + } + + if (!subTree.type || !subTree.type.startsWith("ATXHeading")) { + return false; + } + + // We already found the first header + if (from !== undefined) { + to = subTree.from; + return true; + } + + const mark = findNodeOfType(subTree, "HeaderMark"); + if (!mark || mark.from === undefined || mark.to === undefined) { + return true; + } + + if ( + renderToText(subTree) + .slice(mark.to - mark.from) + .trimStart() === details.header.trim() + ) { + from = subTree.from; + } + + // No need to continue into a header + return true; + }); + + // Go till end of file if we can't find a second header + to ??= parseTree.to; + + if (from === undefined) { + return null; + } + + return markdown.slice(from, to); +} + +/** + * Function to generate HTML or markdown for a ![[]] type transclusion. + * @param allowExternal In SB currently, wikilinks don't allow external links + * and markdown links do + * @returns a string for a markdown transclusion or html for everything else + */ +export function inlineContentFromURL( + client: Client, + url: string, + alias: string, + dimension: ContentDimensions | undefined, + allowExternal: boolean = true, +): string | HTMLElement | Promise { + let mimeType: string | null | undefined; + if (!isLocalURL(url) && allowExternal) { + // TODO + // Realistically we should dertermine the mine type by sending a HEAD + // request, this poses multiple problems + // 1. This makes `async` a hard requirement here + // 2. We would need to proxy the request (because of CORS) + // 3. It won't work "offline" (i.e. away from the SB instance, because it + // can't proxy the request anymore) + // 4. It can be pretty heavy. If your internet connection is bad you will + // have to wait for all HEAD request, for your `markdownToHtml` to + // complete. This could take a noticeable amount of time. + // For this reason we will stick to doing it the `dumb` way by just getting + // it from the URL extension + const extension = URL.parse(url)?.pathname.split(".").pop(); + if (extension) { + mimeType = mime.getType(extension); + } + } else { + const ref = parseToRef(url); + if (!ref) { + return `Failed to parse url`; + } + + mimeType = mime.getType(getPathExtension(ref.path)); + } + + if (!mimeType) { + return `Failed to determine mime type`; + } + + const style = `max-width: 100%;` + + (dimension?.width ? `width: ${dimension.width}px;` : "") + + (dimension?.height ? `height: ${dimension.height}px;` : ""); + + // If the URL is a local, encode the : so that it's not interpreted as a protocol + const sanitizedURL = isLocalURL(url) ? url.replace(":", "%3A") : url; + + let result: HTMLElement | string | Promise; + if (mimeType.startsWith("image/")) { + const img = document.createElement("img"); + img.src = sanitizedURL; + img.alt = alias; + img.style = style; + result = img; + } else if (mimeType.startsWith("video/")) { + const video = document.createElement("video"); + video.src = sanitizedURL; + video.title = alias; + video.controls = true; + video.autoplay = false; + video.style = style; + result = video; + } else if (mimeType.startsWith("audio/")) { + const audio = document.createElement("audio"); + audio.src = sanitizedURL; + audio.title = alias; + audio.controls = true; + audio.autoplay = false; + audio.style = style; + result = audio; + } else if (mimeType === "application/pdf") { + const embed = document.createElement("object"); + embed.type = mimeType; + embed.data = sanitizedURL; + embed.style.width = "100%"; + embed.style.height = "20em"; + embed.style = style; + result = embed; + } else if (mimeType === "text/markdown") { + if (!isLocalURL(url) && allowExternal) { + return `Transcluding markdown from external sources is not supported`; + } + + const ref = parseToRef(url); + + if (!ref || !isMarkdownPath(ref.path)) { + // We can be fairly sure this can't happen, but just be sure + return `Couldn't transclude markdown, invalid path`; + } + + // Do a pre-check, because `readPage` is quiete heavy + if (!client.clientSystem.allKnownFiles.has(ref.path)) { + return `Couldn't transclude markdown, page doesn't exist`; + } + + result = (async () => { + // Don't try catch, we just checked the existence + const { text: markdown } = await client.space.readPage( + getNameFromPath(ref.path), + ); + + const transclusion = extractTransclusion(markdown, ref.details); + if (!transclusion) { + return `Couldn't extract transclusion from markdown, try removing any headers '\\#' or positions '@' from your link`; + } + + return transclusion; + })(); + } else { + result = `File has unsupported mimeType: ${mimeType}`; + } + + return result; +} + +/** + * Parse an alias, possibly containing dimensions into an object + * @example "alias", "alias|100", "alias|100x200", "100", "100x200" + */ +export function parseDimensionFromAlias( + text: string, +): { alias: string; dimension?: ContentDimensions } { + let alias: string; + let dim: ContentDimensions | undefined; + if (text.includes("|")) { + const [aliasPart, dimPart] = text.split("|"); + alias = aliasPart; + const [width, height] = dimPart.split("x"); + dim = {}; + if (width) { + dim.width = parseInt(width); + } + if (height) { + dim.height = parseInt(height); + } + } else if (/^[x\d]/.test(text)) { + const [width, height] = text.split("x"); + dim = {}; + if (width) { + dim.width = parseInt(width); + } + if (height) { + dim.height = parseInt(height); + } + alias = ""; + } else { + alias = text; + } + + return { alias, dimension: dim }; +} + +/** + * Parses a transclusion of the type `![[]]` or `![]()` + * @param text + */ +export function parseTransclusion( + text: string, +): { + url: string; + alias: string; + dimension?: ContentDimensions; + linktype: "wikilink" | "markdown"; +} | null { + let url, alias = undefined; + let linktype: "wikilink" | "markdown" = "markdown"; + // TODO: Take in the tree and use tree nodes to get url and alias (Applies to all regex uses) + mdLinkRegex.lastIndex = 0; + wikiLinkRegex.lastIndex = 0; + let match: RegExpMatchArray | null = null; + if ((match = mdLinkRegex.exec(text)) && match.groups) { + ({ url, title: alias } = match.groups); + + if (isLocalURL(url)) { + url = resolveMarkdownLink( + client.currentName(), + decodeURI(url), + ); + } + linktype = "markdown"; + } else if ((match = wikiLinkRegex.exec(text)) && match.groups) { + ({ stringRef: url, alias } = match.groups); + linktype = "wikilink"; + } else { + // We found no match + return null; + } + + let dimension: ContentDimensions | undefined; + if (alias) { + ({ alias, dimension: dimension } = parseDimensionFromAlias(alias)); + } else { + alias = ""; + } + + return { + url, + alias, + dimension, + linktype, + }; +} diff --git a/web/markdown/markdown_render.ts b/web/markdown/markdown_render.ts index d475f0db..bc12360d 100644 --- a/web/markdown/markdown_render.ts +++ b/web/markdown/markdown_render.ts @@ -9,17 +9,16 @@ import { } from "@silverbulletmd/silverbullet/lib/tree"; import { encodeRef, parseToRef } from "@silverbulletmd/silverbullet/lib/ref"; import { Fragment, renderHtml, type Tag } from "./html_render.ts"; -import { isLocalURL } from "@silverbulletmd/silverbullet/lib/resolve"; import * as TagConstants from "../../plugs/index/constants.ts"; import { extractHashtag } from "@silverbulletmd/silverbullet/lib/tags"; import { justifiedTableRender } from "./justified_tables.ts"; import type { PageMeta } from "../../type/index.ts"; +import { inlineContentFromURL, parseTransclusion } from "./inline.ts"; export type MarkdownRenderOptions = { failOnUnknown?: true; smartHardBreak?: true; annotationPositions?: true; - documentUrlPrefix?: string; preserveAttributes?: true; // When defined, use to inline images as data: urls translateUrls?: (url: string, type: "link" | "image") => string; @@ -218,19 +217,10 @@ function render( if (!urlNode) { return renderToText(t); } - let url = urlNode.children![0].text!; - if (isLocalURL(url)) { - if ( - options.documentUrlPrefix && - !url.startsWith(options.documentUrlPrefix) - ) { - url = `${options.documentUrlPrefix}${url}`; - } - } return { name: "a", attrs: { - href: url, + href: urlNode.children![0].text!, target: "_blank", }, body: cleanTags(mapRender(linkTextChildren)), @@ -241,15 +231,7 @@ function render( if (!urlNode) { return renderToText(t); } - let url = urlNode.children![0].text!; - if (isLocalURL(url)) { - if ( - options.documentUrlPrefix && - !url.startsWith(options.documentUrlPrefix) - ) { - url = `${options.documentUrlPrefix}${url}`; - } - } + const url = urlNode.children![0].text!; return { name: "a", attrs: { @@ -260,50 +242,33 @@ function render( }; } case "Image": { - const altTextNode = findNodeOfType(t, "WikiLinkAlias") || - t.children![1]; - let altText = altTextNode && altTextNode.type !== "LinkMark" - ? renderToText(altTextNode) - : ""; - const dimReg = /\d*[^\|\s]*?[xX]\d*[^\|\s]*/.exec(altText); - let style = ""; - if (dimReg) { - const [, width, widthUnit = "px", height, heightUnit = "px"] = - dimReg[0].match(/(\d*)(\S*?x?)??[xX](\d*)(.*)?/) ?? []; - if (width) { - style += `width: ${width}${widthUnit};`; - } - if (height) { - style += `height: ${height}${heightUnit};`; - } - altText = altText.replace(dimReg[0], "").replace("|", ""); + const text = renderToText(t); + + const transclusion = parseTransclusion(text); + if (!transclusion) { + return text; } - const urlNode = findNodeOfType(t, "WikiLinkPage") || - findNodeOfType(t, "URL"); - if (!urlNode) { - return renderToText(t); - } - let url = renderToText(urlNode); - if (urlNode.type === "WikiLinkPage") { - url = "/" + url; - } - - if ( - isLocalURL(url) && - options.documentUrlPrefix && - !url.startsWith(options.documentUrlPrefix) - ) { - url = `${options.documentUrlPrefix}${url}`; + const result = inlineContentFromURL( + client, + transclusion.url, + transclusion.alias, + transclusion.dimension, + transclusion.linktype !== "wikilink", + ); + if (!(result instanceof HTMLElement)) { + return text; } return { - name: "img", - attrs: { - src: url, - alt: altText, - style: style, - }, + name: result.tagName, + attrs: Array.from(result.attributes).reduce( + (obj, attr) => { + obj[attr.name] = attr.value; + return obj; + }, + {} as Record, + ), body: "", }; } diff --git a/web/markdown_util.ts b/web/markdown/result_render.ts similarity index 98% rename from web/markdown_util.ts rename to web/markdown/result_render.ts index 43815a0b..eeb6a1de 100644 --- a/web/markdown_util.ts +++ b/web/markdown/result_render.ts @@ -1,4 +1,4 @@ -import { LuaTable, luaToString } from "../lib/space_lua/runtime.ts"; +import { LuaTable, luaToString } from "../../lib/space_lua/runtime.ts"; export function defaultTransformer(v: any): Promise { if (v === undefined) { diff --git a/web/syscalls/markdown.ts b/web/syscalls/markdown.ts index ab897a08..9d41a302 100644 --- a/web/syscalls/markdown.ts +++ b/web/syscalls/markdown.ts @@ -2,7 +2,7 @@ import type { SysCallMapping } from "../../lib/plugos/system.ts"; import { parse } from "../markdown_parser/parse_tree.ts"; import { type ParseTree, renderToText } from "../../plug-api/lib/tree.ts"; import { extendedMarkdownLanguage } from "../markdown_parser/parser.ts"; -import { expandMarkdown } from "../markdown.ts"; +import { expandMarkdown } from "../markdown/inline.ts"; import type { Client } from "../client.ts"; import { LuaEnv, LuaStackFrame } from "../../lib/space_lua/runtime.ts"; import {