From 2faab5b5edb42bf8e4dc89b165e5731498b4f3b4 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 24 Oct 2026 13:59:28 -0500 Subject: [PATCH 1/8] feat(site[link-preview]) Say where an entry lives and which types its summary names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: The approved hover card ends in a muted line, `package · owner`, and marks each type named in its summary with the mark of its kind. A payload carried neither: the summary was one plain string, and nothing said where an entry lives. what: - Add two optional fields to the preview payload: `footer`, the places an entry lives, and `descriptionParts`, the summary as runs of text and the references it names, each with a site path and a kind. Schema 1 stays and an older payload reads as before; `description` is unchanged and is what a card shows when the runs are absent or differ from it - symbolPreview writes the declaring package and owner as the footer, and the runs from the same index and resolver that render the page's own summary; a declaration is never linked to itself - mcpObjectPreview writes the port and MCP section as the footer, and links the tools and prompts a description names by the rule the object's page uses - Glossary terms name their glossary and group; manual and catalog entries name the tmux release and where the entry is documented - Test that every symbol of every port reads as its description once the runs are joined, that references are site paths with a kind that has a mark, and that each producer's footer names what it should Measured with symbolPreview over every symbol of every port at `latest`: a footer on each of 17,170 cards, and named types on 1,333 of them. --- site/src/lib/link-preview.ts | 74 ++++++++++++++++++++-- site/src/lib/mcp-preview.ts | 46 ++++++++++++-- site/src/lib/tmux-catalog-preview.ts | 3 +- site/test/link-preview-payload.test.ts | 87 ++++++++++++++++++++++++++ site/test/tmux-mentions.test.ts | 4 +- 5 files changed, 203 insertions(+), 11 deletions(-) create mode 100644 site/test/link-preview-payload.test.ts diff --git a/site/src/lib/link-preview.ts b/site/src/lib/link-preview.ts index 19286a888..64d06bbe6 100644 --- a/site/src/lib/link-preview.ts +++ b/site/src/lib/link-preview.ts @@ -1,33 +1,93 @@ -import { docSummaryText, qualifiedNameOf, sourceUrl, type ApiModel, type ApiSymbol } from '@libtmux/api-model' -import { productApiHref } from './product-api' +import { docSummaryText, qualifiedNameOf, sourceUrl, type ApiModel, type ApiSymbol, type SymbolIndex } from '@libtmux/api-model' +import { productApiHref, productApiIndex } from './product-api' +import { PORT_BY_SLUG } from './ports' import { apiGlossary } from './api-glossary' import { codeLang, highlightTokens, type CodeHighlight } from './highlight' import { tmuxEntityHref } from './tmux-links' import { tmuxManual, tmuxManualEntities, tmuxManualEntityHref, tmuxManualUrl, type TmuxManualEntity } from './tmux-manual-data' +/** A name in a card's summary that has a page of its own, drawn with the mark of its kind. */ +export interface PreviewReference { + text: string + /** A path on this site. */ + href: string + kind?: string +} + /** Small, inert metadata shared by reference links and their preview cards. */ export interface LinkPreview { schema: 1 title: string kind?: string description: string + /** + * `description` as runs of text and the references it names, so a card can mark each with its kind. The runs read as + * `description`; a card that does not use them, or finds that they differ, shows `description` as it is. + */ + descriptionParts?: (string | PreviewReference)[] detail?: string signature?: string signatureLanguage?: string signatureHighlight?: CodeHighlight href: string + /** Where the entry lives, as the muted line at the foot of the card, such as its package and its owner. */ + footer?: string[] /** Replaces the card's default "Open reference" link text. */ actionLabel?: string source?: string terms?: Record } +const symbolsById = new WeakMap>() + +/** The symbol a member is declared in. */ +function ownerOf(model: ApiModel, symbol: ApiSymbol): ApiSymbol | undefined { + if (!symbol.parent) return undefined + let table = symbolsById.get(model) + if (!table) { table = new Map(model.symbols.map((entry) => [entry.id, entry])); symbolsById.set(model, table) } + return table.get(symbol.parent) +} + +/** A description as runs: neighbouring text is one run, and a named reference stands alone. */ +export function previewRuns() { + const parts: (string | PreviewReference)[] = [] + let referenced = false + return { + text(text: string) { + const last = parts.at(-1) + if (typeof last === 'string') parts[parts.length - 1] = last + text + else if (text) parts.push(text) + }, + reference(reference: PreviewReference) { parts.push(reference); referenced = true }, + /** The runs, when one of them names a reference and they read as `description`; a card shows `description` otherwise. */ + finish(description: string): LinkPreview['descriptionParts'] { + return referenced && parts.map((part) => typeof part === 'string' ? part : part.text).join('') === description ? parts : undefined + }, + } +} + +/** The summary as runs of text and the references that resolve to a page of this site. */ +function summaryParts(index: SymbolIndex, summary: string, context: ApiSymbol, description: string): LinkPreview['descriptionParts'] { + const runs = previewRuns() + for (const span of index.linkText(summary, context)) { + const text = span.kind === 'ref' || span.kind === 'citation' ? span.label : span.text + const target = span.kind === 'ref' && span.link && !span.link.external ? span.link.symbol : undefined + if (target && target.id !== context.id) runs.reference({ text, href: span.link!.href, kind: target.command?.kind ?? target.kind }) + else runs.text(text) + } + return runs.finish(description) +} + export function symbolPreview(model: ApiModel, symbol: ApiSymbol, version: string): LinkPreview { const summary = symbol.doc?.summary ?? symbol.signatures.find((signature) => signature.doc?.summary)?.doc?.summary const signature = symbol.signatures[0]?.raw ?? (symbol.value !== undefined ? `${symbol.name} = ${symbol.value}` : undefined) + const description = summary ? docSummaryText(summary, model.port) : '' + const footer = [symbol.package ?? PORT_BY_SLUG[model.port]?.packageName, ownerOf(model, symbol)?.name].filter((place): place is string => !!place) return { schema: 1, title: qualifiedNameOf(symbol), kind: symbol.command?.kind ?? symbol.kind, - description: summary ? docSummaryText(summary, model.port) : '', + description, + descriptionParts: summary ? summaryParts(productApiIndex(model, version), summary, symbol, description) : undefined, + footer: footer.length ? footer : undefined, signature, signatureLanguage: signature ? codeLang(model.port) : undefined, detail: symbol.signatures.length > 1 ? `${symbol.signatures.length} signatures in the full reference.` : undefined, @@ -46,16 +106,20 @@ export function glossaryPreview(href: string): LinkPreview { return { schema: 1, title: glossary.title, description: glossary.description, href: glossary.path, terms: Object.fromEntries(glossary.groups.flatMap((group) => group.terms.map((term) => [term.id, { schema: 1, title: term.id, kind: term.id, description: term.definition, detail: term.detail, - href: `${glossary.path}#${term.id}`, + href: `${glossary.path}#${term.id}`, footer: [glossary.title, group.title], } satisfies LinkPreview]))), } } const MANUAL_ACTION = 'Open manual' +/** Where a manual entry lives: the release it describes, then the manual. */ +const manualFooter = (version: string) => [`tmux ${tmuxManual(version).version}`, 'Manual'] + function tmuxEntityPreview(entity: TmuxManualEntity, version: string): LinkPreview { return { schema: 1, title: entity.name, kind: entity.kind, description: entity.summary || entity.detail, detail: entity.detail, + footer: manualFooter(version), signature: entity.usage, signatureLanguage: entity.usage ? 'tmux-usage' : undefined, href: tmuxManualEntityHref(entity.kind, entity.name, version)!, actionLabel: MANUAL_ACTION, } @@ -79,6 +143,6 @@ export function tmuxManualPreview(version: string, slug: string): LinkPreview { return { schema: 1, title: command.name, kind: 'command', description: command.summary, href: tmuxEntityHref('command', command.name, version)!, signature: `tmux ${command.name}${command.usage ? ` ${command.usage}` : ''}`, signatureLanguage: 'tmux-usage', - detail: command.alias ? `Alias: ${command.alias}.` : undefined, actionLabel: MANUAL_ACTION, + detail: command.alias ? `Alias: ${command.alias}.` : undefined, footer: manualFooter(version), actionLabel: MANUAL_ACTION, } } diff --git a/site/src/lib/mcp-preview.ts b/site/src/lib/mcp-preview.ts index 30e1e6bb7..5e36b01a8 100644 --- a/site/src/lib/mcp-preview.ts +++ b/site/src/lib/mcp-preview.ts @@ -1,14 +1,52 @@ -import { docSummaryText } from '@libtmux/api-model' -import type { McpObject } from './mcp-catalog' -import type { LinkPreview } from './link-preview' +import { docSummaryText, tokenizeDoc } from '@libtmux/api-model' +import { MCP_SECTIONS, resolveMcpObject, type McpObject } from './mcp-catalog' +import { previewRuns, type LinkPreview, type PreviewReference } from './link-preview' import { PORT_BY_SLUG, portPageUrl } from './ports' +/** The names a description gives its sibling tools and prompts, the way the object's own page links them. */ +const BARE_NAME = /\b[a-z][a-z0-9]*_[a-z0-9_]+\b/g + +/** + * The first paragraph as runs of text and the protocol objects it names, which resolve exactly as they do on the page + * (a backticked name, or a bare tool name, never the object itself). Nothing is returned when no name resolves. + */ +function descriptionParts(port: string, version: string, object: McpObject, paragraph: string): LinkPreview['descriptionParts'] { + const runs = previewRuns() + const link = (text: string): PreviewReference | undefined => { + const target = resolveMcpObject(port, text) + if (!target || target.id === object.id || (target.kind === 'tool' && object.kind === 'tool' && target.name === object.name)) return undefined + return { text, href: portPageUrl(PORT_BY_SLUG[port], version, target.path), kind: target.kind } + } + for (const span of tokenizeDoc(paragraph, port)) { + if (span.kind === 'code') { + const reference = link(span.text) + if (reference) runs.reference(reference) + else runs.text(span.text) + } else if (span.kind === 'ref' || span.kind === 'citation') runs.text(span.label) + else { + let start = 0 + for (const match of span.text.matchAll(BARE_NAME)) { + const reference = link(match[0]) + if (!reference) continue + runs.text(span.text.slice(start, match.index)) + runs.reference(reference) + start = match.index + match[0].length + } + runs.text(span.text.slice(start)) + } + } + return runs.finish(docSummaryText(paragraph, port)) +} + /** Preview protocol objects from the same captured registration as their page. */ export function mcpObjectPreview(port: string, version: string, object: McpObject): LinkPreview { const source = object.tool?.source + const paragraph = object.description.split(/\n\s*\n/, 1)[0] return { schema: 1, title: object.name, kind: object.kind, - description: docSummaryText(object.description.split(/\n\s*\n/, 1)[0], port), + description: docSummaryText(paragraph, port), + descriptionParts: descriptionParts(port, version, object, paragraph), + footer: [PORT_BY_SLUG[port].name, `MCP ${MCP_SECTIONS[object.section].toLowerCase()}`], signature: object.item?.uriTemplate ?? object.item?.uri, detail: object.tool?.enabledByDefault === false ? object.tool.enableOption ? `Enable with ${object.tool.enableOption}.` : 'Disabled in the default configuration.' diff --git a/site/src/lib/tmux-catalog-preview.ts b/site/src/lib/tmux-catalog-preview.ts index 46be31da3..df957dea5 100644 --- a/site/src/lib/tmux-catalog-preview.ts +++ b/site/src/lib/tmux-catalog-preview.ts @@ -1,5 +1,5 @@ import type { LinkPreview } from './link-preview' -import { CATALOG_KINDS, OPTION_TYPES, tmuxCatalogDefault, tmuxCatalogSourceUrl, tmuxCatalogUrl, tmuxCatalogValues, type CatalogEntry } from './tmux-catalog' +import { CATALOG_KINDS, OPTION_TYPES, tmuxCatalog, tmuxCatalogDefault, tmuxCatalogSourceUrl, tmuxCatalogUrl, tmuxCatalogValues, type CatalogEntry } from './tmux-catalog' /** Preview an entry from the same record as its page. */ export function tmuxCatalogPreview(version: string, entry: CatalogEntry): LinkPreview { @@ -15,6 +15,7 @@ export function tmuxCatalogPreview(version: string, entry: CatalogEntry): LinkPr schema: 1, title: entry.name, kind: entry.kind, description: entry.summary || `The ${entry.name} ${CATALOG_KINDS[entry.kind].singular} in tmux ${version}.`, detail: detail.filter(Boolean).join('; ') + '.', + footer: [`tmux ${tmuxCatalog(version).version}`, CATALOG_KINDS[entry.kind].label], signature: entry.kind === 'format' ? `#{${entry.name}}` : entry.kind === 'hook' ? `set-hook -g ${entry.name} 'command'` : `set-option -g ${entry.name} value`, signatureLanguage: 'tmux-config', href: tmuxCatalogUrl(version, entry.kind, entry.name), diff --git a/site/test/link-preview-payload.test.ts b/site/test/link-preview-payload.test.ts new file mode 100644 index 000000000..a7e2bc0f2 --- /dev/null +++ b/site/test/link-preview-payload.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest' +import { docSummaryText } from '@libtmux/api-model' +import { API_GLOSSARY_PATH } from '../src/lib/api-glossary' +import { API_MODELS } from '../src/lib/api-models' +import { kindMark } from '../src/lib/api-labels' +import { glossaryPreview, symbolPreview, tmuxManualPreview } from '../src/lib/link-preview' +import { mcpObjects } from '../src/lib/mcp-catalog' +import { mcpObjectPreview } from '../src/lib/mcp-preview' +import { tmuxCatalogEntries } from '../src/lib/tmux-catalog' +import { tmuxCatalogPreview } from '../src/lib/tmux-catalog-preview' + +/** What the producers write for a card: its footer, and the names its summary mentions. Both are optional additions to schema 1. */ +describe('the payloads that feed the card', () => { + it('keeps schema 1 and the original fields, and adds only optional ones', () => { + const model = API_MODELS.rs + for (const symbol of model.symbols.slice(0, 300)) { + const preview = symbolPreview(model, symbol, 'latest') + expect(preview.schema).toBe(1) + const summary = symbol.doc?.summary ?? symbol.signatures.find((signature) => signature.doc?.summary)?.doc?.summary + expect(preview.description).toBe(summary ? docSummaryText(summary, model.port) : '') + expect(Object.keys(JSON.parse(JSON.stringify(preview))).every((key) => ['schema', 'title', 'kind', 'description', 'descriptionParts', 'detail', 'signature', 'signatureLanguage', + 'href', 'footer', 'source'].includes(key)), symbol.id).toBe(true) + } + }) + + it('names the package and the owner of a member in its footer, and the package alone for a type', () => { + const model = API_MODELS.rs + const member = model.symbols.find((symbol) => symbol.parent && model.symbols.some((owner) => owner.id === symbol.parent))! + const owner = model.symbols.find((symbol) => symbol.id === member.parent)! + expect(symbolPreview(model, member, 'latest').footer).toEqual([member.package ?? 'libtmux', owner.name]) + const type = model.symbols.find((symbol) => !symbol.parent)! + expect(symbolPreview(model, type, 'latest').footer).toEqual([type.package ?? 'libtmux']) + }) + + it('reads each summary as its text and the names that resolve to a page, in every port', () => { + let marked = 0 + for (const [port, model] of Object.entries(API_MODELS)) { + for (const symbol of model.symbols) { + const preview = symbolPreview(model, symbol, 'latest') + if (!preview.descriptionParts) continue + marked++ + expect(preview.descriptionParts.map((part) => typeof part === 'string' ? part : part.text).join(''), `${port} ${symbol.id}`).toBe(preview.description) + for (const part of preview.descriptionParts) { + if (typeof part === 'string') continue + expect(part.href, `${port} ${symbol.id}`).toMatch(/^\/(?!\/)/) + expect(kindMark(part.kind === 'cmdlet' ? 'function' : part.kind!), `${port} ${symbol.id}: ${part.text}`).toBeDefined() + expect(part.text, `${port} ${symbol.id}`).not.toBe('') + } + // The card does not link a declaration to itself. + expect(preview.descriptionParts.some((part) => typeof part !== 'string' && part.href === preview.href), `${port} ${symbol.id}`).toBe(false) + } + } + expect(marked).toBeGreaterThan(0) + }) + + it('footers the rest of the kinds with where they live', () => { + const glossary = glossaryPreview(API_GLOSSARY_PATH) + expect(glossary.footer).toBeUndefined() + expect(glossary.terms!.struct.footer).toEqual(['API glossary', 'Symbol kinds']) + expect(glossary.terms!.inherited.footer).toEqual(['API glossary', 'Modifiers']) + const manual = tmuxManualPreview('latest', 'full') + expect(Object.values(manual.terms!).every((term) => term.footer?.[1] === 'Manual' && /^tmux \d/.test(term.footer[0]))).toBe(true) + expect(tmuxManualPreview('latest', 'new-session').footer).toEqual(manual.terms![Object.keys(manual.terms!)[0]].footer) + const hook = tmuxCatalogEntries('latest', 'hook')[0] + expect(tmuxCatalogPreview('latest', hook).footer).toEqual([manual.terms![Object.keys(manual.terms!)[0]].footer![0], 'Hooks']) + }) + + it('links the names that an MCP description gives its sibling objects, as its page does, and never the object itself', () => { + let linked = 0 + for (const port of ['ruby', 'py', 'ts', 'rs', 'go', 'java', 'julia']) { + for (const object of mcpObjects(port)) { + const preview = mcpObjectPreview(port, 'latest', object) + expect(preview.footer?.[0]).toBeTruthy() + expect(preview.footer?.[1]).toMatch(/^MCP (tools|prompts|resources)$/) + if (!preview.descriptionParts) continue + linked++ + expect(preview.descriptionParts.map((part) => typeof part === 'string' ? part : part.text).join('')).toBe(preview.description) + for (const part of preview.descriptionParts) { + if (typeof part === 'string') continue + expect(part.href).not.toBe(preview.href) + expect(['tool', 'prompt', 'resource', 'resource-template']).toContain(part.kind) + } + } + } + expect(linked).toBeGreaterThan(0) + }) +}) diff --git a/site/test/tmux-mentions.test.ts b/site/test/tmux-mentions.test.ts index a060bdc26..0a9aada6f 100644 --- a/site/test/tmux-mentions.test.ts +++ b/site/test/tmux-mentions.test.ts @@ -190,7 +190,7 @@ describe('tmux hover cards', () => { expect(tmuxManualPreview('latest', 'list-clients')).toEqual({ schema: 1, title: 'list-clients', kind: 'command', description: command.summary, signature: `tmux list-clients ${command.usage}`, signatureLanguage: 'tmux-usage', detail: 'Alias: lsc.', - href: '/tmux/latest/manual/list-clients/', actionLabel: 'Open manual', + href: '/tmux/latest/manual/list-clients/', actionLabel: 'Open manual', footer: [`tmux ${tmuxManual('latest').version}`, 'Manual'], }) }) @@ -200,12 +200,14 @@ describe('tmux hover cards', () => { expect(terms!.session_attached).toEqual({ schema: 1, title: 'session_attached', kind: 'format', description: 'Number of clients session is attached to', detail: 'Format variable', href: '/tmux/latest/manual/full/#session_attached', actionLabel: 'Open manual', + footer: [`tmux ${tmuxManual('latest').version}`, 'Manual'], }) expect(terms!['options-destroy-unattached']).toEqual({ schema: 1, title: 'destroy-unattached', kind: 'option', detail: 'Session option', description: 'If on, destroy the session after the last client has detached.', signature: 'destroy-unattached [off | on | keep-last | keep-group]', signatureLanguage: 'tmux-usage', href: '/tmux/latest/manual/full/#options-destroy-unattached', actionLabel: 'Open manual', + footer: [`tmux ${tmuxManual('latest').version}`, 'Manual'], }) expect(terms!['hooks-session-created']).toMatchObject({ kind: 'hook', detail: 'Hook', description: 'Run when a new session created.' }) for (const [anchor, term] of Object.entries(terms!)) { From 41a41bfc0253b81a308289b2547176e0bae8c2da Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 24 Oct 2026 14:06:00 -0500 Subject: [PATCH 2/8] feat(site[link-preview]) Draw every hover card from one description MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: Two paths drew a card: LinkPreview.astro wrote the keyword help in HTML, and the browser filled a second card by hand, slot by slot, from its own code. Neither matched the approved card in section 10 of the badge demo (Q+M): the legend chip and qualified name in the header, the declaration on its own band, kind marks on the types the summary names, and a muted `package · owner` footer. what: - link-preview-card.ts describes the card as data (`previewCard`) and writes it as HTML (`cardHtml`, for LinkPreview.astro) or into the live card (`paintCard`, for the browser). `paintCard` replaces what is in each `data-preview-*` slot and keeps the slot's element, so a focused control stays focused and the frame around the slots never varies - The header chip is the legend chip markup of the heading badge; a cmdlet keeps its word on the function colours, as the badge does. A name the summary mentions is drawn as prose draws it: the compact kind mark, then the name as a link. The mark letter is aria-hidden and the link's accessible name says the kind; a destination that is not a path on this site is shown as text - Restyle the card on gp-sphinx tokens only: header and declaration band on the secondary surface, summary on the page surface, muted footer carrying the way to the page. It is 28rem wide as in the demo and never wider than the viewport less 2rem. The signature band no longer takes the highlighter's own background - preview-signature.ts is the head-of-declaration limit from the tmux-usage-and-reference branch, unchanged, so a long C declaration shows only its head here too - The painter drops renderPreviewKind, renderPreviewSignature and the title painter; expanding a long name repaints the same payload - ApiKeyword passes its help as a payload to the same component, and seven fixtures that compile LinkPreview.astro by hand map its import - Test that LinkPreview.astro, cardHtml and paintCard give the same elements, classes and text for every kind of real payload, with controls that fail on a drifted class and on a missing slot; that the header chip and the body mark match ApiBadge.astro; and, in Chromium with the site's stylesheets, the surfaces in light and dark, no sideways overflow at 280 to 768 px, the head of a long declaration, and the Tab order close, named types, way to the page --- site/src/components/LinkPreview.astro | 111 +++++--- site/src/components/api/ApiKeyword.astro | 4 +- site/src/lib/link-preview-browser.ts | 116 +------- site/src/lib/link-preview-card.ts | 248 ++++++++++++++++ site/src/lib/preview-signature.ts | 22 ++ site/test/api-signature-scope.test.ts | 2 +- site/test/cxx-signature.test.ts | 2 +- site/test/link-preview-card.outer.test.ts | 203 +++++++++++++ site/test/link-preview-card.test.ts | 331 ++++++++++++++++++++++ site/test/link-preview-payloads.ts | 41 +++ site/test/link-preview.test.ts | 31 +- site/test/native-signature.test.ts | 2 +- site/test/parameter-permalinks.test.ts | 2 +- site/test/python-layout.test.ts | 2 +- site/test/signature-component.ts | 2 +- site/test/signature-fragment.ts | 2 +- 16 files changed, 954 insertions(+), 167 deletions(-) create mode 100644 site/src/lib/link-preview-card.ts create mode 100644 site/src/lib/preview-signature.ts create mode 100644 site/test/link-preview-card.outer.test.ts create mode 100644 site/test/link-preview-card.test.ts create mode 100644 site/test/link-preview-payloads.ts diff --git a/site/src/components/LinkPreview.astro b/site/src/components/LinkPreview.astro index 1d0a1fb4f..1cc12def7 100644 --- a/site/src/components/LinkPreview.astro +++ b/site/src/components/LinkPreview.astro @@ -1,24 +1,17 @@ --- +import type { LinkPreview as Preview } from '../lib/link-preview' +import { cardHtml, previewCard, previewLabel } from '../lib/link-preview-card' + interface Props { id?: string - title?: string - description?: string - href?: string - actionLabel?: string + /** The card to carry in the page's own HTML; without one, the card the browser fills for each reference link. */ + preview?: Preview class?: string } -const { id = 'reference-link-preview', title = 'Reference preview', description = '', href, - actionLabel = 'Open reference', class: className } = Astro.props +const { id = 'reference-link-preview', preview, class: className } = Astro.props --- - - {title} - - {description} - - - {actionLabel} - + ', footer: ['x', 'a & b'], signature: '', + actionLabel: 'go', detail: '', + }) + const shell = await staticCard(hostile) + const painted = await paintedCard(hostile) + for (const card of [shell, painted]) { + expect(card.querySelectorAll('script, img, svg, b, i')).toHaveLength(0) + expect(card.querySelector('[data-preview-title]')!.textContent).toBe(hostile.title) + expect(card.querySelector('[data-preview-footer]')!.textContent).toBe('x · a & b') + expect(card.querySelector('[data-preview-signature]')!.textContent).toBe(hostile.signature) + } + expect(inside(painted)).toBe(inside(shell)) + }) +}) + +describe('what a card holds', () => { + it('keeps the close control first and the way to the page last, so that Tab reaches them in that order', async () => { + const shell = await staticCard({ schema: 1, title: 'Name', kind: 'method', description: 'See Session.', href: '/en/x/', + descriptionParts: ['See ', { text: 'Session', href: '/en/rs/latest/reference/session/', kind: 'struct' }, '.'], footer: ['libtmux', 'Server'] }) + const reachable = [...shell.querySelectorAll('button, a[href]')].filter((element) => !element.closest('[hidden]') && !element.hasAttribute('hidden')) + expect(reachable.map((element) => element.getAttribute('data-preview-close') !== null ? 'close' : element.getAttribute('data-preview-open') !== null ? 'open' : 'mention')) + .toEqual(['close', 'mention', 'open']) + const close = shell.querySelector('[data-preview-close]')! + expect(close.getAttribute('popovertarget')).toBe(ID) + expect(close.getAttribute('popovertargetaction')).toBe('hide') + expect(close.getAttribute('aria-label')).toBe('Close preview') + }) + + it('names the dialog by its payload', async () => { + expect(previewLabel({ schema: 1, title: 'Server', description: '', href: '/' })).toBe('Server preview') + expect(previewLabel(undefined)).toBe('Reference preview') + expect((await staticCard({ schema: 1, title: 'Server', description: '', href: '/' })).getAttribute('aria-label')).toBe('Server preview') + }) + + it('shows only the head of a declaration too long for a card, in the page\'s HTML and in the browser alike', async () => { + const token = (content: string) => ({ content, light: { color: '#A626A4', fontStyle: 0 }, dark: { color: '#F97583', fontStyle: 0 } }) + const lines = Array.from({ length: 40 }, (_, index) => `case_${index}`) + const signature = `enum {\n${lines.join('\n')}\n}` + const huge = { schema: 1 as const, title: 'enum', kind: 'enum', description: '', signature, signatureLanguage: 'c', href: '/en/c/', signatureHighlight: { + language: 'c', light: { foreground: '#24292E', background: '#FFFFFF' }, dark: { foreground: '#E1E4E8', background: '#24292E' }, + lines: signature.split('\n').map((line) => [token(line)]) } } + const kept = `${signature.split('\n').slice(0, PREVIEW_SIGNATURE_LINES).join('\n')}\n…` + for (const card of [await staticCard(huge), await paintedCard(huge)]) { + const code = card.querySelector('[data-preview-signature]')! + expect(code.textContent).toBe(kept) + // The cut text no longer matches its highlighting, so it is plain text. + expect(code.querySelectorAll('*')).toHaveLength(0) + } + const oneLine = { ...huge, signature: `enum { ${'KEYC_X, '.repeat(60_000)}}`, signatureHighlight: undefined } + for (const card of [await staticCard(oneLine), await paintedCard(oneLine)]) { + const text = card.querySelector('[data-preview-signature]')!.textContent! + expect(text.length).toBeLessThanOrEqual(PREVIEW_SIGNATURE_CHARS + 2) + expect(text.endsWith('\n…')).toBe(true) + } + // The control: a declaration that fits keeps its text and its highlighting. + const short = 'enum { A, B }' + const fits = { ...huge, signature: short, signatureHighlight: { ...huge.signatureHighlight, lines: [[token(short)]] } } + for (const card of [await staticCard(fits), await paintedCard(fits)]) { + const code = card.querySelector('[data-preview-signature]')! + expect(code.textContent).toBe(short) + expect(code.classList.contains('lm-highlighted')).toBe(true) + expect(code.querySelectorAll('span')).toHaveLength(1) + } + }) + + it('draws a highlighted declaration from the payload alone and a malformed one as plain text', async () => { + const token = (content: string, color: string) => ({ content, light: { color, fontStyle: 0 }, dark: { color: '#F97583', fontStyle: 1 } }) + const base = { schema: 1 as const, title: 'T', description: '', signature: 'final class T', href: '/en/x/' } + const good = { ...base, signatureHighlight: { language: 'java', light: { foreground: '#24292E', background: '#FFFFFF' }, dark: { foreground: '#E1E4E8', background: '#24292E' }, + lines: [[token('final class ', '#A626A4'), token('T', '#032F62')]] } } + const code = (await staticCard(good)).querySelector('[data-preview-signature]')! + expect(code.classList.contains('lm-highlighted')).toBe(true) + expect(code.getAttribute('data-language')).toBe('java') + expect(code.getAttribute('style')).toContain('--shiki-dark:#E1E4E8') + expect(code.querySelector('span')!.getAttribute('style')).toContain('--shiki-dark-font-style:italic') + const bad = { ...good, signatureHighlight: { ...good.signatureHighlight, lines: [[token('final class T', 'url(https://evil.test/)')]] } } + const plain = (await staticCard(bad)).querySelector('[data-preview-signature]')! + expect(plain.textContent).toBe('final class T') + expect(plain.querySelectorAll('*')).toHaveLength(0) + expect(plain.classList.contains('lm-highlighted')).toBe(false) + }) +}) + +describe('node data', () => { + it('serializes as the DOM builds it, for text that needs escaping and attributes that are bare', () => { + const nodes: CardNode[] = [{ tag: 'span', attrs: { hidden: true, title: 'a "b" & ', skipped: undefined }, children: ['x < y & z', { tag: 'wbr' }, 'w'] }] + const html = cardHtml(nodes) + expect(html).toBe('') + const host = win.document.createElement('div') + host.innerHTML = html + const span = host.firstElementChild! + expect(span.hasAttribute('hidden')).toBe(true) + expect(span.getAttribute('title')).toBe('a "b" & ') + expect(span.hasAttribute('skipped')).toBe(false) + expect(span.textContent).toBe('x < y & zw') + }) +}) diff --git a/site/test/link-preview-payloads.ts b/site/test/link-preview-payloads.ts new file mode 100644 index 000000000..979bdf7d4 --- /dev/null +++ b/site/test/link-preview-payloads.ts @@ -0,0 +1,41 @@ +import { API_GLOSSARY_PATH } from '../src/lib/api-glossary' +import { API_MODELS } from '../src/lib/api-models' +import { glossaryPreview, highlightedPreview, symbolPreview, tmuxManualPreview, type LinkPreview } from '../src/lib/link-preview' +import { mcpObjects } from '../src/lib/mcp-catalog' +import { mcpObjectPreview } from '../src/lib/mcp-preview' +import { tmuxCatalogEntries } from '../src/lib/tmux-catalog' +import { tmuxCatalogPreview } from '../src/lib/tmux-catalog-preview' + +/** Real payloads of every kind the site writes: the producers, not fixtures, so that a change to one is seen here. */ +export async function cardPayloads(): Promise<[string, LinkPreview][]> { + const rs = API_MODELS.rs + const referenced = (model: typeof rs, kind?: string) => model.symbols.find((symbol) => (!kind || symbol.kind === kind) && symbolPreview(model, symbol, 'latest').descriptionParts)! + const long = API_MODELS.java.symbols.find((symbol) => symbol.id.length > 70 && symbol.signatures[0]?.raw)! + const glossary = glossaryPreview(API_GLOSSARY_PATH) + const manual = tmuxManualPreview('latest', 'full') + const object = (kind: string) => { + for (const port of ['py', 'ts', 'rs', 'go', 'ruby', 'java']) { + const found = mcpObjects(port).find((entry) => entry.kind === kind) + if (found) return mcpObjectPreview(port, 'latest', found) + } + throw new Error(`No MCP ${kind}`) + } + const tool = mcpObjects('ruby').find((entry) => mcpObjectPreview('ruby', 'latest', entry).descriptionParts)! + return Promise.all(([ + ['API method with a named type', symbolPreview(rs, referenced(rs, 'method'), 'latest')], + ['API declaration without references', symbolPreview(API_MODELS.cxx, API_MODELS.cxx.symbols.find((symbol) => symbol.kind === 'class')!, 'latest')], + ['API name long enough to abbreviate', symbolPreview(API_MODELS.java, long, 'latest')], + ['glossary page', glossary], + ['glossary term that is a kind', glossary.terms!.struct], + ['glossary term that is not a kind', glossary.terms!.inherited], + ['MCP object naming another', mcpObjectPreview('ruby', 'latest', tool)], + ['MCP prompt', object('prompt')], + ['MCP resource template', object('resource-template')], + ['tmux manual', manual], + ['tmux command', tmuxManualPreview('latest', 'new-session')], + ['tmux manual option', Object.values(manual.terms!).find((term) => term.kind === 'option')!], + ['tmux catalog hook', tmuxCatalogPreview('latest', tmuxCatalogEntries('latest', 'hook')[0])], + ['page with no kind', { schema: 1, title: 'Exit codes', description: 'What each command returns.', href: '/en/rs/latest/workspace/reference/exit-codes/', actionLabel: 'Open page' }], + ['an older payload with only the original fields', { schema: 1, title: 'Older', description: 'Written before footers and references.', href: '/en/rs/latest/reference/older/' }], + ] satisfies [string, LinkPreview][]).map(async ([name, preview]) => [name, await highlightedPreview(preview)] as [string, LinkPreview])) +} diff --git a/site/test/link-preview.test.ts b/site/test/link-preview.test.ts index e1d219e21..9a25e1bef 100644 --- a/site/test/link-preview.test.ts +++ b/site/test/link-preview.test.ts @@ -1,9 +1,6 @@ import { Window, type HTMLAnchorElement, type HTMLButtonElement, type HTMLElement } from 'happy-dom' -import { readFileSync, realpathSync } from 'node:fs' -import { createRequire } from 'node:module' -import { pathToFileURL } from 'node:url' +import { readFileSync } from 'node:fs' import { runInNewContext } from 'node:vm' -import { experimental_AstroContainer } from 'astro/container' import { createRenderer } from 'astro-expressive-code' import { select } from 'astro-expressive-code/hast' import { fromHtml } from 'hast-util-from-html' @@ -14,9 +11,11 @@ import { API_MODELS } from '../src/lib/api-models' import { productApiIndex } from '../src/lib/product-api' import { apiGlossaryHref } from '../src/lib/api-glossary' import { initLinkPreviews, disposeLinkPreviews, linkPreviewTarget, positionLinkPreview } from '../src/lib/link-preview-browser' +import { PREVIEW_DEFAULT_ACTION } from '../src/lib/link-preview-card' import { GET } from '../src/pages/[...slug].preview.json' import { highlightTokens } from '../src/lib/highlight' import config from '../ec.config.mjs' +import { loadAstroTemplate, renderAstroTemplate } from './astro-templates' it.each([ ['/en/powershell/latest/workspace/reference/libtmux-workspace/', 'cmdlet', '/en/powershell/latest/workspace/reference/glossary/#cmdlet'], @@ -110,26 +109,12 @@ it('only fetches same-origin supported reference URLs', () => { }) it('keeps native keyword help and parameter permalinks inside their inline paragraph', async () => { - const astroRequire = createRequire(realpathSync(new URL('../node_modules/astro/package.json', import.meta.url))) - const { transform } = await import(astroRequire.resolve('@astrojs/compiler-rs')) - async function compile(relative: string, imports: Record = {}) { - const file = new URL(relative, import.meta.url) - const source = readFileSync(file, 'utf8').replace(//g, '').replace(//g, '') - const result = await transform(source, { filename: file.pathname, internalURL: 'astro/compiler-runtime', - resultScopedSlot: true, resolvePath: (specifier: string) => specifier }) - expect(result.diagnostics.filter((item: { severity: string }) => item.severity === 'error')).toEqual([]) - let code = result.code.replaceAll('"astro/compiler-runtime"', JSON.stringify(pathToFileURL(astroRequire.resolve('astro/compiler-runtime')).href)) - for (const [specifier, url] of Object.entries(imports)) code = code.replaceAll(JSON.stringify(specifier), JSON.stringify(url)) - return `data:text/javascript;base64,${Buffer.from(code).toString('base64')}` - } - const preview = await compile('../src/components/LinkPreview.astro') - const keyword = await compile('../src/components/api/ApiKeyword.astro', { '../LinkPreview.astro': preview }) + const keyword = await loadAstroTemplate('components/api/ApiKeyword.astro', { real: ['components/LinkPreview.astro'] }) const model = API_MODELS.kotlin const symbol = model.symbols.find((entry) => entry.id === 'io.github.libtmux.kotlin.ControlClient.output')! const parameter = symbol.signatures.flatMap((signature) => signature.params).find((entry) => entry.name === 'onSubscribed')! const helped = productApiIndex(model, 'latest').linkType(parameter.type!, symbol).find((span) => span.help)! - const container = await experimental_AstroContainer.create() - const html = await container.renderToString((await import(/* @vite-ignore */ keyword)).default, { props: { text: helped.text, help: helped.help } }) + const html = await renderAstroTemplate(keyword, { props: { text: helped.text, help: helped.help } }) const tree = fromHtml(`

onSubscribed (${html} () → Unit) #

`, { fragment: true }) // Use the HTML5 parser: a hidden block element can still close the parameter paragraph. expect(tree.children).toHaveLength(1) @@ -277,7 +262,11 @@ describe('preview lifecycle', () => { expect(short).not.toBe(name) expect(short).toContain('applyWorkspace') expect(expand.hidden).toBe(false) + expand.focus() expand.click() + // Painting the card again leaves the control in place, so a keyboard reader keeps their place. + expect(win.document.activeElement).toBe(expand) + expect(panel.querySelector('[data-preview-expand]')).toBe(expand) expect(title()).toBe(name) expect(expand.getAttribute('aria-expanded')).toBe('true') expect(expand.textContent).toBe('Collapse') @@ -308,7 +297,7 @@ describe('preview lifecycle', () => { expect(open.textContent).toBe('Open manual') expect(open.getAttribute('href')).toBe('https://libtmux.org/tmux/latest/manual/full/#options-destroy-unattached') escape(); hover('b'); await settle() - expect(open.textContent).toBe('') + expect(open.textContent).toBe(PREVIEW_DEFAULT_ACTION) }) it('treats punctuation in a preview name as text when adding break opportunities', async () => { diff --git a/site/test/native-signature.test.ts b/site/test/native-signature.test.ts index 1c34e270a..80fc05173 100644 --- a/site/test/native-signature.test.ts +++ b/site/test/native-signature.test.ts @@ -35,7 +35,7 @@ async function signatureComponent() { return `data:text/javascript;base64,${Buffer.from(code).toString('base64')}` } const name = await compile('../src/components/api/SymbolName.astro', { '../../lib/word-break': new URL('../src/lib/word-break.ts', import.meta.url).href }) - const preview = await compile('../src/components/LinkPreview.astro') + const preview = await compile('../src/components/LinkPreview.astro', { '../lib/link-preview-card': new URL('../src/lib/link-preview-card.ts', import.meta.url).href }) const keyword = await compile('../src/components/api/ApiKeyword.astro', { '../LinkPreview.astro': preview }) const type = await compile('../src/components/api/ApiType.astro', { './SymbolName.astro': name, './ApiKeyword.astro': keyword, diff --git a/site/test/parameter-permalinks.test.ts b/site/test/parameter-permalinks.test.ts index 5f5b4950c..d7bad5e20 100644 --- a/site/test/parameter-permalinks.test.ts +++ b/site/test/parameter-permalinks.test.ts @@ -34,7 +34,7 @@ async function parameterComponents() { } const bridge = 'data:text/javascript,export const { parameterId, parameterBindingFacts, POWER_SHELL_COMMON_HELP, linkTmuxDoc, signatureSpans, typeLayout } = globalThis.__apiParameterPermalinks' const name = await compile('../src/components/api/SymbolName.astro', { '../../lib/word-break': new URL('../src/lib/word-break.ts', import.meta.url).href }) - const preview = await compile('../src/components/LinkPreview.astro') + const preview = await compile('../src/components/LinkPreview.astro', { '../lib/link-preview-card': new URL('../src/lib/link-preview-card.ts', import.meta.url).href }) const keyword = await compile('../src/components/api/ApiKeyword.astro', { '../LinkPreview.astro': preview }) const type = await compile('../src/components/api/ApiType.astro', { './SymbolName.astro': name, './ApiKeyword.astro': keyword, diff --git a/site/test/python-layout.test.ts b/site/test/python-layout.test.ts index 581b1228b..6b04fde77 100644 --- a/site/test/python-layout.test.ts +++ b/site/test/python-layout.test.ts @@ -202,7 +202,7 @@ describe('Python layouts in the rendered declaration', () => { return `data:text/javascript;base64,${Buffer.from(code).toString('base64')}` } const bridge = 'data:text/javascript,export const { parameterId, qualifiedNameOf, signatureMultiline } = globalThis.__pythonDeclaration' - const preview = await compile('../src/components/LinkPreview.astro') + const preview = await compile('../src/components/LinkPreview.astro', { '../lib/link-preview-card': new URL('../src/lib/link-preview-card.ts', import.meta.url).href }) const keyword = await compile('../src/components/api/ApiKeyword.astro', { '../LinkPreview.astro': preview }) const name = await compile('../src/components/api/SymbolName.astro', { '../../lib/word-break': new URL('../src/lib/word-break.ts', import.meta.url).href }) const type = await compile('../src/components/api/ApiType.astro', { diff --git a/site/test/signature-component.ts b/site/test/signature-component.ts index 47f392cab..e506516b3 100644 --- a/site/test/signature-component.ts +++ b/site/test/signature-component.ts @@ -20,7 +20,7 @@ export async function signatureComponent() { return `data:text/javascript;base64,${Buffer.from(code).toString('base64')}` } const name = await compile('../src/components/api/SymbolName.astro', { '../../lib/word-break': new URL('../src/lib/word-break.ts', import.meta.url).href }) - const preview = await compile('../src/components/LinkPreview.astro') + const preview = await compile('../src/components/LinkPreview.astro', { '../lib/link-preview-card': new URL('../src/lib/link-preview-card.ts', import.meta.url).href }) const keyword = await compile('../src/components/api/ApiKeyword.astro', { '../LinkPreview.astro': preview }) const type = await compile('../src/components/api/ApiType.astro', { './SymbolName.astro': name, './ApiKeyword.astro': keyword, diff --git a/site/test/signature-fragment.ts b/site/test/signature-fragment.ts index ac210d0e1..f87e381af 100644 --- a/site/test/signature-fragment.ts +++ b/site/test/signature-fragment.ts @@ -25,7 +25,7 @@ async function compileFragment() { return `data:text/javascript;base64,${Buffer.from(code).toString('base64')}` } const name = await compile('../src/components/api/SymbolName.astro', { '../../lib/word-break': new URL('../src/lib/word-break.ts', import.meta.url).href }) - const preview = await compile('../src/components/LinkPreview.astro') + const preview = await compile('../src/components/LinkPreview.astro', { '../lib/link-preview-card': new URL('../src/lib/link-preview-card.ts', import.meta.url).href }) const keyword = await compile('../src/components/api/ApiKeyword.astro', { '../LinkPreview.astro': preview }) const type = await compile('../src/components/api/ApiType.astro', { './SymbolName.astro': name, './ApiKeyword.astro': keyword, From e993384deba4d56f4cc9ed26a827bb6eef9a836d Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 24 Oct 2026 15:40:16 -0500 Subject: [PATCH 3/8] feat(site[native-name]) Name a Rust or TypeScript declaration as its language writes it why: A card header and the page's Qualified name row showed the public id, which every model writes as one dotted path. For Rust that is `control.ControlSender.unmute_pane` where the language writes `libtmux::control::ControlSender::unmute_pane`, so a card could read `Self::mute_pane` in its summary under a dotted header. For TypeScript it began with the file the symbol is written in (`client.Client.session`), which no reader writes. what: - nativeQualifiedName spells a declaration as its language does, for display only. Rust joins the path with `::` from the crate its file is in (`tmux_workspace`, with the underscore the path uses) and drops the markers the extractor adds for the product and for the crate root. TypeScript names a member by its owner and leaves out the file part of the id. Every other port keeps the public id it had: C++ and Ruby already write `::` and `#`, Lua `:`, Elixir `/arity`, PowerShell `\`, and the rest dots - symbolPreview heads the card with it, and the Qualified name row of a reference page shows and copies it, so the two read the same - The public id, the anchors and the page addresses are untouched - Test every symbol of the Rust and TypeScript ports against the spelling of each family, that no other port's name changes, and that the Rust check fails on a dotted id Before and after, as the card headed them: Rust control.ControlSender.unmute_pane libtmux::control::ControlSender::unmute_pane TypeScript client.Client.session Client.session --- site/src/components/api/ApiReference.astro | 3 +- site/src/lib/link-preview.ts | 5 +- site/src/lib/native-name.ts | 61 ++++++++++ site/test/api-glossary-navigation.test.ts | 3 +- site/test/api-qualified-name.test.ts | 2 +- site/test/native-name.test.ts | 134 +++++++++++++++++++++ 6 files changed, 203 insertions(+), 5 deletions(-) create mode 100644 site/src/lib/native-name.ts create mode 100644 site/test/native-name.test.ts diff --git a/site/src/components/api/ApiReference.astro b/site/src/components/api/ApiReference.astro index 7ed2c1548..9bce7f46d 100644 --- a/site/src/components/api/ApiReference.astro +++ b/site/src/components/api/ApiReference.astro @@ -24,6 +24,7 @@ import { withRoot } from '../../lib/site-root' import { API_MODELS, API_NAV, PORT_NAME, indexFor, isMemberOwner, ownersOf, pageSlug, referenceAlternatives, topLevelTypesOf } from '../../lib/api-models' import { PORT_BY_SLUG, referenceUrl } from '../../lib/ports' import { productApiHref } from '../../lib/product-api' +import { nativeQualifiedName } from '../../lib/native-name' import { symbolSource } from '../../lib/markdown-twins' import { localeSourcePath } from '../../i18n/locales' import { buildLocale } from '../../i18n/resolve' @@ -687,7 +688,7 @@ const bases = owner && 'extends' in owner ? owner.extends ?? [] : []
{/* The module, namespace or package this symbol is in, and its full name with a button to copy it; the page heading above carries neither. */}
Qualified name
-
+
{ownerModule && ( <>
{moduleLabel}
diff --git a/site/src/lib/link-preview.ts b/site/src/lib/link-preview.ts index 64d06bbe6..9fa4bdcc5 100644 --- a/site/src/lib/link-preview.ts +++ b/site/src/lib/link-preview.ts @@ -1,5 +1,6 @@ -import { docSummaryText, qualifiedNameOf, sourceUrl, type ApiModel, type ApiSymbol, type SymbolIndex } from '@libtmux/api-model' +import { docSummaryText, sourceUrl, type ApiModel, type ApiSymbol, type SymbolIndex } from '@libtmux/api-model' import { productApiHref, productApiIndex } from './product-api' +import { nativeQualifiedName } from './native-name' import { PORT_BY_SLUG } from './ports' import { apiGlossary } from './api-glossary' import { codeLang, highlightTokens, type CodeHighlight } from './highlight' @@ -84,7 +85,7 @@ export function symbolPreview(model: ApiModel, symbol: ApiSymbol, version: strin const description = summary ? docSummaryText(summary, model.port) : '' const footer = [symbol.package ?? PORT_BY_SLUG[model.port]?.packageName, ownerOf(model, symbol)?.name].filter((place): place is string => !!place) return { - schema: 1, title: qualifiedNameOf(symbol), kind: symbol.command?.kind ?? symbol.kind, + schema: 1, title: nativeQualifiedName(model, symbol), kind: symbol.command?.kind ?? symbol.kind, description, descriptionParts: summary ? summaryParts(productApiIndex(model, version), summary, symbol, description) : undefined, footer: footer.length ? footer : undefined, diff --git a/site/src/lib/native-name.ts b/site/src/lib/native-name.ts new file mode 100644 index 000000000..4c9437c9a --- /dev/null +++ b/site/src/lib/native-name.ts @@ -0,0 +1,61 @@ +import { qualifiedNameOf, type ApiSymbol } from '@libtmux/api-model' + +/** + * The name a programmer writes for a declaration, in the language's own spelling. + * + * A symbol's public id is the same dotted path in every model, because the extractors share one shape. Most ports + * write that path as it is (Python `libtmux.Server.new_session`, Go `tmux.Client.Session`), and two already keep + * their own separators in the id (C++ `libtmux::Server`, Ruby `LibTmux::Server#list_sessions`, Lua + * `libtmux.Buffer:reference`, Elixir `LibTmux.Capture.fetch/2`, PowerShell `LibTmux\Connect-TmuxServer`). Rust and + * TypeScript are the two that need a spelling of their own: + * + * - Rust names a path with `::` from the crate: `libtmux::control::ControlSender::unmute_pane`. The id begins at the + * module, so the crate comes from the file the symbol is written in, and the markers the extractor adds for the + * product (`mcp`) and for the crate root (`src`) are not part of the path. + * - TypeScript names a member by its owner: `Client.session`. The id begins with the file the symbol is written in + * (`client`), which a reader never writes; the file is the Module row of the page. + * + * This is for display. The public id, the anchors and the URLs stay as the model has them. + */ +export function nativeQualifiedName(model: { port?: string; symbols: readonly ApiSymbol[] } | undefined, symbol: ApiSymbol): string { + const id = qualifiedNameOf(symbol) + if (model?.port === 'rs') return rustName(model, symbol, id) + if (model?.port === 'ts') return typescriptName(model, symbol, id) + return id +} + +const byId = new WeakMap>() + +/** The outermost declaration that `symbol` is written in, or `symbol` itself when it has no owner. */ +function outermost(symbols: readonly ApiSymbol[], symbol: ApiSymbol): ApiSymbol { + let table = byId.get(symbols) + if (!table) { table = new Map(symbols.map((entry) => [entry.id, entry])); byId.set(symbols, table) } + const seen = new Set([symbol.id]) + let top = symbol + while (top.parent) { + const next = table.get(top.parent) + if (!next || seen.has(next.id)) break + seen.add(next.id) + top = next + } + return top +} + +function rustName(model: { symbols: readonly ApiSymbol[] }, symbol: ApiSymbol, id: string): string { + const file = symbol.source?.file ?? '' + // A package name uses hyphens where the crate that it builds does not. + const crate = /^crates\/([^/]+)\/src\//.exec(file)?.[1]?.replace(/-/g, '_') + const path = id.split('.') + if (symbol.product && symbol.product !== 'core' && path[0] === symbol.product) path.shift() + // A member can be written in another file than its type, so the root is told by the file of the outermost declaration. + if (path[0] === 'src' && /\/(?:lib|main)\.rs$/.test(outermost(model.symbols, symbol).source?.file ?? file)) path.shift() + return [crate, ...path].filter(Boolean).join('::') +} + +function typescriptName(model: { symbols: readonly ApiSymbol[] }, symbol: ApiSymbol, id: string): string { + const top = outermost(model.symbols, symbol) + const topId = qualifiedNameOf(top) + // The file's part of the id is what comes before the name of the outermost declaration. + const file = topId.endsWith(`.${top.name}`) ? topId.slice(0, topId.length - top.name.length) : '' + return file && id.startsWith(file) ? id.slice(file.length) : id +} diff --git a/site/test/api-glossary-navigation.test.ts b/site/test/api-glossary-navigation.test.ts index eace36116..5817e02ff 100644 --- a/site/test/api-glossary-navigation.test.ts +++ b/site/test/api-glossary-navigation.test.ts @@ -18,6 +18,7 @@ import * as search from '../src/lib/api-search' import * as treeState from '../src/components/api/api-tree-state' import * as labels from '../src/lib/api-labels' import * as wordBreak from '../src/lib/word-break' +import * as nativeName from '../src/lib/native-name' import * as ports from '../src/lib/ports' import * as products from '../src/lib/product-api' import * as versions from '../src/lib/versions' @@ -55,7 +56,7 @@ async function components(stubs: Readonly> = {}) { ...Object.fromEntries(Object.entries({ 'api-glossary': glossary, 'api-models': models, 'api-sections': sections, 'api-relationships': relationships, 'api-tree': tree, 'api-search': search, - 'api-labels': labels, 'word-break': wordBreak, ports, 'product-api': products, + 'api-labels': labels, 'word-break': wordBreak, 'native-name': nativeName, ports, 'product-api': products, versions, 'site-root': roots, sidebar, 'documentation-navigation': documentation, 'page-ports-for': pagePorts, 'markdown-twins': markdown, 'tmux-manual-data': manual, 'tmux-reference': reference, 'tmux-catalog': catalog, branding, diff --git a/site/test/api-qualified-name.test.ts b/site/test/api-qualified-name.test.ts index bef45d9dd..1faedf405 100644 --- a/site/test/api-qualified-name.test.ts +++ b/site/test/api-qualified-name.test.ts @@ -126,7 +126,7 @@ function placement(source: string): string[] { const header = source.slice(source.indexOf('')) if (/ApiQualifiedName|api-qualified-name/.test(header)) problems.push('the heading still carries the qualified name') const panel = source.slice(source.indexOf('
', source.indexOf('
Qualified name<\/dt>\s*
<\/dd>/.test(panel)) problems.push('the disclosure has no qualified name row') + if (!/
Qualified name<\/dt>\s*
<\/dd>/.test(panel)) problems.push('the disclosure has no qualified name row') if (!/
\{moduleLabel\}<\/dt>/.test(panel)) problems.push('the disclosure does not label its module row for the port') return problems } diff --git a/site/test/native-name.test.ts b/site/test/native-name.test.ts new file mode 100644 index 000000000..6ae4733df --- /dev/null +++ b/site/test/native-name.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it } from 'vitest' +import { qualifiedNameOf, type ApiSymbol } from '@libtmux/api-model' +import { API_MODELS } from '../src/lib/api-models' +import { symbolPreview } from '../src/lib/link-preview' +import { nativeQualifiedName } from '../src/lib/native-name' +import { productApiHref } from '../src/lib/product-api' + +/** + * A card's header and the page's Qualified name row say a declaration the way the language writes it. Rust spells a path + * with `::` from its crate and TypeScript names a member by its owner; every other port already keeps its own spelling in + * the public id, which must stay as it was. + */ +const symbolNamed = (port: string, id: string) => { + const symbol = API_MODELS[port].symbols.find((entry) => (entry.publicId ?? entry.id) === id) + if (!symbol) throw new Error(`${port} has no ${id}`) + return symbol +} +const name = (port: string, id: string) => nativeQualifiedName(API_MODELS[port], symbolNamed(port, id)) + +/** What is wrong with a Rust display name, so that a control can show the check is able to fail. */ +function rustProblems(symbol: ApiSymbol, shown: string): string[] { + const problems: string[] = [] + if (/\./.test(shown)) problems.push('has a dot where a path has `::`') + if (!/^[a-z][a-z0-9_]*::/.test(shown)) problems.push('does not begin at its crate') + if (!shown.endsWith(`::${symbol.name}`)) problems.push('does not end with its own name') + if (/^[a-z_]+::(?:src|mcp)(?:::|$)/.test(shown)) problems.push('keeps the extractor\'s marker for the crate root or the product') + return problems +} + +describe('Rust names', () => { + it('spell the path from the crate with `::`, as `use` writes it', () => { + expect(name('rs', 'control.ControlSender.unmute_pane')).toBe('libtmux::control::ControlSender::unmute_pane') + expect(name('rs', 'blocking.Runtime.new')).toBe('libtmux::blocking::Runtime::new') + expect(name('rs', 'client.Client')).toBe('libtmux::client::Client') + expect(name('rs', 'error.scoped.ScopeError.Creation')).toBe('libtmux::error::scoped::ScopeError::Creation') + }) + + it('take the crate each product is built in, with the underscores its path uses', () => { + expect(name('rs', 'config.ConfigError')).toBe('tmux_workspace::config::ConfigError') + expect(name('rs', 'mcp.caller.Relation')).toBe('tmux_mcp::caller::Relation') + }) + + it('leave out the marker for the crate root and the marker for the product', () => { + const root = API_MODELS.rs.symbols.find((symbol) => (symbol.publicId ?? symbol.id).startsWith('src.') && symbol.source.file.endsWith('/lib.rs') && !symbol.parent)! + expect(nativeQualifiedName(API_MODELS.rs, root)).toBe(`libtmux::${root.name}`) + expect(name('rs', 'mcp.cli.Options')).toBe('tmux_mcp::cli::Options') + expect(name('rs', 'mcp.src.TmuxTools.new')).toBe('tmux_mcp::TmuxTools::new') + }) + + it('read as a path for every symbol of the port', { timeout: 30_000 }, () => { + for (const symbol of API_MODELS.rs.symbols) { + const shown = nativeQualifiedName(API_MODELS.rs, symbol) + expect(rustProblems(symbol, shown), `${qualifiedNameOf(symbol)} -> ${shown}`).toEqual([]) + } + }) + + it('has a control: the public id is not a Rust path, and the check says why', () => { + const symbol = symbolNamed('rs', 'control.ControlSender.unmute_pane') + expect(rustProblems(symbol, nativeQualifiedName(API_MODELS.rs, symbol))).toEqual([]) + expect(rustProblems(symbol, qualifiedNameOf(symbol))).toEqual(['has a dot where a path has `::`', 'does not begin at its crate', 'does not end with its own name']) + }) +}) + +describe('TypeScript names', () => { + it('name a member by its owner and leave out the file it is written in', () => { + expect(name('ts', 'client.Client.session')).toBe('Client.session') + expect(name('ts', 'client.Client')).toBe('Client') + expect(name('ts', 'common.isSafeInteger')).toBe('isSafeInteger') + expect(name('ts', 'errors.TmuxTransportError.#stderr')).toBe('TmuxTransportError.#stderr') + }) + + it('leave out the file of a product that the id also prefixes', () => { + expect(name('ts', 'mcp.server.createTmuxMcpServer')).toBe('createTmuxMcpServer') + expect(name('ts', 'mcp.policy.Policy.tools')).toBe('Policy.tools') + }) + + it('are the end of the public id for every symbol of the port, and end with its own name', { timeout: 30_000 }, () => { + for (const symbol of API_MODELS.ts.symbols) { + const shown = nativeQualifiedName(API_MODELS.ts, symbol) + expect(qualifiedNameOf(symbol).endsWith(shown), qualifiedNameOf(symbol)).toBe(true) + expect(shown.endsWith(symbol.name), qualifiedNameOf(symbol)).toBe(true) + // A member keeps its owner, and a declaration with none is a bare name. + expect(shown.includes('.'), qualifiedNameOf(symbol)).toBe(!!symbol.parent) + } + }) +}) + +describe('the other ports', () => { + it('keep the public id exactly, for every symbol', { timeout: 30_000 }, () => { + for (const [port, model] of Object.entries(API_MODELS)) { + if (port === 'rs' || port === 'ts') continue + for (const symbol of model.symbols) expect(nativeQualifiedName(model, symbol), `${port} ${symbol.id}`).toBe(qualifiedNameOf(symbol)) + } + }) + + // Each family keeps the separator its language writes, which the id carries. + it.each([ + ['cxx', /::/, undefined], ['ruby', /::/, undefined], ['lua', /:/, undefined], ['elixir', /\//, undefined], ['powershell', /\\/, undefined], + ['py', /\./, /::/], ['go', /\./, /::/], ['swift', /\./, /::/], ['java', /\./, /::/], ['csharp', /\./, /::/], ['julia', /\./, /::/], + ] as const)('%s keeps the separator its language writes', (port, wanted, unwanted) => { + const shown = API_MODELS[port].symbols.map((symbol) => nativeQualifiedName(API_MODELS[port], symbol)) + expect(shown.some((entry) => wanted.test(entry)), port).toBe(true) + // A port that writes dots never gets `::` from this change. + if (unwanted) expect(shown.some((entry) => unwanted.test(entry)), port).toBe(false) + }) + + it('keep Ruby\'s `#` for instance members and Elixir\'s arity', () => { + expect(API_MODELS.ruby.symbols.some((symbol) => nativeQualifiedName(API_MODELS.ruby, symbol).includes('#'))).toBe(true) + expect(API_MODELS.elixir.symbols.some((symbol) => /\/\d+$/.test(nativeQualifiedName(API_MODELS.elixir, symbol)))).toBe(true) + }) +}) + +describe('where the name is used', () => { + it('heads the card of a Rust or TypeScript symbol, and every other card as before', () => { + expect(symbolPreview(API_MODELS.rs, symbolNamed('rs', 'control.ControlSender.unmute_pane'), 'latest').title).toBe('libtmux::control::ControlSender::unmute_pane') + expect(symbolPreview(API_MODELS.ts, symbolNamed('ts', 'client.Client.session'), 'latest').title).toBe('Client.session') + for (const port of ['py', 'go', 'cxx', 'ruby', 'lua']) { + const symbol = API_MODELS[port].symbols[0] + expect(symbolPreview(API_MODELS[port], symbol, 'latest').title, port).toBe(qualifiedNameOf(symbol)) + } + }) + + it('leaves the public id, the page address and the anchor as they were', () => { + for (const [port, id, href] of [ + ['rs', 'control.ControlSender.unmute_pane', '/rs/latest/reference/control-controlsender-unmute_pane/'], + ['ts', 'client.Client.session', '/ts/latest/reference/client-client-session/'], + ] as const) { + const symbol = symbolNamed(port, id) + expect(productApiHref(API_MODELS[port], symbol, 'latest')).toBe(href) + expect(symbolPreview(API_MODELS[port], symbol, 'latest').href).toBe(href) + expect(qualifiedNameOf(symbol)).toBe(id) + } + }) +}) From df902831a45e64202be0e30a1217288e961d92a0 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 24 Oct 2026 15:40:16 -0500 Subject: [PATCH 4/8] fix(site[link-preview]) Keep a named type on this site and test every paint sequence why: The check for a named type's address, `/^\/(?!\/)/`, passed `/\evil.test` and a slash, a tab and a slash, which a browser reads as `//evil.test`. The tests compared a card painted once with a fresh card, so a slot that kept an attribute of the card before it went unseen, and the lifecycle test painted a hand-built card without the kind and footer slots, which `paintCard` skips without a word. Three tests ran 3.5 to 3.9 s against a 5 s limit. what: - A mention is linked only when its address resolves, as a browser reads it, on the site's own origin. The static page and the browser decide alike, since both resolve against the same origin of no site - Paint every payload after every other and require each result to read as a fresh card does; a control leaves a stale `style`, `data-language`, class or kind slot behind and must be told apart - The lifecycle test uses the card that LinkPreview.astro writes, with every slot, in place of its own - Compile the card component once for the tests, and give the tests that walk every payload or every symbol of a port, and the browser suite's launch, a limit of their own --- site/src/lib/link-preview-card.ts | 12 +++- site/test/link-preview-card.outer.test.ts | 14 ++--- site/test/link-preview-card.test.ts | 69 +++++++++++++++++++++-- site/test/link-preview-payload.test.ts | 4 +- site/test/link-preview.test.ts | 10 ++-- 5 files changed, 89 insertions(+), 20 deletions(-) diff --git a/site/src/lib/link-preview-card.ts b/site/src/lib/link-preview-card.ts index d6bd0378f..48b1bd52f 100644 --- a/site/src/lib/link-preview-card.ts +++ b/site/src/lib/link-preview-card.ts @@ -87,8 +87,16 @@ function legendChip(kind: string | undefined): CardElement | undefined { /* ------------------------------------------------------------------- the body */ -/** A page of this site: a path, never another origin. */ -const sitePath = (href: string) => /^\/(?!\/)/.test(href) +/** + * A page of this site: a path that resolves on the site's own origin. A browser reads `\` as `/` and drops a tab or a + * newline inside a URL, so `/\evil.test` and `//evil.test` are as far from this site as `//evil.test`. The + * address is resolved as the browser would, against an origin of no site, and must stay on that origin. + */ +const SITE = 'https://reference.invalid' +function sitePath(href: string): boolean { + if (!href.startsWith('/')) return false + try { return new URL(href, SITE).origin === SITE } catch { return false } +} /** * A name in the summary, as prose writes it: its kind's small mark, then the name as a link. The mark is decoration, diff --git a/site/test/link-preview-card.outer.test.ts b/site/test/link-preview-card.outer.test.ts index cb77464c0..16c3e7afb 100644 --- a/site/test/link-preview-card.outer.test.ts +++ b/site/test/link-preview-card.outer.test.ts @@ -26,7 +26,7 @@ const page = (cards: string, mode: 'light' | 'dark') => ` `${cardHtml(previewCard(preview, { id: 'card' }))}` let browser: Browser -beforeAll(async () => { browser = await chromium.launch({ headless: true }) }) +beforeAll(async () => { browser = await chromium.launch({ headless: true }) }, 60_000) afterAll(async () => { await browser?.close() }) async function open(target: Page, preview: LinkPreview, mode: 'light' | 'dark', width = 480) { @@ -46,7 +46,7 @@ const spills = (target: Page) => target.evaluate(() => { }) describe('the card in a browser', () => { - it('draws the header, the declaration band, the summary and the footer on the site\'s own tokens, in light and dark', async () => { + it('draws the header, the declaration band, the summary and the footer on the site\'s own tokens, in light and dark', { timeout: 30_000 }, async () => { const [, preview] = (await cardPayloads())[0]! const target = await browser.newPage() try { @@ -83,7 +83,7 @@ describe('the card in a browser', () => { } finally { await target.close() } }) - it('keeps the mark of a named type tinted by its kind in the summary, apart from the header\'s kind', async () => { + it('keeps the mark of a named type tinted by its kind in the summary, apart from the header\'s kind', { timeout: 30_000 }, async () => { const [, preview] = (await cardPayloads())[0]! const target = await browser.newPage() try { @@ -118,7 +118,7 @@ describe('the card in a browser', () => { } finally { await target.close() } }) - it('catches a card that spills, so that the check above can fail', async () => { + it('catches a card that spills, so that the check above can fail', { timeout: 30_000 }, async () => { const [, preview] = (await cardPayloads())[0]! const wide = { ...preview, signature: `fn ${'a'.repeat(160)}()`, signatureHighlight: undefined, title: 'b'.repeat(120) } const target = await browser.newPage() @@ -133,7 +133,7 @@ describe('the card in a browser', () => { } finally { await target.close() } }) - it('shows the head of a very long declaration and keeps the card within its height', async () => { + it('shows the head of a very long declaration and keeps the card within its height', { timeout: 30_000 }, async () => { const lines = Array.from({ length: 400 }, (_, index) => ` KEYC_CASE_${index} = ${index},`) const huge: LinkPreview = { schema: 1, title: 'enum', kind: 'enum', description: 'Key codes.', signature: `enum {\n${lines.join('\n')}\n}`, signatureLanguage: 'c', href: '/en/tmux/latest/reference/enum/' } const target = await browser.newPage() @@ -150,7 +150,7 @@ describe('the card in a browser', () => { } finally { await target.close() } }) - it('opens from its trigger, reaches the close control, each named type and the way to the page in that order, and closes on Escape', async () => { + it('opens from its trigger, reaches the close control, each named type and the way to the page in that order, and closes on Escape', { timeout: 30_000 }, async () => { const [, preview] = (await cardPayloads())[0]! const target = await browser.newPage() try { @@ -180,7 +180,7 @@ describe('the card in a browser', () => { } finally { await target.close() } }) - it('reaches the control that shows the whole name of a long one, ahead of the declaration', async () => { + it('reaches the control that shows the whole name of a long one, ahead of the declaration', { timeout: 30_000 }, async () => { const long = (await cardPayloads()).find(([name]) => name === 'API name long enough to abbreviate')![1] const target = await browser.newPage() try { diff --git a/site/test/link-preview-card.test.ts b/site/test/link-preview-card.test.ts index 4a7ab5b7c..133cd116f 100644 --- a/site/test/link-preview-card.test.ts +++ b/site/test/link-preview-card.test.ts @@ -41,10 +41,13 @@ const inside = (element: Element) => [...element.childNodes].map(canonical).join /** `paintCard` on a card of the test window, which the browser's own types do not describe. */ const paint = (shell: Element, ...rest: Parameters extends [unknown, ...infer Rest] ? Rest : never) => paintCard(shell as unknown as globalThis.HTMLElement, ...rest) +/** The component compiles once; each card is rendered from it. */ +let component: ReturnType | undefined + /** The card as the page carries it: the component's own HTML, as the keyword help of a declaration is written. */ async function staticCard(preview: LinkPreview | undefined) { - const template = await loadAstroTemplate('components/LinkPreview.astro') - const html = await renderAstroTemplate(template, { props: { id: ID, preview } }) + component ??= loadAstroTemplate('components/LinkPreview.astro') + const html = await renderAstroTemplate(await component, { props: { id: ID, preview } }) win.document.body.innerHTML = html return win.document.getElementById(ID)! } @@ -57,7 +60,7 @@ async function paintedCard(preview: LinkPreview, options: { expanded?: boolean } } describe('one card, two renderers', () => { - it('reads the same from the page\'s own HTML as it does painted into the browser\'s card', async () => { + it('reads the same from the page\'s own HTML as it does painted into the browser\'s card', { timeout: 30_000 }, async () => { for (const [name, preview] of await payloads()) { const direct = await staticCard(preview) const markup = inside(direct) @@ -101,6 +104,53 @@ describe('one card, two renderers', () => { expect(shell.querySelector('[data-preview-signature]')!.textContent).toBe('') }) + it('paints one payload after another as a fresh card reads, for every pair of kinds', { timeout: 30_000 }, async () => { + const all = await payloads() + const expected = new Map(all.map(([name, preview]) => { + const fresh = win.document.createElement('span') + fresh.innerHTML = cardHtml(previewCard(preview, { id: ID })) + return [name, inside(fresh)] as const + })) + await staticCard(undefined) + const blankHtml = win.document.body.innerHTML + for (const [firstName, first] of all) { + for (const [secondName, second] of all) { + win.document.body.innerHTML = blankHtml + const shell = win.document.getElementById(ID)! + paint(shell, first, { id: ID }) + paint(shell, second, { id: ID }) + // Nothing of the first card is left in the second: no style, language or class of a highlight, no chip, no footer. + expect(inside(shell), `${firstName} then ${secondName}`).toBe(expected.get(secondName)) + } + } + }) + + it('shows what a stale slot would leave, so that the sequence above can fail', async () => { + const all = new Map(await payloads()) + const highlighted = all.get('API method with a named type')! + const plain = all.get('page with no kind')! + expect(highlighted.signatureHighlight).toBeDefined() + const fresh = await staticCard(plain) + const expected = inside(fresh) + const shell = await paintedCard(highlighted) + const signature = shell.querySelector('[data-preview-signature]')! + expect(signature.hasAttribute('style') && signature.hasAttribute('data-language') && signature.classList.contains('lm-highlighted')).toBe(true) + paint(shell, plain, { id: ID }) + // The control: painted over, the slot is as a fresh card has it. + expect(inside(shell)).toBe(expected) + for (const stale of [['style', '--shiki-light:#000'], ['data-language', 'rust'], ['class', 'reference-link-preview__signature lm-highlighted']] as const) { + const leftover = await paintedCard(highlighted) + paint(leftover, plain, { id: ID }) + leftover.querySelector('[data-preview-signature]')!.setAttribute(stale[0], stale[1]) + expect(inside(leftover), stale[0]).not.toBe(expected) + } + // A chip left in the kind slot and a footer left on the card are seen the same way. + const chipped = await paintedCard(highlighted) + paint(chipped, plain, { id: ID }) + chipped.querySelector('[data-preview-kind]')!.removeAttribute('hidden') + expect(inside(chipped)).not.toBe(expected) + }) + it('notices a card that has drifted from the description, and passes the card that has not', async () => { const [, preview] = (await payloads())[0] const expected = inside(await staticCard(preview)) @@ -136,7 +186,7 @@ describe('the header chip and the marks in the body', () => { 'resource-template', 'format', 'tool', 'resource', 'hook', 'typealias', 'module', 'union', 'cmdlet'] const cardOf = (kind: string, extra: Partial = {}): LinkPreview => ({ schema: 1, title: 'Name', kind, description: 'Summary.', href: '/en/x/', ...extra }) - it('is the legend chip a heading carries, for every kind', async () => { + it('is the legend chip a heading carries, for every kind', { timeout: 30_000 }, async () => { const badge = await loadAstroTemplate('components/api/ApiBadge.astro') for (const kind of KINDS) { const word = kind.replace(/-/g, ' ') @@ -217,12 +267,21 @@ describe('the header chip and the marks in the body', () => { }) it('does not link a destination that is not a page of this site, and reads the plain description when the runs differ', async () => { - for (const href of ['javascript:alert(1)', '//evil.test/x', 'https://evil.test/', 'data:text/html,x', '']) { + // A browser reads a backslash as a slash and drops a tab or a newline inside an address, so each of these leaves the site. + const offSite = ['javascript:alert(1)', '//evil.test/x', 'https://evil.test/', 'data:text/html,x', '', '/\\evil.test', '/\\\\evil.test', '/\t/evil.test', '/\n/evil.test', + '/\r/evil.test', '\\evil.test', '\t/evil.test', '/\t\\evil.test'] + for (const href of offSite) { + // The control for the check: the browser's own reading of the address, from an origin of its own, is off that origin. + if (href.startsWith('/')) expect(new URL(href, 'https://libtmux.org/en/ts/').origin, JSON.stringify(href)).not.toBe('https://libtmux.org') const preview = cardOf('method', { description: 'See Session.', descriptionParts: ['See ', { text: 'Session', href, kind: 'struct' }, '.'] }) const shell = await staticCard(preview) expect(shell.querySelectorAll('[data-preview-description] a'), href).toHaveLength(0) expect(shell.querySelector('[data-preview-description]')!.textContent, href).toBe('See Session.') } + for (const href of ['/en/rs/latest/reference/server/', '/rs/latest/reference/server/#libtmux.Server.new_session', '/a/../b/', '/%5C%5Cevil.test']) { + const shell = await staticCard(cardOf('method', { description: 'See Session.', descriptionParts: ['See ', { text: 'Session', href, kind: 'struct' }, '.'] })) + expect(shell.querySelector('[data-preview-description] a')?.getAttribute('href'), href).toBe(href) + } const disagree = await staticCard(cardOf('method', { description: 'Plain words.', descriptionParts: ['Other ', { text: 'words', href: '/en/x/', kind: 'struct' }] })) expect(disagree.querySelector('[data-preview-description]')!.textContent).toBe('Plain words.') expect(disagree.querySelectorAll('[data-preview-description] a')).toHaveLength(0) diff --git a/site/test/link-preview-payload.test.ts b/site/test/link-preview-payload.test.ts index a7e2bc0f2..17f46c5af 100644 --- a/site/test/link-preview-payload.test.ts +++ b/site/test/link-preview-payload.test.ts @@ -32,7 +32,7 @@ describe('the payloads that feed the card', () => { expect(symbolPreview(model, type, 'latest').footer).toEqual([type.package ?? 'libtmux']) }) - it('reads each summary as its text and the names that resolve to a page, in every port', () => { + it('reads each summary as its text and the names that resolve to a page, in every port', { timeout: 30_000 }, () => { let marked = 0 for (const [port, model] of Object.entries(API_MODELS)) { for (const symbol of model.symbols) { @@ -65,7 +65,7 @@ describe('the payloads that feed the card', () => { expect(tmuxCatalogPreview('latest', hook).footer).toEqual([manual.terms![Object.keys(manual.terms!)[0]].footer![0], 'Hooks']) }) - it('links the names that an MCP description gives its sibling objects, as its page does, and never the object itself', () => { + it('links the names that an MCP description gives its sibling objects, as its page does, and never the object itself', { timeout: 30_000 }, () => { let linked = 0 for (const port of ['ruby', 'py', 'ts', 'rs', 'go', 'java', 'julia']) { for (const object of mcpObjects(port)) { diff --git a/site/test/link-preview.test.ts b/site/test/link-preview.test.ts index 9a25e1bef..66a45b89d 100644 --- a/site/test/link-preview.test.ts +++ b/site/test/link-preview.test.ts @@ -137,16 +137,18 @@ let requests: ReturnType let opened: boolean let serial = 0 let prefix: string -beforeEach(() => { +let shell = '' +let cardHtml: Promise | undefined +beforeEach(async () => { + // Rendered before the timers are faked, and once: the card that the layout writes, with every slot the painter fills. + shell = await (cardHtml ??= loadAstroTemplate('components/LinkPreview.astro').then((template) => renderAstroTemplate(template, { props: { id: 'reference-link-preview' } }))) prefix = `/en/ts/latest/reference/preview-test-${++serial}` win = new Window({ url: 'https://libtmux.org/en/ts/latest/guides/' }) for (const [name, value] of Object.entries({ window: win, document: win.document, location: win.location, Element: win.Element, Node: win.Node, HTMLElement: win.HTMLElement, innerHeight: 800 })) vi.stubGlobal(name, value) vi.useFakeTimers() opened = false - win.document.body.innerHTML = `ab - - ` + win.document.body.innerHTML = `ab${shell}` const panel = win.document.getElementById('reference-link-preview')! Object.assign(panel, { showPopover: () => { opened = true }, hidePopover: () => { opened = false } }) const matches = panel.matches.bind(panel) From 5f06e3751142f50eb1fa544256f59297c6499090 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 24 Oct 2026 15:40:16 -0500 Subject: [PATCH 5/8] fix(site[link-preview]) Set the card header in the face the demo uses why: The approved card sets its whole header in the mono face. Ours left the header container in the card's sans face, so only the name and the legend chip, which declare their own faces, were right; nothing else in the header should depend on that. what: - Set the header in `--font-mono`; the legend chip and the close control keep the faces they declare themselves, so the page looks the same and the header now matches the demo's structure --- site/src/components/LinkPreview.astro | 1 + 1 file changed, 1 insertion(+) diff --git a/site/src/components/LinkPreview.astro b/site/src/components/LinkPreview.astro index 1cc12def7..0f33b9172 100644 --- a/site/src/components/LinkPreview.astro +++ b/site/src/components/LinkPreview.astro @@ -52,6 +52,7 @@ const { id = 'reference-link-preview', preview, class: className } = Astro.props .reference-link-preview__heading { display: flex; align-items: center; gap: .5rem; padding: .55rem .8rem; border-bottom: 1px solid var(--color-background-border); background: var(--color-background-secondary); + font-family: var(--font-mono, ui-monospace, monospace); } .reference-link-preview__kind:not([hidden]) { display: inline-flex; flex: none; } .reference-link-preview__kind .api-badge.api-leg { font-size: 1.05em; } From af0e24aaf4cf0383c48e67026d495b6e42a3d513 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 24 Oct 2026 15:40:42 -0500 Subject: [PATCH 6/8] fix(site[link-preview]) Keep the close control at the smallest target size why: The close control drew 23.8 px wide, and 23.3 px in the 280 px card, under the 24 px that a pointer or touch target needs. The approved card has no close control, so nothing in the demo sets its size. what: - Give the control a 1.5rem minimum each way, so the card's header grows by what it needs and no more - Measure the control in Chromium at 280, 390 and 768 px; with the minimum removed the 280 px card fails at 23.3 px --- site/src/components/LinkPreview.astro | 2 +- site/test/link-preview-card.outer.test.ts | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/site/src/components/LinkPreview.astro b/site/src/components/LinkPreview.astro index 0f33b9172..4bf2d127d 100644 --- a/site/src/components/LinkPreview.astro +++ b/site/src/components/LinkPreview.astro @@ -58,7 +58,7 @@ const { id = 'reference-link-preview', preview, class: className } = Astro.props .reference-link-preview__kind .api-badge.api-leg { font-size: 1.05em; } .reference-link-preview__name { flex: 1; min-width: 0; font-weight: 700; } .reference-link-preview__heading button { - flex: none; margin-inline-start: auto; padding: 0 .4rem; border: 0; border-radius: .25rem; background: transparent; + flex: none; margin-inline-start: auto; min-inline-size: 1.5rem; min-block-size: 1.5rem; padding: 0 .4rem; border: 0; border-radius: .25rem; background: transparent; color: var(--color-foreground-muted); font: 400 1.125rem/1.4 var(--font-sans); cursor: pointer; } .reference-link-preview__heading button:hover { background: var(--color-api-background-hover); color: inherit; } diff --git a/site/test/link-preview-card.outer.test.ts b/site/test/link-preview-card.outer.test.ts index 16c3e7afb..6440a9c8d 100644 --- a/site/test/link-preview-card.outer.test.ts +++ b/site/test/link-preview-card.outer.test.ts @@ -150,6 +150,19 @@ describe('the card in a browser', () => { } finally { await target.close() } }) + it('gives the close control a target of at least 24 px each way, at every width', { timeout: 30_000 }, async () => { + const [, preview] = (await cardPayloads())[0]! + const target = await browser.newPage() + try { + for (const width of [280, 390, 768]) { + await open(target, preview, 'light', width) + const box = (await target.locator('[data-preview-close]').boundingBox())! + expect(box.width, `${width}px`).toBeGreaterThanOrEqual(24) + expect(box.height, `${width}px`).toBeGreaterThanOrEqual(24) + } + } finally { await target.close() } + }) + it('opens from its trigger, reaches the close control, each named type and the way to the page in that order, and closes on Escape', { timeout: 30_000 }, async () => { const [, preview] = (await cardPayloads())[0]! const target = await browser.newPage() From 345e0db5ab69d86f09a59bfafa1bbe55bd2bd7e3 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 24 Oct 2026 15:50:05 -0500 Subject: [PATCH 7/8] feat(site[link-preview]) Head a card with the owner and the member, as the demo does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: The approved card heads itself `Server::new_session`, the owner and the member, and says where the declaration lives in its footer. The full native path, `libtmux::server::Server::new_session`, is where the Qualified name row of the page belongs; as a header it wrapped onto a second line and repeated the package that the footer already names. what: - nativeShortName names a member by its owner and itself, in the separator the language writes between them, and a declaration with no owner by its name: Rust `Server::new_session`, `ConfigError`, `TmuxTools::new`; TypeScript `Client.session`; C++ `Server::new_session`; Ruby `Server#new_session`, `Async.open`; Lua `Server:new_session`; Go `Server.NewSession`; Elixir `Capture.fetch/2`; Swift with the labels the page heading shows. It reads the separator from the public id, which keeps it, and Rust's `::` from the language - symbolPreview heads the card with it. The Qualified name row keeps nativeQualifiedName, the full path - The footer stays `package · owner`, as the demo's does: the demo repeats the owner in header and footer, so it is not changed - Test every symbol of every port against its owner and a separator its language writes, that the short form ends the full name, and each family's separator on real ids; the long-name payload is now a Swift member, since a header is long only where a member carries its labels Before and after, as the card headed them: Rust libtmux::control::ControlSender::unmute_pane ControlSender::unmute_pane Rust libtmux::server::Server::new_session Server::new_session TypeScript Client.session Client.session Julia LibTmux.from_env from_env --- site/src/lib/link-preview.ts | 4 +- site/src/lib/native-name.ts | 28 ++++++++- site/test/link-preview-payloads.ts | 5 +- site/test/link-preview.test.ts | 2 +- site/test/native-name.test.ts | 97 +++++++++++++++++++++++++++--- 5 files changed, 120 insertions(+), 16 deletions(-) diff --git a/site/src/lib/link-preview.ts b/site/src/lib/link-preview.ts index 9fa4bdcc5..7a74017a2 100644 --- a/site/src/lib/link-preview.ts +++ b/site/src/lib/link-preview.ts @@ -1,6 +1,6 @@ import { docSummaryText, sourceUrl, type ApiModel, type ApiSymbol, type SymbolIndex } from '@libtmux/api-model' import { productApiHref, productApiIndex } from './product-api' -import { nativeQualifiedName } from './native-name' +import { nativeShortName } from './native-name' import { PORT_BY_SLUG } from './ports' import { apiGlossary } from './api-glossary' import { codeLang, highlightTokens, type CodeHighlight } from './highlight' @@ -85,7 +85,7 @@ export function symbolPreview(model: ApiModel, symbol: ApiSymbol, version: strin const description = summary ? docSummaryText(summary, model.port) : '' const footer = [symbol.package ?? PORT_BY_SLUG[model.port]?.packageName, ownerOf(model, symbol)?.name].filter((place): place is string => !!place) return { - schema: 1, title: nativeQualifiedName(model, symbol), kind: symbol.command?.kind ?? symbol.kind, + schema: 1, title: nativeShortName(model, symbol), kind: symbol.command?.kind ?? symbol.kind, description, descriptionParts: summary ? summaryParts(productApiIndex(model, version), summary, symbol, description) : undefined, footer: footer.length ? footer : undefined, diff --git a/site/src/lib/native-name.ts b/site/src/lib/native-name.ts index 4c9437c9a..2977001ff 100644 --- a/site/src/lib/native-name.ts +++ b/site/src/lib/native-name.ts @@ -15,6 +15,10 @@ import { qualifiedNameOf, type ApiSymbol } from '@libtmux/api-model' * - TypeScript names a member by its owner: `Client.session`. The id begins with the file the symbol is written in * (`client`), which a reader never writes; the file is the Module row of the page. * + * `nativeShortName` is the short form the page heading and a hover card use: the owner and the member in the + * language's separator (`ControlSender::unmute_pane`, `Server#new_session`, `Buffer:reference`, `Capture.fetch/2`), and + * the bare name for a declaration with no owner. The full name is the page's Qualified name row. + * * This is for display. The public id, the anchors and the URLs stay as the model has them. */ export function nativeQualifiedName(model: { port?: string; symbols: readonly ApiSymbol[] } | undefined, symbol: ApiSymbol): string { @@ -26,10 +30,15 @@ export function nativeQualifiedName(model: { port?: string; symbols: readonly Ap const byId = new WeakMap>() -/** The outermost declaration that `symbol` is written in, or `symbol` itself when it has no owner. */ -function outermost(symbols: readonly ApiSymbol[], symbol: ApiSymbol): ApiSymbol { +function symbolTable(symbols: readonly ApiSymbol[]): Map { let table = byId.get(symbols) if (!table) { table = new Map(symbols.map((entry) => [entry.id, entry])); byId.set(symbols, table) } + return table +} + +/** The outermost declaration that `symbol` is written in, or `symbol` itself when it has no owner. */ +function outermost(symbols: readonly ApiSymbol[], symbol: ApiSymbol): ApiSymbol { + const table = symbolTable(symbols) const seen = new Set([symbol.id]) let top = symbol while (top.parent) { @@ -59,3 +68,18 @@ function typescriptName(model: { symbols: readonly ApiSymbol[] }, symbol: ApiSym const file = topId.endsWith(`.${top.name}`) ? topId.slice(0, topId.length - top.name.length) : '' return file && id.startsWith(file) ? id.slice(file.length) : id } + +/** + * The owner and the member, as the page heading names them, in the separator the language writes between them. The id + * carries that separator (Ruby `#` for an instance method and `.` for a singleton one, Lua `:`, C++ `::`); Rust's id + * uses dots where the language writes `::`. + */ +export function nativeShortName(model: { port?: string; symbols: readonly ApiSymbol[] } | undefined, symbol: ApiSymbol): string { + const owner = model && symbol.parent ? symbolTable(model.symbols).get(symbol.parent) : undefined + if (!owner) return symbol.name + if (model?.port === 'rs') return `${owner.name}::${symbol.name}` + const id = qualifiedNameOf(symbol), ownerId = qualifiedNameOf(owner) + // Swift writes a member's labels in its name and fewer of them in its id, so the id is not always the owner and the name. + const fits = id.startsWith(ownerId) && id.endsWith(symbol.name) && id.length > ownerId.length + symbol.name.length + return `${owner.name}${(fits && id.slice(ownerId.length, id.length - symbol.name.length)) || '.'}${symbol.name}` +} diff --git a/site/test/link-preview-payloads.ts b/site/test/link-preview-payloads.ts index 979bdf7d4..38c605b28 100644 --- a/site/test/link-preview-payloads.ts +++ b/site/test/link-preview-payloads.ts @@ -10,7 +10,8 @@ import { tmuxCatalogPreview } from '../src/lib/tmux-catalog-preview' export async function cardPayloads(): Promise<[string, LinkPreview][]> { const rs = API_MODELS.rs const referenced = (model: typeof rs, kind?: string) => model.symbols.find((symbol) => (!kind || symbol.kind === kind) && symbolPreview(model, symbol, 'latest').descriptionParts)! - const long = API_MODELS.java.symbols.find((symbol) => symbol.id.length > 70 && symbol.signatures[0]?.raw)! + // A header is the owner and the member, so a name is long only where the member carries its labels, as Swift's do. + const long = API_MODELS.swift.symbols.find((symbol) => symbol.parent && symbol.name.length > 60)! const glossary = glossaryPreview(API_GLOSSARY_PATH) const manual = tmuxManualPreview('latest', 'full') const object = (kind: string) => { @@ -24,7 +25,7 @@ export async function cardPayloads(): Promise<[string, LinkPreview][]> { return Promise.all(([ ['API method with a named type', symbolPreview(rs, referenced(rs, 'method'), 'latest')], ['API declaration without references', symbolPreview(API_MODELS.cxx, API_MODELS.cxx.symbols.find((symbol) => symbol.kind === 'class')!, 'latest')], - ['API name long enough to abbreviate', symbolPreview(API_MODELS.java, long, 'latest')], + ['API name long enough to abbreviate', symbolPreview(API_MODELS.swift, long, 'latest')], ['glossary page', glossary], ['glossary term that is a kind', glossary.terms!.struct], ['glossary term that is not a kind', glossary.terms!.inherited], diff --git a/site/test/link-preview.test.ts b/site/test/link-preview.test.ts index 66a45b89d..0c2c6e68f 100644 --- a/site/test/link-preview.test.ts +++ b/site/test/link-preview.test.ts @@ -40,7 +40,7 @@ it('uses authored, native descriptions and signatures without reconstructing lan const julia = API_MODELS.julia const symbol = julia.symbols.find((entry) => entry.id === 'LibTmux.from_env')! const result = symbolPreview(julia, symbol, 'latest') - expect(result.title).toBe('LibTmux.from_env') + expect(result.title).toBe('from_env') expect(result.description).toContain('without contacting tmux') expect(result.signature).toBe(symbol.signatures[0].raw) expect(result.href).toMatch(/\/julia\/latest\/reference\/libtmux-from_env\/$/) diff --git a/site/test/native-name.test.ts b/site/test/native-name.test.ts index 6ae4733df..f93d98c09 100644 --- a/site/test/native-name.test.ts +++ b/site/test/native-name.test.ts @@ -2,13 +2,14 @@ import { describe, expect, it } from 'vitest' import { qualifiedNameOf, type ApiSymbol } from '@libtmux/api-model' import { API_MODELS } from '../src/lib/api-models' import { symbolPreview } from '../src/lib/link-preview' -import { nativeQualifiedName } from '../src/lib/native-name' +import { nativeQualifiedName, nativeShortName } from '../src/lib/native-name' import { productApiHref } from '../src/lib/product-api' /** - * A card's header and the page's Qualified name row say a declaration the way the language writes it. Rust spells a path - * with `::` from its crate and TypeScript names a member by its owner; every other port already keeps its own spelling in - * the public id, which must stay as it was. + * The page's Qualified name row says a declaration the way the language writes it, in full: Rust spells a path with `::` + * from its crate and TypeScript names a member by its owner, and every other port already keeps its own spelling in the + * public id, which must stay as it was. A card's header says it in short, as the page heading does: the owner and the + * member in the language's separator. */ const symbolNamed = (port: string, id: string) => { const symbol = API_MODELS[port].symbols.find((entry) => (entry.publicId ?? entry.id) === id) @@ -110,13 +111,91 @@ describe('the other ports', () => { }) }) +const shortName = (port: string, id: string) => nativeShortName(API_MODELS[port], symbolNamed(port, id)) + +describe('short names', () => { + it('name a Rust member by its owner with `::`, and a declaration with no owner by itself', () => { + expect(shortName('rs', 'server.Server.new_session')).toBe('Server::new_session') + expect(shortName('rs', 'control.ControlSender.unmute_pane')).toBe('ControlSender::unmute_pane') + expect(shortName('rs', 'config.ConfigError')).toBe('ConfigError') + expect(shortName('rs', 'mcp.src.TmuxTools.new')).toBe('TmuxTools::new') + expect(shortName('rs', 'error.scoped.ScopeError.Creation')).toBe('ScopeError::Creation') + }) + + it('name a TypeScript member by its owner', () => { + expect(shortName('ts', 'server.Server.newSession')).toBe('Server.newSession') + expect(shortName('ts', 'client.Client.session')).toBe('Client.session') + expect(shortName('ts', 'errors.TmuxTransportError.#stderr')).toBe('TmuxTransportError.#stderr') + expect(shortName('ts', 'common.isSafeInteger')).toBe('isSafeInteger') + }) + + it.each([ + ['cxx', 'libtmux::Server::new_session', 'Server::new_session'], + ['cxx', 'libtmux::AttachCommand', 'AttachCommand'], + ['ruby', 'LibTmux::Server#new_session', 'Server#new_session'], + ['ruby', 'LibTmux::Async.open', 'Async.open'], + ['ruby', 'LibTmux::Async::ControlConnection', 'Async::ControlConnection'], + ['lua', 'libtmux.Server:new_session', 'Server:new_session'], + ['lua', 'libtmux.BreakPaneOptions.name', 'BreakPaneOptions.name'], + ['go', 'tmux.Server.NewSession', 'Server.NewSession'], + ['elixir', 'LibTmux.Capture.fetch/2', 'Capture.fetch/2'], + ['powershell', 'LibTmux\\Connect-TmuxControl', 'LibTmux\\Connect-TmuxControl'], + ['py', 'libtmux.Server.new_session', 'Server.new_session'], + ['py', 'libtmux._internal.env.resolve_env', 'resolve_env'], + ['java', 'io.github.libtmux.Server.Server.newSession', 'Server.newSession'], + ['kotlin', 'io.github.libtmux.kotlin.Server.newSession', 'Server.newSession'], + ['csharp', 'LibTmux.TmuxBuffers.SetAsync', 'TmuxBuffers.SetAsync'], + ['julia', 'LibTmux.BatchResult.operations', 'BatchResult.operations'], + ['julia', 'LibTmux.cancel!', 'cancel!'], + ] as const)('keeps the separator %s writes: %s -> %s', (port, id, expected) => { + expect(shortName(port, id)).toBe(expected) + }) + + it('keeps Swift\'s labels, as the page heading does', () => { + const symbol = API_MODELS.swift.symbols.find((entry) => entry.name.startsWith('newSession(named:'))! + expect(nativeShortName(API_MODELS.swift, symbol)).toBe(`Server.${symbol.name}`) + }) + + it('are the owner, a separator that the language writes, and the member, for every symbol of every port', { timeout: 30_000 }, () => { + const separators: Record = { rs: ['::'], cxx: ['::'], ruby: ['::', '.', '#'], lua: ['.', ':'], powershell: ['\\'] } + for (const [port, model] of Object.entries(API_MODELS)) { + const owners = new Map(model.symbols.map((symbol) => [symbol.id, symbol])) + for (const symbol of model.symbols) { + const shown = nativeShortName(model, symbol) + const owner = symbol.parent ? owners.get(symbol.parent) : undefined + if (!owner) { expect(shown, `${port} ${symbol.id}`).toBe(symbol.name); continue } + expect(shown.startsWith(owner.name) && shown.endsWith(symbol.name), `${port} ${symbol.id}`).toBe(true) + const separator = shown.slice(owner.name.length, shown.length - symbol.name.length) + expect(separators[port] ?? ['.'], `${port} ${symbol.id}`).toContain(separator) + } + } + }) + + it('are the end of the full name wherever the id ends with the name, so the card is the page\'s name without its path', { timeout: 30_000 }, () => { + for (const [port, model] of Object.entries(API_MODELS)) { + for (const symbol of model.symbols) { + if (!qualifiedNameOf(symbol).endsWith(symbol.name)) continue + expect(nativeQualifiedName(model, symbol).endsWith(nativeShortName(model, symbol)), `${port} ${symbol.id}`).toBe(true) + } + } + }) + + it('has a control: a full name is longer than its short form wherever the declaration has a path', () => { + const symbol = symbolNamed('rs', 'control.ControlSender.unmute_pane') + expect(nativeQualifiedName(API_MODELS.rs, symbol)).toBe('libtmux::control::ControlSender::unmute_pane') + expect(nativeShortName(API_MODELS.rs, symbol)).toBe('ControlSender::unmute_pane') + expect(nativeShortName(API_MODELS.rs, symbol).length).toBeLessThan(nativeQualifiedName(API_MODELS.rs, symbol).length) + }) +}) + describe('where the name is used', () => { - it('heads the card of a Rust or TypeScript symbol, and every other card as before', () => { - expect(symbolPreview(API_MODELS.rs, symbolNamed('rs', 'control.ControlSender.unmute_pane'), 'latest').title).toBe('libtmux::control::ControlSender::unmute_pane') + it('heads the card in short and leaves the full name to the page row', () => { + expect(symbolPreview(API_MODELS.rs, symbolNamed('rs', 'server.Server.new_session'), 'latest').title).toBe('Server::new_session') + expect(symbolPreview(API_MODELS.rs, symbolNamed('rs', 'control.ControlSender.unmute_pane'), 'latest').title).toBe('ControlSender::unmute_pane') expect(symbolPreview(API_MODELS.ts, symbolNamed('ts', 'client.Client.session'), 'latest').title).toBe('Client.session') - for (const port of ['py', 'go', 'cxx', 'ruby', 'lua']) { - const symbol = API_MODELS[port].symbols[0] - expect(symbolPreview(API_MODELS[port], symbol, 'latest').title, port).toBe(qualifiedNameOf(symbol)) + for (const [port, model] of Object.entries(API_MODELS)) { + const symbol = model.symbols.find((entry) => entry.parent) ?? model.symbols[0] + expect(symbolPreview(model, symbol, 'latest').title, port).toBe(nativeShortName(model, symbol)) } }) From 98a0497812d8b493c07cb11df5bb03706dc5d80e Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 24 Oct 2026 16:05:05 -0500 Subject: [PATCH 8/8] fix(site[link-preview]) Name the declaring crate, say a place once, and write tuple fields as rustdoc does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: The critic's review of the hover card found three things the card said wrongly and two comments that claimed too much. 432 Rust symbols in `tmux_mcp` and `tmux_workspace` showed `libtmux` in the footer while the Qualified name row began with their crate. PowerShell showed `LibTmux · LibTmux`, its package and its module. A Rust tuple field read `Window::0`, which is not a path. And two comments called the short name the form the page heading uses, though the heading still joins the owner and the member with a dot in every port. what: - nativePackageName gives a Rust symbol its crate, from the file it is written in, as the Qualified name row does; the footer begins with it. Another port keeps the package its model names, or the port's - A footer says a place once: an owner that is the package is dropped - A Rust tuple field follows its owner with a dot, `Creation.0`, in the short name and in the full one, and is never a `::` path - Say in the comments that the short form is the card header's, and that the page heading is a follow-up, in native-name.ts and its test - Test that every Rust footer begins with the crate its full name begins with, that every other port's begins with its model's or the port's package, that no footer repeats a place, the tuple fields, and the controls that fail without the dedupe and without the tuple rule --- site/src/lib/link-preview.ts | 9 ++++- site/src/lib/native-name.ts | 31 ++++++++++---- site/test/link-preview-payload.test.ts | 32 +++++++++++++++ site/test/native-name.test.ts | 56 ++++++++++++++++++++++---- 4 files changed, 111 insertions(+), 17 deletions(-) diff --git a/site/src/lib/link-preview.ts b/site/src/lib/link-preview.ts index 7a74017a2..f0f7d6a4c 100644 --- a/site/src/lib/link-preview.ts +++ b/site/src/lib/link-preview.ts @@ -1,6 +1,6 @@ import { docSummaryText, sourceUrl, type ApiModel, type ApiSymbol, type SymbolIndex } from '@libtmux/api-model' import { productApiHref, productApiIndex } from './product-api' -import { nativeShortName } from './native-name' +import { nativePackageName, nativeShortName } from './native-name' import { PORT_BY_SLUG } from './ports' import { apiGlossary } from './api-glossary' import { codeLang, highlightTokens, type CodeHighlight } from './highlight' @@ -79,11 +79,16 @@ function summaryParts(index: SymbolIndex, summary: string, context: ApiSymbol, d return runs.finish(description) } +/** The package and the owner a card's footer names; an owner that is the package itself, as PowerShell's module is, is said once. */ +function footerPlaces(...places: (string | undefined)[]): string[] { + return places.filter((place): place is string => !!place).filter((place, index, all) => place !== all[index - 1]) +} + export function symbolPreview(model: ApiModel, symbol: ApiSymbol, version: string): LinkPreview { const summary = symbol.doc?.summary ?? symbol.signatures.find((signature) => signature.doc?.summary)?.doc?.summary const signature = symbol.signatures[0]?.raw ?? (symbol.value !== undefined ? `${symbol.name} = ${symbol.value}` : undefined) const description = summary ? docSummaryText(summary, model.port) : '' - const footer = [symbol.package ?? PORT_BY_SLUG[model.port]?.packageName, ownerOf(model, symbol)?.name].filter((place): place is string => !!place) + const footer = footerPlaces(nativePackageName(model, symbol) ?? PORT_BY_SLUG[model.port]?.packageName, ownerOf(model, symbol)?.name) return { schema: 1, title: nativeShortName(model, symbol), kind: symbol.command?.kind ?? symbol.kind, description, diff --git a/site/src/lib/native-name.ts b/site/src/lib/native-name.ts index 2977001ff..0550d62be 100644 --- a/site/src/lib/native-name.ts +++ b/site/src/lib/native-name.ts @@ -15,9 +15,10 @@ import { qualifiedNameOf, type ApiSymbol } from '@libtmux/api-model' * - TypeScript names a member by its owner: `Client.session`. The id begins with the file the symbol is written in * (`client`), which a reader never writes; the file is the Module row of the page. * - * `nativeShortName` is the short form the page heading and a hover card use: the owner and the member in the - * language's separator (`ControlSender::unmute_pane`, `Server#new_session`, `Buffer:reference`, `Capture.fetch/2`), and - * the bare name for a declaration with no owner. The full name is the page's Qualified name row. + * `nativeShortName` is the short form a hover card uses for its header: the owner and the member in the language's + * separator (`ControlSender::unmute_pane`, `Server#new_session`, `Buffer:reference`, `Capture.fetch/2`), and the bare name + * for a declaration with no owner. The full name is the page's Qualified name row. The page heading still joins the owner + * and the member with a dot in every port, so for Rust, C++, Ruby, Lua and PowerShell it differs from the card's header. * * This is for display. The public id, the anchors and the URLs stay as the model has them. */ @@ -50,15 +51,29 @@ function outermost(symbols: readonly ApiSymbol[], symbol: ApiSymbol): ApiSymbol return top } +/** The crate a Rust symbol is written in: a package name uses hyphens where the crate that it builds does not. */ +const rustCrate = (symbol: ApiSymbol) => /^crates\/([^/]+)\/src\//.exec(symbol.source?.file ?? '')?.[1]?.replace(/-/g, '_') + +/** A tuple field is named by position, which a path cannot hold: rustdoc writes `Window.0`, and so does this. */ +const tupleField = (name: string) => /^\d+$/.test(name) + +/** + * The package a symbol is declared in, where the model does not say: the crate of a Rust symbol, so that a symbol of + * `tmux_mcp` is not credited to `libtmux`. Any other port names the package of a symbol in the symbol itself, or + * has one for the whole port. + */ +export function nativePackageName(model: { port?: string } | undefined, symbol: ApiSymbol): string | undefined { + return symbol.package ?? (model?.port === 'rs' ? rustCrate(symbol) : undefined) +} + function rustName(model: { symbols: readonly ApiSymbol[] }, symbol: ApiSymbol, id: string): string { const file = symbol.source?.file ?? '' - // A package name uses hyphens where the crate that it builds does not. - const crate = /^crates\/([^/]+)\/src\//.exec(file)?.[1]?.replace(/-/g, '_') + const crate = rustCrate(symbol) const path = id.split('.') if (symbol.product && symbol.product !== 'core' && path[0] === symbol.product) path.shift() // A member can be written in another file than its type, so the root is told by the file of the outermost declaration. if (path[0] === 'src' && /\/(?:lib|main)\.rs$/.test(outermost(model.symbols, symbol).source?.file ?? file)) path.shift() - return [crate, ...path].filter(Boolean).join('::') + return [crate, ...path].filter((segment): segment is string => !!segment).reduce((name, segment) => tupleField(segment) ? `${name}.${segment}` : name ? `${name}::${segment}` : segment, '') } function typescriptName(model: { symbols: readonly ApiSymbol[] }, symbol: ApiSymbol, id: string): string { @@ -70,14 +85,14 @@ function typescriptName(model: { symbols: readonly ApiSymbol[] }, symbol: ApiSym } /** - * The owner and the member, as the page heading names them, in the separator the language writes between them. The id + * The owner and the member, in the separator the language writes between them. The id * carries that separator (Ruby `#` for an instance method and `.` for a singleton one, Lua `:`, C++ `::`); Rust's id * uses dots where the language writes `::`. */ export function nativeShortName(model: { port?: string; symbols: readonly ApiSymbol[] } | undefined, symbol: ApiSymbol): string { const owner = model && symbol.parent ? symbolTable(model.symbols).get(symbol.parent) : undefined if (!owner) return symbol.name - if (model?.port === 'rs') return `${owner.name}::${symbol.name}` + if (model?.port === 'rs') return `${owner.name}${tupleField(symbol.name) ? '.' : '::'}${symbol.name}` const id = qualifiedNameOf(symbol), ownerId = qualifiedNameOf(owner) // Swift writes a member's labels in its name and fewer of them in its id, so the id is not always the owner and the name. const fits = id.startsWith(ownerId) && id.endsWith(symbol.name) && id.length > ownerId.length + symbol.name.length diff --git a/site/test/link-preview-payload.test.ts b/site/test/link-preview-payload.test.ts index 17f46c5af..51a6cadca 100644 --- a/site/test/link-preview-payload.test.ts +++ b/site/test/link-preview-payload.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest' import { docSummaryText } from '@libtmux/api-model' import { API_GLOSSARY_PATH } from '../src/lib/api-glossary' import { API_MODELS } from '../src/lib/api-models' +import { nativeQualifiedName } from '../src/lib/native-name' +import { PORT_BY_SLUG } from '../src/lib/ports' import { kindMark } from '../src/lib/api-labels' import { glossaryPreview, symbolPreview, tmuxManualPreview } from '../src/lib/link-preview' import { mcpObjects } from '../src/lib/mcp-catalog' @@ -32,6 +34,36 @@ describe('the payloads that feed the card', () => { expect(symbolPreview(model, type, 'latest').footer).toEqual([type.package ?? 'libtmux']) }) + it('names the declaring crate of a Rust symbol and the package of any other, never the same place twice', { timeout: 30_000 }, () => { + const rs = API_MODELS.rs + const footerOf = (id: string) => symbolPreview(rs, rs.symbols.find((symbol) => (symbol.publicId ?? symbol.id) === id)!, 'latest').footer + expect(footerOf('server.Server.new_session')).toEqual(['libtmux', 'Server']) + expect(footerOf('config.ConfigError')).toEqual(['tmux_workspace']) + expect(footerOf('mcp.src.TmuxTools.new')).toEqual(['tmux_mcp', 'TmuxTools']) + // The crate in the footer is the crate that the page's Qualified name row begins with. + for (const symbol of rs.symbols) expect(nativeQualifiedName(rs, symbol).startsWith(`${symbolPreview(rs, symbol, 'latest').footer![0]}::`), symbol.id).toBe(true) + for (const [port, model] of Object.entries(API_MODELS)) { + if (port === 'rs') continue + const portPackage = PORT_BY_SLUG[port].packageName + for (const symbol of model.symbols) expect(symbolPreview(model, symbol, 'latest').footer![0], `${port} ${symbol.id}`).toBe(symbol.package ?? portPackage) + } + // PowerShell's module is its package: the footer says so once. + const powershell = API_MODELS.powershell + const command = powershell.symbols.find((symbol) => symbol.parent && symbol.package === 'LibTmux')! + expect(symbolPreview(powershell, command, 'latest').footer).toEqual(['LibTmux']) + const workspace = powershell.symbols.find((symbol) => symbol.parent && symbol.package === 'LibTmux.Workspace')! + expect(symbolPreview(powershell, workspace, 'latest').footer).toEqual(['LibTmux.Workspace']) + }) + + it('never repeats a place in a footer', { timeout: 30_000 }, () => { + for (const [port, model] of Object.entries(API_MODELS)) { + for (const symbol of model.symbols) { + const footer = symbolPreview(model, symbol, 'latest').footer ?? [] + expect(footer.every((place, index) => place !== footer[index - 1]), `${port} ${symbol.id}: ${footer.join(' · ')}`).toBe(true) + } + } + }) + it('reads each summary as its text and the names that resolve to a page, in every port', { timeout: 30_000 }, () => { let marked = 0 for (const [port, model] of Object.entries(API_MODELS)) { diff --git a/site/test/native-name.test.ts b/site/test/native-name.test.ts index f93d98c09..de5e9b2cd 100644 --- a/site/test/native-name.test.ts +++ b/site/test/native-name.test.ts @@ -2,14 +2,14 @@ import { describe, expect, it } from 'vitest' import { qualifiedNameOf, type ApiSymbol } from '@libtmux/api-model' import { API_MODELS } from '../src/lib/api-models' import { symbolPreview } from '../src/lib/link-preview' -import { nativeQualifiedName, nativeShortName } from '../src/lib/native-name' +import { nativePackageName, nativeQualifiedName, nativeShortName } from '../src/lib/native-name' import { productApiHref } from '../src/lib/product-api' /** * The page's Qualified name row says a declaration the way the language writes it, in full: Rust spells a path with `::` * from its crate and TypeScript names a member by its owner, and every other port already keeps its own spelling in the - * public id, which must stay as it was. A card's header says it in short, as the page heading does: the owner and the - * member in the language's separator. + * public id, which must stay as it was. A card's header says it in short: the owner and the member in the language's + * separator. The page heading still joins them with a dot in every port. */ const symbolNamed = (port: string, id: string) => { const symbol = API_MODELS[port].symbols.find((entry) => (entry.publicId ?? entry.id) === id) @@ -21,10 +21,13 @@ const name = (port: string, id: string) => nativeQualifiedName(API_MODELS[port], /** What is wrong with a Rust display name, so that a control can show the check is able to fail. */ function rustProblems(symbol: ApiSymbol, shown: string): string[] { const problems: string[] = [] - if (/\./.test(shown)) problems.push('has a dot where a path has `::`') + // A tuple field is named by its position, which a path cannot hold; rustdoc writes it after a dot. + const tuple = /^\d+$/.test(symbol.name) + if (/\./.test(tuple ? shown.replace(/\.\d+$/, '') : shown)) problems.push('has a dot where a path has `::`') if (!/^[a-z][a-z0-9_]*::/.test(shown)) problems.push('does not begin at its crate') - if (!shown.endsWith(`::${symbol.name}`)) problems.push('does not end with its own name') + if (!shown.endsWith(`${tuple ? '.' : '::'}${symbol.name}`)) problems.push('does not end with its own name') if (/^[a-z_]+::(?:src|mcp)(?:::|$)/.test(shown)) problems.push('keeps the extractor\'s marker for the crate root or the product') + if (/::\d+$/.test(shown)) problems.push('writes a tuple field as a path') return problems } @@ -62,6 +65,43 @@ describe('Rust names', () => { }) }) +describe('Rust tuple fields', () => { + const tuples = API_MODELS.rs.symbols.filter((symbol) => /^\d+$/.test(symbol.name)) + + it('are named as rustdoc names them, after a dot, in the full name and in the short one', () => { + expect(tuples.length).toBeGreaterThan(0) + const field = symbolNamed('rs', 'error.scoped.ScopeError.Creation.0') + expect(nativeQualifiedName(API_MODELS.rs, field)).toBe('libtmux::error::scoped::ScopeError::Creation.0') + expect(nativeShortName(API_MODELS.rs, field)).toBe('Creation.0') + for (const symbol of tuples) { + expect(nativeShortName(API_MODELS.rs, symbol), symbol.id).toMatch(/^\w+\.\d+$/) + expect(nativeQualifiedName(API_MODELS.rs, symbol), symbol.id).not.toMatch(/::\d+$/) + } + }) + + it('has a control: written as a path, a tuple field fails the check', () => { + const field = symbolNamed('rs', 'error.scoped.ScopeError.Creation.0') + expect(rustProblems(field, nativeQualifiedName(API_MODELS.rs, field))).toEqual([]) + expect(rustProblems(field, 'libtmux::error::scoped::ScopeError::Creation::0')).toEqual(['does not end with its own name', 'writes a tuple field as a path']) + }) +}) + +describe('the package a symbol is declared in', () => { + it('is the crate for a Rust symbol, which the Qualified name row names first', () => { + expect(nativePackageName(API_MODELS.rs, symbolNamed('rs', 'server.Server.new_session'))).toBe('libtmux') + expect(nativePackageName(API_MODELS.rs, symbolNamed('rs', 'config.ConfigError'))).toBe('tmux_workspace') + expect(nativePackageName(API_MODELS.rs, symbolNamed('rs', 'mcp.src.TmuxTools.new'))).toBe('tmux_mcp') + for (const symbol of API_MODELS.rs.symbols) { + expect(nativeQualifiedName(API_MODELS.rs, symbol).startsWith(`${nativePackageName(API_MODELS.rs, symbol)}::`), symbol.id).toBe(true) + } + }) + + it('is what the model says for every other port, and nothing otherwise', () => { + expect(nativePackageName(API_MODELS.powershell, symbolNamed('powershell', 'LibTmux\\Connect-TmuxControl'))).toBe('LibTmux') + expect(nativePackageName(API_MODELS.py, API_MODELS.py.symbols[0])).toBeUndefined() + }) +}) + describe('TypeScript names', () => { it('name a member by its owner and leave out the file it is written in', () => { expect(name('ts', 'client.Client.session')).toBe('Client.session') @@ -151,7 +191,7 @@ describe('short names', () => { expect(shortName(port, id)).toBe(expected) }) - it('keeps Swift\'s labels, as the page heading does', () => { + it('keeps Swift\'s labels, which its name carries', () => { const symbol = API_MODELS.swift.symbols.find((entry) => entry.name.startsWith('newSession(named:'))! expect(nativeShortName(API_MODELS.swift, symbol)).toBe(`Server.${symbol.name}`) }) @@ -166,7 +206,9 @@ describe('short names', () => { if (!owner) { expect(shown, `${port} ${symbol.id}`).toBe(symbol.name); continue } expect(shown.startsWith(owner.name) && shown.endsWith(symbol.name), `${port} ${symbol.id}`).toBe(true) const separator = shown.slice(owner.name.length, shown.length - symbol.name.length) - expect(separators[port] ?? ['.'], `${port} ${symbol.id}`).toContain(separator) + // A Rust tuple field follows its owner with a dot, as rustdoc writes it; every other Rust member with `::`. + const allowed = port === 'rs' && /^\d+$/.test(symbol.name) ? ['.'] : separators[port] ?? ['.'] + expect(allowed, `${port} ${symbol.id}`).toContain(separator) } } })