diff --git a/client/client_system.ts b/client/client_system.ts index e5e3e8f7..9e3fe4f8 100644 --- a/client/client_system.ts +++ b/client/client_system.ts @@ -43,6 +43,7 @@ import { eventSyscalls } from "./plugos/syscalls/event.ts"; import { DocumentEditorHook } from "./plugos/hooks/document_editor.ts"; import type { Command } from "./types/command.ts"; import { SpaceLuaEnvironment } from "./space_lua.ts"; +import type { ILuaFunction } from "./space_lua/runtime.ts"; import { builtinPlugPaths } from "../plugs/builtin_plugs.ts"; import { registerEditorCommands } from "./editor_commands.ts"; import { ServiceRegistry } from "./service_registry.ts"; @@ -71,6 +72,11 @@ export class ClientSystem { // Space Lua spaceLuaEnv: SpaceLuaEnvironment; readonly scriptCommands = new Map(); + // Code widgets registered from Space Lua (language -> definition) + readonly luaCodeWidgets = new Map< + string, + { language: string; render: ILuaFunction } + >(); scriptsLoaded: boolean = false; // Known files (for UI) @@ -214,6 +220,20 @@ export class ClientSystem { this.scriptCommands.set(name, command); } + // Reset + collect Space Lua code widgets + this.luaCodeWidgets.clear(); + for ( + const [language, def] of Object.entries( + this.client.config.get< + Record + >("codeWidgets", {}), + ) + ) { + if (def && typeof (def as any).render?.call === "function") { + this.luaCodeWidgets.set(language, def); + } + } + // Make scripted (slash) commands available this.commandHook.throttledBuildAllCommandsAndEmit(); this.slashCommandHook.throttledBuildAllCommands(); diff --git a/client/codemirror/fenced_code.ts b/client/codemirror/fenced_code.ts index b87fe33f..83cae2e0 100644 --- a/client/codemirror/fenced_code.ts +++ b/client/codemirror/fenced_code.ts @@ -10,6 +10,8 @@ import { } from "./util.ts"; import { IFrameWidget } from "./iframe_widget.ts"; import { LoadingWidget } from "./loading_widget.ts"; +import { LuaWidget } from "./lua_widget.ts"; +import { renderLuaCallback } from "../space_lua/render_widget.ts"; export function fencedCodePlugin(client: Client) { return decoratorStateField((state: EditorState) => { @@ -23,9 +25,87 @@ export function fencedCodePlugin(client: Client) { } const text = state.sliceDoc(from, to); const [_, lang] = text.match(/^(?:```+|~~~+)(\w+)?/)!; + const renderMode = widgetRenderMode(client); + + const luaWidgetDef = lang + ? client.clientSystem.luaCodeWidgets.get(lang) + : undefined; const codeWidgetCallback = client.clientSystem.codeWidgetHook.codeWidgetCallbacks.get(lang); - const renderMode = widgetRenderMode(client); + + // Lua-registered code widgets win precedence over plug ones. + if (luaWidgetDef && renderMode !== "disabled") { + const lineStrings = text.split("\n"); + + const lines: { from: number; to: number }[] = []; + let fromIt = from; + for (const line of lineStrings) { + lines.push({ + from: fromIt, + to: fromIt + line.length, + }); + fromIt += line.length + 1; + } + + const firstLine = lines[0], + lastLine = lines[lines.length - 1]; + + // In case of doubt, back out + if (!firstLine || !lastLine) return; + + widgets.push( + invisibleDecoration.range(firstLine.from, firstLine.to), + ); + widgets.push(invisibleDecoration.range(lastLine.from, lastLine.to)); + widgets.push( + Decoration.line({ + class: "sb-fenced-code-iframe", + }).range(firstLine.from), + ); + widgets.push( + Decoration.line({ + class: "sb-fenced-code-hide", + }).range(lastLine.from), + ); + + lines.slice(1, lines.length - 1).forEach((line) => { + widgets.push( + Decoration.line({ class: "sb-line-table-outside" }).range( + line.from, + ), + ); + }); + + const bodyText = lineStrings + .slice(1, lineStrings.length - 1) + .join("\n"); + const pageName = client.currentName(); + const currentPageMeta = client.currentPageMeta(); + const widget = renderMode === "loading" + ? new LoadingWidget(true) + : new LuaWidget({ + client, + cacheKey: `codewidget:${lang}:${pageName}:${bodyText}`, + expressionText: bodyText, + codeText: text, + callback: () => + renderLuaCallback( + client, + luaWidgetDef.render, + [bodyText, pageName], + currentPageMeta, + ), + renderEmpty: false, + inPage: true, + }); + widgets.push( + Decoration.widget({ + widget: widget, + }).range(from), + ); + return false; + } + // Only custom render when we have a custom renderer, and the current page is not a template if (codeWidgetCallback && renderMode !== "disabled") { // We got a custom renderer! diff --git a/client/codemirror/lua_directive.ts b/client/codemirror/lua_directive.ts index 6198ac21..599917f7 100644 --- a/client/codemirror/lua_directive.ts +++ b/client/codemirror/lua_directive.ts @@ -8,22 +8,7 @@ import { widgetRenderMode, } from "./util.ts"; import type { Client } from "../client.ts"; -import { parseExpressionString } from "../space_lua/parse.ts"; -import { evalExpression } from "../space_lua/eval.ts"; -import { - LuaEnv, - LuaRuntimeError, - LuaStackFrame, - LuaTable, - luaValueToJS, - singleResult, -} from "../space_lua/runtime.ts"; -import { isTaggedFloat } from "../space_lua/numeric.ts"; -import { - encodeRef, - getNameFromPath, -} from "@silverbulletmd/silverbullet/lib/ref"; -import { resolveASTReference } from "../space_lua.ts"; +import { renderLuaExpression } from "../space_lua/render_widget.ts"; import { LuaWidget } from "./lua_widget.ts"; import { LoadingWidget } from "./loading_widget.ts"; @@ -96,66 +81,8 @@ export function luaDirectivePlugin(client: Client) { cacheKey: `lua:${expressionText}:${currentPageMeta?.name}`, expressionText, codeText, - callback: async (bodyText) => { - if (bodyText.trim().length === 0) { - return "**Error:** Empty Lua expression"; - } - try { - const expr = parseExpressionString(bodyText); - - const tl = new LuaEnv(); - tl.setLocal( - "currentPage", - currentPageMeta || - (client.ui.viewState.current - ? { - name: getNameFromPath( - client.ui.viewState.current.path, - ), - } - : undefined), - ); - const sf = LuaStackFrame.createWithGlobalEnv( - client.clientSystem.spaceLuaEnv.env, - expr.ctx, - ); - const threadLocalizedEnv = new LuaEnv( - client.clientSystem.spaceLuaEnv.env, - ); - threadLocalizedEnv.setLocal("_CTX", tl); - const rawResult = singleResult( - await evalExpression(expr, threadLocalizedEnv, sf), - ); - // keep tagged floats as-is for proper formatting - if ( - isTaggedFloat(rawResult) || - typeof rawResult === "number" - ) { - return rawResult; - } - if (rawResult instanceof LuaTable) { - if (rawResult.rawGet("_isWidget")) { - return luaValueToJS(rawResult, sf); - } - return rawResult; - } - // everything else needs luaValueToJS for widget support - return luaValueToJS(rawResult, sf); - } catch (e: any) { - if (e instanceof LuaRuntimeError) { - if (e.sf?.astCtx) { - const source = resolveASTReference(e.sf.astCtx); - if (source) { - // We know the origin node of the error, let's reference it - return `**Lua error:** ${e.message} (Origin: [[${encodeRef( - source, - )}]])`; - } - } - } - return `**Lua error:** ${e.message}`; - } - }, + callback: (bodyText) => + renderLuaExpression(client, bodyText, currentPageMeta), renderEmpty: true, inPage: true, }), diff --git a/client/codemirror/lua_widget.ts b/client/codemirror/lua_widget.ts index 5a296a0f..84629054 100644 --- a/client/codemirror/lua_widget.ts +++ b/client/codemirror/lua_widget.ts @@ -21,6 +21,7 @@ import { buildTranslateUrls, moveCursorToWidgetStart, } from "./widget_util.ts"; +import { createWidgetSandboxIFrame } from "../components/widget_sandbox_iframe.ts"; export type LuaWidgetCallback = ( bodyText: string, @@ -45,6 +46,8 @@ export type LuaWidgetContent = display?: "block" | "inline"; // Event handlers events?: Record void>; + // when present, html+script render inside a sandbox iframe (see renderContent) + script?: string; } | string; @@ -202,6 +205,46 @@ export class LuaWidget extends WidgetType { if (wc.cssClasses) { div.className = wc.cssClasses.join(" "); } + + // When a script is present, render html+script inside a sandbox iframe + if (wc.script) { + div.className += " sb-lua-directive-block"; + const iframeContent = { + html: typeof wc.html === "string" ? wc.html : "", + script: wc.script, + }; + const iframe = createWidgetSandboxIFrame( + this.opts.client, + this.opts.cacheKey, + iframeContent, + (message) => { + switch (message.type) { + case "blur": { + const pos = this.opts.client.editorView.posAtDOM(iframe, 0); + this.opts.client.editorView.dispatch({ + selection: { anchor: pos }, + }); + this.opts.client.focus(); + break; + } + } + }, + ); + const cachedHeight = this.opts.client.widgetCache.getCachedWidgetHeight( + this.opts.cacheKey, + ); + iframe.style.height = `${cachedHeight > 0 ? cachedHeight : 150}px`; + iframe.style.display = "block"; + const wrapped = this.wrapHtml(true, iframe, wc.markdown); + div.replaceChildren(wrapped); + div.style.minHeight = ""; + this.opts.client.widgetCache.setCachedWidgetMeta(this.opts.cacheKey, { + height: cachedHeight > 0 ? cachedHeight : 150, + block: true, + }); + return; + } + if (wc.html) { if (typeof wc.html === "string") { html = parseHtmlString(wc.html); diff --git a/client/space_lua/render_widget.ts b/client/space_lua/render_widget.ts new file mode 100644 index 00000000..e6ff3259 --- /dev/null +++ b/client/space_lua/render_widget.ts @@ -0,0 +1,104 @@ +import type { ASTCtx } from "./ast.ts"; +import { evalExpression } from "./eval.ts"; +import { parseExpressionString } from "./parse.ts"; +import { + type ILuaFunction, + LuaEnv, + LuaRuntimeError, + LuaStackFrame, + LuaTable, + type LuaValue, + luaValueToJS, + singleResult, +} from "./runtime.ts"; +import { isTaggedFloat } from "./numeric.ts"; +import { + encodeRef, + getNameFromPath, +} from "@silverbulletmd/silverbullet/lib/ref"; +import { resolveASTReference } from "../space_lua.ts"; +import type { Client } from "../client.ts"; + +/** + * Run a Space Lua computation and convert its result into something the + * LuaWidget renderer understands (a widget table, markdown string, or number). + * Shared by the `${...}` directive and Lua code widgets so the conversion + + * error formatting live in one place. + */ +export async function renderLuaWidgetResult( + client: Client, + compute: (env: LuaEnv, sf: LuaStackFrame) => Promise | LuaValue, + ctx: ASTCtx, + currentPageMeta?: { name: string } | undefined, +): Promise { + try { + const tl = new LuaEnv(); + tl.setLocal( + "currentPage", + currentPageMeta || + (client.ui.viewState.current + ? { name: getNameFromPath(client.ui.viewState.current.path) } + : undefined), + ); + const sf = LuaStackFrame.createWithGlobalEnv( + client.clientSystem.spaceLuaEnv.env, + ctx, + ); + const env = new LuaEnv(client.clientSystem.spaceLuaEnv.env); + env.setLocal("_CTX", tl); + const rawResult = singleResult(await compute(env, sf)); + if (isTaggedFloat(rawResult) || typeof rawResult === "number") { + return rawResult; + } + if (rawResult instanceof LuaTable) { + if (rawResult.rawGet("_isWidget")) { + return luaValueToJS(rawResult, sf); + } + return rawResult; + } + return luaValueToJS(rawResult, sf); + } catch (e: any) { + if (e instanceof LuaRuntimeError && e.sf?.astCtx) { + const source = resolveASTReference(e.sf.astCtx); + if (source) { + return `**Lua error:** ${e.message} (Origin: [[${ + encodeRef(source) + }]])`; + } + } + return `**Lua error:** ${e.message}`; + } +} + +/** Evaluate a `${...}`-style expression string and render it as a widget. */ +export async function renderLuaExpression( + client: Client, + expressionText: string, + currentPageMeta?: { name: string } | undefined, +): Promise { + if (expressionText.trim().length === 0) { + return "**Error:** Empty Lua expression"; + } + const expr = parseExpressionString(expressionText); + return renderLuaWidgetResult( + client, + (env, sf) => evalExpression(expr, env, sf), + expr.ctx, + currentPageMeta, + ); +} + +/** Call a stored Lua render function (e.g. a code widget) and render it. */ +export async function renderLuaCallback( + client: Client, + fn: ILuaFunction, + args: LuaValue[], + currentPageMeta?: { name: string } | undefined, +): Promise { + return renderLuaWidgetResult( + client, + (_env, sf) => fn.call(sf, ...args), + {} as ASTCtx, + currentPageMeta, + ); +}