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): strip naming prefixes from a TypeScript reference
Elian Doran82508a2c37f1
diff --git a/apps/edit-docs/src/docs_pipeline.ts b/apps/edit-docs/src/docs_pipeline.tsindex 71ec349612..30ea926157 100644--- a/apps/edit-docs/src/docs_pipeline.ts+++ b/apps/edit-docs/src/docs_pipeline.ts@@ -19,7 +19,7 @@ import { deferred } from "../../../packages/commons/src/index.js";import { buildHelpBundle } from "./help_bundle_generator.js";import { buildHelpMeta, serializeHelpMeta, stripAppVersion } from "./help_meta_generator.js";import { openApiToMarkdown, type OpenApiSpec } from "./openapi_markdown.js";-import { runTypeDoc, typeDocToMarkdown } from "./typedoc_markdown.js";+import { runTypeDoc, type TypeDocMarkdownOptions, typeDocToMarkdown } from "./typedoc_markdown.js";export interface NoteMapping {rootNoteId: string;@@ -47,15 +47,13 @@ export interface OpenApiPage {spec: string;}-export interface TypeDocPage {+export interface TypeDocPage extends TypeDocMarkdownOptions {/** A text note of this mapping with a Markdown data file. */noteId: string;/** The module whose exports the page documents. Relative to the configuration file. */entryPoint: string;/** The tsconfig that compiles it. Relative to the configuration file. */tsconfig: string;- /** The export the page starts with, followed by what it refers to. */- root?: string;}export interface Config {@@ -190,7 +188,7 @@ async function writeGeneratedPages(mapping: NoteMapping) {})),...(mapping.typeDocPages ?? []).map((page) => ({noteId: page.noteId,- render: async () => typeDocToMarkdown(await runTypeDoc(page.entryPoint, page.tsconfig), page.root)+ render: async () => typeDocToMarkdown(await runTypeDoc(page.entryPoint, page.tsconfig), page)}))];if (!pages.length) {diff --git a/apps/edit-docs/src/typedoc_markdown.spec.ts b/apps/edit-docs/src/typedoc_markdown.spec.tsindex 1eb77176a3..a9e08b37c1 100644--- a/apps/edit-docs/src/typedoc_markdown.spec.ts+++ b/apps/edit-docs/src/typedoc_markdown.spec.ts@@ -69,7 +69,7 @@ export interface DemoWindowApi {/** The root of the API. */export interface DemoApi {- /** Window controls. */+ /** Window controls, as \`DemoWindowApi\` lists them. */window: DemoWindowApi;/** The version, as in \`1.2.3\`. */readonly version: string;@@ -83,6 +83,7 @@ export type Audience = "user" | "guest";describe("typeDocToMarkdown", () => {let dir: string;+ let project: Awaited<ReturnType<typeof runTypeDoc>>;let markdown: string;beforeAll(async () => {@@ -93,7 +94,8 @@ describe("typeDocToMarkdown", () => {compilerOptions: { strict: true, target: "ES2022", module: "ESNext", moduleResolution: "bundler" },files: [ "api.ts", "audience.ts" ]}));- markdown = typeDocToMarkdown(await runTypeDoc(join(dir, "api.ts"), join(dir, "tsconfig.json")), "DemoApi");+ project = await runTypeDoc(join(dir, "api.ts"), join(dir, "tsconfig.json"));+ markdown = typeDocToMarkdown(project, { root: "DemoApi" });}, 60_000);afterAll(async () => {@@ -128,7 +130,7 @@ describe("typeDocToMarkdown", () => {"","| Property | Description |","| --- | --- |",- "| `window` | `DemoWindowApi`<br>Window controls. |",+ "| `window` | `DemoWindowApi`<br>Window controls, as `DemoWindowApi` lists them. |","| `version` | `string`<br>The version, as in `1.2.3`. |"].join("\n"));// An optional property says so under its name; a union's pipe is escaped in its cell.@@ -218,4 +220,20 @@ describe("typeDocToMarkdown", () => {"| `\"declined\"` | The user declined it. |"].join("\n"));});++ it("strips the configured prefixes from the names of the declarations it shows", () => {+ const stripped = typeDocToMarkdown(project, { root: "DemoApi", stripPrefixes: [ "Demo" ] });+ const headings = [ ...stripped.matchAll(/^#+ `(\w+)`/gm) ].map(([ , name ]) => name);+ expect(headings).toEqual([ "Api", "WindowApi", "Audience", "ResizeOptions", "Outcome", "Size" ]);+ // References, signatures, links and code spans that name a declaration follow it.+ expect(stripped).toContain("| `window` | `WindowApi`<br>Window controls, as `WindowApi` lists them. |");+ expect(stripped).toContain("Options of `WindowApi.resize`.");+ expect(stripped).toContain("requestClose(audience: Audience): Promise<Outcome>");+ expect(stripped).not.toMatch(/Demo(Window)?Api/);+ });++ it("refuses prefixes that would give two declarations one name", () => {+ expect(() => typeDocToMarkdown(project, { root: "DemoApi", stripPrefixes: [ "Demo", "DemoWindow" ] }))+ .toThrow("DemoApi and DemoWindowApi would both be named Api");+ });});diff --git a/apps/edit-docs/src/typedoc_markdown.ts b/apps/edit-docs/src/typedoc_markdown.tsindex c916b7a5df..71ef0f6ae9 100644--- a/apps/edit-docs/src/typedoc_markdown.ts+++ b/apps/edit-docs/src/typedoc_markdown.ts@@ -61,9 +61,10 @@ export async function runTypeDoc(entryPoint: string, tsconfig: string): Promise<* they use follow under "Types". A union of literals that one place uses is written out there* instead of getting an entry.*/-export function typeDocToMarkdown(project: Project, root?: string): string {+export function typeDocToMarkdown(project: Project, { root, stripPrefixes = [] }: TypeDocMarkdownOptions = {}): string {const { declarations, inlined } = selectDeclarations(project, root);inlinedAliases = inlined;+ displayNames = stripNames(declarations.map((declaration) => declaration.name), stripPrefixes);try {const blocks: string[] = [];if (project.comment) {@@ -88,9 +89,20 @@ export function typeDocToMarkdown(project: Project, root?: string): string {return blocks.filter(Boolean).join("\n\n");} finally {inlinedAliases = new Map();+ displayNames = new Map();}}+export interface TypeDocMarkdownOptions {+ /** The export the page starts with; the page then shows only what it reaches. */+ root?: string;+ /**+ * Prefixes to leave out of the names of the declarations the page shows, such as `Script` to+ * write `ScriptNote` as `Note`. A prefix counts only before an uppercase letter.+ */+ stripPrefixes?: string[];+}+/** The `ReflectionKind` values this module renders. */const KIND = {interface: 256,@@ -103,6 +115,42 @@ const KIND = {/** The aliases `typeToString()` writes out in place of their name, while a page renders. */let inlinedAliases = new Map<string, Declaration>();+/** The names the page writes for the declarations it shows, where they differ, while it renders. */+let displayNames = new Map<string, string>();++/**+ * Maps each name that starts with one of `prefixes`, before an uppercase letter, to the name+ * without it, trying the longest prefix first. Throws when two names would end up the same.+ */+function stripNames(names: string[], prefixes: string[]) {+ const longestFirst = [ ...prefixes ].sort((a, b) => b.length - a.length);+ const renamed = new Map<string, string>();+ const owners = new Map<string, string>();+ for (const name of names) {+ const prefix = longestFirst.find((candidate) => name.startsWith(candidate) && /[A-Z]/.test(name.charAt(candidate.length)));+ const display = prefix ? name.slice(prefix.length) : name;+ const owner = owners.get(display);+ if (owner !== undefined) {+ throw new Error(`${owner} and ${name} would both be named ${display}.`);+ }+ owners.set(display, name);+ if (display !== name) {+ renamed.set(name, display);+ }+ }+ return renamed;+}++function displayName(name: string) {+ return displayNames.get(name) ?? name;+}++/** A dotted reference, such as `Api.member`, with its first part renamed. */+function displayReference(reference: string) {+ const [ first, ...rest ] = reference.split(".");+ return [ displayName(first), ...rest ].join(".");+}+/*** What the page shows: `root` and what it reaches, or else the module's exports and the types they* import from other modules. The unions of literals that one of them uses are left out, and@@ -195,7 +243,7 @@ function referencedNames(declaration: Declaration) {}function renderDeclaration(declaration: Declaration, heading: string) {- const blocks = [ `${heading} ${code(declaration.name)}` ];+ const blocks = [ `${heading} ${code(displayName(declaration.name))}` ];if (declaration.comment) {blocks.push(renderComment(declaration.comment));}@@ -207,7 +255,7 @@ function renderDeclaration(declaration: Declaration, heading: string) {code(typeToString(value)),oneLine(partsToMarkdown(type.elementSummaries?.[index] ?? []))]))- : fence(`type ${declaration.name} = ${typeToString(type)}`));+ : fence(`type ${displayName(declaration.name)} = ${typeToString(type)}`));return blocks;}@@ -297,9 +345,19 @@ function blockTag(comment: Comment | undefined, tag: string) {return content ? partsToMarkdown(content) : "";}-/** Comment text as Markdown; a `{@link}` becomes its target's name as code. */+/**+ * Comment text as Markdown; a `{@link}` becomes its target's name as code. A code span that names+ * a declaration, such as `` `Api` `` or `` `Api.member` ``, follows its display name.+ */function partsToMarkdown(parts: JSONOutput.CommentDisplayPart[]) {- return parts.map((part) => part.kind === "inline-tag" ? code(part.text) : part.text).join("")+ const renderPart = (part: JSONOutput.CommentDisplayPart) => {+ if (part.kind === "inline-tag") {+ return code(displayReference(part.text));+ }+ const reference = part.kind === "code" ? /^`([\w$]+(?:\.[\w$]+)*)`$/.exec(part.text) : null;+ return reference ? code(displayReference(reference[1])) : part.text;+ };+ return parts.map(renderPart).join("").replaceAll("\r\n", "\n").trim();}@@ -342,7 +400,8 @@ function typeToString(type: SomeType | undefined): string {return typeToString(alias.type);}const args = type.typeArguments?.map(typeToString).join(", ");- return args ? `${type.name}<${args}>` : type.name;+ const name = displayName(type.name);+ return args ? `${name}<${args}>` : name;}case "literal":return type.value === null ? "null"diff --git a/docs/Developer Guide/Developer Guide/Documentation.md b/docs/Developer Guide/Developer Guide/Documentation.mdindex e7311cec49..05a117436d 100644--- a/docs/Developer Guide/Developer Guide/Documentation.md+++ b/docs/Developer Guide/Developer Guide/Documentation.md@@ -73,7 +73,7 @@ The `deploy-docs` workflow triggers the documentation build and uploads it to ClThe REST API references (ETAPI and the internal API), the Electron API reference and the frontend and backend script API references are User Guide pages whose Markdown is generated from their sources, so they appear both in the in-app help and on the website. `edit-docs-config.yaml` lists them for each documentation tree:* `openApiPages` renders an OpenAPI document (`apps/server/src/assets/etapi.openapi.yaml`, `apps/server/internal.openapi.yaml`), through `apps/edit-docs/src/openapi_markdown.ts`.-* `typeDocPages` renders the exports of a TypeScript module, as TypeDoc reads them, through `apps/edit-docs/src/typedoc_markdown.ts`. The Electron API page documents `packages/commons/src/lib/electron_api_interface.ts`, starting from `ElectronApi`; its introduction is the module's `@packageDocumentation` comment. The Frontend API and Backend API pages document `packages/commons/src/lib/script_api.ts`, the curated types that script notes' autocomplete also uses, starting from `FrontendApi` and `BackendApi`. A page with a `root` shows only what the root reaches, so one module can hold the types of several pages.+* `typeDocPages` renders the exports of a TypeScript module, as TypeDoc reads them, through `apps/edit-docs/src/typedoc_markdown.ts`. The Electron API page documents `packages/commons/src/lib/electron_api_interface.ts`, starting from `ElectronApi`; its introduction is the module's `@packageDocumentation` comment. The Frontend API and Backend API pages document `packages/commons/src/lib/script_api.ts`, the curated types that script notes' autocomplete also uses, starting from `FrontendApi` and `BackendApi`. A page with a `root` shows only what the root reaches, so one module can hold the types of several pages. `stripPrefixes` leaves a naming prefix out of the names the page shows, so `ScriptBNote` reads `BNote` and `ElectronWindowApi` reads `WindowApi`; references, signatures and code spans that name a type follow, and two types that would end up with one name stop the sync.Both `pnpm edit-docs:sync-docs` and `pnpm edit-docs:edit-docs` regenerate these pages before importing the documentation, so any edit made to them directly is overwritten. To change one, edit its source (the OpenAPI document, or the comments of the TypeScript module), then run `pnpm edit-docs:sync-docs` and commit the regenerated page along with the help files.