The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(docs): guide reference perf enhancements (#50239)
Anthony Lio6d08a747f1c1
diff --git a/apps/docs/features/docs/Reference.ui.client.tsx b/apps/docs/features/docs/Reference.ui.client.tsxindex ef64b13a7de..33a7abe0f09 100644--- a/apps/docs/features/docs/Reference.ui.client.tsx+++ b/apps/docs/features/docs/Reference.ui.client.tsx@@ -2,10 +2,20 @@import { ReferenceContentInitiallyScrolledContext } from '~/features/docs/Reference.navigation.client'import { safeHistoryReplaceState } from '~/lib/historyUtils'+import { XCircle } from 'lucide-react'import type { HTMLAttributes, PropsWithChildren } from 'react'import { useContext, useEffect, useRef, useState } from 'react'import { useInView } from 'react-intersection-observer'-import { cn, Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from 'ui'+import {+ cn,+ CollapsibleTrigger,+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from 'ui'import { type IApiEndPoint } from './Reference.api.utils'import { API_REFERENCE_REQUEST_BODY_SCHEMA_DATA_ATTRIBUTES } from './Reference.ui.shared'@@ -106,3 +116,12 @@ export function ApiOperationBodySchemeSelector({</div>)}++export function DetailsTrigger({ label, className }: { label: string; className?: string }) {+ return (+ <CollapsibleTrigger className={cn('group reference-details-trigger', className)}>+ <XCircle size={14} aria-hidden="true" className="reference-details-trigger-icon" />+ {label}+ </CollapsibleTrigger>+ )+}diff --git a/apps/docs/features/docs/Reference.ui.tsx b/apps/docs/features/docs/Reference.ui.tsxindex 441976c8d35..7d722a33eaf 100644--- a/apps/docs/features/docs/Reference.ui.tsx+++ b/apps/docs/features/docs/Reference.ui.tsx@@ -8,10 +8,10 @@ import type {TypeDetails,} from '~/features/docs/Reference.typeSpec'import { TYPESPEC_NODE_ANONYMOUS } from '~/features/docs/Reference.typeSpec'-import { ReferenceSectionWrapper } from '~/features/docs/Reference.ui.client'+import { DetailsTrigger, ReferenceSectionWrapper } from '~/features/docs/Reference.ui.client'import { normalizeMarkdown } from '~/features/docs/Reference.utils'import { isEqual } from 'lodash-es'-import { ChevronRight, XCircle } from 'lucide-react'+import { ChevronRight } from 'lucide-react'import { fromMarkdown } from 'mdast-util-from-markdown'import type { HTMLAttributes, PropsWithChildren } from 'react'import ReactMarkdown from 'react-markdown'@@ -302,43 +302,12 @@ function TypeSubDetails({}) {return (<Collapsible defaultOpen={defaultOpen}>- <CollapsibleTrigger- className={cn(- 'group',- 'w-fit rounded-full',- 'px-5 py-1',- 'border border-default',- 'flex items-center gap-2',- 'text-left text-sm text-foreground-light',- 'hover:bg-surface-100',- 'data-open:w-full',- 'data-open:rounded-b-none data-open:rounded-tl-lg data-open:rounded-tr-lg',- 'transition [transition-property:width,background-color]',- className- )}- >- <XCircle- size={14}- className={cn(- 'text-foreground-muted',- 'group-data-closed:rotate-45',- 'transition-transform'- )}- />- Details- </CollapsibleTrigger>+ <DetailsTrigger label="Details" className={className} /><CollapsibleContent>- <ul className={cn('border-b border-x border-default', 'rounded-b-lg')}>+ <ul className="reference-details-panel">{details.map((detail: SubContent | CustomTypePropertyType | TypeDetails, index: number) => (- <li- key={index}- className={cn(- 'px-5 py-3',- 'border-t border-default first:border-t-0',- 'flex flex-col gap-3'- )}- >+ <li key={index} className="reference-details-item"><ParamOrTypeDetails paramOrType={detail} /></li>)@@ -542,42 +511,10 @@ export function ApiSchemaParamSubdetails({return (<Collapsible>- <CollapsibleTrigger- className={cn(- 'group',- 'w-fit rounded-full',- 'px-5 py-1',- 'border border-default',- 'flex items-center gap-2',- 'text-left text-sm text-foreground-light',- 'hover:bg-surface-100',- 'data-open:w-full',- 'data-open:rounded-b-none data-open:rounded-tl-lg data-open:rounded-tr-lg',- 'transition [transition-property:width,background-color]',- className- )}- >- <XCircle- size={14}- className={cn(- 'text-foreground-muted',- 'group-data-closed:rotate-45',- 'transition-transform'- )}- />- {'enum' in schema- ? 'Accepted values'- : 'allOf' in schema || 'anyOf' in schema || 'oneOf' in schema- ? 'Options'- : schema.type === 'array'- ? 'Items'- : schema.type === 'object'- ? 'Object schema'- : 'Details'}- </CollapsibleTrigger>+ <DetailsTrigger label={schemaDetailsLabel(schema)} className={className} /><CollapsibleContent>{'type' in schema && schema.type === 'object' ? (- <div className={cn('border-b border-x border-default', 'rounded-b-lg')}>+ <div className="reference-details-panel"><div className="p-5 border-b border-default"><ApiSchema schema={schema} /></div>@@ -590,23 +527,16 @@ export function ApiSchemaParamSubdetails({typeof schema.items === 'object' &&'type' in schema.items &&schema.items.type === 'object' ? (- <div className={cn('border-b border-x border-default', 'rounded-b-lg')}>+ <div className="reference-details-panel"><div className="p-5 border-b border-default"><ApiSchema schema={schema} /></div><ApiOperationRequestBodyDetailsInternal schema={schema.items} className="px-5" /></div>) : (- <ul className={cn('border-b border-x border-default', 'rounded-b-lg')}>+ <ul className="reference-details-panel">{subContent.map((detail: any, index: number) => (- <li- key={index}- className={cn(- 'px-5 py-3',- 'border-t border-default first:border-t-0',- 'flex flex-col gap-3'- )}- >+ <li key={index} className="reference-details-item">{'enum' in schema ? (<span className="font-mono text-sm font-medium text-foreground">{String(detail)}@@ -635,6 +565,15 @@ export function ApiSchemaParamSubdetails({)}+const schemaDetailsLabel = (schema: ISchema): string => {+ if ('enum' in schema) return 'Accepted values'+ if ('allOf' in schema || 'anyOf' in schema || 'oneOf' in schema) return 'Options'+ if (schema.type === 'array') return 'Items'+ if (schema.type === 'object') return 'Object schema'++ return 'Details'+}+/*** Whether the param comes from overwritten params in the library spec file or* directly from the type spec.diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsx b/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsxindex f51bda0be2e..d7676e4f4d8 100644--- a/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsx+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsx@@ -2,21 +2,14 @@import { ArrowRightFromLine, Check, Copy, WrapText, type LucideIcon } from 'lucide-react'import { useCallback, useEffect, useRef, useState, type MouseEvent } from 'react'-import { type ThemedToken } from 'shiki'import { type NodeHover } from 'twoslash'import { Button, cn, copyToClipboard, Tooltip, TooltipContent, TooltipTrigger } from 'ui'-import { getFontStyle } from './CodeBlock.utils'-type CodeAnnotation = Pick<NodeHover, 'text' | 'docs' | 'tags'>export type CodeToken = [content: string,- color: ThemedToken['color'],- fontStyle: number,- annotation?: {- annotations: Array<CodeAnnotation>- htmlStyle: ThemedToken['htmlStyle']- },+ className: string | undefined,+ annotations?: Array<CodeAnnotation>,]export function CodeBlockTokens({@@ -30,6 +23,7 @@ export function CodeBlockTokens({<pre><codeclassName={cn(+ '[contain:content]',lineNumbers && 'grid grid-cols-[auto_1fr] w-fit min-w-full py-3','[--row-rest:var(--background-200)]','[--row-hover:color-mix(in_srgb,var(--foreground)_3%,var(--background-200))]'@@ -61,11 +55,16 @@ export function CodeBlockTokens({function CodeLine({ tokens }: { tokens: Array<CodeToken> }) {return (<span className="block min-h-5 leading-5">- {tokens.map(([content, color, fontStyle, annotation], idx) =>- annotation ? (- <AnnotatedSpan key={idx} content={content} {...annotation} />+ {tokens.map(([content, className, annotations], idx) =>+ annotations ? (+ <AnnotatedSpan+ key={idx}+ content={content}+ className={className}+ annotations={annotations}+ />) : (- <span key={idx} style={{ color, ...getFontStyle(fontStyle) }}>+ <span key={idx} className={className}>{content}</span>)@@ -76,11 +75,11 @@ function CodeLine({ tokens }: { tokens: Array<CodeToken> }) {export function AnnotatedSpan({content,- htmlStyle,+ className,annotations,}: {content: string- htmlStyle: ThemedToken['htmlStyle']+ className: string | undefinedannotations: Array<CodeAnnotation>}) {const [open, setOpen] = useState(false)@@ -115,8 +114,8 @@ export function AnnotatedSpan({<TooltipTrigger asChild onClick={handleClick}><buttontabIndex={0}- style={htmlStyle}className={cn(+ className,isTouchDevice &&'underline underline-offset-4 decoration-dashed decoration-[rgba(from_currentColor_r_g_b/0.5)]')}diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.test.ts b/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.test.tsnew file mode 100644index 00000000000..866f55dd1a8--- /dev/null+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.test.ts@@ -0,0 +1,223 @@+import { bundledLanguages, createHighlighter, type BundledLanguage } from 'shiki'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++import theme from './supabase-2.json' with { type: 'json' }++vi.mock('shiki', async (importOriginal) => {+ const actual = await importOriginal<typeof import('shiki')>()+ return { ...actual, createHighlighter: vi.fn(actual.createHighlighter) }+})++const fixtures: Array<{ name: string; lang: BundledLanguage | null; code: string }> = [+ { name: 'Bash', lang: 'bash', code: 'echo "hello ${USER}"\n# A comment' },+ { name: 'shell alias', lang: 'shell', code: "supabase sso add --metadata-url 'https://...'" },+ {+ name: 'JavaScript',+ lang: 'javascript',+ code: 'const greeting = /hello/g\ngreeting.test("hello")',+ },+ { name: 'JavaScript alias', lang: 'js', code: 'const value = 42\nconsole.log(value)' },+ {+ name: 'TypeScript',+ lang: 'typescript',+ code: 'interface User { id: number }\nconst id: User["id"] = 42',+ },+ { name: 'TypeScript alias', lang: 'ts', code: 'const count: number = 42' },+ {+ name: 'SQL',+ lang: 'sql',+ code: "select 'You had me at SELECT' as greeting, 42 as count;\n-- A comment",+ },+ { name: 'JSON', lang: 'json', code: '{"name":"reader","active":true}' },+ {+ name: 'Elixir',+ lang: 'elixir',+ code: 'defmodule Hello do\n def greet(name), do: "Hello #{name}"\nend',+ },+ {+ name: 'HTML scripts and styles',+ lang: 'html',+ code: '<style>.item { color: red; }</style>\n<script>const greeting = "hello"</script>',+ },+ {+ name: 'Markdown frontmatter, raw HTML, and fenced aliases',+ lang: 'markdown',+ code: [+ '---',+ 'title: "Greeting"',+ 'published: true',+ '---',+ '# Heading',+ '<div class="item">Hi</div>',+ '',+ '```ts',+ 'const value: number = 42',+ '```',+ '',+ '```sh',+ 'echo "hello ${USER}"',+ '```',+ ].join('\n'),+ },+ {+ name: 'MDX frontmatter, JSX, and fenced SQL',+ lang: 'mdx',+ code: '---\ntitle: "Greeting"\n---\nimport Component from "./component"\n\n<Component value={42} />\n\n```sql\nselect 42;\n```',+ },+ {+ name: 'Vue TypeScript and SCSS',+ lang: 'vue',+ code: '<template><div>{{ greeting }}</div></template>\n<script setup lang="ts">const greeting: string = "hello"</script>\n<style lang="scss">.item { &.active { color: red; } }</style>',+ },+ {+ name: 'Astro frontmatter and SCSS',+ lang: 'astro',+ code: '---\nconst title: string = "Hello"\n---\n<h1>{title}</h1>\n<style lang="scss">h1 { color: red; }</style>',+ },+ { name: 'empty code', lang: 'typescript', code: '' },+ { name: 'plain text', lang: null, code: 'plain <text> & punctuation\n second line' },+ {+ name: 'JavaScript tagged template injections',+ lang: 'javascript',+ code: 'const result = sql`select * from users where id = 42`\nconst style = css`div { color: red; }`\nconst markup = html`<div class="item">Hi</div>`',+ },+ {+ name: 'JSX tagged template injections',+ lang: 'jsx',+ code: 'const style = css`div { color: red; }`\nconst element = <div>{style}</div>',+ },+ {+ name: 'Markdown Vue and Angular injections',+ lang: 'markdown',+ code: '<div v-if="active">{{ name }}</div>\n\n@if (active) { <p>Hello</p> }\n\n```vue\n<template><p>{{ name }}</p></template>\n```',+ },+ {+ name: 'HTML embedded tagged templates',+ lang: 'html',+ code: '<script>const result = sql`select 42`</script>',+ },+]++describe('selective code block highlighting', () => {+ let baseline: Awaited<ReturnType<typeof createHighlighter>>+ let createActualHighlighter: typeof createHighlighter+ const create = vi.mocked(createHighlighter)++ beforeAll(async () => {+ const actual = await vi.importActual<typeof import('shiki')>('shiki')+ createActualHighlighter = actual.createHighlighter+ baseline = await createActualHighlighter({+ themes: [structuredClone(theme)],+ langs: Object.keys(bundledLanguages),+ })+ })++ beforeEach(() => {+ vi.resetModules()+ create.mockReset().mockImplementation(createActualHighlighter)+ })++ afterEach(async () => {+ for (const result of create.mock.results) {+ if (result.type === 'return') {+ await result.value.then(+ (highlighter) => highlighter.dispose(),+ () => {}+ )+ }+ }+ vi.restoreAllMocks()+ })++ afterAll(() => baseline.dispose())++ function expected({ code, lang }: (typeof fixtures)[number]) {+ return baseline.codeToTokens(code, {+ lang: lang || undefined,+ theme: 'Supabase Theme',+ tokenizeTimeLimit: 0,+ tokenizeMaxLineLength: 100_000,+ }).tokens+ }++ it('defers initialization until first use and reuses the theme and highlighter', async () => {+ const { highlightCode } = await import('./CodeBlock.highlight')+ expect(create).not.toHaveBeenCalled()++ const first = fixtures[0]+ expect((await highlightCode(first.code, first.lang)).tokens).toEqual(expected(first))+ expect(create).toHaveBeenCalledTimes(1)+ const highlighter = await create.mock.results[0].value+ expect(highlighter.getLoadedLanguages()).toContain('bash')+ expect(highlighter.getLoadedLanguages()).not.toContain('sql')+ expect(highlighter.getLoadedLanguages()).not.toContain('markdown')+ expect(highlighter.getLoadedLanguages()).not.toContain('typescript')++ const loadLanguage = vi.spyOn(highlighter, 'loadLanguage')+ const loadTheme = vi.spyOn(highlighter, 'loadTheme')+ const second = fixtures.find(({ lang }) => lang === 'sql')!+ await highlightCode(second.code, second.lang)+ expect((await highlightCode(first.code, first.lang)).tokens).toEqual(expected(first))+ expect(create).toHaveBeenCalledTimes(1)+ expect(highlighter.getLoadedLanguages()).toContain('sql')+ expect(loadLanguage.mock.calls.filter((args) => args.length)).toEqual([['sql']])+ expect(loadTheme.mock.calls.every((args) => args.length === 0)).toBe(true)+ expect(highlighter.getLoadedThemes()).toEqual(['Supabase Theme'])+ })++ it('shares initialization across concurrent languages and aliases', async () => {+ const { highlightCode } = await import('./CodeBlock.highlight')+ const selected = [fixtures[0], fixtures[0], fixtures[1], fixtures[6]]+ const results = await Promise.all(selected.map(({ code, lang }) => highlightCode(code, lang)))+ expect(results.map(({ tokens }) => tokens)).toEqual(selected.map(expected))+ expect(create).toHaveBeenCalledTimes(1)+ })++ it.each(fixtures)(+ 'matches eager token colors, font flags, and offsets for $name',+ async (fixture) => {+ const { highlightCode } = await import('./CodeBlock.highlight')+ const result = await highlightCode(fixture.code, fixture.lang)+ expect(result.tokens).toEqual(expected(fixture))+ }+ )++ it('keeps embedded tokens and CSS-variable colors stable across rendering order', async () => {+ const { highlightCode } = await import('./CodeBlock.highlight')+ const selected = fixtures.filter(({ lang }) =>+ ['markdown', 'vue', 'html', 'typescript'].includes(lang || '')+ )+ const first = await Promise.all(selected.map(({ code, lang }) => highlightCode(code, lang)))+ const reversed = await Promise.all(+ [...selected].reverse().map(({ code, lang }) => highlightCode(code, lang))+ )+ expect(first.map(({ tokens }) => tokens)).toEqual(selected.map(expected))+ expect(reversed.reverse().map(({ tokens }) => tokens)).toEqual(+ first.map(({ tokens }) => tokens)+ )+ const colors = first.flatMap(({ tokens }) => tokens.flat().map(({ color }) => color))+ expect(colors).toContain('var(--code-token-keyword)')+ expect(colors.every((color) => !color || color.startsWith('var(--'))).toBe(true)+ })++ it('surfaces supported grammar loading failures', async () => {+ const { highlightCode } = await import('./CodeBlock.highlight')+ await highlightCode('echo hello', 'bash')+ const highlighter = await create.mock.results[0].value+ const failure = new Error('Grammar could not be loaded')+ vi.spyOn(highlighter, 'loadLanguage').mockImplementation(async (...languages) => {+ if (languages.length) throw failure+ })+ await expect(highlightCode('select 42', 'sql')).rejects.toBe(failure)+ expect(create).toHaveBeenCalledTimes(1)+ })++ it('retains native singleton initialization failure without adding retries', async () => {+ const failure = new Error('Highlighter could not be initialized')+ create.mockRejectedValue(failure)+ const { highlightCode } = await import('./CodeBlock.highlight')+ await expect(highlightCode('echo hello', 'bash')).rejects.toBe(failure)+ await expect(highlightCode('select 42', 'sql')).rejects.toBe(failure)+ expect(create).toHaveBeenCalledTimes(1)+ })+})diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.ts b/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.tsnew file mode 100644index 00000000000..bf287d629cc--- /dev/null+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.ts@@ -0,0 +1,54 @@+import {+ bundledLanguages,+ createHighlighter,+ makeSingletonHighlighter,+ type BundledLanguage,+} from 'shiki'++import theme from './supabase-2.json' with { type: 'json' }++const getHighlighter = makeSingletonHighlighter(() =>+ createHighlighter({ themes: [structuredClone(theme)], langs: [] })+)++// keep the eager highlighter's tagged templates and component syntax intact+const INJECTED_LANGUAGES: Record<string, Array<BundledLanguage>> = {+ 'source.js': ['ts-tags'],+ 'source.ts': ['ts-tags'],+ 'text.html.markdown': ['vue'],+ 'text.html.derivative': ['angular-html', 'vue'],+ 'text.pug': ['vue'],+}++export async function highlightCode(code: string, lang: BundledLanguage | null) {+ const highlighter = await getHighlighter()+ if (lang && !highlighter.getLoadedLanguages().includes(lang)) {+ const languages = new Set<BundledLanguage>()++ async function collectLanguages(language: BundledLanguage) {+ if (languages.has(language)) return+ languages.add(language)+ const { default: grammars } = await bundledLanguages[language]()+ await Promise.all(+ grammars.flatMap(({ embeddedLangsLazy = [], scopeName }) => {+ const injected = Object.entries(INJECTED_LANGUAGES).flatMap(([scope, languages]) =>+ scopeName === scope || scopeName.startsWith(`${scope}.`) ? languages : []+ )+ return [...embeddedLangsLazy, ...injected].map((embedded) =>+ collectLanguages(embedded as BundledLanguage)+ )+ })+ )+ }++ await collectLanguages(lang)+ await highlighter.loadLanguage(...languages)+ }++ return highlighter.codeToTokens(code, {+ lang: lang || undefined,+ theme: 'Supabase Theme',+ tokenizeTimeLimit: 0,+ tokenizeMaxLineLength: 100_000,+ })+}diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsx b/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsxnew file mode 100644index 00000000000..715db31e754--- /dev/null+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsx@@ -0,0 +1,187 @@+import { readFile } from 'node:fs/promises'+import { load } from 'cheerio'+import { type ComponentProps, type PropsWithChildren } from 'react'+import { renderToStaticMarkup } from 'react-dom/server'+import { createHighlighter, type BundledLanguage, type ThemeRegistration } from 'shiki'+import { createTwoslasher } from 'twoslash'+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'++import { CodeBlock } from './CodeBlock'+import { type CodeToken } from './CodeBlock.client'+import { getTokenClassName } from './CodeBlock.utils'++vi.mock('./types/lib.deno.d.ts.include', async () => ({+ default: await readFile(new URL('./types/lib.deno.d.ts.include', import.meta.url), 'utf8'),+}))++// Keep the real token renderer while isolating unrelated UI imports and tooltip portals.+vi.mock('ui', async () => {+ const { createElement } = await import('react')+ return {+ cn: (...classes: Array<unknown>) => classes.filter(Boolean).join(' '),+ Tooltip: ({ children }: PropsWithChildren) => children,+ TooltipTrigger: ({ children }: PropsWithChildren) => children,+ TooltipContent: () => null,+ Button: ({ variant, ...props }: ComponentProps<'button'> & { variant?: string }) =>+ createElement('button', props),+ copyToClipboard: vi.fn(),+ }+})++function getLines(block: Awaited<ReturnType<typeof CodeBlock>>): Array<Array<CodeToken>> {+ return block.props.children[0].props.children.props.lines+}++const fixtures: Array<{ name: string; lang?: string; code: string }> = [+ {+ name: 'JavaScript',+ lang: 'javascript',+ code: '// A greeting\nconst greeting = "hello"\ngreeting',+ },+ {+ name: 'TypeScript',+ lang: 'typescript',+ code: 'const count: number = 42\nconst values = [count]',+ },+ { name: 'SQL', lang: 'sql', code: "select 'hello' as greeting, 42 as count;\n-- A comment" },+ { name: 'shell', lang: 'shell', code: 'echo "hello ${USER}"\n# A comment' },+ { name: 'JSON', lang: 'json', code: '{\n "greeting": "hello",\n "count": 42\n}' },+ { name: 'empty code', lang: 'typescript', code: '' },+ { name: 'plain text', code: 'plain <text> & punctuation\n second line' },+ { name: 'unsupported language', lang: 'not-a-language', code: 'plain <text> & punctuation' },+]++describe('code block serialization and rendering', () => {+ let highlighter: Awaited<ReturnType<typeof createHighlighter>>++ beforeAll(async () => {+ // Shiki mutates theme.colors, so use a fresh raw theme for this independent tokenization.+ const theme: ThemeRegistration = JSON.parse(+ await readFile(new URL('./supabase-2.json', import.meta.url), 'utf8')+ )+ highlighter = await createHighlighter({+ themes: [theme],+ langs: ['javascript', 'typescript', 'sql', 'shell', 'json'],+ })+ })++ afterEach(() => vi.restoreAllMocks())+ afterAll(() => highlighter.dispose())++ it.each(fixtures)(+ 'preserves $name token boundaries using compact namespaced classes',+ async ({ lang, code }) => {+ const block = await CodeBlock({+ contents: code,+ lang,+ skipTypeGeneration: true,+ hideControls: true,+ })+ const lines = getLines(block)+ const { tokens } = highlighter.codeToTokens(code, {+ lang: lang === 'not-a-language' ? undefined : (lang as BundledLanguage | undefined),+ theme: 'Supabase Theme',+ tokenizeTimeLimit: 0,+ tokenizeMaxLineLength: 100_000,+ })++ expect(lines.map((line) => line.map(([content]) => content))).toEqual(+ tokens.map((line) => line.map(({ content }) => content))+ )+ for (const [lineIndex, line] of tokens.entries()) {+ for (const [tokenIndex, token] of line.entries()) {+ expect(lines[lineIndex][tokenIndex]).toEqual([+ token.content,+ getTokenClassName(token.color, token.fontStyle),+ ])+ }+ }++ const $ = load(renderToStaticMarkup(block))+ expect(+ $('.code-line-number')+ .toArray()+ .map((element) => $(element).text())+ ).toEqual(lines.map((_, index) => String(index + 1)))+ expect(+ $('.code-line-content')+ .toArray()+ .map((element) => $(element).text())+ ).toEqual(lines.map((line) => line.map(([content]) => content).join('')))+ expect($('.code-content [style]')).toHaveLength(0)+ }+ )++ it('preserves actual Twoslash annotations and offsets after its source edits', async () => {+ const source = [+ "const prefix = 'Hello'",+ '// ---cut---',+ '/** The name shown in the greeting. */',+ "const username = 'reader'",+ 'const message = `${prefix}, ${username}`',+ 'message',+ ].join('\n')+ const twoslashed = createTwoslasher({ compilerOptions: { ignoreDeprecations: '6.0' } })(source)+ const hovers = twoslashed.nodes.filter((node) => node.type === 'hover')+ expect(hovers.length).toBeGreaterThan(0)+ expect(twoslashed.code).not.toContain('// ---cut---')++ const block = await CodeBlock({ contents: source, lang: 'typescript', hideControls: true })+ const lines = getLines(block)+ expect(lines.map((line) => line.map(([content]) => content).join('')).join('\n')).toBe(+ twoslashed.code+ )++ for (const [lineIndex, line] of lines.entries()) {+ let offset = 0+ for (const token of line) {+ const annotations = hovers+ .filter((hover) => hover.line === lineIndex && hover.character === offset)+ .map(({ text, docs, tags }) => ({ text, docs, tags }))+ expect(token[2]).toEqual(annotations.length ? annotations : undefined)+ expect(token).toHaveLength(annotations.length ? 3 : 2)+ offset += token[0].length+ }+ }+ const annotated = lines.flat().filter((token) => token[2])+ expect(annotated.length).toBeGreaterThan(0)+ const $ = load(renderToStaticMarkup(block))+ expect(+ $('.code-content button')+ .toArray()+ .map((element) => $(element).text())+ ).toEqual(annotated.map(([content]) => content))+ expect($('.code-content button[tabindex="0"]')).toHaveLength(annotated.length)+ })++ it('keeps classes stable across repeated renders in a different order', async () => {+ const render = async ({ lang, code }: (typeof fixtures)[number]) =>+ getLines(await CodeBlock({ contents: code, lang, skipTypeGeneration: true }))+ const first = await Promise.all(fixtures.map(render))+ const reversed = await Promise.all([...fixtures].reverse().map(render))+ expect(reversed.reverse()).toEqual(first)+ })++ it('retains unnumbered layout, source text, hidden controls, and the accessible label', async () => {+ const code = 'echo "hello"\necho "reader"'+ const block = await CodeBlock({+ contents: code,+ lang: 'shell',+ lineNumbers: false,+ hideControls: true,+ })+ const $ = load(renderToStaticMarkup(block))+ expect($('.code-line-number')).toHaveLength(0)+ expect($('.code-content')).toHaveLength(1)+ expect(+ $('.code-content > span')+ .toArray()+ .map((element) => $(element).text())+ .join('\n')+ ).toBe(code)+ expect($('button')).toHaveLength(0)+ expect($('.code-scroll').attr('aria-label')).toBe('Shell, 2 lines')+ expect($('.code-scroll').attr('tabindex')).toBe('0')+ expect($('pre > code').hasClass('grid')).toBe(false)+ })+})diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.tsx b/apps/docs/features/ui/CodeBlock/CodeBlock.tsxindex 84769bebe25..538a2dea08b 100644--- a/apps/docs/features/ui/CodeBlock/CodeBlock.tsx+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.tsx@@ -1,23 +1,23 @@import { type PropsWithChildren } from 'react'-import { bundledLanguages, createHighlighter, type BundledLanguage } from 'shiki'+import { bundledLanguages, type BundledLanguage } from 'shiki'import { createTwoslasher, type ExtraFiles, type NodeHover } from 'twoslash'import { cn } from 'ui'import { CodeBlockControls, CodeBlockTokens, type CodeToken } from './CodeBlock.client'-import { getCodeBlockLabel } from './CodeBlock.utils'-import theme from './supabase-2.json' with { type: 'json' }+import { highlightCode } from './CodeBlock.highlight'+import { getCodeBlockLabel, getTokenClassName } from './CodeBlock.utils'import denoTypes from './types/lib.deno.d.ts.include'const extraFiles: ExtraFiles = { 'deno.d.ts': denoTypes }-const twoslasher = createTwoslasher({ extraFiles })+const twoslasher = createTwoslasher({+ extraFiles,+ // todo: remove once Twoslash stops using deprecated baseUrl and node10 resolution+ compilerOptions: { ignoreDeprecations: '6.0' },+})const TWOSLASHABLE_LANGS: ReadonlyArray<string> = ['js', 'ts', 'javascript', 'typescript']const BUNDLED_LANGUAGES = Object.keys(bundledLanguages)-const highlighter = await createHighlighter({- themes: [theme],- langs: BUNDLED_LANGUAGES,-})export async function CodeBlock({className,@@ -52,10 +52,7 @@ export async function CodeBlock({}}- const { tokens } = highlighter.codeToTokens(code, {- lang: lang || undefined,- theme: 'Supabase Theme',- })+ const { tokens } = await highlightCode(code, lang)return (<div@@ -87,15 +84,15 @@ export async function CodeBlock({lineNumbers={lineNumbers}lines={tokens.map((line, lineIndex) => {let offset = 0- return line.map(({ content, color, fontStyle, htmlStyle }): CodeToken => {+ return line.map(({ content, color, fontStyle }): CodeToken => {const annotations = twoslashed?.get(lineIndex)?.get(offset)?.map(({ text, docs, tags }) => ({ text, docs, tags }))offset += content.length- return annotations- ? [content, color, fontStyle || 0, { annotations, htmlStyle }]- : [content, color, fontStyle || 0]+ const className = getTokenClassName(color, fontStyle)++ return annotations ? [content, className, annotations] : [content, className]})})}/>diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.utils.test.ts b/apps/docs/features/ui/CodeBlock/CodeBlock.utils.test.tsnew file mode 100644index 00000000000..39d7d4a7361--- /dev/null+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.utils.test.ts@@ -0,0 +1,58 @@+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'++import { getCodeBlockLabel, getTokenClassName } from './CodeBlock.utils'+import theme from './supabase-2.json' with { type: 'json' }++const themeColors = (): Array<string> => {+ const colors = new Set<string>()++ const walk = (node: unknown) => {+ if (Array.isArray(node)) {+ node.forEach(walk)+ return+ }+ if (node === null || typeof node !== 'object') return++ for (const [key, value] of Object.entries(node)) {+ if ((key === 'foreground' || key === 'background') && typeof value === 'string') {+ colors.add(value)+ }+ walk(value)+ }+ }++ walk(theme)+ return [...colors]+}++describe('token class names', () => {+ it('maps every theme color to a class', () => {+ const colors = themeColors()+ expect(colors.length).toBeGreaterThan(0)++ const css = readFileSync(new URL('../../../styles/code-block.css', import.meta.url), 'utf8')+ for (const color of colors) {+ expect(getTokenClassName(color, 0), `${color} is missing from the class table`).toMatch(+ /^s-[a-z]$/+ )+ expect(css).toContain(`.shiki .${getTokenClassName(color, 0)} {\n color: ${color};`)+ }+ })++ it('appends font style classes', () => {+ expect(getTokenClassName('var(--code-token-comment)', 1)).toBe('s-c s-i')+ expect(getTokenClassName(undefined, 2 | 4)).toBe('s-b s-l')+ expect(getTokenClassName(undefined, 0)).toBeUndefined()+ expect(getTokenClassName(undefined, -1)).toBeUndefined()+ })+})++describe('code block labels', () => {+ it('names language aliases and singular or plural line counts', () => {+ expect(getCodeBlockLabel('ts', 1)).toBe('TypeScript, 1 line')+ expect(getCodeBlockLabel('sh', 2)).toBe('Shell, 2 lines')+ expect(getCodeBlockLabel('rust', 3)).toBe('rust, 3 lines')+ expect(getCodeBlockLabel(null, 1)).toBe('1 line')+ })+})diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.utils.ts b/apps/docs/features/ui/CodeBlock/CodeBlock.utils.tsindex b3046183a38..db04c39b574 100644--- a/apps/docs/features/ui/CodeBlock/CodeBlock.utils.ts+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.utils.ts@@ -1,5 +1,3 @@-import { type CSSProperties } from 'react'-// As defined in @shikijs/core/dist/chunk-tokens.d.mtsenum FontStyle {NotSet = -1,@@ -9,24 +7,6 @@ enum FontStyle {Underline = 4,}-export function getFontStyle(styleFlags: number): CSSProperties {- let style: CSSProperties = {}-- if (styleFlags & FontStyle.Italic) {- ;(style ??= {}).fontStyle = 'italic'- }-- if (styleFlags & FontStyle.Bold) {- ;(style ??= {}).fontWeight = 'bold'- }-- if (styleFlags & FontStyle.Underline) {- ;(style ??= {}).textDecoration = 'underline'- }-- return style-}-// Fence aliases a screen reader would otherwise read letter by letterconst LANGUAGE_LABELS: Record<string, string> = {c: 'C',@@ -49,3 +29,38 @@ export function getCodeBlockLabel(lang: string | null, lineCount: number): strinif (!lang) return linesreturn `${LANGUAGE_LABELS[lang] ?? lang}, ${lines}`}++/*+ * Shiki gives every token a ~30 char css variable name making page heavier+ * this sends a one letter code instead for perf optimization+ *+ * nb. color missing from this table still renders but full length+ */+const COLOR_CLASSES: Record<string, string> = {+ 'var(--code-foreground)': 's-f',+ 'var(--code-token-comment)': 's-c',+ 'var(--code-token-constant)': 's-n',+ 'var(--code-token-function)': 's-u',+ 'var(--code-token-keyword)': 's-k',+ 'var(--code-token-parameter)': 's-a',+ 'var(--code-token-property)': 's-r',+ 'var(--code-token-punctuation)': 's-p',+ 'var(--code-token-string)': 's-s',+ 'var(--code-token-string-expression)': 's-e',+ 'var(--code-token-variable)': 's-v',+}++export const getTokenClassName = (+ color: string | undefined,+ fontStyle: number | undefined+): string | undefined => {+ const classes: Array<string> = []+ const colorClass = color === undefined ? undefined : COLOR_CLASSES[color]+ if (colorClass) classes.push(colorClass)+ if (fontStyle && fontStyle > 0) {+ if (fontStyle & FontStyle.Italic) classes.push('s-i')+ if (fontStyle & FontStyle.Bold) classes.push('s-b')+ if (fontStyle & FontStyle.Underline) classes.push('s-l')+ }+ return classes.length ? classes.join(' ') : undefined+}diff --git a/apps/docs/styles/code-block.css b/apps/docs/styles/code-block.cssnew file mode 100644index 00000000000..b70345df653--- /dev/null+++ b/apps/docs/styles/code-block.css@@ -0,0 +1,113 @@+@utility code-line-number {+ @apply select-none text-right text-muted/70 pl-3 pr-2 min-h-5 leading-5;+ @apply bg-[var(--row-rest)] sticky left-0 z-10;+ @apply group-hover/row:text-muted group-hover/row:bg-[var(--row-hover)];+ @apply after:pointer-events-none after:absolute after:inset-y-0 after:left-full after:w-4;+ @apply [--gutter-fade:var(--row-rest)] group-hover/row:[--gutter-fade:var(--row-hover)];+ @apply after:bg-[image:linear-gradient(to_right,var(--gutter-fade)_0%,color-mix(in_srgb,var(--gutter-fade)_85%,transparent)_25%,color-mix(in_srgb,var(--gutter-fade)_50%,transparent)_50%,color-mix(in_srgb,var(--gutter-fade)_15%,transparent)_75%,transparent_100%)];+}++@utility code-line-content {+ @apply min-h-5 leading-5 pl-3 pr-18 group-hover/row:bg-[var(--row-hover)];+}++/* Code blocks need margin applied when in content container */+.prose :where(.shiki:not(.shiki-wrapper *), .shiki-wrapper) {+ margin-block: 2rem;+}++/* Code block theme colors for use with Supabase Theme */+[data-theme='dark'],+.dark {+ --code-token-keyword: #bda4ff;+ --code-foreground: #ffffff;+ --code-token-constant: #3ecf8e;+ --code-token-string: #ffcda1;+ --code-token-comment: #949494;+ --code-token-parameter: #ffffff;+ --code-token-function: #3ecf8e;+ --code-token-string-expression: #ffcda1;+ --code-token-punctuation: #ffffff;+ --code-token-link: #ffffff;+ --code-token-number: #ffffff;+ --code-token-property: #3ecf8e;+ --code-token-variable: var(--code-foreground);+ --code-highlight-color: #232323;+ --shadow-codeblock:+ 0 0 0 0 var(--border-default), 0 1px 2px 0 rgba(0, 0, 0, 0.3), 0 1px 3px 0 rgba(0, 0, 0, 0.3);+}+[data-theme='light'],+.light {+ --code-token-keyword: #5f2fc4;+ --code-foreground: oklch(from var(--foreground-light) l c h / 1);+ --code-token-constant: #15593b;+ --code-token-string: #9a5200;+ --code-token-comment: #6a6a6a;+ --code-token-parameter: oklch(from var(--foreground-light) l c h / 1);+ --code-token-function: #15593b;+ --code-token-string-expression: #9a5200;+ --code-token-punctuation: oklch(from var(--foreground-light) l c h / 1);+ --code-token-link: oklch(from var(--foreground-light) l c h / 1);+ --code-token-number: oklch(from var(--foreground-light) l c h / 1);+ --code-token-property: #15593b;+ --code-token-variable: var(--code-foreground);+ --code-highlight-color: #1c1c1c;+}++/* Token classes emitted by CodeBlock.utils.ts */+.shiki .s-f {+ color: var(--code-foreground);+}+.shiki .s-c {+ color: var(--code-token-comment);+}+.shiki .s-n {+ color: var(--code-token-constant);+}+.shiki .s-u {+ color: var(--code-token-function);+}+.shiki .s-k {+ color: var(--code-token-keyword);+}+.shiki .s-a {+ color: var(--code-token-parameter);+}+.shiki .s-r {+ color: var(--code-token-property);+}+.shiki .s-p {+ color: var(--code-token-punctuation);+}+.shiki .s-s {+ color: var(--code-token-string);+}+.shiki .s-e {+ color: var(--code-token-string-expression);+}+.shiki .s-v {+ color: var(--code-token-variable);+}+.shiki .s-i {+ font-style: italic;+}+.shiki .s-b {+ font-weight: bold;+}+.shiki .s-l {+ text-decoration: underline;+}++/* Word wrap styles for code blocks */+.shiki[data-wrapped='true'] .code-scroll {+ overflow-x: hidden !important;+}++.shiki[data-wrapped='true'] .code-content {+ white-space: pre-wrap !important;+ overflow-wrap: anywhere !important;+}++.shadow-codeblock {+ box-shadow: var(--shadow-codeblock, none);+}diff --git a/apps/docs/styles/globals.css b/apps/docs/styles/globals.cssindex 6b15dd3e07a..58ba8ace980 100644--- a/apps/docs/styles/globals.css+++ b/apps/docs/styles/globals.css@@ -1,5 +1,7 @@@import 'config/tailwind.config.css';@import './../../../packages/ui/build/css/themes/faux-classic-dark.css';+@import './code-block.css';+@import './reference.css';@source '../app/**/*.{ts,tsx,mdx}';@source '../components/**/*.tsx';@@ -34,19 +36,6 @@--font-weight-normal: 450;}-@utility code-line-number {- @apply select-none text-right text-muted/70 pl-3 pr-2 min-h-5 leading-5;- @apply bg-[var(--row-rest)] sticky left-0 z-10;- @apply group-hover/row:text-muted group-hover/row:bg-[var(--row-hover)];- @apply after:pointer-events-none after:absolute after:inset-y-0 after:left-full after:w-4;- @apply [--gutter-fade:var(--row-rest)] group-hover/row:[--gutter-fade:var(--row-hover)];- @apply after:bg-[image:linear-gradient(to_right,var(--gutter-fade)_0%,color-mix(in_srgb,var(--gutter-fade)_85%,transparent)_25%,color-mix(in_srgb,var(--gutter-fade)_50%,transparent)_50%,color-mix(in_srgb,var(--gutter-fade)_15%,transparent)_75%,transparent_100%)];-}--@utility code-line-content {- @apply min-h-5 leading-5 pl-3 pr-18 group-hover/row:bg-[var(--row-hover)];-}-@layer utilities {.prose--remove-p-margin p {margin: 0;@@ -418,58 +407,3 @@ th code {[data-rmiz-modal-img] {image-rendering: high-quality;}--/* Code blocks need margin applied when in content container */-.prose :where(.shiki:not(.shiki-wrapper *), .shiki-wrapper) {- margin-block: 2rem;-}--/* Code block theme colors for use with Supabase Theme */-[data-theme='dark'],-.dark {- --code-token-keyword: #bda4ff;- --code-foreground: #ffffff;- --code-token-constant: #3ecf8e;- --code-token-string: #ffcda1;- --code-token-comment: #949494;- --code-token-parameter: #ffffff;- --code-token-function: #3ecf8e;- --code-token-string-expression: #ffcda1;- --code-token-punctuation: #ffffff;- --code-token-link: #ffffff;- --code-token-number: #ffffff;- --code-token-property: #3ecf8e;- --code-highlight-color: #232323;- --shadow-codeblock:- 0 0 0 0 var(--border-default), 0 1px 2px 0 rgba(0, 0, 0, 0.3), 0 1px 3px 0 rgba(0, 0, 0, 0.3);-}-[data-theme='light'],-.light {- --code-token-keyword: #5f2fc4;- --code-foreground: oklch(from var(--foreground-light) l c h / 1);- --code-token-constant: #15593b;- --code-token-string: #9a5200;- --code-token-comment: #6a6a6a;- --code-token-parameter: oklch(from var(--foreground-light) l c h / 1);- --code-token-function: #15593b;- --code-token-string-expression: #9a5200;- --code-token-punctuation: oklch(from var(--foreground-light) l c h / 1);- --code-token-link: oklch(from var(--foreground-light) l c h / 1);- --code-token-number: oklch(from var(--foreground-light) l c h / 1);- --code-token-property: #15593b;- --code-highlight-color: #1c1c1c;-}--/* Word wrap styles for code blocks */-.shiki[data-wrapped='true'] .code-scroll {- overflow-x: hidden !important;-}--.shiki[data-wrapped='true'] .code-content {- white-space: pre-wrap !important;- word-break: break-word !important;-}--.shadow-codeblock {- box-shadow: var(--shadow-codeblock, none);-}diff --git a/apps/docs/styles/reference.css b/apps/docs/styles/reference.cssnew file mode 100644index 00000000000..9f5a7fb997e--- /dev/null+++ b/apps/docs/styles/reference.css@@ -0,0 +1,19 @@+@utility reference-details-trigger {+ @apply w-fit rounded-full px-5 py-1 border border-default;+ @apply flex items-center gap-2 text-left text-sm text-foreground-light;+ @apply hover:bg-surface-100;+ @apply data-open:w-full data-open:rounded-b-none data-open:rounded-tl-lg data-open:rounded-tr-lg;+ @apply transition [transition-property:width,background-color];+}++@utility reference-details-trigger-icon {+ @apply text-foreground-muted group-data-closed:rotate-45 transition-transform;+}++@utility reference-details-panel {+ @apply border-b border-x border-default rounded-b-lg;+}++@utility reference-details-item {+ @apply px-5 py-3 border-t border-default first:border-t-0 flex flex-col gap-3;+}diff --git a/apps/docs/vitest.config.ts b/apps/docs/vitest.config.tsindex ba0c0334250..29796cfbbea 100644--- a/apps/docs/vitest.config.ts+++ b/apps/docs/vitest.config.ts@@ -2,6 +2,8 @@ import { defineConfig } from 'vitest/config'export default defineConfig({resolve: { tsconfigPaths: true },+ // compile jsx for tests without nextjs+ oxc: { jsx: { runtime: 'automatic' } },test: {// Exclude examples from test discovery (does not affect tsconfig scanning)exclude: ['examples/**/*', '**/node_modules/**'],