Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(docs): list interface members in one table
Elian Doran51d151a016c8
diff --git a/apps/edit-docs/src/typedoc_markdown.spec.ts b/apps/edit-docs/src/typedoc_markdown.spec.tsindex 06970badf8..4899f4ab4d 100644--- a/apps/edit-docs/src/typedoc_markdown.spec.ts+++ b/apps/edit-docs/src/typedoc_markdown.spec.ts@@ -29,6 +29,9 @@ export interface Unreached {/** Window controls. */export interface DemoWindowApi {+ /** Whether the window has the focus. */+ readonly focused: boolean;+/*** Resizes the window.*@@ -71,6 +74,13 @@ describe("typeDocToMarkdown", () => {await rm(dir, { recursive: true, force: true });});+ /** The row of the members table that documents `name`, which nested tables are part of. */+ const row = (name: string) => {+ const start = markdown.indexOf(`<td><code>${name}</code>`);+ expect(start).toBeGreaterThan(-1);+ return markdown.slice(start, markdown.indexOf("\n </tr>", start));+ };+it("opens with the package comment, then the root and what it reaches, in order of reference", () => {expect(markdown.startsWith("The demo API, exposed as `window.demoApi`.\n\n## `DemoApi`")).toBe(true);@@ -95,40 +105,42 @@ describe("typeDocToMarkdown", () => {expect(markdown).toContain("| `animate`<br>*optional* | `boolean` |");});- it("gives each method its signature, parameters and return value", () => {- expect(markdown).toContain([- "### `resize`",- "",- "```ts",- "resize(options: ResizeOptions): Promise<boolean>",- "```",- "",- "Resizes the window.",- "",- "| Parameter | Description |",- "| --- | --- |",- "| `options` | `ResizeOptions`<br>How to resize. |",- "",- "**Returns** `Promise<boolean>`: Whether it resized."+ it("lists the members of an interface with methods in one HTML table, in the export's layout", () => {+ const section = markdown.slice(markdown.indexOf("## `DemoWindowApi`"), markdown.indexOf("## `ResizeOptions`"));+ expect(section).toContain([+ "<table>",+ " <thead>",+ " <tr>",+ " <th>Member</th>",+ " <th>Description</th>",+ " </tr>",+ " </thead>",+ " <tbody>",+ " <tr>",+ " <td><code>focused</code></td>"].join("\n"));- // A function type is written out; a method without a documented return still names its type.- expect(markdown).toContain("onClose(callback: (reason: string) => void): () => void");- expect(markdown).toContain("| `callback` | `(reason: string) => void` |");- expect(markdown).toContain("**Returns** `() => void`");+ // A blank line would end the HTML block when the page is imported.+ const table = section.slice(section.indexOf("<table>"), section.indexOf("</table>\n") + 8);+ expect(table).not.toMatch(/\n[ \t]*\n/);+ expect(row("focused")).toContain("<code>boolean</code><br>Whether the window has the focus.");+ });++ it("gives a method its signature and description, and parameters and return only when documented", () => {+ const resize = row("resize");+ expect(resize).toMatch(/<pre><code class="language-[^"]+">resize\(options: ResizeOptions\): Promise<boolean><\/code><\/pre>/);+ expect(resize).toContain("<p>Resizes the window.</p>");+ expect(resize).toMatch(/<th>Parameter<\/th>.*<td><code>options<\/code><\/td><td><code>ResizeOptions<\/code><br>How to resize.<\/td>/);+ expect(resize).toContain("<strong>Returns</strong> <code>Promise<boolean></code>: Whether it resized.");++ // Without descriptions, the signature already says everything a table or a Returns line would.+ const onClose = row("onClose");+ expect(onClose).toContain("onClose(callback: (reason: string) => void): () => void");+ expect(onClose).not.toContain("<table>");+ expect(onClose).not.toContain("Returns");});it("warns about a deprecated member and writes links as code", () => {- expect(markdown).toContain([- "### `maximize`",- "",- "```ts",- "maximize(): void",- "```",- "",- "> [!WARNING]",- "> Deprecated. Use `resize`."- ].join("\n"));- expect(markdown).not.toContain("**Returns** `void`");+ expect(row("maximize")).toMatch(/<aside class="admonition warning">.*Deprecated. Use <code>resize<\/code>./);expect(markdown).toContain("Options of `DemoWindowApi.resize`.");});diff --git a/apps/edit-docs/src/typedoc_markdown.ts b/apps/edit-docs/src/typedoc_markdown.tsindex 19eb7aa5f0..e66b8479c7 100644--- a/apps/edit-docs/src/typedoc_markdown.ts+++ b/apps/edit-docs/src/typedoc_markdown.ts@@ -3,6 +3,7 @@* a User Guide page. The page's title comes from its note, so the output starts with the module's* `@packageDocumentation` comment rather than an H1.*/+import { renderToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";import type { JSONOutput } from "typedoc";type Project = JSONOutput.ProjectReflection;@@ -114,32 +115,44 @@ function renderDeclaration(declaration: Declaration) {return blocks;}- const members = declaration.children ?? [];- const properties = members.filter((member) => member.kind === KIND.property || member.kind === KIND.accessor);- const methods = members.filter((member) => member.kind === KIND.method);+ const members = (declaration.children ?? []).filter((member) =>+ member.kind === KIND.property || member.kind === KIND.accessor || member.kind === KIND.method);+ if (!members.length) {+ return blocks;+ }- if (properties.length) {- blocks.push(table([ "Property", "Description" ], properties.map((property) => [+ // Properties alone fit a Markdown table; a method's cell holds blocks, which only HTML can.+ if (!members.some((member) => member.kind === KIND.method)) {+ blocks.push(table([ "Property", "Description" ], members.map((property) => [property.flags.isOptional ? `${code(property.name)}<br>*optional*` : code(property.name),- details(typeToString(property.type ?? property.getSignature?.type), property.comment)+ propertyDetails(property)])));+ return blocks;}- for (const method of methods) {- blocks.push(...renderMethod(method));- }-+ blocks.push(htmlTable([ "Member", "Description" ], members.map((member) => [+ `<code>${escapeHtml(member.name)}</code>${member.flags.isOptional ? "<br><em>optional</em>" : ""}`,+ markdownToHtml(member.kind === KIND.method ? methodDetails(member) : propertyDetails(member))+ ])));return blocks;}-function renderMethod(method: Declaration) {+function propertyDetails(property: Declaration) {+ return details(typeToString(property.type ?? property.getSignature?.type), property.comment);+}++/**+ * A method's signature and description, then its parameters and its return value when a comment+ * describes them; otherwise the signature already says all they would.+ */+function methodDetails(method: Declaration) {const signatures = method.signatures ?? [];- const blocks = [ `### ${code(method.name)}`, fence(signatures.map(signatureToString).join("\n")) ];+ const blocks = [ fence(signatures.map(signatureToString).join("\n")) ];// Overloads share one entry, described by the first signature that has a comment.const signature = signatures.find((candidate) => candidate.comment) ?? signatures[0];if (!signature) {- return blocks;+ return blocks.join("\n\n");}if (signature.comment) {@@ -147,20 +160,19 @@ function renderMethod(method: Declaration) {}const parameters = signature.parameters ?? [];- if (parameters.length) {+ if (parameters.some((parameter) => parameter.comment)) {blocks.push(table([ "Parameter", "Description" ], parameters.map((parameter) => [parameter.flags.isOptional ? `${code(parameter.name)}<br>*optional*` : code(parameter.name),details(typeToString(parameter.type), parameter.comment)])));}- const returnType = typeToString(signature.type);- if (returnType !== "void") {- const description = blockTag(signature.comment, "@returns");- blocks.push(`**Returns** ${code(returnType)}${description ? `: ${description}` : ""}`);+ const returns = blockTag(signature.comment, "@returns");+ if (returns) {+ blocks.push(`**Returns** ${code(typeToString(signature.type))}: ${returns}`);}- return blocks;+ return blocks.filter(Boolean).join("\n\n");}/** A comment's summary, followed by a warning when it carries `@deprecated`. */@@ -290,6 +302,50 @@ function table(headers: string[], rows: string[][]) {return [ line(headers), `| ${headers.map(() => "---").join(" | ")} |`, ...rows.map(line) ].join("\n");}+/**+ * A table as the Markdown export writes one it keeps as HTML: a structural tag per line and+ * each cell's content on one line, so the page comes back from an import and export unchanged.+ */+function htmlTable(headers: string[], rows: string[][]) {+ const tableRow = (tag: string, cells: string[]) => [+ " <tr>",+ ...cells.map((cell) => ` <${tag}>${cell}</${tag}>`),+ " </tr>"+ ];+ return [+ "<table>",+ " <thead>",+ ...tableRow("th", headers),+ " </thead>",+ " <tbody>",+ ...rows.flatMap((cells) => tableRow("td", cells)),+ " </tbody>",+ "</table>"+ ].join("\n");+}++/**+ * Markdown rendered as a table cell takes it, in the form the export writes the cell: the import's+ * renderer, on one line outside `<pre>`, with quotes in text unescaped. A blank line in a `<pre>`+ * becomes ` `, since a blank line would end the HTML block.+ */+function markdownToHtml(markdown: string) {+ const html = renderToHtml(markdown, "", { sanitize: (dirtyHtml) => dirtyHtml, demoteH1: false })+ .trim()+ .replace(/>\n+</g, "><")+ .replace(/>([^<]*)</g, (_, text: string) => `>${text.replaceAll("'", "'").replaceAll(""", "\"")}<`);++ return html.split(/(<pre[\s\S]*?<\/pre>)/)+ .map((part) => part.startsWith("<pre")+ ? part.replace(/\n(?=[ \t]*(?:\n|$))/g, " ")+ : part.replace(/\s*\n\s*/g, " "))+ .join("");+}++function escapeHtml(text: string) {+ return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");+}+function code(text: string) {return text ? `\`${text}\`` : "";}