In modern web applications, typography is often the most fragmented layer of design debt. Over years of iterative development, web codebases accumulate dozens of arbitrary font sizes (e.g., 13px, 14.5px, 15px), inconsistent line heights, and unstandardized letter spacings scattered across component stylesheets.
When engineering teams attempt to establish a unified Design System or reverse-engineer a live web application into reusable design tokens, manual typography auditing is tedious and prone to error. Mirrorit solves this problem through Automated Typography Token Extraction—a deterministic pipeline that inspects runtime DOM font metrics, clusters statistical type scales, deduces fluid clamp() formulas, and synthesizes production-ready tokens for Figma and Tailwind CSS.
In this technical article, we explore the algorithmic architecture behind Mirrorit’s typography extraction engine, covering font face descriptor analysis, mathematical clustering, and Cumulative Layout Shift (CLS) fallback optimization.
Table of Contents
- 1. The Challenge of Unstandardized Web Typography
- 2. Runtime Font Metric Computation & DOM Inspection
- 3. Statistical Clustering & Fluid Scale Deduction
- 4. Fallback Font Matching & Zero-CLS Metric Overrides
- 5. Engineering Blueprint: Typography Extraction Algorithm
- 6. Exporting to Figma Text Styles and Tailwind v4 @theme
- 7. Frequently Asked Questions (FAQ)
1. The Challenge of Unstandardized Web Typography
Modern frontend architectures often employ multiple CSS authoring methodologies simultaneously: utility classes (Tailwind), CSS Modules, styled-components, and legacy global stylesheets. As a result, inspecting typography via static source code scanning produces severe inaccuracies:
- Computed Cascade Divergence: CSS inheritance rules and media query overrides mean that static CSS declarations rarely represent the actual rendered font size at specific viewports.
- Fragmented Line Heights: Developers frequently mix unitless line heights (
1.5), percentage values (150%), and explicit pixel values (24px). - Redundant Font Weight Aliases: Numeric weights (
400,600,700) clash with keyword declarations (normal,semibold,bold), creating duplicate style tokens.
Mirrorit Core Principle: Never rely on static CSS regex parsing for typography. Tokens must be extracted from the fully computed, rendered layout across dynamic viewport widths.
2. Runtime Font Metric Computation & DOM Inspection
Mirrorit’s headless browser crawler injects an evaluation script that performs a bottom-up DOM tree traversal. For every text node, the engine extracts the complete computed typographic signature:
| Property | Extraction Method | Normalization Output |
|---|---|---|
| Font Family | window.getComputedStyle(el).fontFamily |
Sanitized font stack array with fallback prioritization |
| Font Size | Computed pixel value parsed via Float64 | Normalized rem/px baseline with fractional rounding |
| Line Height | Computed px compared to font-size ratio | Unitless multiplier (e.g., 1.428) |
| Font Weight | Normalized numeric integer | Standardized scale (100 to 900) |
| Letter Spacing | Computed pixel value to em translation | Tracking tokens (e.g., tracking-tight = -0.025em) |
3. Statistical Clustering & Fluid Scale Deduction
After sampling hundreds of rendered text elements across standard breakpoints (e.g., 375px mobile, 768px tablet, 1440px desktop), Mirrorit applies K-Means Clustering and Density-Based Spatial Clustering (DBSCAN) to group micro-variations into cohesive modular scale steps.
If the target application implements fluid typography, Mirrorit calculates the linear interpolation slope between minimum and maximum viewport boundaries to generate standard CSS clamp() formulas:
/* Extracted Fluid Scale Token for Heading 1 */
--text-display-2xl: clamp(2.25rem, 1.75rem + 2.5vw, 3.75rem);
4. Fallback Font Matching & Zero-CLS Metric Overrides
A critical innovation in Mirrorit is automated Font Metric Override Generation. When custom web fonts (such as Inter, Roboto, or custom brand typefaces) are loaded over the network, browser fallback rendering can cause significant Cumulative Layout Shift (CLS).
Mirrorit measures the exact ascent, descent, and x-height of the primary web font and computes the exact CSS override parameters for standard system fallbacks (Arial, Georgia, Times New Roman):
@font-face {
font-family: 'CustomSans-Fallback';
src: local('Arial');
ascent-override: 94.2%;
descent-override: 23.8%;
line-gap-override: 0%;
size-adjust: 104.5%;
}
5. Engineering Blueprint: Typography Extraction Algorithm
Below is the core algorithmic module used by Mirrorit to extract, deduplicate, and cluster computed typography styles from a headless Chromium page instance:
import { Page } from "playwright";
export interface RawTypeNode {
fontFamily: string;
fontSize: number;
fontWeight: number;
lineHeight: number;
letterSpacing: number;
occurrences: number;
}
export async function extractTypographySignatures(page: Page): Promise<RawTypeNode[]> {
return await page.evaluate(() => {
const signatureMap = new Map<string, RawTypeNode>();
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
let currentNode: Node | null = walker.nextNode();
while (currentNode) {
const parent = currentNode.parentElement;
if (parent && parent.offsetParent !== null && currentNode.textContent?.trim()) {
const style = window.getComputedStyle(parent);
const fontSize = parseFloat(style.fontSize);
const fontWeight = parseInt(style.fontWeight, 10) || 400;
const lineHeight = style.lineHeight === "normal"
? fontSize * 1.2
: parseFloat(style.lineHeight);
const letterSpacing = style.letterSpacing === "normal"
? 0
: parseFloat(style.letterSpacing);
const key = `${style.fontFamily}|${fontSize}|${fontWeight}|${lineHeight}|${letterSpacing}`;
if (signatureMap.has(key)) {
signatureMap.get(key)!.occurrences += 1;
} else {
signatureMap.set(key, {
fontFamily: style.fontFamily,
fontSize,
fontWeight,
lineHeight: parseFloat((lineHeight / fontSize).toFixed(3)),
letterSpacing,
occurrences: 1
});
}
}
currentNode = walker.nextNode();
}
return Array.from(signatureMap.values()).sort((a, b) => b.occurrences - a.occurrences);
});
}
6. Exporting to Figma Text Styles and Tailwind v4 @theme
Once clustered and classified, Mirrorit exports the extracted typography tokens into multiple consumable industry formats:
- Tailwind CSS v4
@theme: Generates semantic CSS variables mapped to clean utility classes (text-sm,text-base,text-lg,text-xl, etc.). - Figma REST API Payload: Direct generation of Figma TextStyle nodes with exact family, weight, line-height percentages, and letter-spacing tracking.
- W3C Design Token Community Group (DTCG) JSON: Interoperable design tokens compatible with Style Dictionary and Token Studio.
7. Frequently Asked Questions (FAQ)
How does Mirrorit differentiate between headings and body text automatically?
Mirrorit uses a multi-factor heuristic combining DOM hierarchy depth, HTML5 semantic tags (h1-h6, p, span), relative font weight, and rendered frequency across the entire page layout.
Can Mirrorit detect variable fonts with non-standard font weights?
Yes. Mirrorit queries the CSS Font Loading API (document.fonts) and evaluates CSS font-variation-settings to detect variable weight (wght), width (wdth), and slant (slnt) axes.
How does typography token extraction benefit design system migrations?
It eliminates weeks of manual design audits by instantly highlighting redundant font sizes, undocumented inline styles, and unapproved font weights across legacy applications.
Published in the Mirrorit Technical Series on Tibagede. Explore our other deep-dives on DOM conversion, sourcemap reconstruction, and headless web scraping architectures.