@typeset/adapter-web

@typeset/adapter-web translates adapter-facing results from @typeset/typeset into trusted HTML and the CSS required to express them in a browser. It owns the internal markup; framework integrations should treat the returned HTML as an opaque paragraph result and replace it as a whole.

Both Measured line wrappers and Static Flow paragraph wrappers set text-spacing-trim: space-all. Core owns Mojikumi punctuation spacing; the browser must not apply additional CJK punctuation trimming, even when Core emits zero spacing. For example, with PingFang SC at 20px, browser-default trimming renders the adjacent pair 」( at 30px although the individually measured tokens total 40px. This changes a solved line’s width and can also double-apply Static Flow spacing. The rule belongs to the adapter’s layout CSS, so it applies without annotations or Playground-specific styles. Static Flow still uses browser wrapping and CSS justification. Both wrappers also set font-kerning: none to prevent font-defined CJK and punctuation kerning from changing separately measured token widths. Latin words and numeric literals restore font-kerning: normal on ordinary inline spans, preserving the internal kerning included in whole-token measurement. Ligatures are unchanged. This also addresses Smartisan Compact CNS punctuation kerning, which is independent of browser punctuation trimming.

ASCII and fullwidth parentheses remain outside numeric spans: (12) is rendered with only 12 restoring kerning. Parentheses inherit none; Core measures each bracket separately and keeps the group together through boundary constraints. Measurement still uses the existing Pretext provider. This policy does not isolate arbitrary shaping across equal-style spans or provide glyph-level control over ligatures and contextual shaping.

Browser regression checks (2026-09-08, local Chromium): at 20px, PingFang SC and Smartisan Compact CNS both render (1)(2) at the measured 120px in Measured and Static Flow. ASCII brackets and numeric suffix examples differ from Pretext by less than 0.02px. In the supplied Hong Kong typography preface, Measured right edges differ from the solved positions by less than 0.05px, including a composite-font case with Arial Latin text at 80% size and a 0.1em baseline shift. These are tested-font results, not a guarantee for arbitrary shaping.

Measured Composition

import { renderLayoutResultToHtml, serializeWebStyleRules } from "@typeset/adapter-web";

const output = renderLayoutResultToHtml(layoutResult);
const style = document.createElement("style");
style.textContent = serializeWebStyleRules(output.styleRules);
host.before(style);
host.innerHTML = output.html;

Measured lines are authoritative and do not wrap again in the browser. Each solved line is a full-width inline-block span; the returned HTML is a fragment without an additional paragraph wrapper. Set the host element’s inline size to layoutResult.availableWidth so the line spans form visual rows without introducing block formatting boundaries between them. Source text is always HTML-escaped. The caller must render with the same font context and layout unit used for measurement and composition.

An ASCII space run is measured and displayed at one ordinary space’s width, including at the start of a paragraph or after a forced line break. Measured lines beginning with spaces use a zero-width CSS pseudo-element to prevent browser line-start trimming; the original spaces remain unchanged in the HTML. Trailing spaces marked collapsed-at-line-end retain their source characters and collapse to zero width. In space-only lines the pseudo-element preserves the line height while the trailing spaces still collapse to zero width.

LayoutToken.wordSpacing is the Core-solved increment beyond natural separator width, rendered with base-size word-spacing. The adapter does not choose ratios or stretch more to fill a line. Leading indentation and collapsed trailing spaces receive no word-space increment.

Measured line-end spacing is applied to the edge of visible content: positive amounts use inline-end padding and negative amounts use inline-end margin. Collapsed source spaces are emitted outside that edge wrapper, so matching a line-end rule against a trailing space does not make the effect disappear or preserve the space’s natural width. Static Flow retains its existing hard-edge implementation.

Adjacent graphemes with the same final rendering configuration are coalesced across token boundaries. Latin-word and numeric-literal token boundaries, spacing changes, conditional spacing, soft line-start compensation, optional annotations, and Static Flow structural wrappers still create explicit inline-run boundaries.

Pass resolveCompositeFont when the result carries Core composite-font runs. This option is conditionally required: rendering throws when font runs are present without it, while ordinary single-font results do not need it. The resolver maps adapter-neutral candidates to browser family aliases and CSS face properties; Core-owned relativeSize and baselineShift are rendered automatically:

renderLayoutResultToHtml(layoutResult, {
  resolveCompositeFont: (font) => ({
    families: font.candidates.map(({ family }) => family),
    style: "normal",
    weight: 400,
  }),
});

Composite-font declarations use content-addressed typeset-composite-font-* and typeset-composite-font-adjustment-* classes. Each output returns the required dynamic rules in styleRules; the adapter does not create or place a style element. Callers may combine rules from any number of paragraph outputs and pass the complete collection to serializeWebStyleRules, which deduplicates identical class rules in first-seen order.

The serializer keeps spacing and baseline shift on a base-size outer wrapper and applies relative font size to an inner span. Consequently a Core 0.25em spacing decision remains one quarter of the composition em even when the text run is rendered at 80%. A bundled internal compositeFontRun class gives the inner font span zero line height and baseline alignment, so a composite-font face or relative size changes glyph rendering without contributing a different height to the browser line box. This fixed adapter behavior is not repeated in styleRules. Baseline shift uses composition em and visual relative positioning, so it does not enlarge the browser line box. Composite-font runs therefore do not independently determine the surrounding line height; measured empty lines emit an invisible zero-width strut in the inherited font context.

Static Flow

import { renderStaticFlowToHtml } from "@typeset/adapter-web";

const output = renderStaticFlowToHtml(staticFlowResult, {
  alignment: "justify",
});
host.innerHTML = output.html;

Insert the serialized output.styleRules as shown for Measured Composition when the Static Flow result contains composite-font runs.

Static Flow uses the same resolveCompositeFont option as Measured Composition. The resolver must return the final CSS family names that will exist in the consuming page. The adapter neither loads fonts nor emits @font-face; server-side callers may prepare those declarations independently and pass their family aliases through the resolver. If a system or browser-provided family is sufficient, return that family name directly.

Static Flow keeps browser soft wrapping while rendering hard segments, fixed and conditional spacing, known line-edge spacing, and unbreakable runs. Pass alignment: "start" | "justify" to express paragraph alignment with CSS; justification follows browser line breaking and leaves the final line unexpanded. The option is optional: when omitted, the adapter emits no alignment class and the host CSS cascade controls text alignment. The output reports effects that the current Web strategy cannot express exactly:

Hard segments beginning with ASCII spaces use the same zero-width CSS pseudo-element as Measured lines, preserving one space’s width at paragraph starts and after forced line breaks. Soft wrapping and trailing-space collapse remain browser-owned; the original space characters are preserved in the HTML.

Optional annotations

The adapter can add semantic data-typeset-* annotations for inspection tools without owning their visual presentation:

const output = renderLayoutResultToHtml(layoutResult, {
  annotations: { lines: true, hanging: true, spacing: true },
});

Annotations are omitted by default. Consumers such as the Solid Playground may target them from their own CSS to visualize overfull lines, hanging punctuation, spacing, or break constraints. The adapter’s CSS only implements required browser layout semantics.

Pretext measurement

The browser-only Pretext provider has a separate entry so Node and build-time Static Flow consumers do not load it:

import {
  clearPretextMeasurementCache,
  createPretextMeasureToken,
} from "@typeset/adapter-web/pretext";

It measures a token’s natural advance in CSS pixels, normalizes it to composition em, and caches repeated text. For a relatively sized run, pass the actual run size as fontSizePx and the base size as compositionEmPx.

Call clearPretextMeasurementCache() after available fonts change, then compose again. It clears Pretext’s shared caches and invalidates every existing provider’s text cache; callers can reuse their provider functions. The application owns font loading and the document.fonts listener. Handle loadingdone for asynchronously loaded fonts, and invalidate explicitly when adding or removing already-loaded FontFace objects, since those changes need not emit a loading event. The adapter does not attach global listeners or manage font fallback identity.

Security

The serializer escapes all source text and only emits internal tags, CSS Module classes, content-addressed dynamic classes, numeric styles from the typed layout results, accessibility attributes, and explicitly requested data-typeset-* annotations. Dynamic CSS strings escape raw-text delimiters before they enter styleRules. The adapter does not accept raw HTML.

Layout snapshots

The UDHR snapshot group composes Articles 1, 2, 11, 23, and 26 of the Universal Declaration of Human Rights in Simplified Chinese, Traditional Chinese, English, Japanese, and Korean at 20, 24, and 32em: 15 cases. Each fixture retains the declaration title, article headings, and complete selected articles, without the preamble. The selection combines short paragraphs, longer prose, enumerations, and numbered clauses, including the numbered Korean clauses in Article 11.

The AQ group adds six cases: the same Simplified Chinese excerpt from the start of Lu Xun’s 阿Q正传, using default and simple-chinese-pretty-spacing at each width. It contains the title, chapter heading, and first two complete body paragraphs (540 body characters). Wikisource’s original 『』 punctuation is retained; these characters exercise the fullwidth bracket rules. This excerpt does not cover the profile’s separate “” / ‘’ quotation-mark overrides. There are 21 cases across both groups.

All six AQ cases also use a Core composite-font profile: the latin character class retains the same Noto Serif CJK SC Regular face and 100% size, with baselineShift: 0.05 (upward by 1px at the fixed 20px size). Other characters keep the normal baseline. The resolved runs pass through measurement, layout, and the adapter’s composite-font renderer. Since the font face and size are identical, measurement reuses the same Pretext provider; the baseline shift changes visual position only, preserving line widths, breaks, and line height. Text snapshots list the shifted runs and their line-relative UTF-16 ranges; screenshots capture the rendered offset. UDHR remains single-font without this shift.

Each case uses real Pretext measurements, the Core solver, and this adapter, then compares both a readable layout summary and a screenshot of the entire text area. Both groups use Measured Composition with justification, default Kinsoku, no hanging punctuation, and a last-line minimum of two effective units and 16% fill. UDHR uses default Mojikumi; the AQ comparison changes only the Mojikumi profile. These shared policies record current engine behavior across the texts; they are not a claim of complete language-specific typography support. Static Flow and other policy combinations are not covered.

The fixture fixes the font at 20px, line height at 30px, and device scale at 1. It uses bundled Noto Serif CJK Regular 2.003 subsets: SC for Simplified Chinese, HK for Traditional Chinese and English, JP for Japanese, and KR for Korean. Each subset covers its complete fixture text. The browser locale and document language match the selected text, and measurement waits for the selected font to load. The text summary records line text, widths, spacing, hanging, overfull status, and diagnostics; numbers are rounded to the adapter’s four-decimal em precision. ASCII spaces appear as ␠. Internal token IDs and intermediate solver structures are intentionally omitted.

Traditional Chinese uses the 1948 wording, rather than converting the modern Simplified Chinese text. Each selected text has 18 paragraphs including headings; wording differs between versions. The files in test/fixtures/udhr/ are fixed inputs; tests never fetch live text or fonts.

The baselines use Core’s bounded word-spacing profile (80% / 100% / 133% of natural separator width, both priorities 2). English now receives word-space adjustment opportunities. Lines that exhaust this finite capacity may still remain underfull and report spacing-adjustment-capacity-exhausted; the renderer does not exceed the configured maximum. Hangul and Bopomofo contribute effective units, so numbered Korean clauses no longer become a single unbreakable paragraph merely because only the numeral was counted.

Snapshots record the current shared profile, not a complete language-specific typography standard. The browser geometry test additionally checks actual DOM advances against Core output for expanded ASCII spaces, NBSP, hard-line endings, and positive/negative line-end rules matched by collapsed source spaces. It verifies that original text survives serialization; source text equality is not a full clipboard integration test.

From the repository root:

# Once after dependency installation, or after upgrading Playwright
pnpm --filter @typeset/adapter-web exec playwright install chromium --only-shell

# Compare against checked-in baselines; never creates or updates them
pnpm --filter @typeset/adapter-web test:snapshots

# Optionally run one language and width
pnpm --filter @typeset/adapter-web test:snapshots --grep 'UDHR ja.*24em'

# Compare both AQ profiles at all three widths
pnpm --filter @typeset/adapter-web test:snapshots --grep 'AQ'

# After reviewing an intentional behavior change
pnpm --filter @typeset/adapter-web test:snapshots:update

# View failures, including expected / actual / diff images
pnpm --filter @typeset/adapter-web exec playwright show-report

The tests start and stop their own Vite server on port 4174. To inspect the fixture manually, run pnpm --filter @typeset/adapter-web exec vite --host 127.0.0.1 --port 4174 --strictPort and open /test/browser/?language=ja&width=24 (UDHR language choices: zh-Hans, zh-Hant, en, ja, ko). For AQ, open /test/browser/?sample=aq&language=zh-Hans&profile=simple-chinese-pretty-spacing&width=24, or set profile=default for comparison. Stop that server before running the tests. Unit tests remain available through pnpm --filter @typeset/adapter-web test; snapshot tests are a separate command because they need the installed browser.

Baselines live in test/browser/snapshots/{platform}/. The initial baselines were generated on macOS arm64 with Playwright 1.63.0 and its Chromium headless shell 153.0.8010.12 (revision 1243). Compare screenshots on the same OS and architecture with the pinned browser and font; other operating systems need separately generated and reviewed baselines. Screenshot comparison allows no pixel differences. Review both the text diff and the images before accepting an update; generating a baseline does not establish that the layout is correct. Do not update baselines merely to make a failing run pass.

See fixture provenance and font regeneration for the copied text, font license, and pinned source.