@taprootio/site-authoring 0.41.1 → 0.42.0

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 CHANGED
@@ -921,6 +921,25 @@ its pages-generated allowance, or the bandwidth pause on deploys,
921
921
  surfaced at deploy; the allowance shows its reset time, while the bandwidth pause shows the earliest
922
922
  time it can lift, since it lifts only after a month ends under the allowance or on upgrade), and `throttled` (back off).
923
923
 
924
+ ### Indexed contrast in `theme resolve`
925
+
926
+ The authoring report measures header and footer text, graphics and focus
927
+ indicators in the selected schemes and contexts. The default table names
928
+ the element, state, ink, backdrop and WCAG AA result. The JSON adds a
929
+ `chrome` map keyed by scheme and a response-local `chromeCatalog`.
930
+ Each chrome card names its role and context and contains rows
931
+ `[identityIndex, ratio, required]`.
932
+
933
+ Look up `chromeCatalog.pairs[identityIndex]` to get
934
+ `[elementIndex, foregroundIndex, backgroundIndex, stateIndex, kindIndex]`.
935
+ Resolve these indexes through `elements`, `colors`, `colors`, `states`, and
936
+ `kinds`, respectively. All indexes are zero-based and belong to the same
937
+ response. Context display names longer than 128 characters carry
938
+ `contextTruncated` and `contextLength`. Context filtering uses the full name.
939
+ The authoring result fits 64 KiB, preserves all selected chrome measurements
940
+ and reserves at least 24 KiB for legacy surfaces. The indexed report is
941
+ produced by the authoring CLI.
942
+
924
943
  When `GITHUB_OUTPUT` names the runner's existing output file, every
925
944
  operational verb appends the same JSON under `taproot_site_result` through a
926
945
  random delimiter block, plus `taproot_site_verb` on success. Credentials,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@taprootio/site-authoring",
3
- "version": "0.41.1",
3
+ "version": "0.42.0",
4
4
  "description": "Taproot site authoring CLI: sign in once in the browser, then pull, validate, push, preview, approve, and deploy a site from the terminal",
5
5
  "type": "module",
6
6
  "license": "ISC",
@@ -28,7 +28,7 @@
28
28
  "README.md"
29
29
  ],
30
30
  "dependencies": {
31
- "@taprootio/espalier": "7.1.1",
31
+ "@taprootio/espalier": "7.2.0",
32
32
  "mediabunny": "1.61.1"
33
33
  },
34
34
  "scripts": {
package/src/api.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { normalizeNavigationReadiness } from "./navigation-readiness.js";
2
+ import { isNavigationRevision } from "./navigation-workspace.js";
2
3
  import { normalizeLatestCliVersion } from "./cli-release.js";
3
4
  import { imageDescriptionRevision, isImageId, safeImagePreviewUrl } from "./image-description-contract.js";
4
5
  import {
@@ -700,11 +701,11 @@ export async function publishDrafts(client, pageIds) {
700
701
  * site-authoring key actually holds; production resolves against a published
701
702
  * deployment instead.
702
703
  */
703
- export async function getNavigation(client, siteId) {
704
+ export async function getNavigation(client, siteId, { requireEvidence = false } = {}) {
704
705
  const search = query([["environment", SITE_ENVIRONMENT_DRAFT]]);
705
706
  return requireNavigation(await client.request(sitePath(siteId, `navigation${search}`), {
706
707
  maximumResponseBytes: LIMITS.navigationResponseBytes,
707
- }));
708
+ }), requireEvidence);
708
709
  }
709
710
 
710
711
  /**
@@ -722,8 +723,13 @@ export async function saveNavigation(client, siteId, navItems, expectedRevision)
722
723
  }
723
724
 
724
725
  /** A navigation answer: the tree and the revision a later save must present. */
725
- function requireNavigation(value) {
726
+ function requireNavigation(value, requireEvidence = false) {
726
727
  const response = requireObject(value, "api.navigation_contract", "site navigation");
728
+ // ProtoJSON may omit an empty repeated field. A revision proves this is the tree response.
729
+ if (requireEvidence && (!isNavigationRevision(response.revision)
730
+ || (Object.hasOwn(response, "navItems") && !Array.isArray(response.navItems)))) {
731
+ throw new SiteAuthoringError("api.navigation_contract", "Taproot returned incomplete navigation evidence.");
732
+ }
727
733
  return {
728
734
  navItems: Array.isArray(response.navItems) ? response.navItems : [],
729
735
  revision: typeof response.revision === "string" ? response.revision : "",
@@ -364,6 +364,19 @@ export function appearanceScalarInput(definition, value) {
364
364
  return input;
365
365
  }
366
366
 
367
+ function checkedScalar(definition, settings, knownImageIds) {
368
+ return validateScalar(definition, appearanceScalarInput(definition, settings?.[definition.name]), knownImageIds);
369
+ }
370
+
371
+ /** Optional report evidence can be checked independently of other settings groups. */
372
+ export function validateAppearanceScalarGroup(settingsType, settings, knownImageIds) {
373
+ if (settingsType === SETTINGS_TYPE_TAPROOT_STYLES) refuseRetiredScalarFonts(settings);
374
+ for (const definition of APPEARANCE_SCALAR_FIELDS) {
375
+ if (definition.settingsType === settingsType) checkedScalar(definition, settings, knownImageIds);
376
+ }
377
+ return settings;
378
+ }
379
+
367
380
  export function buildAppearanceScalarOperations(documents, knownImageIds) {
368
381
  if (!(knownImageIds instanceof Set)) {
369
382
  throw new TypeError("Appearance validation requires the known site-owned image identities.");
@@ -372,11 +385,7 @@ export function buildAppearanceScalarOperations(documents, knownImageIds) {
372
385
  return APPEARANCE_SCALAR_FIELDS.map((definition) => ({
373
386
  settingsType: definition.settingsType,
374
387
  setting: definition.name,
375
- value: validateScalar(
376
- definition,
377
- appearanceScalarInput(definition, documents[definition.settingsType]?.[definition.name]),
378
- knownImageIds,
379
- ),
388
+ value: checkedScalar(definition, documents[definition.settingsType], knownImageIds),
380
389
  }));
381
390
  }
382
391
 
@@ -21,10 +21,23 @@ export function resolveHeaderBrandColor(value) {
21
21
  return HEADER_BRAND_SEMANTIC_COLOR_TOKENS.has(color) ? `var(${color})` : color;
22
22
  }
23
23
  export function resolveBrandColors(input, resolve = resolveHeaderBrandColor) {
24
- const configured = resolve(input?.brandColor);
25
- const light = resolve(input?.lightBrandColor) || configured;
26
- const dark = resolve(input?.darkBrandColor) || configured || light;
27
- return { light, dark, generic: configured || light || dark };
24
+ const { light, dark, generic } = selectBrandColors(input, resolve);
25
+ return { light: light?.color ?? "", dark: dark?.color ?? "", generic: generic?.color ?? "" };
26
+ }
27
+ /** The source of each scheme's final ink, including the component's generic fallback. */
28
+ export function resolveBrandColorSourceFields(input) {
29
+ const { light, dark, generic } = selectBrandColors(input, resolveBrandColorToken);
30
+ return { light: (light ?? generic)?.field, dark: (dark ?? generic)?.field };
31
+ }
32
+ function selectBrandColors(input, resolve) {
33
+ const select = (field) => {
34
+ const color = resolve(input?.[field]);
35
+ return color ? { field, color } : undefined;
36
+ };
37
+ const configured = select("brandColor");
38
+ const light = select("lightBrandColor") ?? configured;
39
+ const dark = select("darkBrandColor") ?? configured ?? light;
40
+ return { light, dark, generic: configured ?? light ?? dark };
28
41
  }
29
42
  /** The footer preserves the caller's colors without header validation. */
30
43
  export function resolveFooterBrandColors({ light, dark }) {
@@ -1,5 +1,16 @@
1
1
  {
2
2
  "entries": [
3
+ {
4
+ "version": "0.42.0",
5
+ "note": "Check published header and footer contrast while authoring a theme.",
6
+ "behavior": [
7
+ "Theme resolve builds a contrast report for the selected schemes and contexts. JSON chrome rows use response-local indexes in chromeCatalog. The 64 KiB output retains every selected chrome measurement and at least 24 KiB for legacy surfaces.",
8
+ "Validate and theme push report below-AA header and footer paint in the warning list. Validate lists theme.chrome_report_name in siteChecks.skipped while display eligibility is unknown.",
9
+ "Espalier 7.2.0 provides the audited paint catalog and shared WCAG calculation. Contrast measurement runs in the authoring tools.",
10
+ "The help reference version is 63."
11
+ ],
12
+ "help": ["theme", "appearance"]
13
+ },
3
14
  {
4
15
  "version": "0.41.1",
5
16
  "note": "Share renderer URL, social platform and brand-color rules with the authoring CLI while preserving published output.",
@@ -0,0 +1,148 @@
1
+ // Generated from shared/chrome-features.ts by scripts/sync-field-validation.mjs. Do not edit.
2
+ import { isTallHeaderPaint } from "@taprootio/espalier/shared/theme";
3
+ import { resolveFooterTarget } from "./footer-content.js";
4
+ import { resolveHeaderChromePresentation } from "./header-presentation.js";
5
+ import { describeHeaderNavigationItem, MAX_NAVIGATION_DEPTH, prepareHeaderNavigation, SITE_NAVIGATION_KINDS, } from "./site-navigation-groups.js";
6
+ import { isRenderableSocialLink } from "./social-link-url.js";
7
+ /** Flags describe reachable paint across pages, viewport sizes and header scroll positions. */
8
+ export function chromeFeatures({ headerSettings, footerSettings, navItems, footerPagePaths, logoPairs, searchEnabled, hasIconSprite, nameReportEnabled, }) {
9
+ const features = {};
10
+ if (headerSettings) {
11
+ const header = resolveHeaderChromePresentation(headerSettings);
12
+ const navigation = navigationFacts(navItems ?? []);
13
+ const flags = [];
14
+ if (navigation.length) {
15
+ flags.push("burger", `drawer:${header.navDrawerStyle}`);
16
+ if (header.menuDisplay === "auto" && header.layout !== "minimal")
17
+ flags.push("inlineNav");
18
+ }
19
+ if (searchEnabled)
20
+ flags.push("searchButton");
21
+ if (header.showThemeToggle)
22
+ flags.push("themeToggle");
23
+ const modes = [false, ...(header.compactOnScroll ? [true] : [])].map(complete => isTallHeaderPaint({
24
+ heightMultiplier: header.heightMultiplier,
25
+ minHeightMultiplier: header.minHeightMultiplier,
26
+ compactSize: header.compactSizeStandard ? "standard" : "compact",
27
+ complete,
28
+ }) ? "headerPaint:tall" : "headerPaint:standard");
29
+ flags.push(...new Set(modes));
30
+ // Compact artwork only replaces a configured regular logo. The regular
31
+ // logo's generic fallback can supply either scheme.
32
+ const hasLogo = Boolean(logoPairs?.header?.light.url || logoPairs?.header?.dark.url);
33
+ features.header = schemeFeatures(flags, navigation, header.showBrandText ? header.brandText : undefined, {
34
+ light: hasLogo,
35
+ dark: hasLogo,
36
+ });
37
+ }
38
+ if (footerSettings?.enabled === true) {
39
+ const flags = footerContentFlags(footerSettings, footerPagePaths);
40
+ if (hasIconSprite && footerSettings.socialLinks?.some(isRenderableSocialLink))
41
+ flags.push("socialLinks");
42
+ if (nameReportEnabled === true)
43
+ flags.push("footerActionButton");
44
+ const showBrand = footerSettings.showBrand !== false;
45
+ features.footer = schemeFeatures(flags, [], showBrand && footerSettings.showBrandText !== false ? headerSettings?.brandText : undefined, {
46
+ // A one-scheme footer override must not become the opposite scheme's logo.
47
+ light: showBrand && Boolean(logoPairs?.footer?.light.url),
48
+ dark: showBrand && Boolean(logoPairs?.footer?.dark.url),
49
+ });
50
+ }
51
+ else if (nameReportEnabled === true) {
52
+ features.footer = schemeFeatures(["footerActionButton:standalone"], [], undefined, { light: false, dark: false });
53
+ }
54
+ return features;
55
+ }
56
+ /** Use the released button paint, with the page's footer wrapper as the ring backdrop. */
57
+ export function standaloneFooterActionEntries(entries) {
58
+ return entries.filter(entry => entry.flags.includes("footerActionButton")).map(entry => ({
59
+ ...entry,
60
+ flags: entry.flags.map(flag => flag === "footerActionButton" ? "footerActionButton:standalone" : flag),
61
+ background: entry.kind === "ring" ? "background" : entry.background,
62
+ }));
63
+ }
64
+ function schemeFeatures(flags, navigation, brandText, logos) {
65
+ const paintedText = hasText(brandText) ? ["brandText"] : [];
66
+ // Nonbreaking whitespace has no ink but still gives the brand link a focusable box.
67
+ const forScheme = (hasLogo) => ({
68
+ flags: [...flags, ...paintedText, ...(brandText || hasLogo ? ["brandLink"] : [])],
69
+ navigation,
70
+ });
71
+ return { light: forScheme(logos.light), dark: forScheme(logos.dark) };
72
+ }
73
+ // The slots match NavItemKind in Sites.proto.
74
+ const NAVIGATION_KIND_NAMES = ["", SITE_NAVIGATION_KINDS.page, SITE_NAVIGATION_KINDS.externalUrl, SITE_NAVIGATION_KINDS.groupHeader];
75
+ const BUTTON_APPEARANCE = "NAV_ITEM_APPEARANCE_BUTTON";
76
+ function normalizeNavigationItem(item) {
77
+ return {
78
+ ...item,
79
+ kind: typeof item.kind === "number" ? NAVIGATION_KIND_NAMES[item.kind] : item.kind,
80
+ appearance: item.appearance === 2 ? BUTTON_APPEARANCE : item.appearance,
81
+ children: item.children?.map(normalizeNavigationItem),
82
+ };
83
+ }
84
+ function navigationFacts(items) {
85
+ const facts = [];
86
+ const visit = (nodes, depth) => {
87
+ // Linked-group normalization can add a child just past the published cap.
88
+ if (depth > MAX_NAVIGATION_DEPTH)
89
+ return;
90
+ for (const node of nodes) {
91
+ const { group, url, button } = describeHeaderNavigationItem(node, SITE_NAVIGATION_KINDS, BUTTON_APPEARANCE);
92
+ facts.push({
93
+ depth: depth === 1 ? "top-level" : "nested",
94
+ kind: group ? "group" : button ? "button" : "plain",
95
+ anchor: Boolean(url),
96
+ // Espalier compares the raw URL (apart from a trailing slash) to location.pathname.
97
+ canBeCurrent: url.startsWith("/") && new URL(url, "https://taproot.invalid").pathname === url,
98
+ });
99
+ if (node.children?.length)
100
+ visit(node.children, depth + 1);
101
+ }
102
+ };
103
+ visit(prepareHeaderNavigation(items.map(normalizeNavigationItem), SITE_NAVIGATION_KINDS), 1);
104
+ return facts;
105
+ }
106
+ function hasText(text) {
107
+ return Boolean(text?.trim());
108
+ }
109
+ function footerContentFlags(settings, paths) {
110
+ const resolves = (target) => Boolean(resolveFooterTarget(target, paths));
111
+ const hasLinkText = (link) => hasText(link.label) && resolves(link);
112
+ let headings = false;
113
+ let body = false;
114
+ let links = false;
115
+ for (const { groups = [] } of settings.linkColumns ?? []) {
116
+ for (const group of groups) {
117
+ for (const link of group.links ?? []) {
118
+ if (!resolves(link))
119
+ continue;
120
+ headings ||= hasText(group.heading);
121
+ links ||= hasText(link.label);
122
+ }
123
+ }
124
+ }
125
+ const recordParagraph = (paragraph, heading) => {
126
+ for (const run of paragraph?.runs ?? []) {
127
+ if (!hasText(run.text))
128
+ continue;
129
+ if (run.link && resolves(run.link))
130
+ links = true;
131
+ else if (heading)
132
+ headings = true;
133
+ else
134
+ body = true;
135
+ }
136
+ };
137
+ recordParagraph(settings.asideHeadingContent?.paragraphs?.[0], true);
138
+ for (const content of [settings.asideBodyContent, settings.bottomContent]) {
139
+ for (const paragraph of content?.paragraphs ?? [])
140
+ recordParagraph(paragraph, false);
141
+ }
142
+ links ||= Boolean(settings.asideCta && hasLinkText(settings.asideCta)) || Boolean(settings.bottomLinks?.some(hasLinkText));
143
+ return [
144
+ ...(headings ? ["footerHeadings"] : []),
145
+ ...(body ? ["footerBody"] : []),
146
+ ...(links ? ["footerLinks"] : []),
147
+ ];
148
+ }
@@ -0,0 +1,146 @@
1
+ import { NAV_ITEM_KIND_EXTERNAL_URL, NAV_ITEM_KIND_PAGE, PAGE_STATUS_PUBLISHED } from "./api.js";
2
+ import { resolveBrandColors, resolveBrandColorSourceFields, resolveBrandColorToken, resolveFooterBrandColors } from "./brand-color.js";
3
+ import { chromeFeatures } from "./chrome-features.js";
4
+ import { isCanonicalUuid } from "./errors.js";
5
+ import { validateFooterDocument } from "./footer-contract.js";
6
+ import { resolveFooterLogoPairs } from "./footer-branding.js";
7
+ import { resolveHeaderLogoPairs } from "./header-presentation.js";
8
+ import { logoInputsFromSettings } from "./logo-inputs.js";
9
+ import { sharedDeclaredThemeContextNames } from "./theme-contexts.js";
10
+ import { validateNavigationWorkspaceDocument } from "./verbs/nav-push.js";
11
+ import { NAVIGATION_FILE_NAME, normalizePagePath, readWorkspaceJson, WORKSPACE_LIMITS } from "./workspace.js";
12
+
13
+ export const CHROME_NAVIGATION_UNAVAILABLE_MESSAGE =
14
+ "Navigation contrast was not checked because navigation information was unavailable.";
15
+
16
+ export const CHROME_OFFLINE_PAGE_LIMITATION =
17
+ "navigation or footer page-link contrast for destinations without a published path in the workspace inventory";
18
+
19
+ export const CHROME_REPORT_NAME_RULE = "theme.chrome_report_name";
20
+
21
+ // The workspace has no eligibility projection until TR01385.
22
+ export function selectNameReportEligibility({ saved, current, manifest }) {
23
+ return undefined;
24
+ }
25
+
26
+ function isSettingsOnly(resources) {
27
+ return resources.settingsOnly === true || resources.manifest?.authoringSurface !== undefined;
28
+ }
29
+
30
+ /** Take optional workspace evidence while the caller still owns its read snapshot. */
31
+ export async function captureChromeResources(resources) {
32
+ if (resources.workspaceDir === undefined || isSettingsOnly(resources) || Object.hasOwn(resources, "navigation")) return resources;
33
+ const { manifest, siteId, workspaceDir, knownPageResourceIds } = resources;
34
+ try {
35
+ const parsed = await readWorkspaceJson(workspaceDir, NAVIGATION_FILE_NAME, WORKSPACE_LIMITS.navigationBytes);
36
+ const knownPages = manifest === undefined ? undefined : {
37
+ pageIds: new Set(manifest.pages.map((page) => page?.pageId).filter(isCanonicalUuid)),
38
+ resourceIds: knownPageResourceIds,
39
+ };
40
+ const navigation = validateNavigationWorkspaceDocument(parsed, siteId, knownPages);
41
+ return { ...resources, navigation };
42
+ } catch {
43
+ return { ...resources, navigation: undefined };
44
+ }
45
+ }
46
+
47
+ function workspacePublishedPagePaths(manifest) {
48
+ const paths = new Map();
49
+ for (const page of manifest?.pages ?? []) {
50
+ if (page?.status !== PAGE_STATUS_PUBLISHED || !isCanonicalUuid(page.resourceId)) continue;
51
+ const path = normalizePagePath(page.path);
52
+ if (path !== undefined) paths.set(page.resourceId, `/${path}`);
53
+ }
54
+ return paths;
55
+ }
56
+
57
+ function resolveNavigation(items, pagePaths) {
58
+ return items?.map((item) => ({
59
+ ...item,
60
+ url: item.kind === NAV_ITEM_KIND_PAGE
61
+ ? (pagePaths === undefined ? "/" : pagePaths.get(item.resourceId) ?? "")
62
+ : item.kind === NAV_ITEM_KIND_EXTERNAL_URL
63
+ ? item.externalUrl
64
+ : "",
65
+ children: resolveNavigation(item.children, pagePaths) ?? [],
66
+ }));
67
+ }
68
+
69
+ function resolveLogoPairs(style, header, footer, media, delivery) {
70
+ const input = logoInputsFromSettings(style, footer, media);
71
+ // Local art is represented by an image identity. An authoritative response
72
+ // can also say that an assigned image has no delivery URL.
73
+ for (const name of ["light", "dark", "lightCompact", "darkCompact"]) {
74
+ const id = `${name}LogoId`;
75
+ const url = `${name}LogoUrl`;
76
+ const delivered = delivery?.styleSettings;
77
+ if (delivered?.[id] && delivered[id] === style?.[id]) {
78
+ input[url] = typeof delivered[url] === "string" ? delivered[url] : "";
79
+ }
80
+ }
81
+ for (const scheme of ["light", "dark"]) {
82
+ const delivered = delivery?.sitePublishingPreferences?.footerSettings?.[scheme];
83
+ if (delivered?.logoId && delivered.logoId === footer?.[scheme]?.logoId) {
84
+ input[`${scheme}FooterLogoUrl`] = typeof delivered.logoUrl === "string" ? delivered.logoUrl : "";
85
+ }
86
+ }
87
+ return {
88
+ header: resolveHeaderLogoPairs({ ...input, logoVariant: header?.logoVariant }),
89
+ footer: resolveFooterLogoPairs({ ...input, logoVariant: footer?.logoVariant }),
90
+ };
91
+ }
92
+
93
+ function checkedFooterSettings(publishing, resources) {
94
+ if (Object.hasOwn(resources, "footerSettings")) return resources.footerSettings;
95
+ if (publishing?.footerSettings === undefined) return undefined;
96
+ try {
97
+ return validateFooterDocument(publishing.footerSettings, {
98
+ knownPageResourceIds: resources.knownPageResourceIds,
99
+ knownImageIds: resources.knownImageIds,
100
+ });
101
+ } catch {
102
+ return undefined;
103
+ }
104
+ }
105
+
106
+ /** The report uses the appearance and resources already accepted by the caller. */
107
+ export function buildChromeInput({ appearance, resources, nameReportEnabled }) {
108
+ const { style, header, footerPresentation } = appearance;
109
+ const publishing = resources.presentation === undefined
110
+ ? appearance.publishing
111
+ : resources.presentation.sitePublishingPreferences;
112
+ const footer = checkedFooterSettings(publishing, resources);
113
+ const footerSettings = footer === undefined ? undefined : { ...footer, ...footerPresentation };
114
+ const settingsOnly = isSettingsOnly(resources);
115
+ const footerPagePaths = settingsOnly ? new Map()
116
+ : resources.source === "site" ? undefined
117
+ : workspacePublishedPagePaths(resources.manifest);
118
+ const navItems = settingsOnly ? undefined : resolveNavigation(resources.navigation?.navItems, footerPagePaths);
119
+ const logoPairs = resolveLogoPairs(style, header, footerSettings, resources.mediaManifest?.media, resources.presentation);
120
+ const headerBrandColors = resolveBrandColors(header, resolveBrandColorToken);
121
+ const features = chromeFeatures({
122
+ headerSettings: header,
123
+ footerSettings,
124
+ navItems,
125
+ footerPagePaths,
126
+ logoPairs,
127
+ searchEnabled: publishing?.allowSearch === true,
128
+ hasIconSprite: true,
129
+ nameReportEnabled: footerSettings === undefined ? undefined : nameReportEnabled,
130
+ });
131
+ const contexts = new Set(sharedDeclaredThemeContextNames(style?.lightTheme, style?.darkTheme));
132
+ const surfaces = [
133
+ { role: "header", context: header?.context || null, brandColors: headerBrandColors, features: features.header },
134
+ {
135
+ role: "footer",
136
+ context: footerSettings?.enabled === true ? footerSettings.context || null : null,
137
+ brandColors: resolveFooterBrandColors(headerBrandColors),
138
+ features: features.footer,
139
+ },
140
+ ];
141
+ return {
142
+ paintSurfaces: surfaces.filter(({ context, features }) => features !== undefined && (context === null || contexts.has(context))),
143
+ brandColorSourceFields: resolveBrandColorSourceFields(header),
144
+ navigationUnavailable: navItems === undefined,
145
+ };
146
+ }
@@ -0,0 +1,92 @@
1
+ export const CHROME_UNAVAILABLE_MESSAGE = "Chrome contrast was not checked because the theme report was unavailable.";
2
+
3
+ const CONTEXT_DISPLAY_LENGTH = 128;
4
+
5
+ // Shown ratios round down, so a pair 0.004 short of AA never displays as 4.50.
6
+ export function floorTo(value, places) {
7
+ const scale = 10 ** places;
8
+ return Math.floor(value * scale + 1e-9) / scale;
9
+ }
10
+
11
+ export function displayChromeRatio(ratio, required) {
12
+ const shown = floorTo(ratio, 2);
13
+ // The tolerance in floorTo can otherwise round a value just below AA up to AA.
14
+ return ratio < required && shown >= required ? required - 0.01 : shown;
15
+ }
16
+
17
+ export function displayChromeContext(context) {
18
+ if (context === null || context.length <= CONTEXT_DISPLAY_LENGTH) return { context };
19
+ return {
20
+ context: context.slice(0, CONTEXT_DISPLAY_LENGTH),
21
+ contextTruncated: true,
22
+ contextLength: context.length,
23
+ };
24
+ }
25
+
26
+ function dictionary(values) {
27
+ const items = [...new Set(values)].sort();
28
+ return { items, indexes: new Map(items.map((item, index) => [item, index])) };
29
+ }
30
+
31
+ function identityKey({ element, foreground, background, state, kind }) {
32
+ return JSON.stringify([element, foreground, background, state, kind]);
33
+ }
34
+
35
+ /** Index the selected paint while retaining the callers' scheme, card and row order. */
36
+ export function indexChromePaint(entries) {
37
+ const identities = new Map();
38
+ for (const cards of Object.values(entries)) {
39
+ for (const { pairs } of cards) {
40
+ for (const pair of pairs) identities.set(identityKey(pair), pair);
41
+ }
42
+ }
43
+ const pairs = [...identities.values()];
44
+ const elements = dictionary(pairs.map(({ element }) => element));
45
+ const colors = dictionary(pairs.flatMap(({ foreground, background }) => [foreground, background]));
46
+ const states = dictionary(pairs.map(({ state }) => state));
47
+ const kinds = dictionary(pairs.map(({ kind }) => kind));
48
+ // Sorting each dictionary makes an index stay the same or shrink when entries are removed.
49
+ const pairKeys = dictionary(identities.keys());
50
+ const chromeCatalog = {
51
+ elements: elements.items,
52
+ colors: colors.items,
53
+ states: states.items,
54
+ kinds: kinds.items,
55
+ pairs: pairKeys.items.map((key) => {
56
+ const { element, foreground, background, state, kind } = identities.get(key);
57
+ return [
58
+ elements.indexes.get(element),
59
+ colors.indexes.get(foreground),
60
+ colors.indexes.get(background),
61
+ states.indexes.get(state),
62
+ kinds.indexes.get(kind),
63
+ ];
64
+ }),
65
+ };
66
+ const chrome = Object.fromEntries(Object.entries(entries).map(([scheme, cards]) => [
67
+ scheme,
68
+ cards.map(({ role, context, pairs }) => ({
69
+ role,
70
+ ...displayChromeContext(context),
71
+ pairs: pairs.map((pair) => [
72
+ pairKeys.indexes.get(identityKey(pair)),
73
+ displayChromeRatio(pair.ratio, pair.required),
74
+ pair.required,
75
+ ]),
76
+ })),
77
+ ]));
78
+ return { chrome, chromeCatalog };
79
+ }
80
+
81
+ export function decodeChromePair(catalog, [identityIndex, ratio, required]) {
82
+ const [element, foreground, background, state, kind] = catalog.pairs[identityIndex];
83
+ return {
84
+ element: catalog.elements[element],
85
+ foreground: catalog.colors[foreground],
86
+ background: catalog.colors[background],
87
+ state: catalog.states[state],
88
+ kind: catalog.kinds[kind],
89
+ ratio,
90
+ required,
91
+ };
92
+ }
@@ -0,0 +1,52 @@
1
+ {
2
+ "footer": [
3
+ {
4
+ "element": "social-link",
5
+ "foreground": "link",
6
+ "background": "layer2",
7
+ "state": "rest",
8
+ "kind": "graphic",
9
+ "flags": ["socialLinks"]
10
+ },
11
+ {
12
+ "element": "social-link",
13
+ "foreground": "linkHover",
14
+ "background": "linkHoverBg",
15
+ "state": "hover",
16
+ "kind": "graphic",
17
+ "flags": ["socialLinks"]
18
+ },
19
+ {
20
+ "element": "social-link",
21
+ "foreground": "link",
22
+ "background": "layer2",
23
+ "state": "focus",
24
+ "kind": "graphic",
25
+ "flags": ["socialLinks"]
26
+ },
27
+ {
28
+ "element": "social-link",
29
+ "foreground": "link",
30
+ "background": "layer2",
31
+ "state": "focus",
32
+ "kind": "ring",
33
+ "flags": ["socialLinks"]
34
+ },
35
+ {
36
+ "element": "social-link",
37
+ "foreground": "linkHover",
38
+ "background": "linkHoverBg",
39
+ "state": "hover-focus",
40
+ "kind": "graphic",
41
+ "flags": ["socialLinks"]
42
+ },
43
+ {
44
+ "element": "social-link",
45
+ "foreground": "linkHover",
46
+ "background": "layer2",
47
+ "state": "hover-focus",
48
+ "kind": "ring",
49
+ "flags": ["socialLinks"]
50
+ }
51
+ ]
52
+ }