Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix(docs): make code blocks reachable and readable by keyboard and screen reader (#49562)

Miranda Limonczenkof09d35cfd5ef
diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsx b/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsx
index 2db18ab15c4..4ec13d2478a 100644
--- a/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsx
+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsx
@@ -119,6 +119,8 @@ export function CodeCopyButton({ className, content }: { className?: string; con
className
)}
aria-label="Copy code"
+ // Tooltip repeats the label; the description would read the name twice
+ aria-describedby={undefined}
>
{copied ? (
<Check size={14} className="text-lighter" />
@@ -135,29 +137,33 @@ export function CodeCopyButton({ className, content }: { className?: string; con
export function CodeBlockControls({ content }: { content: string }) {
const [isWrapped, setIsWrapped] = useState(false)
+ // Empty until the first toggle, so nothing is announced on mount
+ const [wrapStatus, setWrapStatus] = useState('')
const wrapperRef = useRef<HTMLDivElement>(null)
const toggleWrap = useCallback(() => {
- setIsWrapped((prev) => {
- const newValue = !prev
- // Find the parent code block and toggle the wrap data attribute
- const codeBlock = wrapperRef.current?.closest('.shiki')
- if (codeBlock) {
- if (newValue) {
- codeBlock.setAttribute('data-wrapped', 'true')
- } else {
- codeBlock.removeAttribute('data-wrapped')
- }
+ const newValue = !isWrapped
+ setIsWrapped(newValue)
+ setWrapStatus(newValue ? 'Word wrap enabled' : 'Word wrap disabled')
+
+ const codeBlock = wrapperRef.current?.closest('.shiki')
+ if (codeBlock) {
+ if (newValue) {
+ codeBlock.setAttribute('data-wrapped', 'true')
+ } else {
+ codeBlock.removeAttribute('data-wrapped')
}
- return newValue
- })
- }, [])
+ }
+ }, [isWrapped])
return (
<div
ref={wrapperRef}
- className="opacity-0 flex group-hover:opacity-100 focus-within:opacity-100 absolute top-2 right-2 gap-1"
+ className="opacity-0 flex group-hover:opacity-100 group-focus-within:opacity-100 absolute top-2 right-2 gap-1"
>
+ <span className="sr-only" aria-live="polite">
+ {wrapStatus}
+ </span>
<Tooltip>
<TooltipTrigger asChild>
<button
@@ -165,6 +171,8 @@ export function CodeBlockControls({ content }: { content: string }) {
onClick={toggleWrap}
className={cn('cursor-pointer border rounded-md p-1', 'hover:bg-selection transition')}
aria-label={isWrapped ? 'Disable word wrap' : 'Enable word wrap'}
+ // Tooltip repeats the label; the description would read the name twice
+ aria-describedby={undefined}
>
{isWrapped ? (
<ArrowRightFromLine size={14} className="text-lighter" />
diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.tsx b/apps/docs/features/ui/CodeBlock/CodeBlock.tsx
index 6cfc7f5591d..12316948dc2 100644
--- a/apps/docs/features/ui/CodeBlock/CodeBlock.tsx
+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.tsx
@@ -4,7 +4,7 @@ import { createTwoslasher, type ExtraFiles, type NodeHover } from 'twoslash'
import { cn } from 'ui'
import { AnnotatedSpan, CodeBlockControls } from './CodeBlock.client'
-import { getFontStyle } from './CodeBlock.utils'
+import { getCodeBlockLabel, getFontStyle } from './CodeBlock.utils'
import theme from './supabase-2.json' with { type: 'json' }
import denoTypes from './types/lib.deno.d.ts.include'
@@ -46,11 +46,7 @@ export async function CodeBlock({
twoslashed = annotationsByLine(hoverNodes)
code = editedCode
} catch (_err) {
- // Silently ignore, if imports aren't defined type compilation fails
- // Uncomment lines below to debug in dev
- // console.log('\n==========CODE==========\n')
- // console.log(code)
- // console.error(_err.recommendation)
+ // Type compilation fails when imports aren't defined
}
}
@@ -66,52 +62,64 @@ export async function CodeBlock({
'group',
'relative',
'not-prose',
- 'w-full overflow-x-auto',
+ 'w-full',
'border border-default rounded-lg',
'bg-200',
'text-sm',
className
)}
- role="group"
- aria-roledescription="code block"
>
+ <div
+ className={cn(
+ 'code-scroll',
+ 'w-full overflow-x-auto rounded-lg',
+ 'focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring'
+ )}
+ role="group"
+ aria-roledescription="code block"
+ aria-label={getCodeBlockLabel(lang, tokens.length)}
+ tabIndex={0}
+ >
+ <pre>
+ <code className={lineNumbers ? 'grid grid-cols-[auto_1fr]' : ''}>
+ {lineNumbers ? (
+ <>
+ {tokens.map((line, idx) => (
+ <Fragment key={idx}>
+ <div
+ aria-hidden="true"
+ className={cn(
+ 'select-none text-right text-muted bg-control px-2 min-h-5 leading-5',
+ idx === 0 && 'pt-6',
+ idx === tokens.length - 1 && 'pb-6'
+ )}
+ >
+ {idx + 1}
+ </div>
+ <div
+ className={cn(
+ 'code-content min-h-5 leading-5 pl-6 pr-6',
+ idx === 0 && 'pt-6',
+ idx === tokens.length - 1 && 'pb-6'
+ )}
+ >
+ <CodeLine tokens={line} twoslash={twoslashed?.get(idx)} />
+ </div>
+ </Fragment>
+ ))}
+ </>
+ ) : (
+ <div className="code-content p-6">
+ {tokens.map((line, idx) => (
+ <CodeLine key={idx} tokens={line} twoslash={twoslashed?.get(idx)} />
+ ))}
+ </div>
+ )}
+ </code>
+ </pre>
+ </div>
+ {/* After the code so the block is named before its controls, and outside the scroller so they stay pinned */}
{!hideControls && <CodeBlockControls content={code.trim()} />}
- <pre>
- <code className={lineNumbers ? 'grid grid-cols-[auto_1fr]' : ''}>
- {lineNumbers ? (
- <>
- {tokens.map((line, idx) => (
- <Fragment key={idx}>
- <div
- className={cn(
- 'select-none text-right text-muted bg-control px-2 min-h-5 leading-5',
- idx === 0 && 'pt-6',
- idx === tokens.length - 1 && 'pb-6'
- )}
- >
- {idx + 1}
- </div>
- <div
- className={cn(
- 'code-content min-h-5 leading-5 pl-6 pr-6',
- idx === 0 && 'pt-6',
- idx === tokens.length - 1 && 'pb-6'
- )}
- >
- <CodeLine tokens={line} twoslash={twoslashed?.get(idx)} />
- </div>
- </Fragment>
- ))}
- </>
- ) : (
- <div className="code-content p-6">
- {tokens.map((line, idx) => (
- <CodeLine key={idx} tokens={line} twoslash={twoslashed?.get(idx)} />
- ))}
- </div>
- )}
- </code>
- </pre>
</div>
)
}
diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.utils.ts b/apps/docs/features/ui/CodeBlock/CodeBlock.utils.ts
index 2202c2a5193..b3046183a38 100644
--- a/apps/docs/features/ui/CodeBlock/CodeBlock.utils.ts
+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.utils.ts
@@ -1,8 +1,6 @@
import { type CSSProperties } from 'react'
-/*
- * As defined in @shikijs/core/dist/chunk-tokens.d.mts
- */
+// As defined in @shikijs/core/dist/chunk-tokens.d.mts
enum FontStyle {
NotSet = -1,
None = 0,
@@ -28,3 +26,26 @@ export function getFontStyle(styleFlags: number): CSSProperties {
return style
}
+
+// Fence aliases a screen reader would otherwise read letter by letter
+const LANGUAGE_LABELS: Record<string, string> = {
+ c: 'C',
+ html: 'HTML',
+ js: 'JavaScript',
+ json: 'JSON',
+ jsx: 'JavaScript',
+ py: 'Python',
+ sh: 'Shell',
+ shell: 'Shell',
+ sql: 'SQL',
+ toml: 'TOML',
+ ts: 'TypeScript',
+ tsx: 'TypeScript',
+ yaml: 'YAML',
+}
+
+export function getCodeBlockLabel(lang: string | null, lineCount: number): string {
+ const lines = `${lineCount} ${lineCount === 1 ? 'line' : 'lines'}`
+ if (!lang) return lines
+ return `${LANGUAGE_LABELS[lang] ?? lang}, ${lines}`
+}
diff --git a/apps/docs/styles/globals.css b/apps/docs/styles/globals.css
index 4064aaa2199..42266e52e40 100644
--- a/apps/docs/styles/globals.css
+++ b/apps/docs/styles/globals.css
@@ -452,7 +452,7 @@ th code {
}
/* Word wrap styles for code blocks */
-.shiki[data-wrapped='true'] {
+.shiki[data-wrapped='true'] .code-scroll {
overflow-x: hidden !important;
}