Skip to main content
196

Search Lumen

Find components, APIs, guides, and recipes.

GitHub
All documentation

Make Markdown tables readable

A comparison table can outgrow a phone or an enlarged text column. Keep its native headings and caption, then give the reader a named region they can scroll with the keyboard.

This example follows the table integration used by santi020k.com v5. The application owns Markdown compilation and labels. Lumen supplies table styles and the overflow controller.

Try a wide comparison

Focus the table region and use the arrow keys. At a narrow width, the overflow hint appears after enhancement. Disable JavaScript to check the native scrolling fallback.

Article delivery choices
ContentInitial pageAfter interaction
Article textSemantic headings and complete proseNative fragment navigation
Wide comparisonCaption, column headings, and keyboard scroll regionOverflow hint when the table exceeds its container
Code examplesComplete source with readable fallbackCopy feedback and synchronized tabs

This live preview uses the public Table component. The transform below creates its documented scroll surface around tables emitted by Markdown.

Copy the editable transform

Save this file as src/plugins/rehype-readable-tables.ts. It preserves the original table and caption, wraps each table once, and accepts translated labels. Write a useful caption in your content when supported by the Markdown renderer. Tables without captions receive numbered region names.

typescriptrehype-readable-tables.ts
Show full exampleCollapse example97 lines
/** Editable rehype plugin. Keep Markdown parsing and content policy in the application. */
interface Node {
  type: string
  tagName?: string
  value?: string
  properties?: Record<string, unknown>
  children?: Node[]
}

interface Frame {
  node: Node
  siblings: Node[]
  index: number
}

interface Options {
  label?: (tableNumber: number, caption: string) => string
  cue?: string
}

const textContent = (node: Node): string => {
  const pending = [node]
  let text = ''

  while (pending.length > 0) {
    const current = pending.pop()

    if (current?.type === 'text') text += current.value ?? ''
    else if (current?.children) {
      for (const child of current.children.toReversed()) pending.push(child)
    }
  }

  return text.trim()
}

const captionText = (table: Node): string => {
  const caption = table.children?.find(child => child.tagName === 'caption')

  return caption ? textContent(caption) : ''
}

export const rehypeReadableTables = ({
  label = (number, caption) => caption || `Table ${number}`,
  cue = 'Scroll horizontally to compare'
}: Options = {}) => (tree: Node): void => {
  const pending: Frame[] = [{ node: tree, siblings: [tree], index: 0 }]
  let number = 0

  for (let frame = pending.pop(); frame; frame = pending.pop()) {
    const { node, siblings, index } = frame

    if (node.properties?.dataReadableTable !== undefined) continue

    if (node.type !== 'element' || node.tagName !== 'table') {
      const children = node.children ?? []

      for (const [childIndex, child] of [...children.entries()].toReversed()) {
        pending.push({ node: child, siblings: children, index: childIndex })
      }

      continue
    }

    number++

    const viewport: Node = {
      type: 'element',
      tagName: 'div',
      properties: {
        className: ['ui-table-wrap'],
        dataSlot: 'table',
        dataScrollCueViewport: '',
        role: 'region',
        tabIndex: 0,
        ariaLabel: label(number, captionText(node))
      },
      children: [node]
    }

    siblings[index] = {
      type: 'element',
      tagName: 'div',
      properties: { className: ['ui-table-scroll'], dataUiScrollCue: '', dataReadableTable: '' },
      children: [
        {
          type: 'element',
          tagName: 'div',
          properties: { className: ['ui-scroll-cue'], dataScrollCueMessage: '', dataSlot: 'scroll-cue', hidden: true },
          children: [{ type: 'element', tagName: 'span', properties: {}, children: [{ type: 'text', value: cue }] }]
        },
        viewport
      ]
    }
  }
}
/** Editable rehype plugin. Keep Markdown parsing and content policy in the application. */
interface Node {
  type: string
  tagName?: string
  value?: string
  properties?: Record<string, unknown>
  children?: Node[]
}

interface Frame {
  node: Node
  siblings: Node[]

Run this after plugins that create tables and before HTML serialization. Keep your Markdown renderer's sanitization policy. This transform operates on parsed nodes and adds no HTML parsing or sanitization.

typescriptRegister the rehype plugin
// astro.config.ts — with Astro's rehype Markdown pipeline
import { defineConfig } from 'astro/config'
import { rehypeReadableTables } from './src/plugins/rehype-readable-tables'

export default defineConfig({
  markdown: {
    rehypePlugins: [[rehypeReadableTables, {
      cue: 'Scroll horizontally to compare'
    }]]
  }
})

The setup uses Astro's rehype pipeline. If an application selects a custom Markdown processor, register an equivalent transform through that processor's documented AST API.

Load styles and the shared runtime

Import the foundation and table CSS in the article layout because generated Markdown does not pass through an Astro component. Mount the shared runtime once in the root layout. Omit a second runtime here if the root already supplies it.

astroSelective article setup
---
// ArticleLayout.astro — generated Markdown needs explicit stylesheet imports.
import '@santi020k/lumen-astro/styles/foundation.css'
import '@santi020k/lumen-astro/styles/components/table.css'
import UIPrimitives from '@santi020k/lumen-astro/runtime'
---
<main><slot /></main>
<UIPrimitives />

Without JavaScript, the caption and complete table remain readable in a focusable scroll region. The cue starts hidden and appears only when the runtime observes overflow. Check the built page at 320px, at 200% text, in both themes, and with keyboard navigation.

Continue with Build an editorial article to combine the table with contents navigation and code examples.

All documentationWeb and native guides