diff --git a/site/src/components/LinkPreview.astro b/site/src/components/LinkPreview.astro index 1d0a1fb4f..4bf2d127d 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-payload.test.ts b/site/test/link-preview-payload.test.ts new file mode 100644 index 000000000..51a6cadca --- /dev/null +++ b/site/test/link-preview-payload.test.ts @@ -0,0 +1,119 @@ +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' +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('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)) { + 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', { timeout: 30_000 }, () => { + 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/link-preview-payloads.ts b/site/test/link-preview-payloads.ts new file mode 100644 index 000000000..a39c3220c --- /dev/null +++ b/site/test/link-preview-payloads.ts @@ -0,0 +1,48 @@ +import { API_GLOSSARY_PATH } from '../src/lib/api-glossary' +import { API_MODELS } from '../src/lib/api-models' +import { glossaryPreview, highlightedPreview, pagePreview, 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' +import { tmuxReferencePreview, tmuxReferenceRoutes } from '../src/lib/tmux-reference' + +/** 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)! + // 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) => { + 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)! + // The longest declaration of tmux's source: the preview cuts it to its head, and the card shows what it was given. + const cRoute = tmuxReferenceRoutes().filter((route) => route.version === 'latest' && route.symbol) + .reduce((longest, route) => (route.symbol!.signatures[0]?.raw?.length ?? 0) > (longest.symbol!.signatures[0]?.raw?.length ?? 0) ? route : longest) + const cDeclaration = tmuxReferencePreview(cRoute.version, cRoute.symbol!) + 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.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], + ['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', pagePreview({ title: 'Exit codes', description: 'What each command returns.' }, '/en/rs/latest/workspace/reference/exit-codes/')], + ['tmux C declaration cut to its head', cDeclaration], + ['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 d3240baf5..ffa44570c 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' @@ -15,10 +12,12 @@ 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 { PREVIEW_SIGNATURE_CHARS, PREVIEW_SIGNATURE_LINES } from '../src/lib/preview-signature' 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'], @@ -43,7 +42,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\/$/) @@ -112,26 +111,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) @@ -154,16 +139,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) @@ -309,7 +296,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') @@ -340,7 +331,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-name.test.ts b/site/test/native-name.test.ts new file mode 100644 index 000000000..de5e9b2cd --- /dev/null +++ b/site/test/native-name.test.ts @@ -0,0 +1,255 @@ +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 { 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: 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) + 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[] = [] + // 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(`${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 +} + +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('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') + 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) + }) +}) + +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, 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}`) + }) + + 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) + // 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) + } + } + }) + + 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 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, 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)) + } + }) + + 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) + } + }) +}) 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, diff --git a/site/test/tmux-mentions.test.ts b/site/test/tmux-mentions.test.ts index 8b4b9099e..7d2f21628 100644 --- a/site/test/tmux-mentions.test.ts +++ b/site/test/tmux-mentions.test.ts @@ -191,7 +191,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'], }) }) @@ -201,12 +201,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!)) {