1
0
silverbullet/plugs/directive/util.ts

78 lines
1.9 KiB
TypeScript
Raw Normal View History

import { handlebars, space } from "$sb/syscalls.ts";
import { handlebarHelpers } from "../../common/syscalls/handlebar_helpers.ts";
import { PageMeta } from "$sb/types.ts";
import { cleanTemplate } from "../template/plug_api.ts";
export function defaultJsonTransformer(_k: string, v: any) {
if (v === undefined) {
return "";
}
if (typeof v === "string") {
return v.replaceAll("\n", " ").replaceAll("|", "\\|");
}
return "" + v;
}
// Nicely format an array of JSON objects as a Markdown table
export function jsonToMDTable(
jsonArray: any[],
valueTransformer: (k: string, v: any) => string = defaultJsonTransformer,
): string {
2023-10-29 11:09:12 +00:00
const headers = new Set<string>();
2022-10-15 17:02:56 +00:00
for (const entry of jsonArray) {
for (const k of Object.keys(entry)) {
2023-10-29 11:09:12 +00:00
headers.add(k);
}
}
2022-04-29 11:37:31 +00:00
2023-10-29 11:09:12 +00:00
const headerList = [...headers];
2022-10-14 13:11:33 +00:00
const lines = [];
2022-04-29 11:37:31 +00:00
lines.push(
"|" +
headerList
.map(
2023-10-29 11:09:12 +00:00
(headerName) => headerName,
2022-04-29 11:37:31 +00:00
)
.join("|") +
2022-10-12 09:47:13 +00:00
"|",
2022-04-29 11:37:31 +00:00
);
lines.push(
"|" +
headerList
2023-10-29 11:09:12 +00:00
.map(() => "--")
2022-04-29 11:37:31 +00:00
.join("|") +
2022-10-12 09:47:13 +00:00
"|",
2022-04-29 11:37:31 +00:00
);
for (const val of jsonArray) {
2022-10-15 17:02:56 +00:00
const el = [];
for (const prop of headerList) {
const s = valueTransformer(prop, val[prop]);
2023-10-29 11:09:12 +00:00
el.push(s);
}
lines.push("|" + el.join("|") + "|");
}
return lines.join("\n");
}
export async function renderQueryTemplate(
pageMeta: PageMeta,
templatePage: string,
data: any[],
2023-10-30 13:15:12 +00:00
renderAll: boolean,
): Promise<string> {
let templateText = await space.readPage(templatePage);
templateText = await cleanTemplate(templateText);
2023-10-30 13:15:12 +00:00
if (!renderAll) {
templateText = `{{#each .}}\n${templateText}\n{{/each}}`;
}
return handlebars.renderTemplate(templateText, data, { page: pageMeta });
}
export function buildHandebarOptions(pageMeta: PageMeta) {
return {
helpers: handlebarHelpers(),
data: { page: pageMeta },
};
}