@aglyn/shared-ui-theme 1.0.0-beta.221 → 1.0.0-beta.223
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/package.json +4 -4
- package/src/lib/console.theme.js +40 -1
- package/src/lib/console.theme.js.map +1 -1
- package/src/lib/util/accent-text.d.ts +72 -1
- package/src/lib/util/accent-text.js +121 -4
- package/src/lib/util/accent-text.js.map +1 -1
- package/src/lib/util/create-responsive-theme.js +64 -1
- package/src/lib/util/create-responsive-theme.js.map +1 -1
- package/src/lib/util/self-hosted-fonts.d.ts +96 -0
- package/src/lib/util/self-hosted-fonts.js +169 -0
- package/src/lib/util/self-hosted-fonts.js.map +1 -0
- package/src/vendor/mui.d.ts +25 -0
- package/src/vendor/mui.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/shared/ui/theme/src/lib/util/accent-text.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Palette, PaletteColor, Theme } from '../../vendor/mui'\nimport {\n AA_TEXT_CONTRAST,\n accessibleShade,\n contrastRatio,\n} from './accessible-shade'\n\n/**\n * The palette slot that carries \"this accent, rendered AS TEXT on the\n * scheme's own surfaces\" (AGL-1293 / AGL-1297).\n *\n * `dark` is deliberately overloaded rather than a new slot being invented:\n * `ensureAccessibleShades` already guarantees the value of this slot clears\n * {@link AA_TEXT_CONTRAST} against `background.default` and\n * `background.paper` in whichever direction the scheme needs (darker in\n * light, LIGHTER in dark), so every tenant palette carries an accessible\n * value here whether or not its author thought about one. A second slot\n * would have to be whitelisted in `host-theme.ts`, authored per host, and\n * kept in sync — three new ways for a palette to be missing it.\n *\n * `console.theme.ts` authors the shade explicitly for both schemes rather\n * than relying on that repair, so the value a link resolves to is readable\n * in the palette instead of recomputed at boot.\n */\nexport const ACCENT_TEXT_SHADE = 'dark' as const\n\n/** WCAG AA contrast bar for non-text UI (borders, icon fills, indicators). */\nexport const AA_NON_TEXT_CONTRAST = 3\n\n/**\n * The accent-as-text color for `color`, as a value safe to hand to a\n * `styleOverrides` root.\n *\n * Wired into `MuiButton`'s `--variant-textColor` / `--variant-outlinedColor`\n * and `MuiLink`'s `color` in `console.theme.ts`. Those three are the places\n * MUI paints an accent at normal text size, where `main` owes 4.5:1 and the\n * brand blue delivers 2.43:1 on white. Everything that paints the accent as\n * a FILL, a BORDER or an INDICATOR — `--variant-containedBg`,\n * `--variant-outlinedBorder`, the Tabs indicator — keeps `main`: those owe\n * 3:1, and the brand color is meant to be seen there.\n *\n * Returns a CSS variable reference (`var(--mui-palette-primary-dark)`) on a\n * CSS-vars theme and a literal on a single-mode theme. That distinction is\n * load-bearing: `components` are evaluated ONCE against the root theme, so\n * baking a light-scheme literal would freeze it into dark mode.\n *\n * @param theme the active MUI theme (CSS-vars or single-mode)\n * @param color a palette key — `'primary'`, `'error'`, … Anything without a\n * PaletteColor shape (`'inherit'`, `'textPrimary'`, `undefined`) returns\n * `undefined`.\n */\nexport function accentTextColor(\n theme: Theme | undefined,\n color: string | undefined,\n): string | undefined {\n if (!theme || !color) return undefined\n // `theme.vars` is the CSS-variable mirror of the palette; prefer it so the\n // emitted value is a `var()` that follows the scheme.\n const source = ((theme as unknown as { vars?: { palette?: unknown } }).vars ??\n theme) as { palette?: Record<string, unknown> }\n const paletteColor = source?.palette?.[color] as\n Record<string, string> | undefined\n if (!paletteColor || typeof paletteColor !== 'object') return undefined\n const accent = paletteColor[ACCENT_TEXT_SHADE]\n return typeof accent === 'string' ? accent : undefined\n}\n\n/**\n * The accent shade a FILLED surface can paint under the accent's own ink —\n * the counterpart to {@link accentTextColor}, and a different value for a\n * different question (AGL-2704).\n *\n * {@link ACCENT_TEXT_SHADE} answers \"this accent, READ ON the page\", so it\n * inverts direction per scheme: darker than `main` in light, LIGHTER in\n * dark. That makes it wrong as a fill in exactly one scheme. The console's\n * `primary.dark` is `#0077ad` in light, where white on it measures 4.95:1,\n * and `#4dc8ff` in dark, where the same white measures 1.91:1 — below the\n * 2.43:1 the brand fill it replaced already scored.\n *\n * This shade answers \"this accent, PAINTED UNDER its own `contrastText`\"\n * instead. The constraint is the ink, not the page, so the walk starts at\n * `main` and darkens until the ink clears the bar — and the answer is the\n * SAME in both schemes, which is the property a token reference needs. An\n * `sx` value resolves against whichever scheme is active, so a fill token\n * that only holds in one of them cannot be authored safely.\n *\n * Takes a resolved `Palette`, never `theme.vars`: the walk decomposes real\n * colors, and a CSS-variable mirror hands it `var(--mui-palette-…)`.\n *\n * @param palette a resolved (non-`vars`) palette\n * @param color a palette key — `'primary'`, `'error'`, …\n * @param minContrast the bar the ink must clear. Default\n * {@link AA_TEXT_CONTRAST}.\n */\nexport function accentFillColor(\n palette: Palette | undefined,\n color: string | undefined,\n minContrast: number = AA_TEXT_CONTRAST,\n): string | undefined {\n if (!palette || !color) return undefined\n const paletteColor = (palette as unknown as Record<string, unknown>)[\n color\n ] as Record<string, string> | undefined\n if (!paletteColor || typeof paletteColor !== 'object') return undefined\n const { main, contrastText } = paletteColor\n if (typeof main !== 'string' || typeof contrastText !== 'string') {\n return undefined\n }\n try {\n return accessibleShade(main, [contrastText], 'darken', { minContrast })\n } catch {\n // Unparseable color (a `color()` literal, an unresolved variable). A\n // caller gets nothing rather than a guess, the same as `accentTextColor`.\n return undefined\n }\n}\n\n/** One measured way a palette fails its accessibility contract. */\nexport type PaletteContrastViolation = {\n /** Palette key — `'primary'`, `'error'`, … */\n color: string\n /**\n * `accentText` — the accent painted as text on the scheme's surfaces.\n * `contrastText` — the foreground painted ON that accent.\n * `accentFill` — that same foreground painted on the accent's TEXT shade,\n * i.e. a surface filled with {@link ACCENT_TEXT_SHADE}. Off by default;\n * see {@link AuditPaletteContrastOptions.roles}.\n */\n role: 'accentText' | 'contrastText' | 'accentFill'\n /** The foreground colour that failed. */\n value: string\n /** The background it failed against. */\n against: string\n /** Measured WCAG ratio, 1–21. */\n ratio: number\n /** The bar it had to clear. */\n required: number\n /**\n * Set only when this exact pairing matches a\n * {@link DOCUMENTED_CONTRAST_EXCEPTIONS} entry: the human decision that\n * knowingly accepts the measured ratio. Excluded from the default result;\n * surfaced by `includeExempt`.\n */\n exemption?: string\n}\n\n/**\n * Pairings a human has knowingly SIGNED OFF below the bar — decided, not\n * outstanding.\n *\n * The rest of what {@link auditPaletteContrast} reports is a FINDING: a\n * measurement offered for a decision the account owner owns, not a defect queued for\n * repair. Nothing in this module changes a rendered colour.\n *\n * This is not a suppression list and it must not become one. Each entry pins\n * all four coordinates of one pairing — palette key, role, the exact\n * foreground and the exact background — so it waives a decision, not a slot.\n * Change the brand blue, change the white, or move the same white onto\n * `secondary`, and none of them match: the audit reports it again, which is\n * the point. A new entry needs a named person, a date, their words, and the\n * measured ratio, the same as this one.\n */\nexport const DOCUMENTED_CONTRAST_EXCEPTIONS: ReadonlyArray<{\n color: string\n role: PaletteContrastViolation['role']\n value: string\n against: string\n reason: string\n}> = [\n {\n // AGL-1293. Computing this slot for contrast resolves it to dark ink\n // (8.65:1), which turns every filled primary button dark-on-blue. The\n // tradeoff is to darken the brand or to keep it and accept sub-AA white,\n // and the brand blue is fixed: white on `#00b0ff` is 2.43:1, below the\n // 4.5:1 AA text bar and below the 3:1 non-text bar. Accepted knowingly.\n //\n // This is the ONE decided pairing. Everything else the audit reports —\n // the five other authored sub-AA `contrastText` literals, and `#00b0ff`\n // as text — is a finding, not a waiver, and stays undecided here.\n color: 'primary',\n role: 'contrastText',\n value: '#FFFFFF',\n against: '#00b0ff',\n reason:\n 'AGL-1293 — the brand blue stays as authored, with white text (white on #00b0ff = 2.43:1, knowingly below AA)',\n },\n]\n\n/** Case-insensitive exact colour match; nothing fuzzy, nothing normalised away. */\nfunction sameColor(a: string, b: string) {\n return a.trim().toLowerCase() === b.trim().toLowerCase()\n}\n\n/**\n * The signed-off reason for this exact pairing, or `undefined`. Exact on all\n * four coordinates — a near miss is not a match.\n */\nfunction documentedExemption(\n color: string,\n role: PaletteContrastViolation['role'],\n value: string,\n against: string,\n): string | undefined {\n return DOCUMENTED_CONTRAST_EXCEPTIONS.find(\n (exception) =>\n exception.color === color &&\n exception.role === role &&\n sameColor(exception.value, value) &&\n sameColor(exception.against, against),\n )?.reason\n}\n\nconst AUDITED_COLOR_KEYS = [\n 'primary',\n 'secondary',\n 'tertiary',\n 'error',\n 'warning',\n 'info',\n 'success',\n] as const\n\nexport type AuditPaletteContrastOptions = {\n /** Bar for foreground text. Default {@link AA_TEXT_CONTRAST}. */\n minContrast?: number\n /** Restrict the audit to these palette keys. Default: all accents. */\n colors?: ReadonlyArray<string>\n /**\n * Include pairings matched by {@link DOCUMENTED_CONTRAST_EXCEPTIONS},\n * carrying their `exemption`. Default `false`, so a signed-off decision does\n * not read as an open defect. Pass `true` to see everything measured — the\n * spec that proves the exception is still exactly 2.43:1 uses this, so the\n * waiver documents a number rather than hiding one.\n */\n includeExempt?: boolean\n /**\n * Which roles to measure. Default {@link DEFAULT_AUDITED_ROLES} — the two\n * pairings every palette owes unconditionally.\n *\n * `accentFill` is opt-in because it is a question about a SURFACE, not\n * about the palette: it asks what a fill painted with\n * {@link ACCENT_TEXT_SHADE} does to the accent's own ink. In a dark scheme\n * that shade is lighter than `main` by design, so every accent fails it —\n * correctly, and uselessly for a palette that fills with nothing. Pass it\n * where something actually does (AGL-2704: the marketing pricing page\n * filled a nav CTA and a badge with `primary.dark`, which held in light at\n * 4.95:1 and collapsed to 1.91:1 in dark).\n */\n roles?: ReadonlyArray<PaletteContrastViolation['role']>\n}\n\n/** The roles {@link auditPaletteContrast} measures unless told otherwise. */\nexport const DEFAULT_AUDITED_ROLES: ReadonlyArray<\n PaletteContrastViolation['role']\n> = ['accentText', 'contrastText']\n\n/**\n * Measures whether a palette actually keeps the AGL-1293 promise, rather\n * than trusting that the derivation ran.\n *\n * This is the part that can go RED. `ensureAccessibleShades` only repairs\n * shades it DERIVED — an explicitly authored `primary.dark`, or an accent\n * whose AA bar is simply unreachable in the scheme's foreground direction\n * (walking toward white on a mid-grey page tops out at 3.95:1), passes\n * straight through. Those palettes are exactly the ones a customer can build\n * in the theme editor, so the contract has to be checked, not assumed.\n *\n * Returns every violation with its measured ratio; an empty array means the\n * palette is AA-clean for text.\n */\nexport function auditPaletteContrast(\n palette: Palette | undefined,\n options: AuditPaletteContrastOptions = {},\n): PaletteContrastViolation[] {\n const {\n minContrast = AA_TEXT_CONTRAST,\n colors = AUDITED_COLOR_KEYS,\n includeExempt = false,\n roles = DEFAULT_AUDITED_ROLES,\n } = options\n const measures = (role: PaletteContrastViolation['role']) =>\n roles.includes(role)\n const violations: PaletteContrastViolation[] = []\n /** Records a measured failure unless a documented decision waives it. */\n const record = (violation: PaletteContrastViolation) => {\n const exemption = documentedExemption(\n violation.color,\n violation.role,\n violation.value,\n violation.against,\n )\n if (exemption && !includeExempt) return\n violations.push(exemption ? { ...violation, exemption } : violation)\n }\n if (!palette) return violations\n const indexed = palette as unknown as Record<string, PaletteColor | undefined>\n const backgrounds = [\n palette.background?.default,\n palette.background?.paper,\n ].filter((background): background is string => typeof background === 'string')\n\n for (const key of colors) {\n const color = indexed[key]\n if (!color || typeof color.main !== 'string') continue\n const accent = (color as unknown as Record<string, string>)[\n ACCENT_TEXT_SHADE\n ]\n for (const background of backgrounds) {\n if (!measures('accentText') || typeof accent !== 'string') continue\n try {\n const ratio = contrastRatio(accent, background)\n if (ratio < minContrast) {\n record({\n color: key,\n role: 'accentText',\n value: accent,\n against: background,\n ratio,\n required: minContrast,\n })\n }\n } catch {\n // Unparseable colour (CSS variable, color-mix()): not measurable\n // here. Silence rather than a false violation — the caller audits a\n // resolved palette, not a `vars` mirror.\n }\n }\n if (typeof color.contrastText !== 'string') continue\n if (measures('contrastText')) {\n try {\n const ratio = contrastRatio(color.contrastText, color.main)\n if (ratio < minContrast) {\n record({\n color: key,\n role: 'contrastText',\n value: color.contrastText,\n against: color.main,\n ratio,\n required: minContrast,\n })\n }\n } catch {\n // As above.\n }\n }\n // The same ink, on a surface filled with the accent's TEXT shade. That\n // shade is chosen to be READ ON the page, so in a dark scheme it sits\n // lighter than `main` and cannot carry a light ink — which is invisible\n // to the `contrastText` measure above, because that one only ever looks\n // at `main`.\n if (measures('accentFill') && typeof accent === 'string') {\n try {\n const ratio = contrastRatio(color.contrastText, accent)\n if (ratio < minContrast) {\n record({\n color: key,\n role: 'accentFill',\n value: color.contrastText,\n against: accent,\n ratio,\n required: minContrast,\n })\n }\n } catch {\n // As above.\n }\n }\n }\n return violations\n}\n\n/** Human-readable one-liner per violation, for test output and dev warnings. */\nexport function formatPaletteContrastViolation(\n violation: PaletteContrastViolation,\n): string {\n const measured = `${violation.color}.${violation.role} ${violation.value} on ${\n violation.against\n } is ${violation.ratio.toFixed(2)}:1, below ${violation.required}:1`\n // The waived line still carries its number, so a reader sees what was\n // accepted rather than a bare \"exempt\".\n return violation.exemption\n ? `${measured} — KNOWN EXCEPTION: ${violation.exemption}`\n : measured\n}\n\nexport default accentTextColor\n"],"names":["AA_TEXT_CONTRAST","accessibleShade","contrastRatio","ACCENT_TEXT_SHADE","AA_NON_TEXT_CONTRAST","accentTextColor","theme","color","source","undefined","vars","paletteColor","palette","accent","accentFillColor","minContrast","main","contrastText","DOCUMENTED_CONTRAST_EXCEPTIONS","role","value","against","reason","sameColor","a","b","trim","toLowerCase","documentedExemption","find","exception","AUDITED_COLOR_KEYS","DEFAULT_AUDITED_ROLES","auditPaletteContrast","options","colors","includeExempt","roles","measures","includes","violations","record","violation","exemption","push","indexed","backgrounds","background","default","paper","filter","key","ratio","required","formatPaletteContrastViolation","meas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ACd;QACF;QACA,uEAAuE;QACvE,sEAAsE;QACtE,wEAAwE;QACxE,wEAAwE;QACxE,aAAa;QACb,IAAIuB,SAAS,iBAAiB,OAAOzB,WAAW,UAAU;YACxD,IAAI;gBACF,MAAMuC,QAAQlD,cAAcK,MAAMU,YAAY,EAAEJ;gBAChD,IAAIuC,QAAQrC,aAAa;oBACvB0B,OAAO;wBACLlC,OAAO4C;wBACPhC,MAAM;wBACNC,OAAOb,MAAMU,YAAY;wBACzBI,SAASR;wBACTuC;wBACAC,UAAUtC;oBACZ;gBACF;YACF,EAAE,eAAM;YACN,YAAY;YACd;QACF;IACF;IACA,OAAOyB;AACT;AAEA,8EAA8E,GAC9E,OAAO,SAASc,+BACdZ,SAAmC;IAEnC,MAAMa,WAAW,GAAGb,UAAUnC,KAAK,CAAC,CAAC,EAAEmC,UAAUvB,IAAI,CAAC,CAAC,EAAEuB,UAAUtB,KAAK,CAAC,IAAI,EAC3EsB,UAAUrB,OAAO,CAClB,IAAI,EAAEqB,UAAUU,KAAK,CAACI,OAAO,CAAC,GAAG,UAAU,EAAEd,UAAUW,QAAQ,CAAC,EAAE,CAAC;IACpE,sEAAsE;IACtE,wCAAwC;IACxC,OAAOX,UAAUC,SAAS,GACtB,GAAGY,SAAS,oBAAoB,EAAEb,UAAUC,SAAS,EAAE,GACvDY;AACN;AAEA,eAAelD,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/shared/ui/theme/src/lib/util/accent-text.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n darken,\n decomposeColor,\n hslToRgb,\n lighten,\n rgbToHex,\n type Palette,\n type PaletteColor,\n type Theme,\n} from '../../vendor/mui'\nimport {\n AA_TEXT_CONTRAST,\n accessibleShade,\n contrastRatio,\n relativeLuminance,\n type ShadeDirection,\n} from './accessible-shade'\n\n/**\n * The palette slot that carries \"this accent, rendered AS TEXT on the\n * scheme's own surfaces\" (AGL-1293 / AGL-1297).\n *\n * `dark` is deliberately overloaded rather than a new slot being invented:\n * `ensureAccessibleShades` already guarantees the value of this slot clears\n * {@link AA_TEXT_CONTRAST} against `background.default` and\n * `background.paper` in whichever direction the scheme needs (darker in\n * light, LIGHTER in dark), so every tenant palette carries an accessible\n * value here whether or not its author thought about one. A second slot\n * would have to be whitelisted in `host-theme.ts`, authored per host, and\n * kept in sync — three new ways for a palette to be missing it.\n *\n * `console.theme.ts` authors the shade explicitly for both schemes rather\n * than relying on that repair, so the value a link resolves to is readable\n * in the palette instead of recomputed at boot.\n */\nexport const ACCENT_TEXT_SHADE = 'dark' as const\n\n/** WCAG AA contrast bar for non-text UI (borders, icon fills, indicators). */\nexport const AA_NON_TEXT_CONTRAST = 3\n\n/**\n * The accent-as-text color for `color`, as a value safe to hand to a\n * `styleOverrides` root.\n *\n * Wired into `MuiButton`'s `--variant-textColor` / `--variant-outlinedColor`\n * and `MuiLink`'s `color` in `console.theme.ts`. Those three are the places\n * MUI paints an accent at normal text size, where `main` owes 4.5:1 and the\n * brand blue delivers 2.43:1 on white. Everything that paints the accent as\n * a FILL, a BORDER or an INDICATOR — `--variant-containedBg`,\n * `--variant-outlinedBorder`, the Tabs indicator — keeps `main`: those owe\n * 3:1, and the brand color is meant to be seen there.\n *\n * Returns a CSS variable reference (`var(--mui-palette-primary-dark)`) on a\n * CSS-vars theme and a literal on a single-mode theme. That distinction is\n * load-bearing: `components` are evaluated ONCE against the root theme, so\n * baking a light-scheme literal would freeze it into dark mode.\n *\n * @param theme the active MUI theme (CSS-vars or single-mode)\n * @param color a palette key — `'primary'`, `'error'`, … Anything without a\n * PaletteColor shape (`'inherit'`, `'textPrimary'`, `undefined`) returns\n * `undefined`.\n */\nexport function accentTextColor(\n theme: Theme | undefined,\n color: string | undefined,\n): string | undefined {\n return paletteSlot(theme, color, ACCENT_TEXT_SHADE)\n}\n\n/**\n * One slot of one palette color, as a value safe to hand to a\n * `styleOverrides` root: a `var(--mui-palette-…)` reference on a CSS-vars\n * theme, a literal on a single-mode theme. `undefined` for anything without\n * a PaletteColor shape (`'inherit'`, `'textPrimary'`, `undefined`) or a\n * palette that lacks the slot.\n */\nfunction paletteSlot(\n theme: Theme | undefined,\n color: string | undefined,\n slot: string,\n): string | undefined {\n if (!theme || !color) return undefined\n // `theme.vars` is the CSS-variable mirror of the palette; prefer it so the\n // emitted value is a `var()` that follows the scheme.\n const source = ((theme as unknown as { vars?: { palette?: unknown } }).vars ??\n theme) as { palette?: Record<string, unknown> }\n const paletteColor = source?.palette?.[color] as\n Record<string, string> | undefined\n if (!paletteColor || typeof paletteColor !== 'object') return undefined\n const value = paletteColor[slot]\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * The palette slot that carries \"this accent's FILL under the pointer\": the\n * background a contained Button or a Fab takes on hover, painted under the\n * accent's own `contrastText` (AGL-3465).\n *\n * MUI paints that hover with `palette[color].dark`, and `dark` here is\n * {@link ACCENT_TEXT_SHADE} — chosen to be READ ON the page, so it is LIGHTER\n * than `main` in a dark scheme. A white label on the console's dark-scheme\n * `primary.dark` measures 1.91:1; on the tenant default's `#5e9fe0`,\n * 2.80:1. The fill and the text shade answer different questions, so they\n * get different slots, and `createResponsiveTheme` derives this one for\n * every palette color with a `contrastText` — see {@link hoverFillShade}.\n */\nexport const ACCENT_HOVER_FILL = 'hover' as const\n\n/**\n * The hover fill for `color`, as a value safe to hand to a `styleOverrides`\n * root — the counterpart of {@link accentTextColor}, and resolved the same\n * way: a `var()` on a CSS-vars theme so it follows the scheme, a literal on\n * a single-mode theme. Wired into `MuiButton`'s contained hover and\n * `MuiFab`'s hover in `console.theme.ts`.\n */\nexport function accentHoverFillColor(\n theme: Theme | undefined,\n color: string | undefined,\n): string | undefined {\n return paletteSlot(theme, color, ACCENT_HOVER_FILL)\n}\n\n/**\n * The palette slot that carries \"this accent as TEXT, on its own hover\n * wash\": the label of a hovered text or outlined Button (AGL-3465).\n *\n * MUI hovers those two variants by laying `main` at\n * `palette.action.hoverOpacity` over whatever they sit on, and leaves the\n * label on {@link ACCENT_TEXT_SHADE}. That shade is held to 4.5:1 against\n * the bare page and paper, so one sitting near the bar drops under it the\n * moment the wash lands — the console's light-scheme `primary.dark` goes\n * from 4.54:1 to 4.37:1 on the page. This slot is the same shade walked on\n * until it clears the washed surfaces too, and equals `dark` wherever `dark`\n * already does.\n */\nexport const ACCENT_HOVER_TEXT = 'hoverText' as const\n\n/**\n * The hovered text/outlined label for `color`, resolved like\n * {@link accentTextColor}. Wired into `MuiButton`'s hover in\n * `console.theme.ts`.\n */\nexport function accentHoverTextColor(\n theme: Theme | undefined,\n color: string | undefined,\n): string | undefined {\n return paletteSlot(theme, color, ACCENT_HOVER_TEXT)\n}\n\n/**\n * The smallest contrast ratio between a fill and its hover shade that still\n * reads as a change. Below it the pointer gets no feedback at all — the\n * failure a near-white fill hits when it is lightened.\n */\nconst MIN_HOVER_STEP = 1.1\n\n/**\n * `ink` as it actually renders on `fill`. A `contrastText` such as\n * `#000000DE` is translucent, so the color a reader sees is the blend; the\n * contrast of that blend is the honest number.\n */\nexport function inkOnFill(ink: string, fill: string): string {\n const foreground = rgbChannels(ink)\n const alpha = foreground.type.endsWith('a') ? (foreground.values[3] ?? 1) : 1\n if (alpha >= 1) return ink\n const background = rgbChannels(fill)\n const channels = [0, 1, 2].map((index) =>\n Math.round(\n foreground.values[index] * alpha + background.values[index] * (1 - alpha),\n ),\n )\n return `rgb(${channels.join(', ')})`\n}\n\n/** A color decomposed into 0–255 RGB channels, whatever notation it came in. */\nfunction rgbChannels(color: string) {\n const decomposed = decomposeColor(color)\n return decomposed.type.startsWith('hsl')\n ? decomposeColor(hslToRgb(color))\n : decomposed\n}\n\n/** Contrast of `ink` rendered on `fill`, alpha included. */\nexport function inkContrast(ink: string, fill: string): number {\n return contrastRatio(inkOnFill(ink, fill), fill)\n}\n\n/** How far each further step of the hover-fill walk moves the fill. */\nconst HOVER_WALK_STEP = 0.1\n\n/**\n * The hover fill of one palette color: a shade of `main` that visibly\n * differs from it and still carries `contrastText` at `minContrast`.\n *\n * In order:\n * 1. `dark`, when it already does both. That is MUI's own hover, and every\n * palette whose hover was legible keeps it byte-identical.\n * 2. Otherwise `main` stepped by `tonalOffset` AWAY from the ink — darker\n * under a light label, lighter under a dark one — then walked further\n * the same way until the ink clears the bar. Away from the ink is the\n * one direction in which every step raises the ratio.\n * 3. If that step is too small to see — a fill already at the pole the ink\n * is not, like white under black — `main` stepped TOWARD the ink, as long\n * as the ink still clears the bar there.\n *\n * Throws on an unparseable color; the theme pass that calls it leaves such\n * a palette color without the slot.\n */\nexport function hoverFillShade(\n color: Pick<PaletteColor, 'main' | 'contrastText'> & { dark?: string },\n tonalOffset = 0.3,\n minContrast: number = AA_TEXT_CONTRAST,\n): string {\n const { main, dark, contrastText: ink } = color\n const visible = (fill: string) => contrastRatio(main, fill) >= MIN_HOVER_STEP\n const legible = (fill: string) => inkContrast(ink, fill) >= minContrast\n if (typeof dark === 'string' && visible(dark) && legible(dark)) return dark\n\n const away: ShadeDirection =\n relativeLuminance(inkOnFill(ink, main)) > relativeLuminance(main)\n ? 'darken'\n : 'lighten'\n const shift = (fill: string, direction: ShadeDirection, amount: number) =>\n rgbToHex(\n direction === 'darken' ? darken(fill, amount) : lighten(fill, amount),\n )\n\n let awayFill = shift(main, away, tonalOffset)\n while (!legible(awayFill)) {\n const next = shift(awayFill, away, HOVER_WALK_STEP)\n // At the pole: nothing further exists in this direction.\n if (next === awayFill) break\n awayFill = next\n }\n if (visible(awayFill)) return awayFill\n const towardFill = shift(\n main,\n away === 'darken' ? 'lighten' : 'darken',\n tonalOffset,\n )\n return legible(towardFill) ? towardFill : awayFill\n}\n\n/**\n * The accent shade a FILLED surface can paint under the accent's own ink —\n * the counterpart to {@link accentTextColor}, and a different value for a\n * different question (AGL-2704).\n *\n * {@link ACCENT_TEXT_SHADE} answers \"this accent, READ ON the page\", so it\n * inverts direction per scheme: darker than `main` in light, LIGHTER in\n * dark. That makes it wrong as a fill in exactly one scheme. The console's\n * `primary.dark` is `#0077ad` in light, where white on it measures 4.95:1,\n * and `#4dc8ff` in dark, where the same white measures 1.91:1 — below the\n * 2.43:1 the brand fill it replaced already scored.\n *\n * This shade answers \"this accent, PAINTED UNDER its own `contrastText`\"\n * instead. The constraint is the ink, not the page, so the walk starts at\n * `main` and darkens until the ink clears the bar — and the answer is the\n * SAME in both schemes, which is the property a token reference needs. An\n * `sx` value resolves against whichever scheme is active, so a fill token\n * that only holds in one of them cannot be authored safely.\n *\n * Takes a resolved `Palette`, never `theme.vars`: the walk decomposes real\n * colors, and a CSS-variable mirror hands it `var(--mui-palette-…)`.\n *\n * @param palette a resolved (non-`vars`) palette\n * @param color a palette key — `'primary'`, `'error'`, …\n * @param minContrast the bar the ink must clear. Default\n * {@link AA_TEXT_CONTRAST}.\n */\nexport function accentFillColor(\n palette: Palette | undefined,\n color: string | undefined,\n minContrast: number = AA_TEXT_CONTRAST,\n): string | undefined {\n if (!palette || !color) return undefined\n const paletteColor = (palette as unknown as Record<string, unknown>)[\n color\n ] as Record<string, string> | undefined\n if (!paletteColor || typeof paletteColor !== 'object') return undefined\n const { main, contrastText } = paletteColor\n if (typeof main !== 'string' || typeof contrastText !== 'string') {\n return undefined\n }\n try {\n return accessibleShade(main, [contrastText], 'darken', { minContrast })\n } catch {\n // Unparseable color (a `color()` literal, an unresolved variable). A\n // caller gets nothing rather than a guess, the same as `accentTextColor`.\n return undefined\n }\n}\n\n/** One measured way a palette fails its accessibility contract. */\nexport type PaletteContrastViolation = {\n /** Palette key — `'primary'`, `'error'`, … */\n color: string\n /**\n * `accentText` — the accent painted as text on the scheme's surfaces.\n * `contrastText` — the foreground painted ON that accent.\n * `accentFill` — that same foreground painted on the accent's TEXT shade,\n * i.e. a surface filled with {@link ACCENT_TEXT_SHADE}. Off by default;\n * see {@link AuditPaletteContrastOptions.roles}.\n */\n role: 'accentText' | 'contrastText' | 'accentFill'\n /** The foreground colour that failed. */\n value: string\n /** The background it failed against. */\n against: string\n /** Measured WCAG ratio, 1–21. */\n ratio: number\n /** The bar it had to clear. */\n required: number\n /**\n * Set only when this exact pairing matches a\n * {@link DOCUMENTED_CONTRAST_EXCEPTIONS} entry: the human decision that\n * knowingly accepts the measured ratio. Excluded from the default result;\n * surfaced by `includeExempt`.\n */\n exemption?: string\n}\n\n/**\n * Pairings a human has knowingly SIGNED OFF below the bar — decided, not\n * outstanding.\n *\n * The rest of what {@link auditPaletteContrast} reports is a FINDING: a\n * measurement offered for a decision the account owner owns, not a defect queued for\n * repair. Nothing in this module changes a rendered colour.\n *\n * This is not a suppression list and it must not become one. Each entry pins\n * all four coordinates of one pairing — palette key, role, the exact\n * foreground and the exact background — so it waives a decision, not a slot.\n * Change the brand blue, change the white, or move the same white onto\n * `secondary`, and none of them match: the audit reports it again, which is\n * the point. A new entry needs a named person, a date, their words, and the\n * measured ratio, the same as this one.\n */\nexport const DOCUMENTED_CONTRAST_EXCEPTIONS: ReadonlyArray<{\n color: string\n role: PaletteContrastViolation['role']\n value: string\n against: string\n reason: string\n}> = [\n {\n // AGL-1293. Computing this slot for contrast resolves it to dark ink\n // (8.65:1), which turns every filled primary button dark-on-blue. The\n // tradeoff is to darken the brand or to keep it and accept sub-AA white,\n // and the brand blue is fixed: white on `#00b0ff` is 2.43:1, below the\n // 4.5:1 AA text bar and below the 3:1 non-text bar. Accepted knowingly.\n //\n // This is the ONE decided pairing. Everything else the audit reports —\n // the five other authored sub-AA `contrastText` literals, and `#00b0ff`\n // as text — is a finding, not a waiver, and stays undecided here.\n color: 'primary',\n role: 'contrastText',\n value: '#FFFFFF',\n against: '#00b0ff',\n reason:\n 'AGL-1293 — the brand blue stays as authored, with white text (white on #00b0ff = 2.43:1, knowingly below AA)',\n },\n]\n\n/** Case-insensitive exact colour match; nothing fuzzy, nothing normalised away. */\nfunction sameColor(a: string, b: string) {\n return a.trim().toLowerCase() === b.trim().toLowerCase()\n}\n\n/**\n * The signed-off reason for this exact pairing, or `undefined`. Exact on all\n * four coordinates — a near miss is not a match.\n */\nfunction documentedExemption(\n color: string,\n role: PaletteContrastViolation['role'],\n value: string,\n against: string,\n): string | undefined {\n return DOCUMENTED_CONTRAST_EXCEPTIONS.find(\n (exception) =>\n exception.color === color &&\n exception.role === role &&\n sameColor(exception.value, value) &&\n sameColor(exception.against, against),\n )?.reason\n}\n\nconst AUDITED_COLOR_KEYS = [\n 'primary',\n 'secondary',\n 'tertiary',\n 'error',\n 'warning',\n 'info',\n 'success',\n] as const\n\nexport type AuditPaletteContrastOptions = {\n /** Bar for foreground text. Default {@link AA_TEXT_CONTRAST}. */\n minContrast?: number\n /** Restrict the audit to these palette keys. Default: all accents. */\n colors?: ReadonlyArray<string>\n /**\n * Include pairings matched by {@link DOCUMENTED_CONTRAST_EXCEPTIONS},\n * carrying their `exemption`. Default `false`, so a signed-off decision does\n * not read as an open defect. Pass `true` to see everything measured — the\n * spec that proves the exception is still exactly 2.43:1 uses this, so the\n * waiver documents a number rather than hiding one.\n */\n includeExempt?: boolean\n /**\n * Which roles to measure. Default {@link DEFAULT_AUDITED_ROLES} — the two\n * pairings every palette owes unconditionally.\n *\n * `accentFill` is opt-in because it is a question about a SURFACE, not\n * about the palette: it asks what a fill painted with\n * {@link ACCENT_TEXT_SHADE} does to the accent's own ink. In a dark scheme\n * that shade is lighter than `main` by design, so every accent fails it —\n * correctly, and uselessly for a palette that fills with nothing. Pass it\n * where something actually does (AGL-2704: the marketing pricing page\n * filled a nav CTA and a badge with `primary.dark`, which held in light at\n * 4.95:1 and collapsed to 1.91:1 in dark).\n */\n roles?: ReadonlyArray<PaletteContrastViolation['role']>\n}\n\n/** The roles {@link auditPaletteContrast} measures unless told otherwise. */\nexport const DEFAULT_AUDITED_ROLES: ReadonlyArray<\n PaletteContrastViolation['role']\n> = ['accentText', 'contrastText']\n\n/**\n * Measures whether a palette actually keeps the AGL-1293 promise, rather\n * than trusting that the derivation ran.\n *\n * This is the part that can go RED. `ensureAccessibleShades` only repairs\n * shades it DERIVED — an explicitly authored `primary.dark`, or an accent\n * whose AA bar is simply unreachable in the scheme's foreground direction\n * (walking toward white on a mid-grey page tops out at 3.95:1), passes\n * straight through. Those palettes are exactly the ones a customer can build\n * in the theme editor, so the contract has to be checked, not assumed.\n *\n * Returns every violation with its measured ratio; an empty array means the\n * palette is AA-clean for text.\n */\nexport function auditPaletteContrast(\n palette: Palette | undefined,\n options: AuditPaletteContrastOptions = {},\n): PaletteContrastViolation[] {\n const {\n minContrast = AA_TEXT_CONTRAST,\n colors = AUDITED_COLOR_KEYS,\n includeExempt = false,\n roles = DEFAULT_AUDITED_ROLES,\n } = options\n const measures = (role: PaletteContrastViolation['role']) =>\n roles.includes(role)\n const violations: PaletteContrastViolation[] = []\n /** Records a measured failure unless a documented decision waives it. */\n const record = (violation: PaletteContrastViolation) => {\n const exemption = documentedExemption(\n violation.color,\n violation.role,\n violation.value,\n violation.against,\n )\n if (exemption && !includeExempt) return\n violations.push(exemption ? { ...violation, exemption } : violation)\n }\n if (!palette) return violations\n const indexed = palette as unknown as Record<string, PaletteColor | undefined>\n const backgrounds = [\n palette.background?.default,\n palette.background?.paper,\n ].filter((background): background is string => typeof background === 'string')\n\n for (const key of colors) {\n const color = indexed[key]\n if (!color || typeof color.main !== 'string') continue\n const accent = (color as unknown as Record<string, string>)[\n ACCENT_TEXT_SHADE\n ]\n for (const background of backgrounds) {\n if (!measures('accentText') || typeof accent !== 'string') continue\n try {\n const ratio = contrastRatio(accent, background)\n if (ratio < minContrast) {\n record({\n color: key,\n role: 'accentText',\n value: accent,\n against: background,\n ratio,\n required: minContrast,\n })\n }\n } catch {\n // Unparseable colour (CSS variable, color-mix()): not measurable\n // here. Silence rather than a false violation — the caller audits a\n // resolved palette, not a `vars` mirror.\n }\n }\n if (typeof color.contrastText !== 'string') continue\n if (measures('contrastText')) {\n try {\n const ratio = contrastRatio(color.contrastText, color.main)\n if (ratio < minContrast) {\n record({\n color: key,\n role: 'contrastText',\n value: color.contrastText,\n against: color.main,\n ratio,\n required: minContrast,\n })\n }\n } catch {\n // As above.\n }\n }\n // The same ink, on a surface filled with the accent's TEXT shade. That\n // shade is chosen to be READ ON the page, so in a dark scheme it sits\n // lighter than `main` and cannot carry a light ink — which is invisible\n // to the `contrastText` measure above, because that one only ever looks\n // at `main`.\n if (measures('accentFill') && typeof accent === 'string') {\n try {\n const ratio = contrastRatio(color.contrastText, accent)\n if (ratio < minContrast) {\n record({\n color: key,\n role: 'accentFill',\n value: color.contrastText,\n against: accent,\n ratio,\n required: minContrast,\n })\n }\n } catch {\n // As above.\n }\n }\n }\n return violations\n}\n\n/** Human-readable one-liner per violation, for test output and dev warnings. */\nexport function formatPaletteContrastViolation(\n violation: PaletteContrastViolation,\n): string {\n const measured = `${violation.color}.${violation.role} ${violation.value} on ${\n violation.against\n } is ${violation.ratio.toFixed(2)}:1, below ${violation.required}:1`\n // The waived line still carries its number, so a reader sees what was\n // accepted rather than a bare \"exempt\".\n return violation.exemption\n ? `${measured} — KNOWN EXCEPTION: ${violation.exemption}`\n : measured\n}\n\nexport default accentTextColor\n"],"names":["darken","decomposeColor","hslToRgb","lighten","rgbToHex","AA_TEXT_CONTRAST","accessibleShade","contrastRatio","relativeLuminance","ACCENT_TEXT_SHADE","AA_NON_TEXT_CONTRAST","accentTextColor","theme","color","paletteSlot","slot","source","undefined","vars","paletteColor","palette","value","ACCENT_HOVER_FILL","accentHoverFillColor","ACCENT_HOVER_TEXT","accentHoverTextColor","MIN_HOVER_STEP","inkOnFill","ink","fill","foreground","rgbChannels","alpha","type","endsWith","values","background","channels","map","index","Math","round","join","decomposed","startsWith","inkContrast","HOVER_WALK_STEP","hoverFillShade","tonalOffset","minContrast","main","dark","contrastText","visible","legible","away","shift","direction","amount","awayFill","next","towardFill","accentFillColor","DOCUMENTED_CONTRAST_EXCEPTIONS","role","against","reason","sameColor","a","b","trim","toLowerCase","documentedExemption","find","exception","AUDITED_COLOR_KEYS","DEFAULT_AUDITED_ROLES","auditPaletteContrast","options","colors","includeExempt","roles","measures","includes","violations","record","violation","exemption","push","indexed","backgrounds","default","paper","filter","key","accent","ratio","required","formatPaletteContrastViolation","measured","toFixed"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,MAAM,EACNC,cAAc,EACdC,QAAQ,EACRC,OAAO,EACPC,QAAQ,QAIH,sBAAkB;AACzB,SACEC,gBAAgB,EAChBC,eAAe,EACfC,aAAa,EACbC,iBAAiB,QAEZ,wBAAoB;AAE3B;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,MAAMC,oBAAoB,OAAe;AAEhD,4EAA4E,GAC5E,OAAO,MAAMC,uBAAuB,EAAC;AAErC;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,SAASC,gBACdC,KAAwB,EACxBC,KAAyB;IAEzB,OAAOC,YAAYF,OAAOC,OAAOJ;AACnC;AAEA;;;;;;CAMC,GACD,SAASK,YACPF,KAAwB,EACxBC,KAAyB,EACzBE,IAAY;QAKI;QAEKC;IALrB,IAAI,CAACJ,SAAS,CAACC,OAAO,OAAOI;IAC7B,2EAA2E;IAC3E,sDAAsD;IACtD,MAAMD,UAAU,cAAA,AAACJ,MAAsDM,IAAI,YAA3D,cACdN;IACF,MAAMO,eAAeH,2BAAAA,kBAAAA,OAAQI,OAAO,qBAAfJ,eAAiB,CAACH,MAAM;IAE7C,IAAI,CAACM,gBAAgB,OAAOA,iBAAiB,UAAU,OAAOF;IAC9D,MAAMI,QAAQF,YAAY,CAACJ,KAAK;IAChC,OAAO,OAAOM,UAAU,WAAWA,QAAQJ;AAC7C;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO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IAAI8C,QAAQ/C,aAAa;oBACvBoC,OAAO;wBACLxE,OAAOiF;wBACP9B,MAAM;wBACN3C,OAAOR,MAAMuC,YAAY;wBACzBa,SAASpD,MAAMqC,IAAI;wBACnB8C;wBACAC,UAAUhD;oBACZ;gBACF;YACF,EAAE,eAAM;YACN,YAAY;YACd;QACF;QACA,uEAAuE;QACvE,sEAAsE;QACtE,wEAAwE;QACxE,wEAAwE;QACxE,aAAa;QACb,IAAIiC,SAAS,iBAAiB,OAAOa,WAAW,UAAU;YACxD,IAAI;gBACF,MAAMC,QAAQzF,cAAcM,MAAMuC,YAAY,EAAE2C;gBAChD,IAAIC,QAAQ/C,aAAa;oBACvBoC,OAAO;wBACLxE,OAAOiF;wBACP9B,MAAM;wBACN3C,OAAOR,MAAMuC,YAAY;wBACzBa,SAAS8B;wBACTC;wBACAC,UAAUhD;oBACZ;gBACF;YACF,EAAE,eAAM;YACN,YAAY;YACd;QACF;IACF;IACA,OAAOmC;AACT;AAEA,8EAA8E,GAC9E,OAAO,SAASc,+BACdZ,SAAmC;IAEnC,MAAMa,WAAW,GAAGb,UAAUzE,KAAK,CAAC,CAAC,EAAEyE,UAAUtB,IAAI,CAAC,CAAC,EAAEsB,UAAUjE,KAAK,CAAC,IAAI,EAC3EiE,UAAUrB,OAAO,CAClB,IAAI,EAAEqB,UAAUU,KAAK,CAACI,OAAO,CAAC,GAAG,UAAU,EAAEd,UAAUW,QAAQ,CAAC,EAAE,CAAC;IACpE,sEAAsE;IACtE,wCAAwC;IACxC,OAAOX,UAAUC,SAAS,GACtB,GAAGY,SAAS,oBAAoB,EAAEb,UAAUC,SAAS,EAAE,GACvDY;AACN;AAEA,eAAexF,gBAAe"}
|
|
@@ -16,7 +16,8 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
|
|
|
16
16
|
* See the License for the specific language governing permissions and
|
|
17
17
|
* limitations under the License.
|
|
18
18
|
*/ import { extendTheme as muiExtendTheme } from "@mui/material/styles";
|
|
19
|
-
import { createTheme, darken, getContrastRatio, lighten, responsiveFontSizes } from "../../vendor/mui.js";
|
|
19
|
+
import { alpha, createTheme, darken, getContrastRatio, lighten, responsiveFontSizes } from "../../vendor/mui.js";
|
|
20
|
+
import { ACCENT_HOVER_FILL, ACCENT_HOVER_TEXT, hoverFillShade, inkOnFill } from "./accent-text.js";
|
|
20
21
|
import { accessibleShade, contrastRatio, meetsContrast } from "./accessible-shade.js";
|
|
21
22
|
var ContrastText = /*#__PURE__*/ function(ContrastText) {
|
|
22
23
|
ContrastText["LIGHT"] = "rgba(0, 0, 0, 0.87)";
|
|
@@ -152,6 +153,65 @@ function addShadeVariants(paletteColor, tonalOffset) {
|
|
|
152
153
|
}
|
|
153
154
|
}
|
|
154
155
|
}
|
|
156
|
+
/**
|
|
157
|
+
* Post-`createTheme` pass giving every palette color a defined HOVER
|
|
158
|
+
* (AGL-3465): `palette[color].hover`, the fill ({@link ACCENT_HOVER_FILL}),
|
|
159
|
+
* and `palette[color].hoverText`, the label ({@link ACCENT_HOVER_TEXT}).
|
|
160
|
+
* The `MuiButton` and `MuiFab` overrides read both.
|
|
161
|
+
*
|
|
162
|
+
* - **The fill.** MUI fills a hovered contained Button and Fab with
|
|
163
|
+
* `palette[color].dark`, which this theme uses as the accent-as-TEXT
|
|
164
|
+
* shade: lighter than `main` in a dark scheme, so a white label on it
|
|
165
|
+
* sinks to ~2:1. Every entry with a string `main` and `contrastText` gets
|
|
166
|
+
* one — the built-in accents, `tertiary`, `surface`, and any custom color
|
|
167
|
+
* a palette adds — so a color a component can be asked to wear always has
|
|
168
|
+
* a hover that carries its own ink at AA.
|
|
169
|
+
* - **The label.** A hovered text or outlined Button keeps `dark` as its
|
|
170
|
+
* label and lays `main` at `action.hoverOpacity` under it. Foreground
|
|
171
|
+
* colors get `dark` walked in the scheme's foreground direction until it
|
|
172
|
+
* clears AA on that wash over both `background.default` and
|
|
173
|
+
* `background.paper`; it stays `dark`, byte-identical, wherever `dark`
|
|
174
|
+
* already does. `surface` gets none: its `dark` is a surface step, not
|
|
175
|
+
* text, so it has no label to protect.
|
|
176
|
+
*
|
|
177
|
+
* A slot the caller authored passes through untouched.
|
|
178
|
+
*/ function ensureHoverShades(theme, inputPalette) {
|
|
179
|
+
var _ref;
|
|
180
|
+
var _theme_palette_background, _theme_palette_background1, _theme_palette_action;
|
|
181
|
+
const palette = theme.palette;
|
|
182
|
+
const providedColors = inputPalette;
|
|
183
|
+
const tonalOffsetDark = resolveTonalOffsets(theme.palette.tonalOffset).dark;
|
|
184
|
+
const foregroundDirection = theme.palette.mode === 'dark' ? 'lighten' : 'darken';
|
|
185
|
+
const backgrounds = [
|
|
186
|
+
(_theme_palette_background = theme.palette.background) == null ? void 0 : _theme_palette_background.default,
|
|
187
|
+
(_theme_palette_background1 = theme.palette.background) == null ? void 0 : _theme_palette_background1.paper
|
|
188
|
+
].filter((background)=>typeof background === 'string');
|
|
189
|
+
const hoverOpacity = (_ref = (_theme_palette_action = theme.palette.action) == null ? void 0 : _theme_palette_action.hoverOpacity) != null ? _ref : 0;
|
|
190
|
+
for (const [key, value] of Object.entries(palette)){
|
|
191
|
+
var _ref1;
|
|
192
|
+
if (!value || typeof value !== 'object') continue;
|
|
193
|
+
const color = value;
|
|
194
|
+
const { main, dark, contrastText } = color;
|
|
195
|
+
if (typeof main !== 'string' || typeof contrastText !== 'string') continue;
|
|
196
|
+
const provided = (_ref1 = providedColors == null ? void 0 : providedColors[key]) != null ? _ref1 : {};
|
|
197
|
+
try {
|
|
198
|
+
if (typeof provided[ACCENT_HOVER_FILL] !== 'string') {
|
|
199
|
+
color[ACCENT_HOVER_FILL] = hoverFillShade({
|
|
200
|
+
main,
|
|
201
|
+
contrastText,
|
|
202
|
+
dark: typeof dark === 'string' ? dark : undefined
|
|
203
|
+
}, tonalOffsetDark);
|
|
204
|
+
}
|
|
205
|
+
if (typeof provided[ACCENT_HOVER_TEXT] !== 'string' && FOREGROUND_COLOR_KEYS.includes(key) && typeof dark === 'string' && backgrounds.length) {
|
|
206
|
+
const wash = alpha(main, hoverOpacity);
|
|
207
|
+
color[ACCENT_HOVER_TEXT] = accessibleShade(dark, backgrounds.map((background)=>inkOnFill(wash, background)), foregroundDirection);
|
|
208
|
+
}
|
|
209
|
+
} catch (unused) {
|
|
210
|
+
// Unparseable colour (CSS variable, color-mix()): no slot, so the
|
|
211
|
+
// component overrides fall back to MUI's own hover for this color.
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
155
215
|
/**
|
|
156
216
|
* MUI's own default `responsiveFontSizes` variant list, spelled out because
|
|
157
217
|
* passing `variants` replaces it rather than extending it.
|
|
@@ -238,6 +298,9 @@ function addShadeVariants(paletteColor, tonalOffset) {
|
|
|
238
298
|
// Scheme- and AA-aware repair of DERIVED shades only (AGL-1297); explicit
|
|
239
299
|
// palette values pass through byte-identical.
|
|
240
300
|
ensureAccessibleShades(theme, themeOptions == null ? void 0 : themeOptions.palette);
|
|
301
|
+
// After the shade repair, because both hover slots start from `dark` and
|
|
302
|
+
// have to see the value that ships.
|
|
303
|
+
ensureHoverShades(theme, themeOptions == null ? void 0 : themeOptions.palette);
|
|
241
304
|
theme = responsiveFontSizes(theme, _extends({
|
|
242
305
|
// Override to include `xs` and `xl` - default: ['sm', 'md', 'lg']
|
|
243
306
|
breakpoints: [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/shared/ui/theme/src/lib/util/create-responsive-theme.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2024 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CssVarsThemeOptions,\n extendTheme as muiExtendTheme,\n} from '@mui/material/styles'\nimport {\n createTheme,\n darken,\n getContrastRatio,\n lighten,\n type PaletteColor,\n type PaletteOptions,\n responsiveFontSizes,\n type Theme,\n type ThemeOptions,\n} from '../../vendor/mui'\nimport {\n accessibleShade,\n contrastRatio,\n meetsContrast,\n type ShadeDirection,\n} from './accessible-shade'\n\nenum ContrastText {\n LIGHT = 'rgba(0, 0, 0, 0.87)',\n DARK = '#FFFFFF',\n}\n\ntype TonalOffset = number | { light?: number; dark?: number }\n\nfunction resolveTonalOffsets(tonalOffset: TonalOffset | undefined) {\n const offsetObj = typeof tonalOffset === 'number' ? undefined : tonalOffset\n const offsetNum = typeof tonalOffset === 'number' ? tonalOffset : undefined\n return {\n light: offsetObj?.light ?? offsetNum ?? 0.2,\n dark: offsetObj?.dark ?? (offsetNum ?? 0.2) * 1.5,\n }\n}\n\nfunction getContrastTextColor(background: string, contrastThreshold: number) {\n return getContrastRatio(background, ContrastText.DARK) >= (contrastThreshold ?? 3)\n ? ContrastText.DARK\n : ContrastText.LIGHT\n}\nfunction addShade(paletteColor: PaletteColor, shade: string, variant: string | undefined, tonalOffset: TonalOffset) {\n // Custom palette colors (tertiary, surface) are optional in host themes.\n if (!paletteColor?.main) return\n const { light: tonalOffsetLight, dark: tonalOffsetDark } =\n resolveTonalOffsets(tonalOffset)\n const indexed = paletteColor as unknown as Record<string, string>\n\n if (!indexed[shade]) {\n // eslint-disable-next-line no-prototype-builtins\n if (paletteColor.hasOwnProperty(variant)) {\n indexed[shade] = indexed[variant]\n } else if (shade === 'light') {\n paletteColor.light = lighten(paletteColor.main, tonalOffsetLight)\n } else if (shade === 'dark') {\n paletteColor.dark = darken(paletteColor.main, tonalOffsetDark)\n } else if (shade === 'contrastText') {\n paletteColor.contrastText = getContrastTextColor(\n paletteColor.main,\n tonalOffsetDark,\n )\n }\n }\n}\nfunction addShadeVariants(paletteColor: PaletteColor, tonalOffset?: TonalOffset) {\n addShade(paletteColor, 'dark', undefined, tonalOffset)\n addShade(paletteColor, 'light', undefined, tonalOffset)\n addShade(paletteColor, 'contrastText', undefined, tonalOffset)\n}\n\n/**\n * Colour families whose shades act as FOREGROUNDS — the `dark` slot carries\n * \"accessible accent text\" (AGL-1293 put the marketing brand blue there), so\n * its derivation must clear AA against the scheme's real backgrounds.\n *\n * `surface` is deliberately absent: its `light`/`dark` are surface STEPS\n * (panel fills, borders — see the designer's box styler), and walking them to\n * text contrast would repaint layout chrome, not fix any text.\n */\nconst FOREGROUND_COLOR_KEYS = [\n 'primary',\n 'secondary',\n 'tertiary',\n 'error',\n 'warning',\n 'info',\n 'success',\n] as const\n\n/** `contrastText` IS a text pairing wherever it lives, so `surface` joins here. */\nconst CONTRAST_TEXT_COLOR_KEYS = [...FOREGROUND_COLOR_KEYS, 'surface'] as const\n\n/**\n * Post-`createTheme` pass making DERIVED shades scheme- and AA-aware\n * (AGL-1297). Fixed tonal offsets derive `dark = darken(main, 0.3)` no\n * matter the scheme, which (a) misses 4.5:1 on real off-white surfaces and\n * (b) points the wrong way entirely in dark mode, where the accessible\n * direction for a foreground shade is LIGHTER.\n *\n * Invariants:\n * - Only slots ABSENT from the caller's `palette` input are ever touched;\n * an explicitly authored shade passes through byte-identical (the\n * marketing host's hand-set `primary.dark` values depend on this).\n * - A derived value that already clears 4.5:1 against both\n * `background.default` and `background.paper` is kept byte-identical, so\n * themes that were fine yesterday do not shift.\n * - A failing derived `dark` is re-seeded at the tonal offset from `main`\n * in the scheme's foreground direction (darken in light, lighten in\n * dark), then walked in HSL lightness until it clears the bar.\n * - A light-scheme `light` is a background TINT — its ramp direction points\n * away from the text bar by design — so it keeps the tonal derivation.\n * In dark schemes `light` is foreground-capable and gets the same walk.\n * - Derived `contrastText` keeps the threshold choice unless that pairing\n * is below 4.5:1 against `main`; then it walks toward the pole with more\n * contrast headroom.\n */\nfunction ensureAccessibleShades(\n theme: Theme,\n inputPalette: PaletteOptions | undefined,\n) {\n const { palette } = theme\n const backgrounds = [\n palette.background?.default,\n palette.background?.paper,\n ].filter((background): background is string => typeof background === 'string')\n if (!backgrounds.length) return\n const mode: 'light' | 'dark' = palette.mode === 'dark' ? 'dark' : 'light'\n const foregroundDirection: ShadeDirection =\n mode === 'dark' ? 'lighten' : 'darken'\n const tonalOffsetDark = resolveTonalOffsets(palette.tonalOffset).dark\n const providedColors = inputPalette as\n | Record<string, unknown>\n | undefined\n\n for (const key of CONTRAST_TEXT_COLOR_KEYS) {\n const color = (palette as unknown as Record<string, PaletteColor>)[key]\n if (!color || typeof color.main !== 'string') continue\n const provided = providedColors?.[key]\n // A ColorPartial ramp (`{ 50…900 }`) is an author-owned scale — MUI maps\n // its shades straight across, so nothing in it counts as derived.\n if (provided && typeof provided === 'object' && !('main' in provided)) {\n continue\n }\n // Read with brackets, not dots: these keys come from an index signature,\n // and `json-editor` compiles this file under\n // `noPropertyAccessFromIndexSignature` (paths resolve to source, so a\n // consumer's flags check its dependencies). Dot access reds that build\n // while this project's own stays green — AGL-1323.\n const explicit = (provided ?? {}) as Record<string, unknown>\n const isForeground = (FOREGROUND_COLOR_KEYS as readonly string[]).includes(\n key,\n )\n\n try {\n if (\n isForeground &&\n !explicit['dark'] &&\n typeof color.dark === 'string' &&\n !meetsContrast(color.dark, backgrounds)\n ) {\n const seed =\n mode === 'dark' ? lighten(color.main, tonalOffsetDark) : color.dark\n color.dark = accessibleShade(seed, backgrounds, foregroundDirection)\n }\n if (\n isForeground &&\n mode === 'dark' &&\n !explicit['light'] &&\n typeof color.light === 'string' &&\n !meetsContrast(color.light, backgrounds)\n ) {\n color.light = accessibleShade(color.light, backgrounds, 'lighten')\n }\n if (\n !explicit['contrastText'] &&\n typeof color.contrastText === 'string' &&\n !meetsContrast(color.contrastText, [color.main])\n ) {\n const textDirection: ShadeDirection =\n contrastRatio('#fff', color.main) >= contrastRatio('#000', color.main)\n ? 'lighten'\n : 'darken'\n color.contrastText = accessibleShade(\n color.contrastText,\n [color.main],\n textDirection,\n )\n }\n } catch {\n // Unparseable colour (CSS variable, color-mix()): leave the derived\n // value alone rather than failing theme creation.\n }\n }\n}\n\n/**\n * MUI's own default `responsiveFontSizes` variant list, spelled out because\n * passing `variants` replaces it rather than extending it.\n */\nconst RAMPED_MUI_VARIANTS = [\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'subtitle1',\n 'subtitle2',\n 'body1',\n 'body2',\n 'caption',\n 'button',\n 'overline',\n] as const\n\n/**\n * The brand's custom display rungs, which MUI cannot know about.\n *\n * Only variants whose size genuinely needs to shrink belong here. `lede`,\n * `bodyCompact` and `micro` are body-scale text that reads the same at every\n * width and are deliberately absent.\n */\nconst RAMPED_DISPLAY_VARIANTS = ['displayXl'] as const\n\nexport type CreateResponsiveThemeOptions = {\n themeOptions?: ThemeOptions\n responsiveFontSizesOptions?: Parameters<typeof responsiveFontSizes>[1]\n}\n\n/**\n * START EXAMPLE – OVERRIDE DEFAULT PROPS ↓\n * ⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄\n * ```typescript\n * const theme = createMuiTheme({\n * props: {\n * // Name of the component ⚛️\n * MuiButtonBase: {\n * // The default props to change\n * disableRipple: true, // No more ripple, on the whole application 💣!\n * },\n * },\n * })\n * ```\n * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n * END EXAMPLE – OVERRIDE DEFAULT PROPS ↑\n *\n * START EXAMPLE – OVERRIDE DEFAULT STYLES ↓\n * ⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄\n * ```typescript\n * const theme = createMuiTheme({\n * overrides: {\n * // Style sheet name ⚛️\n * MuiButton: {\n * // Name of the rule\n * text: {\n * // Some CSS\n * color: 'white',\n * },\n * },\n * MuiCssBaseline: {\n * '@global': {\n * html: {\n * WebkitFontSmoothing: 'auto',\n * },\n * },\n * },\n * },\n * })\n * ```\n * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n * END EXAMPLE – OVERRIDE DEFAULT STYLES ↑\n *\n * @param {ThemeOptions} options\n * @returns {Theme}\n */\nexport function createResponsiveTheme(\n options: CreateResponsiveThemeOptions,\n): Theme {\n const { themeOptions, responsiveFontSizesOptions } = options\n let theme = createTheme(themeOptions)\n addShadeVariants(theme.palette.tertiary, theme.palette.tonalOffset)\n addShadeVariants(theme.palette.surface, theme.palette.tonalOffset)\n // `tint` is deliberately absent from BOTH shade passes (AGL-1244). It is a\n // group of string leaves rather than a PaletteColor — no `main` to ramp\n // from, no `contrastText` to pair — so `addShadeVariants` would no-op and\n // `ensureAccessibleShades` (which keys off `CONTRAST_TEXT_COLOR_KEYS`) never\n // sees it. Both correct: a 90%-desaturated wash is authored, not derived,\n // and walking it to a text-contrast bar would repaint the fill.\n // Scheme- and AA-aware repair of DERIVED shades only (AGL-1297); explicit\n // palette values pass through byte-identical.\n ensureAccessibleShades(theme, themeOptions?.palette)\n\n theme = responsiveFontSizes(theme, {\n // Override to include `xs` and `xl` - default: ['sm', 'md', 'lg']\n breakpoints: ['xs', 'sm', 'md', 'lg', 'xl'],\n // MUI only ramps the variants it ships, so a CUSTOM display variant would\n // keep its desktop size on a phone — `displayXl` at 72px on a 375px\n // screen. Passing `variants` REPLACES MUI's default list, so the defaults\n // are spelled out here and ours appended; drop one and that variant\n // silently stops scaling.\n variants: [...RAMPED_MUI_VARIANTS, ...RAMPED_DISPLAY_VARIANTS],\n ...responsiveFontSizesOptions,\n })\n\n return theme\n}\n\nexport function createResponsiveCssVarTheme(\n light: Theme,\n dark: Theme,\n options?: CssVarsThemeOptions,\n) {\n const { palette: lightPalette, ...lightTheme } = light\n const { palette: darkPalette } = dark\n\n return muiExtendTheme({\n ...lightTheme,\n // Allow setMode() to work by driving the color scheme via a CSS class on\n // <html> instead of the OS-level @media query (the default 'media' selector\n // makes setMode() a no-op because media queries can't be overridden in JS).\n colorSchemeSelector: 'class',\n ...options,\n colorSchemes: {\n ...options?.colorSchemes,\n light: { palette: lightPalette, ...((options?.colorSchemes?.light ?? {}) as object) },\n dark: { palette: darkPalette, ...((options?.colorSchemes?.dark ?? {}) as object) },\n },\n })\n}\n\nexport default createResponsiveTheme\n"],"names":["extendTheme","muiExtendTheme","createTheme","darken","getContrastRatio","lighten","responsiveFontSizes","accessibleShade","contrastRatio","meetsContrast","ContrastText","resolveTonalOffsets","tonalOffset","offsetObj","undefined","offsetNum","light","dark","getContrastTextColor","background","contrastThreshold","addShade","paletteColor","shade","variant","main","tonalOffsetLight","tonalOffsetDark","indexed","hasOwnProperty","contrastText","addShadeVariants","FOREGROUND_COLOR_KEYS","CONTRAST_TEXT_COLOR_KEYS","ensureAccessibleShades","theme","inputPalette","palette","backgrounds","default","paper","filter","length","mode","foregroundDirection","providedColors","key","color","provided","explicit","isForeground","includes","seed","textDirection","RAMPED_MUI_VARIANTS","RAMPED_DISPLAY_VARIANTS","createResponsiveTheme","options","themeOptions","responsiveFontSizesOptions","tertiary","surface","breakpoints","variants","createResponsiveCssVarTheme","lightPalette","lightTheme","darkPalette","colorSchemeSelector","colorSchemes"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,eAAeC,cAAc,QACxB,uBAAsB;AAC7B,SACEC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,OAAO,EAGPC,mBAAmB,QAGd,sBAAkB;AACzB,SACEC,eAAe,EACfC,aAAa,EACbC,aAAa,QAER,wBAAoB;AAE3B,IAAA,AAAKC,sCAAAA;;;WAAAA;EAAAA;AAOL,SAASC,oBAAoBC,WAAoC;QAItDC;IAHT,MAAMA,YAAY,OAAOD,gBAAgB,WAAWE,YAAYF;IAChE,MAAMG,YAAY,OAAOH,gBAAgB,WAAWA,cAAcE;IAClE,OAAO;QACLE,KA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0E;IAC1E,gEAAgE;IAChE,0EAA0E;IAC1E,8CAA8C;IAC9CsB,uBAAuBC,OAAOuB,gCAAAA,aAAcrB,OAAO;IAEnDF,QAAQ7B,oBAAoB6B,OAAO;QACjC,kEAAkE;QAClE2B,aAAa;YAAC;YAAM;YAAM;YAAM;YAAM;SAAK;QAC3C,0EAA0E;QAC1E,oEAAoE;QACpE,0EAA0E;QAC1E,oEAAoE;QACpE,0BAA0B;QAC1BC,UAAU;eAAIT;eAAwBC;SAAwB;OAC3DI;IAGL,OAAOxB;AACT;AAEA,OAAO,SAAS6B,4BACdhD,KAAY,EACZC,IAAW,EACXwC,OAA6B;;QAcYA,uBACFA;IAbvC,MAAM,EAAEpB,SAAS4B,YAAY,EAAiB,GAAGjD,OAAfkD,8CAAelD;;;IACjD,MAAM,EAAEqB,SAAS8B,WAAW,EAAE,GAAGlD;IAEjC,OAAOhB,eAAe,aACjBiE;QACH,yEAAyE;QACzE,4EAA4E;QAC5E,4EAA4E;QAC5EE,qBAAqB;OAClBX;QACHY,cAAc,aACTZ,2BAAAA,QAASY,YAAY;YACxBrD,OAAO;gBAAEqB,SAAS4B;uBAAmBR,4BAAAA,wBAAAA,QAASY,YAAY,qBAArBZ,sBAAuBzC,KAAK,mBAAI,CAAC;YACtEC,MAAM;gBAAEoB,SAAS8B;wBAAkBV,4BAAAA,yBAAAA,QAASY,YAAY,qBAArBZ,uBAAuBxC,IAAI,oBAAI,CAAC;;;AAGzE;AAEA,eAAeuC,sBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/shared/ui/theme/src/lib/util/create-responsive-theme.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2024 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CssVarsThemeOptions,\n extendTheme as muiExtendTheme,\n} from '@mui/material/styles'\nimport {\n alpha,\n createTheme,\n darken,\n getContrastRatio,\n lighten,\n type PaletteColor,\n type PaletteOptions,\n responsiveFontSizes,\n type Theme,\n type ThemeOptions,\n} from '../../vendor/mui'\nimport {\n ACCENT_HOVER_FILL,\n ACCENT_HOVER_TEXT,\n hoverFillShade,\n inkOnFill,\n} from './accent-text'\nimport {\n accessibleShade,\n contrastRatio,\n meetsContrast,\n type ShadeDirection,\n} from './accessible-shade'\n\nenum ContrastText {\n LIGHT = 'rgba(0, 0, 0, 0.87)',\n DARK = '#FFFFFF',\n}\n\ntype TonalOffset = number | { light?: number; dark?: number }\n\nfunction resolveTonalOffsets(tonalOffset: TonalOffset | undefined) {\n const offsetObj = typeof tonalOffset === 'number' ? undefined : tonalOffset\n const offsetNum = typeof tonalOffset === 'number' ? tonalOffset : undefined\n return {\n light: offsetObj?.light ?? offsetNum ?? 0.2,\n dark: offsetObj?.dark ?? (offsetNum ?? 0.2) * 1.5,\n }\n}\n\nfunction getContrastTextColor(background: string, contrastThreshold: number) {\n return getContrastRatio(background, ContrastText.DARK) >= (contrastThreshold ?? 3)\n ? ContrastText.DARK\n : ContrastText.LIGHT\n}\nfunction addShade(paletteColor: PaletteColor, shade: string, variant: string | undefined, tonalOffset: TonalOffset) {\n // Custom palette colors (tertiary, surface) are optional in host themes.\n if (!paletteColor?.main) return\n const { light: tonalOffsetLight, dark: tonalOffsetDark } =\n resolveTonalOffsets(tonalOffset)\n const indexed = paletteColor as unknown as Record<string, string>\n\n if (!indexed[shade]) {\n // eslint-disable-next-line no-prototype-builtins\n if (paletteColor.hasOwnProperty(variant)) {\n indexed[shade] = indexed[variant]\n } else if (shade === 'light') {\n paletteColor.light = lighten(paletteColor.main, tonalOffsetLight)\n } else if (shade === 'dark') {\n paletteColor.dark = darken(paletteColor.main, tonalOffsetDark)\n } else if (shade === 'contrastText') {\n paletteColor.contrastText = getContrastTextColor(\n paletteColor.main,\n tonalOffsetDark,\n )\n }\n }\n}\nfunction addShadeVariants(paletteColor: PaletteColor, tonalOffset?: TonalOffset) {\n addShade(paletteColor, 'dark', undefined, tonalOffset)\n addShade(paletteColor, 'light', undefined, tonalOffset)\n addShade(paletteColor, 'contrastText', undefined, tonalOffset)\n}\n\n/**\n * Colour families whose shades act as FOREGROUNDS — the `dark` slot carries\n * \"accessible accent text\" (AGL-1293 put the marketing brand blue there), so\n * its derivation must clear AA against the scheme's real backgrounds.\n *\n * `surface` is deliberately absent: its `light`/`dark` are surface STEPS\n * (panel fills, borders — see the designer's box styler), and walking them to\n * text contrast would repaint layout chrome, not fix any text.\n */\nconst FOREGROUND_COLOR_KEYS = [\n 'primary',\n 'secondary',\n 'tertiary',\n 'error',\n 'warning',\n 'info',\n 'success',\n] as const\n\n/** `contrastText` IS a text pairing wherever it lives, so `surface` joins here. */\nconst CONTRAST_TEXT_COLOR_KEYS = [...FOREGROUND_COLOR_KEYS, 'surface'] as const\n\n/**\n * Post-`createTheme` pass making DERIVED shades scheme- and AA-aware\n * (AGL-1297). Fixed tonal offsets derive `dark = darken(main, 0.3)` no\n * matter the scheme, which (a) misses 4.5:1 on real off-white surfaces and\n * (b) points the wrong way entirely in dark mode, where the accessible\n * direction for a foreground shade is LIGHTER.\n *\n * Invariants:\n * - Only slots ABSENT from the caller's `palette` input are ever touched;\n * an explicitly authored shade passes through byte-identical (the\n * marketing host's hand-set `primary.dark` values depend on this).\n * - A derived value that already clears 4.5:1 against both\n * `background.default` and `background.paper` is kept byte-identical, so\n * themes that were fine yesterday do not shift.\n * - A failing derived `dark` is re-seeded at the tonal offset from `main`\n * in the scheme's foreground direction (darken in light, lighten in\n * dark), then walked in HSL lightness until it clears the bar.\n * - A light-scheme `light` is a background TINT — its ramp direction points\n * away from the text bar by design — so it keeps the tonal derivation.\n * In dark schemes `light` is foreground-capable and gets the same walk.\n * - Derived `contrastText` keeps the threshold choice unless that pairing\n * is below 4.5:1 against `main`; then it walks toward the pole with more\n * contrast headroom.\n */\nfunction ensureAccessibleShades(\n theme: Theme,\n inputPalette: PaletteOptions | undefined,\n) {\n const { palette } = theme\n const backgrounds = [\n palette.background?.default,\n palette.background?.paper,\n ].filter((background): background is string => typeof background === 'string')\n if (!backgrounds.length) return\n const mode: 'light' | 'dark' = palette.mode === 'dark' ? 'dark' : 'light'\n const foregroundDirection: ShadeDirection =\n mode === 'dark' ? 'lighten' : 'darken'\n const tonalOffsetDark = resolveTonalOffsets(palette.tonalOffset).dark\n const providedColors = inputPalette as\n | Record<string, unknown>\n | undefined\n\n for (const key of CONTRAST_TEXT_COLOR_KEYS) {\n const color = (palette as unknown as Record<string, PaletteColor>)[key]\n if (!color || typeof color.main !== 'string') continue\n const provided = providedColors?.[key]\n // A ColorPartial ramp (`{ 50…900 }`) is an author-owned scale — MUI maps\n // its shades straight across, so nothing in it counts as derived.\n if (provided && typeof provided === 'object' && !('main' in provided)) {\n continue\n }\n // Read with brackets, not dots: these keys come from an index signature,\n // and `json-editor` compiles this file under\n // `noPropertyAccessFromIndexSignature` (paths resolve to source, so a\n // consumer's flags check its dependencies). Dot access reds that build\n // while this project's own stays green — AGL-1323.\n const explicit = (provided ?? {}) as Record<string, unknown>\n const isForeground = (FOREGROUND_COLOR_KEYS as readonly string[]).includes(\n key,\n )\n\n try {\n if (\n isForeground &&\n !explicit['dark'] &&\n typeof color.dark === 'string' &&\n !meetsContrast(color.dark, backgrounds)\n ) {\n const seed =\n mode === 'dark' ? lighten(color.main, tonalOffsetDark) : color.dark\n color.dark = accessibleShade(seed, backgrounds, foregroundDirection)\n }\n if (\n isForeground &&\n mode === 'dark' &&\n !explicit['light'] &&\n typeof color.light === 'string' &&\n !meetsContrast(color.light, backgrounds)\n ) {\n color.light = accessibleShade(color.light, backgrounds, 'lighten')\n }\n if (\n !explicit['contrastText'] &&\n typeof color.contrastText === 'string' &&\n !meetsContrast(color.contrastText, [color.main])\n ) {\n const textDirection: ShadeDirection =\n contrastRatio('#fff', color.main) >= contrastRatio('#000', color.main)\n ? 'lighten'\n : 'darken'\n color.contrastText = accessibleShade(\n color.contrastText,\n [color.main],\n textDirection,\n )\n }\n } catch {\n // Unparseable colour (CSS variable, color-mix()): leave the derived\n // value alone rather than failing theme creation.\n }\n }\n}\n\n/**\n * Post-`createTheme` pass giving every palette color a defined HOVER\n * (AGL-3465): `palette[color].hover`, the fill ({@link ACCENT_HOVER_FILL}),\n * and `palette[color].hoverText`, the label ({@link ACCENT_HOVER_TEXT}).\n * The `MuiButton` and `MuiFab` overrides read both.\n *\n * - **The fill.** MUI fills a hovered contained Button and Fab with\n * `palette[color].dark`, which this theme uses as the accent-as-TEXT\n * shade: lighter than `main` in a dark scheme, so a white label on it\n * sinks to ~2:1. Every entry with a string `main` and `contrastText` gets\n * one — the built-in accents, `tertiary`, `surface`, and any custom color\n * a palette adds — so a color a component can be asked to wear always has\n * a hover that carries its own ink at AA.\n * - **The label.** A hovered text or outlined Button keeps `dark` as its\n * label and lays `main` at `action.hoverOpacity` under it. Foreground\n * colors get `dark` walked in the scheme's foreground direction until it\n * clears AA on that wash over both `background.default` and\n * `background.paper`; it stays `dark`, byte-identical, wherever `dark`\n * already does. `surface` gets none: its `dark` is a surface step, not\n * text, so it has no label to protect.\n *\n * A slot the caller authored passes through untouched.\n */\nfunction ensureHoverShades(\n theme: Theme,\n inputPalette: PaletteOptions | undefined,\n) {\n const palette = theme.palette as unknown as Record<string, unknown>\n const providedColors = inputPalette as Record<string, unknown> | undefined\n const tonalOffsetDark = resolveTonalOffsets(theme.palette.tonalOffset).dark\n const foregroundDirection: ShadeDirection =\n theme.palette.mode === 'dark' ? 'lighten' : 'darken'\n const backgrounds = [\n theme.palette.background?.default,\n theme.palette.background?.paper,\n ].filter((background): background is string => typeof background === 'string')\n const hoverOpacity = theme.palette.action?.hoverOpacity ?? 0\n\n for (const [key, value] of Object.entries(palette)) {\n if (!value || typeof value !== 'object') continue\n const color = value as Record<string, unknown>\n const { main, dark, contrastText } = color\n if (typeof main !== 'string' || typeof contrastText !== 'string') continue\n const provided = (providedColors?.[key] ?? {}) as Record<string, unknown>\n try {\n if (typeof provided[ACCENT_HOVER_FILL] !== 'string') {\n color[ACCENT_HOVER_FILL] = hoverFillShade(\n {\n main,\n contrastText,\n dark: typeof dark === 'string' ? dark : undefined,\n },\n tonalOffsetDark,\n )\n }\n if (\n typeof provided[ACCENT_HOVER_TEXT] !== 'string' &&\n (FOREGROUND_COLOR_KEYS as readonly string[]).includes(key) &&\n typeof dark === 'string' &&\n backgrounds.length\n ) {\n const wash = alpha(main, hoverOpacity)\n color[ACCENT_HOVER_TEXT] = accessibleShade(\n dark,\n backgrounds.map((background) => inkOnFill(wash, background)),\n foregroundDirection,\n )\n }\n } catch {\n // Unparseable colour (CSS variable, color-mix()): no slot, so the\n // component overrides fall back to MUI's own hover for this color.\n }\n }\n}\n\n/**\n * MUI's own default `responsiveFontSizes` variant list, spelled out because\n * passing `variants` replaces it rather than extending it.\n */\nconst RAMPED_MUI_VARIANTS = [\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'subtitle1',\n 'subtitle2',\n 'body1',\n 'body2',\n 'caption',\n 'button',\n 'overline',\n] as const\n\n/**\n * The brand's custom display rungs, which MUI cannot know about.\n *\n * Only variants whose size genuinely needs to shrink belong here. `lede`,\n * `bodyCompact` and `micro` are body-scale text that reads the same at every\n * width and are deliberately absent.\n */\nconst RAMPED_DISPLAY_VARIANTS = ['displayXl'] as const\n\nexport type CreateResponsiveThemeOptions = {\n themeOptions?: ThemeOptions\n responsiveFontSizesOptions?: Parameters<typeof responsiveFontSizes>[1]\n}\n\n/**\n * START EXAMPLE – OVERRIDE DEFAULT PROPS ↓\n * ⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄\n * ```typescript\n * const theme = createMuiTheme({\n * props: {\n * // Name of the component ⚛️\n * MuiButtonBase: {\n * // The default props to change\n * disableRipple: true, // No more ripple, on the whole application 💣!\n * },\n * },\n * })\n * ```\n * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n * END EXAMPLE – OVERRIDE DEFAULT PROPS ↑\n *\n * START EXAMPLE – OVERRIDE DEFAULT STYLES ↓\n * ⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄\n * ```typescript\n * const theme = createMuiTheme({\n * overrides: {\n * // Style sheet name ⚛️\n * MuiButton: {\n * // Name of the rule\n * text: {\n * // Some CSS\n * color: 'white',\n * },\n * },\n * MuiCssBaseline: {\n * '@global': {\n * html: {\n * WebkitFontSmoothing: 'auto',\n * },\n * },\n * },\n * },\n * })\n * ```\n * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n * END EXAMPLE – OVERRIDE DEFAULT STYLES ↑\n *\n * @param {ThemeOptions} options\n * @returns {Theme}\n */\nexport function createResponsiveTheme(\n options: CreateResponsiveThemeOptions,\n): Theme {\n const { themeOptions, responsiveFontSizesOptions } = options\n let theme = createTheme(themeOptions)\n addShadeVariants(theme.palette.tertiary, theme.palette.tonalOffset)\n addShadeVariants(theme.palette.surface, theme.palette.tonalOffset)\n // `tint` is deliberately absent from BOTH shade passes (AGL-1244). It is a\n // group of string leaves rather than a PaletteColor — no `main` to ramp\n // from, no `contrastText` to pair — so `addShadeVariants` would no-op and\n // `ensureAccessibleShades` (which keys off `CONTRAST_TEXT_COLOR_KEYS`) never\n // sees it. Both correct: a 90%-desaturated wash is authored, not derived,\n // and walking it to a text-contrast bar would repaint the fill.\n // Scheme- and AA-aware repair of DERIVED shades only (AGL-1297); explicit\n // palette values pass through byte-identical.\n ensureAccessibleShades(theme, themeOptions?.palette)\n // After the shade repair, because both hover slots start from `dark` and\n // have to see the value that ships.\n ensureHoverShades(theme, themeOptions?.palette)\n\n theme = responsiveFontSizes(theme, {\n // Override to include `xs` and `xl` - default: ['sm', 'md', 'lg']\n breakpoints: ['xs', 'sm', 'md', 'lg', 'xl'],\n // MUI only ramps the variants it ships, so a CUSTOM display variant would\n // keep its desktop size on a phone — `displayXl` at 72px on a 375px\n // screen. Passing `variants` REPLACES MUI's default list, so the defaults\n // are spelled out here and ours appended; drop one and that variant\n // silently stops scaling.\n variants: [...RAMPED_MUI_VARIANTS, ...RAMPED_DISPLAY_VARIANTS],\n ...responsiveFontSizesOptions,\n })\n\n return theme\n}\n\nexport function createResponsiveCssVarTheme(\n light: Theme,\n dark: Theme,\n options?: CssVarsThemeOptions,\n) {\n const { palette: lightPalette, ...lightTheme } = light\n const { palette: darkPalette } = dark\n\n return muiExtendTheme({\n ...lightTheme,\n // Allow setMode() to work by driving the color scheme via a CSS class on\n // <html> instead of the OS-level @media query (the default 'media' selector\n // makes setMode() a no-op because media queries can't be overridden in JS).\n colorSchemeSelector: 'class',\n ...options,\n colorSchemes: {\n ...options?.colorSchemes,\n light: { palette: lightPalette, ...((options?.colorSchemes?.light ?? {}) as object) },\n dark: { palette: darkPalette, ...((options?.colorSchemes?.dark ?? {}) as object) },\n },\n })\n}\n\nexport default createResponsiveTheme\n"],"names":["extendTheme","muiExtendTheme","alpha","createTheme","darken","getContrastRatio","lighten","responsiveFontSizes","ACCENT_HOVER_FILL","ACCENT_HOVER_TEXT","hoverFillShade","inkOnFill","accessibleShade","contrastRatio","meetsContrast","ContrastText","resolveTonalOffsets","tonalOffset","offsetObj","undefined","offsetNum","light","dark","getContrastTextColor","background","contrastThreshold","addShade","paletteColor","shade","variant","main","tonalOffsetLight","tonalOffsetDark","indexed","hasOwnProperty","contrastText","addShadeVariants","FOREGROUND_COLOR_KEYS","CONTRAST_TEXT_COLOR_KEYS","ensureAccessibleShades","theme","inputPalette","palette","backgrounds","default","paper","filter","length","mode","foregroundDirection","providedColors","key","color","provided","explicit","isForeground","includes","seed","textDirection","ensureHoverShades","hoverOpacity","action","value","Object","entries","wash","map","RAMPED_MUI_VARIANTS","RAMPED_DISPLAY_VARIANTS","createResponsiveTheme","options","themeOptions","responsiveFontSizesOptions","tertiary","surface","breakpoints","variants","createResponsiveCssVarTheme","lightPalette","lightTheme","darkPalette","colorSchemeSelector","colorSchemes"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,eAAeC,cAAc,QACxB,uBAAsB;AAC7B,SACEC,KAAK,EACLC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,OAAO,EAGPC,mBAAmB,QAGd,sBAAkB;AACzB,SACEC,iBAAiB,EACjBC,iBAAiB,EACjBC,cAAc,EACdC,SAAS,QACJ,mBAAe;AACtB,SACEC,eAAe,EACfC,aAAa,EACbC,aAAa,QAER,wBAAoB;AAE3B,IAAA,AAAKC,sCAAAA;;;WAAAA;EAAAA;AAOL,SAASC,oBAAoBC,WAAoC;QAItDC;IAHT,MAAMA,YAAY,OAAOD,gBAAgB,WAAWE,YAAYF;IAChE,MAAMG,YAAY,OAAOH,gBAAgB,WAAWA,cAAcE;IAClE,OAAO;QACLE,KAAK,GAAEH,gBAAAA,6BAAAA,UAAWG,KAAK,oBAAID,qBAApBF,OAAiC;QACxCI,IAAI,WAAEJ,6BAAAA,UAAWI,IAAI,oBAAI,CAACF,oBAAAA,YAAa,OAAO;IAChD;AACF;AAEA,SAASG,qBAAqBC,UAAkB,EAAEC,iBAAyB;IACzE,OAAOpB,iBAAiBmB,2BAAmCC,4BAAAA,oBAAqB;AAGlF;AACA,SAASC,SAASC,YAA0B,EAAEC,KAAa,EAAEC,OAA2B,EAAEZ,WAAwB;IAChH,yEAAyE;IACzE,IAAI,EAACU,gCAAAA,aAAcG,IAAI,GAAE;IACzB,MAAM,EAAET,OAAOU,gBAAgB,EAAET,MAAMU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AAQjC,oBAAoBiC,OAAO;QACjC,kEAAkE;QAClEmC,aAAa;YAAC;YAAM;YAAM;YAAM;YAAM;SAAK;QAC3C,0EAA0E;QAC1E,oEAAoE;QACpE,0EAA0E;QAC1E,oEAAoE;QACpE,0BAA0B;QAC1BC,UAAU;eAAIT;eAAwBC;SAAwB;OAC3DI;IAGL,OAAOhC;AACT;AAEA,OAAO,SAASqC,4BACdxD,KAAY,EACZC,IAAW,EACXgD,OAA6B;;QAcYA,uBACFA;IAbvC,MAAM,EAAE5B,SAASoC,YAAY,EAAiB,GAAGzD,OAAf0D,8CAAe1D;;;IACjD,MAAM,EAAEqB,SAASsC,WAAW,EAAE,GAAG1D;IAEjC,OAAOrB,eAAe,aACjB8E;QACH,yEAAyE;QACzE,4EAA4E;QAC5E,4EAA4E;QAC5EE,qBAAqB;OAClBX;QACHY,cAAc,aACTZ,2BAAAA,QAASY,YAAY;YACxB7D,OAAO;gBAAEqB,SAASoC;uBAAmBR,4BAAAA,wBAAAA,QAASY,YAAY,qBAArBZ,sBAAuBjD,KAAK,mBAAI,CAAC;YACtEC,MAAM;gBAAEoB,SAASsC;wBAAkBV,4BAAAA,yBAAAA,QAASY,YAAY,qBAArBZ,uBAAuBhD,IAAI,oBAAI,CAAC;;;AAGzE;AAEA,eAAe+C,sBAAqB"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import type { HostTheme } from '@aglyn/shared-data-types';
|
|
18
|
+
/**
|
|
19
|
+
* A theme's Google fonts, served from the site's own origin (AGL-3485).
|
|
20
|
+
*
|
|
21
|
+
* A published page loaded its theme font as a `<link rel="stylesheet">` to
|
|
22
|
+
* `fonts.googleapis.com`: a render-blocking request to a third origin, then a
|
|
23
|
+
* second connection to `fonts.gstatic.com` for the files it names — about
|
|
24
|
+
* 800 ms before first paint on the page Lighthouse measured. Nothing about a
|
|
25
|
+
* theme font needs either round trip at view time. The stylesheet is a short
|
|
26
|
+
* list of `@font-face` rules that changes only when the theme does, and the
|
|
27
|
+
* files are versioned in their own paths (`/s/inter/v18/…woff2`), so neither
|
|
28
|
+
* changes under a URL.
|
|
29
|
+
*
|
|
30
|
+
* So the server fetches the stylesheet once, keeps the rules, and inlines them
|
|
31
|
+
* in the page with each `src` pointing at {@link SELF_HOSTED_FONT_ROUTE} on the
|
|
32
|
+
* site's own origin, which serves the file with a year-long `immutable`
|
|
33
|
+
* policy. The one or two faces the first screen paints with are preloaded.
|
|
34
|
+
* Nothing on the page asks Google for anything, which also means a visitor's
|
|
35
|
+
* address is no longer handed to Google by every page view.
|
|
36
|
+
*
|
|
37
|
+
* This module is the pure half: reading Google's stylesheet, writing the
|
|
38
|
+
* rules back, and choosing the faces to preload. The fetching and the file
|
|
39
|
+
* route live with the tenant (`libs/tenant/runtime/.../self-hosted-fonts.ts`).
|
|
40
|
+
*
|
|
41
|
+
* The rules are REBUILT from validated fields rather than echoed, so the
|
|
42
|
+
* inlined CSS can only ever contain a family name the theme chose, a style, a
|
|
43
|
+
* weight, a unicode range and a path on our own route.
|
|
44
|
+
*/
|
|
45
|
+
/** Where a site serves its theme's font files from. */
|
|
46
|
+
export declare const SELF_HOSTED_FONT_ROUTE = "/api/fonts";
|
|
47
|
+
/** The origin Google serves font files from. */
|
|
48
|
+
export declare const GOOGLE_FONT_FILE_ORIGIN = "https://fonts.gstatic.com";
|
|
49
|
+
/** One `@font-face` rule from Google's stylesheet. */
|
|
50
|
+
export interface GoogleFontFace {
|
|
51
|
+
family: string;
|
|
52
|
+
style: 'normal' | 'italic';
|
|
53
|
+
/** A weight (`400`) or, for a variable font, a range (`100 900`). */
|
|
54
|
+
weight: string;
|
|
55
|
+
/** Google's subset comment above the rule (`latin`, `latin-ext`, …). */
|
|
56
|
+
subset?: string;
|
|
57
|
+
/** The file's path below `/s/` on Google's origin. */
|
|
58
|
+
path: string;
|
|
59
|
+
unicodeRange?: string;
|
|
60
|
+
}
|
|
61
|
+
/** Whether a path is one {@link SELF_HOSTED_FONT_ROUTE} will serve. */
|
|
62
|
+
export declare function isSelfHostedFontPath(path: string): boolean;
|
|
63
|
+
/** The site-relative URL a face's file is served from. */
|
|
64
|
+
export declare function selfHostedFontUrl(path: string): string;
|
|
65
|
+
/** Google's own URL for a self-hosted path. */
|
|
66
|
+
export declare function googleFontFileUrl(path: string): string;
|
|
67
|
+
/**
|
|
68
|
+
* Reads the `@font-face` rules out of a Google Fonts CSS2 stylesheet fetched
|
|
69
|
+
* with a browser that accepts WOFF2. A rule that is not exactly the shape
|
|
70
|
+
* Google writes — a missing field, a file off Google's origin, a path the
|
|
71
|
+
* route would refuse — is dropped, never repaired.
|
|
72
|
+
*/
|
|
73
|
+
export declare function parseGoogleFontFaces(css: string): GoogleFontFace[];
|
|
74
|
+
/**
|
|
75
|
+
* The faces as `@font-face` rules on the site's own route, every one
|
|
76
|
+
* `font-display: swap` so text paints in the fallback while a file loads.
|
|
77
|
+
*
|
|
78
|
+
* Every subset Google declared is kept, each with its `unicode-range`: a
|
|
79
|
+
* browser downloads a subset only when the page uses a character in it, so
|
|
80
|
+
* the Cyrillic file costs an English page nothing, and a Polish or Greek page
|
|
81
|
+
* keeps its typeface. Only the Latin faces are preloaded.
|
|
82
|
+
*/
|
|
83
|
+
export declare function selfHostedFontFaceCss(faces: readonly GoogleFontFace[]): string;
|
|
84
|
+
/**
|
|
85
|
+
* The paths of the one or two faces the first screen paints with: the body
|
|
86
|
+
* text's face, and the headline's when it is a different file. Those are the
|
|
87
|
+
* fonts the largest text on the page — usually the LCP element — waits for,
|
|
88
|
+
* so they are worth starting with the document; every other face is fetched
|
|
89
|
+
* when the page first uses it.
|
|
90
|
+
*
|
|
91
|
+
* The body face is the theme's `fontFamily` (else the first Google font it
|
|
92
|
+
* loads) at `body1`'s weight, 400 by default; the headline face is `h1`'s
|
|
93
|
+
* family and weight, 700 by default. A variable font serves every weight
|
|
94
|
+
* from one file, which is then preloaded once.
|
|
95
|
+
*/
|
|
96
|
+
export declare function selfHostedFontPreloads(theme: Pick<HostTheme, 'fonts' | 'typography'> | undefined, faces: readonly GoogleFontFace[]): string[];
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
|
+
/**
|
|
18
|
+
* A theme's Google fonts, served from the site's own origin (AGL-3485).
|
|
19
|
+
*
|
|
20
|
+
* A published page loaded its theme font as a `<link rel="stylesheet">` to
|
|
21
|
+
* `fonts.googleapis.com`: a render-blocking request to a third origin, then a
|
|
22
|
+
* second connection to `fonts.gstatic.com` for the files it names — about
|
|
23
|
+
* 800 ms before first paint on the page Lighthouse measured. Nothing about a
|
|
24
|
+
* theme font needs either round trip at view time. The stylesheet is a short
|
|
25
|
+
* list of `@font-face` rules that changes only when the theme does, and the
|
|
26
|
+
* files are versioned in their own paths (`/s/inter/v18/…woff2`), so neither
|
|
27
|
+
* changes under a URL.
|
|
28
|
+
*
|
|
29
|
+
* So the server fetches the stylesheet once, keeps the rules, and inlines them
|
|
30
|
+
* in the page with each `src` pointing at {@link SELF_HOSTED_FONT_ROUTE} on the
|
|
31
|
+
* site's own origin, which serves the file with a year-long `immutable`
|
|
32
|
+
* policy. The one or two faces the first screen paints with are preloaded.
|
|
33
|
+
* Nothing on the page asks Google for anything, which also means a visitor's
|
|
34
|
+
* address is no longer handed to Google by every page view.
|
|
35
|
+
*
|
|
36
|
+
* This module is the pure half: reading Google's stylesheet, writing the
|
|
37
|
+
* rules back, and choosing the faces to preload. The fetching and the file
|
|
38
|
+
* route live with the tenant (`libs/tenant/runtime/.../self-hosted-fonts.ts`).
|
|
39
|
+
*
|
|
40
|
+
* The rules are REBUILT from validated fields rather than echoed, so the
|
|
41
|
+
* inlined CSS can only ever contain a family name the theme chose, a style, a
|
|
42
|
+
* weight, a unicode range and a path on our own route.
|
|
43
|
+
*/ /** Where a site serves its theme's font files from. */ export const SELF_HOSTED_FONT_ROUTE = '/api/fonts';
|
|
44
|
+
/** The origin Google serves font files from. */ export const GOOGLE_FONT_FILE_ORIGIN = 'https://fonts.gstatic.com';
|
|
45
|
+
/**
|
|
46
|
+
* A font file's path on {@link GOOGLE_FONT_FILE_ORIGIN} below `/s/`, as the
|
|
47
|
+
* route accepts it: `{family}/v{n}/{file}.woff2`. Anything else is refused,
|
|
48
|
+
* so the route can never be used to fetch an arbitrary URL.
|
|
49
|
+
*/ const FONT_FILE_PATH = /^[a-z0-9]+\/v\d{1,4}\/[A-Za-z0-9_-]{1,200}\.woff2$/;
|
|
50
|
+
/** Whether a path is one {@link SELF_HOSTED_FONT_ROUTE} will serve. */ export function isSelfHostedFontPath(path) {
|
|
51
|
+
return FONT_FILE_PATH.test(path);
|
|
52
|
+
}
|
|
53
|
+
/** The site-relative URL a face's file is served from. */ export function selfHostedFontUrl(path) {
|
|
54
|
+
return `${SELF_HOSTED_FONT_ROUTE}/${path}`;
|
|
55
|
+
}
|
|
56
|
+
/** Google's own URL for a self-hosted path. */ export function googleFontFileUrl(path) {
|
|
57
|
+
return `${GOOGLE_FONT_FILE_ORIGIN}/s/${path}`;
|
|
58
|
+
}
|
|
59
|
+
const FACE_BLOCK = /(?:\/\*\s*([a-z0-9-]+)\s*\*\/\s*)?@font-face\s*\{([^}]*)\}/g;
|
|
60
|
+
const FAMILY = /font-family:\s*'([^']{1,80})'/;
|
|
61
|
+
const STYLE = /font-style:\s*(normal|italic)/;
|
|
62
|
+
const WEIGHT = /font-weight:\s*(\d{3}(?:\s+\d{3})?)/;
|
|
63
|
+
const SRC = /src:\s*url\((https:\/\/fonts\.gstatic\.com\/s\/[^)\s]+)\)\s*format\('woff2'\)/;
|
|
64
|
+
const RANGE = /unicode-range:\s*([U+0-9A-Fa-f?,\s-]{1,4000});/;
|
|
65
|
+
/**
|
|
66
|
+
* Reads the `@font-face` rules out of a Google Fonts CSS2 stylesheet fetched
|
|
67
|
+
* with a browser that accepts WOFF2. A rule that is not exactly the shape
|
|
68
|
+
* Google writes — a missing field, a file off Google's origin, a path the
|
|
69
|
+
* route would refuse — is dropped, never repaired.
|
|
70
|
+
*/ export function parseGoogleFontFaces(css) {
|
|
71
|
+
const faces = [];
|
|
72
|
+
for (const match of css.matchAll(FACE_BLOCK)){
|
|
73
|
+
var _FAMILY_exec, _STYLE_exec, _WEIGHT_exec, _SRC_exec, _RANGE_exec_, _RANGE_exec;
|
|
74
|
+
const [, subset, body] = match;
|
|
75
|
+
const family = (_FAMILY_exec = FAMILY.exec(body)) == null ? void 0 : _FAMILY_exec[1];
|
|
76
|
+
const style = (_STYLE_exec = STYLE.exec(body)) == null ? void 0 : _STYLE_exec[1];
|
|
77
|
+
const weight = (_WEIGHT_exec = WEIGHT.exec(body)) == null ? void 0 : _WEIGHT_exec[1];
|
|
78
|
+
const url = (_SRC_exec = SRC.exec(body)) == null ? void 0 : _SRC_exec[1];
|
|
79
|
+
if (!family || !style || !weight || !url) continue;
|
|
80
|
+
const path = url.slice(`${GOOGLE_FONT_FILE_ORIGIN}/s/`.length);
|
|
81
|
+
if (!isSelfHostedFontPath(path)) continue;
|
|
82
|
+
const unicodeRange = (_RANGE_exec = RANGE.exec(body)) == null ? void 0 : (_RANGE_exec_ = _RANGE_exec[1]) == null ? void 0 : _RANGE_exec_.trim();
|
|
83
|
+
faces.push(_extends({
|
|
84
|
+
family,
|
|
85
|
+
style,
|
|
86
|
+
weight: weight.replace(/\s+/g, ' ')
|
|
87
|
+
}, subset ? {
|
|
88
|
+
subset
|
|
89
|
+
} : {}, {
|
|
90
|
+
path
|
|
91
|
+
}, unicodeRange ? {
|
|
92
|
+
unicodeRange
|
|
93
|
+
} : {}));
|
|
94
|
+
}
|
|
95
|
+
return faces;
|
|
96
|
+
}
|
|
97
|
+
/** A family name as it may appear quoted in CSS. */ function cssFamily(family) {
|
|
98
|
+
return `'${family.replace(/['\\\n\r]/g, '')}'`;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The faces as `@font-face` rules on the site's own route, every one
|
|
102
|
+
* `font-display: swap` so text paints in the fallback while a file loads.
|
|
103
|
+
*
|
|
104
|
+
* Every subset Google declared is kept, each with its `unicode-range`: a
|
|
105
|
+
* browser downloads a subset only when the page uses a character in it, so
|
|
106
|
+
* the Cyrillic file costs an English page nothing, and a Polish or Greek page
|
|
107
|
+
* keeps its typeface. Only the Latin faces are preloaded.
|
|
108
|
+
*/ export function selfHostedFontFaceCss(faces) {
|
|
109
|
+
return faces.map((face)=>[
|
|
110
|
+
'@font-face{',
|
|
111
|
+
`font-family:${cssFamily(face.family)};`,
|
|
112
|
+
`font-style:${face.style};`,
|
|
113
|
+
`font-weight:${face.weight};`,
|
|
114
|
+
'font-display:swap;',
|
|
115
|
+
`src:url(${selfHostedFontUrl(face.path)}) format('woff2');`,
|
|
116
|
+
face.unicodeRange ? `unicode-range:${face.unicodeRange};` : '',
|
|
117
|
+
'}'
|
|
118
|
+
].join('')).join('');
|
|
119
|
+
}
|
|
120
|
+
/** The first family named in a CSS `font-family` stack. */ function firstFamily(stack) {
|
|
121
|
+
var _stack_split_;
|
|
122
|
+
if (typeof stack !== 'string') return undefined;
|
|
123
|
+
const first = (_stack_split_ = stack.split(',')[0]) == null ? void 0 : _stack_split_.trim().replace(/^['"]|['"]$/g, '');
|
|
124
|
+
return first || undefined;
|
|
125
|
+
}
|
|
126
|
+
/** How far a face is from a wanted weight; 0 when its range covers it. */ function weightDistance(face, wanted) {
|
|
127
|
+
const [low, high = low] = face.weight.split(' ').map(Number);
|
|
128
|
+
if (wanted >= low && wanted <= high) return 0;
|
|
129
|
+
return Math.min(Math.abs(wanted - low), Math.abs(wanted - high));
|
|
130
|
+
}
|
|
131
|
+
/** The Latin, upright face of `family` closest to `weight`. */ function latinFace(faces, family, weight) {
|
|
132
|
+
if (!family) return undefined;
|
|
133
|
+
const wanted = family.toLowerCase();
|
|
134
|
+
const candidates = faces.filter((face)=>face.family.toLowerCase() === wanted && face.style === 'normal' && (face.subset === undefined || face.subset === 'latin'));
|
|
135
|
+
return candidates.sort((a, b)=>weightDistance(a, weight) - weightDistance(b, weight))[0];
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* The paths of the one or two faces the first screen paints with: the body
|
|
139
|
+
* text's face, and the headline's when it is a different file. Those are the
|
|
140
|
+
* fonts the largest text on the page — usually the LCP element — waits for,
|
|
141
|
+
* so they are worth starting with the document; every other face is fetched
|
|
142
|
+
* when the page first uses it.
|
|
143
|
+
*
|
|
144
|
+
* The body face is the theme's `fontFamily` (else the first Google font it
|
|
145
|
+
* loads) at `body1`'s weight, 400 by default; the headline face is `h1`'s
|
|
146
|
+
* family and weight, 700 by default. A variable font serves every weight
|
|
147
|
+
* from one file, which is then preloaded once.
|
|
148
|
+
*/ export function selfHostedFontPreloads(theme, faces) {
|
|
149
|
+
var _firstFamily, _ref, _firstFamily1, _ref1;
|
|
150
|
+
var _theme_fonts_find, _theme_fonts, _variants_body1, _variants_h1, _variants_h11;
|
|
151
|
+
const typography = theme == null ? void 0 : theme.typography;
|
|
152
|
+
const variants = typography == null ? void 0 : typography.variants;
|
|
153
|
+
const fallback = theme == null ? void 0 : (_theme_fonts = theme.fonts) == null ? void 0 : (_theme_fonts_find = _theme_fonts.find((font)=>{
|
|
154
|
+
var _font_source;
|
|
155
|
+
return ((_font_source = font.source) != null ? _font_source : 'google') === 'google';
|
|
156
|
+
})) == null ? void 0 : _theme_fonts_find.family;
|
|
157
|
+
const bodyFamily = (_firstFamily = firstFamily(typography == null ? void 0 : typography.fontFamily)) != null ? _firstFamily : fallback;
|
|
158
|
+
const body = latinFace(faces, bodyFamily, (_ref = variants == null ? void 0 : (_variants_body1 = variants.body1) == null ? void 0 : _variants_body1.fontWeight) != null ? _ref : 400);
|
|
159
|
+
const heading = latinFace(faces, (_firstFamily1 = firstFamily(variants == null ? void 0 : (_variants_h1 = variants.h1) == null ? void 0 : _variants_h1.fontFamily)) != null ? _firstFamily1 : bodyFamily, (_ref1 = variants == null ? void 0 : (_variants_h11 = variants.h1) == null ? void 0 : _variants_h11.fontWeight) != null ? _ref1 : 700);
|
|
160
|
+
const paths = [
|
|
161
|
+
body,
|
|
162
|
+
heading
|
|
163
|
+
].filter((face)=>Boolean(face)).map((face)=>selfHostedFontUrl(face.path));
|
|
164
|
+
return [
|
|
165
|
+
...new Set(paths)
|
|
166
|
+
];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
//# sourceMappingURL=self-hosted-fonts.js.map
|