Improve Lua Widget Rendering

Lua `${...}` expression results are rendered using two parallel paths:

- **HTML path** (display path) for visual display in the editor and
- **Markdown path** (copy path) for the *copy button* output.

Every Lua value is classified as one of:

- **Scalar:** number, string, boolean, or `nil`
- **Empty table:** `{}`
- **Array:** a `LuaTable` with only sequential integer keys (no string keys)
- **Array of tables:** an array where every element is a `LuaTable`
- **Record:** a `LuaTable` with any string key (may also have integer keys)

Scalars are rendered as inline Markdown - wiki links, tags, bold, and
other inline syntax are resolved, `nil` renders as `<span data-empty>`.

Empty tables render as `<table data-table-empty>`.

An array of tables renders as a multi-row `<table>`. Column headers
are the union of all element keys. Each cell value recurses through
the same classification.

An array of scalars (or a mix of scalars and tables) renders as `<ul>`
with one `<li>` per element. Each item value recurses.

A record renders as a single-row `<table>` with one column per key.
Cell values recurse.

Every `<td>` carries `data-table-cell-type` and optionally
`data-table-cell-empty`.  Every `<li>` carries `data-list-item-type` and
optionally `data-list-item-empty`.  The outermost element carries
`data-type`.  These attributes allow CSS styling of rendered widgets.

Nesting is **unlimited**. Tables inside cells, lists inside cells,
tables inside list items all render correctly in HTML.

Scalars render as plain text. Lua `nil` renders as `nil`. Empty tables
render as `*(empty table)*`.

An array of tables renders as a pipe-delimited Markdown table. Nested
values in cells are rendered as Lua literals via `toStringAsync()`
(e.g. `{1, 2, 3}` or `{a = 1}`), since Markdown table cells cannot
contain block-level content.

An array of scalars renders as a Markdown list (`- item`). When a list
item is itself multi-line (a sublist) it uses an empty bullet with
two-space indented content on the next line:

```
- 1
- 2
-
  - nested 1
  - nested 2
```

Nested tables or arrays **beyond the first list nesting** level are
rendered as Lua literals.

A record renders as a single-row Markdown table.

Column headers follow the order returned by `LuaTable.keys`: string keys
in their insertion order, followed by integer keys in ascending order.
For example, `{a = 1, b = 2, 3, d = 4}` produces columns `a
| b | d | 1`. This is consequence of `LuaTable` storing string keys
and the array part separately (for performance).

Arrays mixing plain scalars and record-like tables (e.g.  `{1, 2, 3,
{a=3}}`) were previously rendered as a single flat table due to an
internal JS conversion (`toJS`). They now render as a list, with record
elements shown as nested tables - which more accurately reflects their
Lua structure. This is the only divergence from the original
presentation.

To restore the old tabular layout, wrap all elements as records with
a consistent key:

```lua
-- Before (was a flat table, now a list with nested table):
${{1, 2, 3, {a=3}}}

-- After (explicit records, renders as a table):
${{{value=1}, {value=2}, {value=3}, {a=3}}}
```

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>
This commit is contained in:
Matouš Jan Fialka
2026-03-09 11:45:04 +01:00
parent a5c9227499
commit 2aaa797bda
4 changed files with 557 additions and 63 deletions
+53 -56
View File
@@ -13,15 +13,13 @@ import {
moveCursorIntoText,
} from "./widget_util.ts";
import { expandMarkdown } from "../markdown_renderer/inline.ts";
import { luaFormatNumber, LuaTable } from "../space_lua/runtime.ts";
import { isTaggedFloat } from "../space_lua/numeric.ts";
import {
isBlockMarkdown,
jsonToMDTable,
refCellTransformer,
renderExpressionResult,
} from "../markdown_renderer/result_render.ts";
import { activeWidgets } from "./code_widget.ts";
import type { Ref } from "@silverbulletmd/silverbullet/lib/ref";
import { renderResultToHtml } from "../space_lua/render_lua_html.ts";
export type LuaWidgetCallback = (
bodyText: string,
@@ -95,6 +93,26 @@ export class LuaWidget extends WidgetType {
return wrapperSpan;
}
// Build an inline Markdown renderer bound to the current client context
private buildInlineRenderer(): (text: string) => string {
return (text: string): string => {
const mdTree = parse(extendedMarkdownLanguage, text);
return renderMarkdownToHtml(mdTree, {
shortWikiLinks: this.client.config.get("shortWikiLinks", false),
translateUrls: (url) => {
if (isLocalURL(url)) {
url = resolveMarkdownLink(
this.client.currentName(),
decodeURI(url),
);
}
return url;
},
preserveAttributes: true,
}, this.client.ui.viewState.allPages);
};
}
async renderContent(
div: HTMLElement,
) {
@@ -121,38 +139,53 @@ export class LuaWidget extends WidgetType {
let block = false;
let copyContent: string | undefined = undefined;
// Normalization
// Normalization (non-widget results go through dual-path rendering)
if (typeof widgetContent === "string" || !widgetContent._isWidget) {
// Apply heuristic to render the object as a markdown table
// HTML path for display (with data attributes, nested structures)
const inlineRenderer = this.buildInlineRenderer();
const { html: displayHtml, dataType } = await renderResultToHtml(
widgetContent,
inlineRenderer,
);
// Markdown path for copy button (flat tables, `{...}` for nested)
const markdownCopy = await renderExpressionResult(widgetContent);
widgetContent = {
_isWidget: true,
markdown: await renderExpressionResult(widgetContent),
html: `<span data-type="${dataType}">${displayHtml}</span>`,
display: (dataType === "table" || dataType === "list")
? "block"
: "inline",
};
copyContent = markdownCopy;
}
if (widgetContent.cssClasses) {
div.className = widgetContent.cssClasses.join(" ");
// After normalization `widgetContent` is always the object form
const wc = widgetContent as Exclude<LuaWidgetContent, string>;
if (wc.cssClasses) {
div.className = wc.cssClasses.join(" ");
}
if (widgetContent.html) {
if (typeof widgetContent.html === "string") {
html = parseHtmlString(widgetContent.html);
copyContent = widgetContent.html;
if (wc.html) {
if (typeof wc.html === "string") {
html = parseHtmlString(wc.html);
if (!copyContent) copyContent = wc.html;
} else {
html = widgetContent.html;
copyContent = widgetContent.html.outerHTML;
html = wc.html;
if (!copyContent) copyContent = wc.html.outerHTML;
}
block = widgetContent.display === "block";
block = wc.display === "block";
if (block) {
div.className += " sb-lua-directive-block";
} else {
div.className += " sb-lua-directive-inline";
}
}
if (widgetContent.markdown) {
if (wc.markdown) {
let mdTree = parse(
extendedMarkdownLanguage,
widgetContent.markdown || "",
wc.markdown || "",
);
mdTree = await expandMarkdown(
@@ -176,7 +209,7 @@ export class LuaWidget extends WidgetType {
return;
}
block = widgetContent._isWidget && widgetContent.display === "block" ||
block = wc._isWidget && wc.display === "block" ||
isBlockMarkdown(trimmedMarkdown);
if (block) {
div.className += " sb-lua-directive-block";
@@ -211,7 +244,7 @@ export class LuaWidget extends WidgetType {
div,
this.client,
this.inPage ? this.codeText : undefined,
widgetContent._isWidget && widgetContent.events,
wc._isWidget && wc.events,
);
}
@@ -343,42 +376,6 @@ export class LuaWidget extends WidgetType {
}
}
export function renderExpressionResult(result: any): Promise<string> {
if (result instanceof LuaTable) {
result = result.toJS();
}
// Must check before object/array checks — tagged floats are plain objects
if (isTaggedFloat(result)) {
return Promise.resolve(luaFormatNumber(result.value, "float"));
}
if (typeof result === "number") {
return Promise.resolve(luaFormatNumber(result));
}
if (
Array.isArray(result) && result.length > 0 && typeof result[0] === "object"
) {
// If result is an array of objects, render as a Markdown table
try {
return jsonToMDTable(result, refCellTransformer);
} catch (e: any) {
console.error(
`Error rendering expression directive: ${e.message} for value ${
JSON.stringify(result)
}`,
);
return Promise.resolve(JSON.stringify(result));
}
} else if (typeof result === "object" && result.constructor === Object) {
// If result is a plain object, render as a Markdown table
return jsonToMDTable([result], refCellTransformer);
} else if (Array.isArray(result)) {
// Not-object array, let's render it as a Markdown list
return Promise.resolve(result.map((item) => `- ${item}`).join("\n"));
} else {
return Promise.resolve("" + result);
}
}
export function parseHtmlString(html: string): HTMLElement {
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");