Files
supabase/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsx
Miranda Limonczenko f09d35cfd5 fix(docs): make code blocks reachable and readable by keyboard and screen reader (#49562)
Closes DOCS-1283



https://github.com/user-attachments/assets/6e55a27f-6f73-453b-b98f-e91d3c14a9e4



## Problem

Three defects in the docs code block:

- The scroll container has no `tabindex`. On `/guides/database/tables`,
18 blocks, none focusable, 2 overflowing at 1280px. Tab skips the scroll
region, so a keyboard-only user cannot scroll code that runs off the
edge.
- The container has `role="group"` with no accessible name, so it
announces as bare "group".
- The line-number gutter has no `aria-hidden`, so digits are read inline
with the code. A block linearizes as `1import { createClient } from
'@supabase/supabase-js'23const supabase = ...`, with lines 2 and 3
collapsing into "23".

Four more surfaced while testing the fix:

- The wrap and copy buttons were absolutely positioned inside the
element that scrolls, so `right-2` measured against the scrollable
content box. Scrolling dragged them out of the corner into the middle of
the code. This one predates the PR.
- The buttons preceded the code in the DOM, so a screen reader read two
actions before naming what they act on.
- `focus-within` only fired for the buttons, so focusing the block left
the controls invisible.
- Both buttons set an `aria-label` identical to their tooltip text, and
Radix points `aria-describedby` at the tooltip on focus, producing "Copy
code, button, Copy code".

## Solution

Keyboard:

- Split the scroll region out of the positioning container, so the
controls stay pinned.
- Give the scroll region a `tabIndex` and a focus ring.
- Reveal the controls on `group-focus-within`.

Screen reader:

- Name the region `<language>, <n> lines`. Code content stays readable;
the summary goes in the name so the group can be skipped or stepped
into.
- Map fence aliases to spoken names, so `ts` announces as TypeScript.
Only the ambiguous ones; `bash`, `python`, `kotlin`, `dart`, `swift`
already read fine.
- `aria-hidden` the gutter. The numbers are already `select-none`, and
copy takes its content from the source string rather than the DOM, so
copy behavior is unchanged.
- Order the controls after the code.
- Announce the word wrap toggle through a live region, matching the copy
button.
- Opt both buttons out of Radix's generated description.

Also moved the `data-wrapped` side effect out of the `setIsWrapped`
updater, since React calls updaters twice under StrictMode.

## Manual testing

1. Open `/docs/guides/database/tables`.
2. Run `document.querySelectorAll('.code-scroll[tabindex="0"]').length`
in the console. Expect `18`.
3. Run `[...document.querySelectorAll('.code-scroll')].map(b =>
b.getAttribute('aria-label'))`. Expect entries like `SQL, 11 lines` and
`bash, 2 lines`, plus one bare `2 lines` for the fence with no language.
4. Tab to a code block. Expect a visible focus ring, and the wrap and
copy buttons to appear.
5. Press ArrowRight on the block under "Basic data loading", which
overflows. Expect it to scroll, and the buttons to stay in the top-right
corner.
6. Press Enter on the wrap button. Expect the code to wrap and a screen
reader to announce "Word wrap enabled".
7. With VoiceOver on, focus a code block. Expect "SQL, 11 lines, code
block", then the code read without line numbers interleaved. Focus each
button and expect its name once, not twice.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Accessibility**
- Improved code block labels for screen readers, including programming
language and line count.
  - Added announcements when word wrap is enabled or disabled.
  - Enhanced keyboard focus behavior for code block controls.

- **Usability**
  - Kept code block controls visible while scrolling through code.
  - Improved wrapped-code overflow handling.
- Removed redundant tooltip descriptions for copy and word-wrap
controls.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-26 10:43:40 -07:00

190 lines
5.4 KiB
TypeScript

'use client'
import { ArrowRightFromLine, Check, Copy, WrapText } from 'lucide-react'
import { useCallback, useEffect, useRef, useState, type MouseEvent } from 'react'
import { type ThemedToken } from 'shiki'
import { type NodeHover } from 'twoslash'
import { cn, copyToClipboard, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import { getFontStyle } from './CodeBlock.utils'
export function AnnotatedSpan({
token,
annotations,
}: {
token: ThemedToken
annotations: Array<NodeHover>
}) {
const [open, setOpen] = useState(false)
const [isTouchDevice, setIsTouchDevice] = useState(false)
useEffect(() => {
const touchDevice = !window.matchMedia('(pointer: fine)').matches
setIsTouchDevice(touchDevice)
}, [])
const handleClick = useCallback(
(evt: MouseEvent) => {
if (isTouchDevice) {
evt.preventDefault()
evt.stopPropagation()
setOpen((open) => !open)
}
},
[isTouchDevice]
)
const onOpenChange = useCallback(
(open: boolean) => {
if (!isTouchDevice || !open) {
setOpen(open)
}
},
[isTouchDevice]
)
return (
<Tooltip open={open} onOpenChange={onOpenChange}>
<TooltipTrigger asChild onClick={handleClick}>
<button
tabIndex={0}
style={token.htmlStyle}
className={cn(
isTouchDevice &&
'underline underline-offset-4 decoration-dashed decoration-[rgba(from_currentColor_r_g_b/0.5)]'
)}
>
{token.content}
</button>
</TooltipTrigger>
<TooltipContent className="max-w-[min(80vw,400px)] p-0 divide-y">
{annotations.map((annotation, idx) => (
<Annotation key={idx} annotation={annotation} />
))}
</TooltipContent>
</Tooltip>
)
}
function Annotation({ annotation }: { annotation: NodeHover }) {
const { text, docs, tags } = annotation
return (
<div className="flex flex-col gap-2">
<code className={cn('block bg-200 p-2', (docs || tags) && 'border-b border-default')}>
{text}
</code>
{docs && <p className={cn('p-2', tags && 'border-b border-default')}>{docs}</p>}
{tags && (
<div className="p-2 flex flex-col">
{tags.map((tag, idx) => {
return (
<span key={idx}>
<code>@{tag[0]}</code> {tag[1]}
</span>
)
})}
</div>
)}
</div>
)
}
export function CodeCopyButton({ className, content }: { className?: string; content: string }) {
const [copied, setCopied] = useState(false)
const handleCopy = async () => {
copyToClipboard(content, () => {
setCopied(true)
})
}
const resetStatus = () => {
setCopied(false)
}
return (
<>
<span className="sr-only" aria-live="polite">
{copied ? 'Code copied' : ''}
</span>
<Tooltip>
<TooltipTrigger asChild>
<button
tabIndex={0}
onClick={handleCopy}
onBlur={resetStatus}
className={cn(
'cursor-pointer border rounded-md p-1',
copied && 'bg-selection',
'hover:bg-selection transition',
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" />
) : (
<Copy size={14} className="text-lighter" />
)}
</button>
</TooltipTrigger>
<TooltipContent>Copy code</TooltipContent>
</Tooltip>
</>
)
}
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(() => {
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')
}
}
}, [isWrapped])
return (
<div
ref={wrapperRef}
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
tabIndex={0}
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" />
) : (
<WrapText size={14} className="text-lighter" />
)}
</button>
</TooltipTrigger>
<TooltipContent>{isWrapped ? 'Disable word wrap' : 'Enable word wrap'}</TooltipContent>
</Tooltip>
<CodeCopyButton content={content} />
</div>
)
}