@bridge-ds/toolbar 0.2.0 → 0.4.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.
@@ -1 +0,0 @@
1
- {"version":3,"file":"Toolbar-CzR1TM9x.js","sources":["../src/github.ts","../src/diff.ts","../src/outline.ts","../src/useChangedElements.ts","../src/pin.ts","../src/ChangeOutlines.tsx","../src/useTogether.ts","../src/Toolbar.tsx"],"sourcesContent":["// What the toolbar knows about a change, read from the public repository through Bridge's read proxy (reads.ts; GitHub\n// directly when Bridge refuses): its title and head commit, its files (token change or code change, and which themes\n// and brands its tokens touch), how far live has moved on since it started, and the visual impact manifest of that\n// commit. At most six API reads per change and session, kept in sessionStorage. The manifest is looked up in the tree\n// first, so a change without one never shows a failed request.\nimport { DEFAULT_PROXY, githubReads, type Reads } from './reads';\nimport { changedScreens, changeMode, readableTitle, tokenChanges, type BridgeBuild, type ChangeMode, type ManifestShot, type Screen, type TokenChange } from './session';\n\nexport interface ChangeFacts {\n number: number;\n title: string;\n url: string;\n sha: string;\n mode: ChangeMode;\n /** Every file the change edits (token layers tell which themes and brands can differ). */\n files: string[];\n /** Commits live (the default branch) gained since the change started; null when GitHub could not say. */\n behind: number | null;\n /** The tokens whose value the change edits, from its token files before and after (raw files, no API read). */\n tokens: TokenChange[];\n /** Admin screens this change alters, most changed first. Null when the visual impact has not run for this commit. */\n screens: Screen[] | null;\n}\n\nconst VISUAL_BRANCH = 'bridge-visual';\nconst cacheKey = (n: number) => `bridge-admin:facts:v3:${n}`;\n\nfunction session(): Storage | null {\n try {\n return window.sessionStorage;\n } catch {\n return null;\n }\n}\n\n/** The reads of a build: Bridge's proxy for its design system (the product's repository is one it lists), else GitHub. */\nexport function readsOf(build: Pick<BridgeBuild, 'owner' | 'repo' | 'ds' | 'proxy'>): Reads {\n return githubReads({ team: build.ds ?? `${build.owner}/${build.repo}`, proxy: build.proxy === undefined ? DEFAULT_PROXY : build.proxy });\n}\n\ntype Tree = { tree: { path: string; type: string; sha: string }[] };\n\n/** The manifest of pr-<n>/<sha>/ on the visual impact branch, or null when that folder does not exist. */\nasync function readManifest(gh: Reads, build: Pick<BridgeBuild, 'owner' | 'repo'>, R: string, n: number, sha: string): Promise<{ shots?: ManifestShot[] } | null> {\n const root = await gh.api<Tree>(`${R}/git/trees/${VISUAL_BRANCH}`).catch(() => null);\n const pr = root?.tree.find((e) => e.path === `pr-${n}` && e.type === 'tree');\n if (!pr) return null;\n const commits = await gh.api<Tree>(`${R}/git/trees/${pr.sha}`).catch(() => null);\n if (!commits?.tree.some((e) => e.path === sha && e.type === 'tree')) return null;\n return gh\n .file(build.owner, build.repo, VISUAL_BRANCH, `pr-${n}/${sha}/manifest.json`)\n .then((t) => JSON.parse(t) as { shots?: ManifestShot[] })\n .catch(() => null);\n}\n\nexport async function loadChange(build: Pick<BridgeBuild, 'owner' | 'repo' | 'ds' | 'proxy'>, n: number, gh: Reads = readsOf(build)): Promise<ChangeFacts> {\n const store = session();\n try {\n const cached = store?.getItem(cacheKey(n));\n if (cached) return JSON.parse(cached) as ChangeFacts;\n } catch {\n // A broken cache entry is read again from GitHub.\n }\n const R = `/repos/${build.owner}/${build.repo}`;\n const [pull, files] = await Promise.all([\n gh.api<{ number: number; title: string; html_url: string; head: { sha: string }; base: { ref: string; sha: string } }>(`${R}/pulls/${n}`),\n gh.api<{ filename: string; status: string; previous_filename?: string }[]>(`${R}/pulls/${n}/files?per_page=100`),\n ]);\n // Token files at the base and the head of the change: the real diff, token by token. Added files have no base and\n // removed ones no head, so neither is asked for.\n const tokenFiles = files.filter((f) => f.filename.endsWith('.tokens.json')).slice(0, 8);\n const version = (sha: string, path: string) =>\n gh\n .file(build.owner, build.repo, sha, path)\n .then((t) => JSON.parse(t) as unknown)\n .catch(() => null);\n const tokenReads = Promise.all(\n tokenFiles.map(async (f) =>\n tokenChanges(\n f.filename,\n f.status === 'added' ? null : await version(pull.base.sha, f.previous_filename ?? f.filename),\n f.status === 'removed' ? null : await version(pull.head.sha, f.filename),\n ),\n ),\n );\n const [compare, manifest, tokens] = await Promise.all([\n gh.api<{ behind_by?: number }>(`${R}/compare/${encodeURIComponent(pull.base.ref)}...${pull.head.sha}`).catch(() => null),\n readManifest(gh, build, R, n, pull.head.sha),\n tokenReads,\n ]);\n const names = files.map((f) => f.filename);\n const facts: ChangeFacts = {\n number: pull.number,\n title: readableTitle(pull.title),\n url: pull.html_url,\n sha: pull.head.sha,\n mode: changeMode(names),\n files: names,\n tokens: tokens.flat(),\n behind: typeof compare?.behind_by === 'number' ? compare.behind_by : null,\n screens: manifest ? changedScreens(manifest.shots) : null,\n };\n try {\n store?.setItem(cacheKey(n), JSON.stringify(facts));\n } catch {\n // Storage blocked: the next page load reads GitHub again.\n }\n return facts;\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Changes tried together (`?bridge=101,118,120`): no preview holds all of them, so the toolbar runs on the production\n// admin and applies their token edits live. For each change: its title and version (one read), one compare against\n// the library (the files it edits since it started, and where it started), then its token files at its start and now\n// (contents at a commit, kept for good by Bridge). Two API reads per change.\n\nexport interface TogetherFacts {\n number: number;\n title: string;\n url: string;\n sha: string;\n mode: ChangeMode;\n /** Its token files where it started and now (relative to the tokens root); null for a code change. */\n source: { number: number; base: Record<string, string | undefined>; head: Record<string, string | undefined>; files: string[] } | null;\n}\n\nconst togetherKey = (n: number) => `bridge-admin:together:v1:${n}`;\n\nexport async function loadTogetherChange(build: Pick<BridgeBuild, 'owner' | 'repo' | 'defaultBranch' | 'tokensRoot' | 'ds' | 'proxy'>, n: number, gh: Reads = readsOf(build)): Promise<TogetherFacts> {\n const store = session();\n try {\n const cached = store?.getItem(togetherKey(n));\n if (cached) return JSON.parse(cached) as TogetherFacts;\n } catch {\n // A broken cache entry is read again from GitHub.\n }\n const R = `/repos/${build.owner}/${build.repo}`;\n const pull = await gh.api<{ number: number; title: string; html_url: string; head: { sha: string }; base: { ref: string } }>(`${R}/pulls/${n}`);\n const compare = await gh.api<{ merge_base_commit?: { sha: string } | null; files?: { filename: string; status: string; previous_filename?: string }[] }>(\n `${R}/compare/${encodeURIComponent(build.defaultBranch ?? pull.base.ref)}...${pull.head.sha}`,\n );\n const files = compare.files ?? [];\n const names = files.flatMap((f) => (f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]));\n const root = `${(build.tokensRoot ?? 'packages/tokens/src').replace(/^\\/+|\\/+$/g, '')}/`;\n // Only token files under the root (and release notes) can be applied live; anything else is code.\n const tokenOnly = files.length > 0 && files.length < 300 && names.every((f) => (f.startsWith(root) && f.endsWith('.tokens.json')) || /contrast\\.checks\\.json$/.test(f) || f.startsWith('.changeset/'));\n const start = compare.merge_base_commit?.sha;\n let source: TogetherFacts['source'] = null;\n if (tokenOnly && start) {\n const text = (sha: string, path: string) => gh.file(build.owner, build.repo, sha, path);\n const mine = files.filter((f) => f.filename.startsWith(root) && f.filename.endsWith('.tokens.json'));\n const src = { number: n, base: {} as Record<string, string | undefined>, head: {} as Record<string, string | undefined>, files: mine.map((f) => f.filename.slice(root.length)) };\n await Promise.all(\n mine.map(async (f) => {\n const rel = f.filename.slice(root.length);\n src.base[rel] = f.status === 'added' ? undefined : await text(start, f.previous_filename ?? f.filename);\n src.head[rel] = f.status === 'removed' ? undefined : await text(pull.head.sha, f.filename);\n }),\n );\n source = src;\n }\n const facts: TogetherFacts = { number: pull.number, title: readableTitle(pull.title), url: pull.html_url, sha: pull.head.sha, mode: tokenOnly ? 'tokens' : 'code', source };\n try {\n store?.setItem(togetherKey(n), JSON.stringify(facts));\n } catch {\n // Storage blocked: the next page load reads GitHub again.\n }\n return facts;\n}\n","// \"Show what changed\", the pure part: from the page's style rules and the tokens a change edits, which rules can\n// render differently and through which CSS properties. The DOM part (outline.ts) then compares real computed styles\n// with the live tokens and with the change's tokens, and outlines only what differs.\n\nexport interface Decl {\n prop: string;\n value: string;\n}\n\nexport interface RuleLike {\n selector: string;\n decls: Decl[];\n}\n\nexport interface Usage {\n /** Selector without pseudo-elements, for querySelectorAll. */\n selector: string;\n /** \"::before\" or \"::after\" when the rule styles a pseudo-element, else null. */\n pseudo: string | null;\n /** Computed (longhand) properties to compare. */\n props: string[];\n /** CSS variables of the changed tokens this rule depends on, directly or through other variables. */\n roots: string[];\n}\n\nconst VAR = /var\\(\\s*(--[\\w-]+)/g;\n\n/** The custom properties a value reads: \"var(--a, var(--b))\" -> [\"--a\", \"--b\"]. */\nexport function varsIn(value: string): string[] {\n return [...value.matchAll(VAR)].map((m) => m[1]!);\n}\n\n/**\n * Every variable that resolves through a changed one, with the changed ones it comes from. Definitions are read from\n * every rule whatever its scope (a superset: the computed comparison removes what does not really differ).\n */\nexport function dependents(rules: RuleLike[], changed: string[]): Map<string, Set<string>> {\n const deps = new Map<string, Set<string>>();\n for (const r of rules) {\n for (const d of r.decls) {\n if (!d.prop.startsWith('--')) continue;\n for (const v of varsIn(d.value)) {\n if (!deps.has(d.prop)) deps.set(d.prop, new Set());\n deps.get(d.prop)!.add(v);\n }\n }\n }\n const roots = new Map<string, Set<string>>(changed.map((c) => [c, new Set([c])]));\n let grew = true;\n while (grew) {\n grew = false;\n for (const [name, uses] of deps) {\n for (const u of uses) {\n const from = roots.get(u);\n if (!from) continue;\n if (!roots.has(name)) roots.set(name, new Set());\n const mine = roots.get(name)!;\n for (const f of from) {\n if (!mine.has(f)) {\n mine.add(f);\n grew = true;\n }\n }\n }\n }\n }\n return roots;\n}\n\nconst SIDES = ['top', 'right', 'bottom', 'left'];\nconst SHORTHANDS: Record<string, string[]> = {\n background: ['background-color', 'background-image'],\n border: [...SIDES.map((s) => `border-${s}-color`), ...SIDES.map((s) => `border-${s}-width`)],\n 'border-color': SIDES.map((s) => `border-${s}-color`),\n 'border-width': SIDES.map((s) => `border-${s}-width`),\n 'border-block': ['border-top-color', 'border-bottom-color', 'border-top-width', 'border-bottom-width'],\n 'border-inline': ['border-left-color', 'border-right-color', 'border-left-width', 'border-right-width'],\n 'border-radius': ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'],\n outline: ['outline-color', 'outline-width'],\n padding: SIDES.map((s) => `padding-${s}`),\n margin: SIDES.map((s) => `margin-${s}`),\n inset: SIDES,\n gap: ['row-gap', 'column-gap'],\n font: ['font-family', 'font-size', 'font-weight', 'line-height'],\n 'text-decoration': ['text-decoration-color', 'text-decoration-line'],\n transition: ['transition-duration', 'transition-timing-function'],\n};\nfor (const s of SIDES) SHORTHANDS[`border-${s}`] = [`border-${s}-color`, `border-${s}-width`];\nfor (const [logical, physical] of [\n ['border-block-start', 'top'],\n ['border-block-end', 'bottom'],\n ['border-inline-start', 'left'],\n ['border-inline-end', 'right'],\n] as const) {\n SHORTHANDS[logical] = [`border-${physical}-color`, `border-${physical}-width`];\n SHORTHANDS[`${logical}-color`] = [`border-${physical}-color`];\n SHORTHANDS[`${logical}-width`] = [`border-${physical}-width`];\n}\nSHORTHANDS['padding-inline'] = ['padding-left', 'padding-right'];\nSHORTHANDS['padding-block'] = ['padding-top', 'padding-bottom'];\nSHORTHANDS['margin-inline'] = ['margin-left', 'margin-right'];\nSHORTHANDS['margin-block'] = ['margin-top', 'margin-bottom'];\n\n/** The computed properties a declared one sets (shorthands and logical properties expand to physical longhands). */\nexport function longhands(prop: string): string[] {\n return SHORTHANDS[prop] ?? [prop];\n}\n\n/** Splits \"a, b::before\" into its own selectors, keeping commas inside :is() / :where() / :not(). */\nfunction splitSelectors(selector: string): string[] {\n const out: string[] = [];\n let depth = 0;\n let cur = '';\n for (const ch of selector) {\n if (ch === '(') depth++;\n if (ch === ')') depth--;\n if (ch === ',' && depth === 0) {\n out.push(cur.trim());\n cur = '';\n } else cur += ch;\n }\n if (cur.trim()) out.push(cur.trim());\n return out;\n}\n\n/**\n * The rules whose regular (non-custom) properties read a changed token, directly or through other variables, grouped\n * by selector and pseudo-element.\n */\n/** Properties that paint nothing on their own element (native control tint, caret): never a surface. */\nconst NON_PAINT = new Set(['accent-color', 'caret-color']);\n\nexport function usages(rules: RuleLike[], roots: Map<string, Set<string>>): Usage[] {\n const out = new Map<string, Usage>();\n for (const r of rules) {\n const hits = r.decls.filter((d) => !d.prop.startsWith('--') && !NON_PAINT.has(d.prop)).map((d) => ({ d, from: varsIn(d.value).filter((v) => roots.has(v)) })).filter((x) => x.from.length);\n if (!hits.length) continue;\n for (const one of splitSelectors(r.selector)) {\n const m = /::?(before|after|placeholder|marker|selection|backdrop)\\b/i.exec(one);\n const pseudo = m ? `::${m[1]!.toLowerCase()}` : null;\n // A text selection only shows while someone selects: not a surface of the screen.\n if (pseudo === '::selection') continue;\n const selector = (m ? one.slice(0, m.index) + one.slice(m.index + m[0].length) : one).trim() || '*';\n const key = `${selector}|${pseudo ?? ''}`;\n const u = out.get(key) ?? { selector, pseudo, props: [], roots: [] };\n for (const { d, from } of hits) {\n for (const p of longhands(d.prop)) if (!u.props.includes(p)) u.props.push(p);\n for (const v of from) for (const root of roots.get(v)!) if (!u.roots.includes(root)) u.roots.push(root);\n }\n out.set(key, u);\n }\n }\n return [...out.values()];\n}\n\n/**\n * Surfaces: the outermost changed elements. An element whose ancestor changes for the same token and property paints\n * the same thing inside it, so only the ancestor counts, unless it floats (sticky or fixed): then it paints over other\n * content and is a surface of its own. `contains(a, b)` is true when a is an ancestor of b.\n */\nexport function outermost<T extends { keys: string[]; floating?: boolean }>(items: T[], contains: (a: T, b: T) => boolean): T[] {\n return items.filter((b) => b.floating || !items.some((a) => a !== b && contains(a, b) && b.keys.every((k) => a.keys.includes(k))));\n}\n\n/** \"1 token changed: Page canvas, on 3 surfaces\". */\nexport function surfaceLine(tokenNames: string[], surfaces: number): string {\n const names = [...new Set(tokenNames)];\n const tokens = `${names.length} ${names.length === 1 ? 'token' : 'tokens'} changed: ${names.slice(0, 3).join(', ')}${names.length > 3 ? ` and ${names.length - 3} more` : ''}`;\n return `${tokens}, on ${surfaces} ${surfaces === 1 ? 'surface' : 'surfaces'}`;\n}\n\n/** Changed surfaces exist on this screen but none is in view: say so, never \"nothing changes\". */\nexport function outOfView(n: number): string {\n return n === 1 ? 'Nothing changed in view. 1 surface changes further down: scroll to see it.' : `Nothing changed in view. ${n} surfaces change further down: scroll to see them.`;\n}\n\nexport const EMPTY_LINE = \"This change doesn't touch this screen. Open Screens to see where it does.\";\n\nexport interface ElementInfo {\n tag: string;\n role: string | null;\n ariaLabel: string | null;\n /** Class names, to read a CSS module's local name (\"_sticky_1f7pa_38\" -> \"sticky\"). */\n classes: string[];\n /** A heading inside it, or its own short text. */\n text: string | null;\n}\n\nconst LANDMARKS: Record<string, string> = { main: 'Content', header: 'Header', nav: 'Navigation', aside: 'Sidebar', footer: 'Footer', form: 'Form', dialog: 'Dialog' };\nconst ROLES: Record<string, string> = { main: 'Content', banner: 'Header', navigation: 'Navigation', complementary: 'Sidebar', contentinfo: 'Footer', dialog: 'Dialog', toolbar: 'Toolbar', tablist: 'Tabs', table: 'Table', grid: 'Table', menu: 'Menu', listbox: 'List' };\nconst MODULES: Record<string, string> = { mark: 'Shop logo', shell: 'App shell', column: 'Content column', content: 'Content', sticky: 'Save bar', toolbar: 'Save bar', header: 'Header', sidebar: 'Sidebar', card: 'Card', panel: 'Panel' };\nconst MODULE_CLASS = /^_([a-zA-Z][a-zA-Z0-9]*)_[a-z0-9]+_\\d+$/;\n\nconst words = (s: string) => {\n const w = s.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/[-_]+/g, ' ').trim().toLowerCase();\n return w.charAt(0).toUpperCase() + w.slice(1);\n};\n\n/** The role a person would name: landmark, ARIA role, or component (CSS module), then its text in parentheses. */\nexport function roleName(info: ElementInfo): string {\n const tag = info.tag.toLowerCase();\n if (tag === 'html' || tag === 'body') return 'Page';\n // Chart marks (recharts draws SVG): the chart is what a person sees.\n if (['svg', 'path', 'line', 'rect', 'circle', 'g', 'polyline', 'stop'].includes(tag)) return 'Chart';\n const locals = info.classes.map((c) => MODULE_CLASS.exec(c)?.[1]).filter((l): l is string => Boolean(l));\n const local = locals.find((l) => MODULES[l]) ?? locals[0];\n const role = info.ariaLabel || (info.role && ROLES[info.role]) || LANDMARKS[tag] || (local ? (MODULES[local] ?? words(local)) : null);\n // A logo's letters are not a name: \"Shop logo\", not \"Shop logo (NP)\".\n const text = local === 'mark' ? null : info.text && info.text.length <= 32 && info.text !== role ? info.text : null;\n if (role) return text ? `${role} (${text})` : role;\n return text ?? tag;\n}\n\n/** C toggles the outlines, unless the person is typing or holds a modifier. */\nexport function isKey(e: { key: string; altKey: boolean; ctrlKey: boolean; metaKey: boolean; target: unknown }, key: string): boolean {\n if (e.altKey || e.ctrlKey || e.metaKey || e.key.toLowerCase() !== key) return false;\n const t = e.target as { tagName?: string; isContentEditable?: boolean; closest?: (s: string) => unknown } | null;\n if (!t) return true;\n if (t.isContentEditable) return false;\n const tag = (t.tagName ?? '').toLowerCase();\n if (tag === 'input' || tag === 'textarea' || tag === 'select') return false;\n return !(t.closest && t.closest('[role=\"combobox\"], [role=\"textbox\"], [role=\"searchbox\"]'));\n}\n","// \"Show what changed\", the DOM part. Finds the elements of the current screen whose computed style differs between\n// the live tokens and the change's tokens: the rules that read a changed token (diff.ts) give the candidates and the\n// properties to compare, then the live stylesheet is switched on and off inside one synchronous task (no paint in\n// between, so nothing flashes) and only real differences are kept. Never guessed.\nimport { dependents, longhands, outermost, roleName, usages, varsIn, type RuleLike, type Usage } from './diff';\n\nexport interface PropChange {\n prop: string;\n /** Computed value with the live tokens. */\n before: string;\n /** Computed value with the change's tokens. */\n after: string;\n}\n\nexport interface ChangedElement {\n el: Element;\n pseudo: string | null;\n /** CSS variables of the changed tokens behind the difference. */\n roots: string[];\n props: PropChange[];\n /** What a person calls it: \"Page\", \"Save bar (Save changes)\". */\n label: string;\n /** \"root|property\" pairs: an ancestor with all of them paints the same change. */\n keys: string[];\n /** Sticky or fixed: paints over other content, so it is a surface even inside a changed ancestor. */\n floating: boolean;\n}\n\nexport interface DiffResult {\n /** Every element whose computed style differs. */\n elements: ChangedElement[];\n /** The outermost of them: what is outlined and counted (when visible). */\n surfaces: ChangedElement[];\n /** Time the comparison took, in ms (rules are read once per page load and cached). */\n ms: number;\n}\n\nlet ruleCache: { key: string; rules: RuleLike[] } | null = null;\n\nfunction declsOf(style: CSSStyleDeclaration): RuleLike['decls'] {\n // cssText keeps shorthands written with var() (their longhands read empty until substitution).\n return style.cssText\n .split(';')\n .map((d) => {\n const i = d.indexOf(':');\n return i < 0 ? null : { prop: d.slice(0, i).trim().toLowerCase(), value: d.slice(i + 1).trim() };\n })\n .filter((d): d is { prop: string; value: string } => Boolean(d && d.prop && d.value));\n}\n\nfunction walk(list: CSSRuleList, out: RuleLike[]) {\n for (const rule of Array.from(list)) {\n if (rule instanceof CSSStyleRule) {\n out.push({ selector: rule.selectorText, decls: declsOf(rule.style) });\n if (rule.cssRules?.length) walk(rule.cssRules, out);\n } else if ('cssRules' in rule && (rule as CSSGroupingRule).cssRules) {\n walk((rule as CSSGroupingRule).cssRules, out);\n }\n }\n}\n\n/** The page's own style rules (same origin), without the live tokens stylesheet the toolbar adds. Cached. */\nexport function pageRules(): RuleLike[] {\n const sheets = Array.from(document.styleSheets).filter((s) => !(s.ownerNode instanceof Element && s.ownerNode.hasAttribute('data-bridge-live')));\n const key = sheets.map((s) => s.href ?? `inline:${(s.ownerNode as Element | null)?.textContent?.length ?? 0}`).join('|');\n if (ruleCache?.key === key) return ruleCache.rules;\n const rules: RuleLike[] = [];\n for (const s of sheets) {\n try {\n walk(s.cssRules, rules);\n } catch {\n // A cross-origin sheet cannot be read: it holds no rule of this app.\n }\n }\n ruleCache = { key, rules };\n return rules;\n}\n\n/** \"Page\", \"Content column\", \"Save bar (Save changes)\": landmark, ARIA role or component first, its text after. */\nexport function describe(el: Element): string {\n const heading = el.querySelector('h1, h2, h3')?.textContent?.replace(/\\s+/g, ' ').trim();\n const own = el.textContent?.replace(/\\s+/g, ' ').trim();\n return roleName({\n tag: el.tagName,\n role: el.getAttribute('role'),\n ariaLabel: el.getAttribute('aria-label'),\n classes: Array.from(el.classList),\n text: heading || (own && own.length <= 32 ? own : null),\n });\n}\n\n/** The part of an element inside the viewport, or null when none of it shows (hidden, transparent, off screen). */\nexport function shownRect(el: Element): DOMRect | null {\n const check = (el as Element & { checkVisibility?: (o: object) => boolean }).checkVisibility;\n if (check && !check.call(el, { opacityProperty: true, visibilityProperty: true })) return null;\n const r = el.getBoundingClientRect();\n const w = Math.min(r.right, window.innerWidth) - Math.max(r.left, 0);\n const h = Math.min(r.bottom, window.innerHeight) - Math.max(r.top, 0);\n return w > 0 && h > 0 ? r : null;\n}\n\nconst visible = (el: Element) => el.getClientRects().length > 0;\n\n/**\n * Compares the candidates under both token sets. `sheet` is the toolbar's stylesheet that switches sides (loaded):\n * the live tokens over a change's preview (`sheetIs` 'before', one change), or the combination over the live product\n * (`sheetIs` 'after', changes tried together). `ignore` holds the toolbar's own nodes.\n */\nexport function changedElements(changedVars: string[], sheet: HTMLLinkElement | HTMLStyleElement, ignore: (el: Element) => boolean, sheetIs: 'before' | 'after' = 'before'): DiffResult {\n const live = sheet;\n const t0 = performance.now();\n const rules = pageRules();\n const roots = dependents(rules, changedVars);\n const uses: Usage[] = usages(rules, roots);\n type Candidate = { el: Element; pseudo: string | null; props: Set<string>; roots: Set<string> };\n const candidates = new Map<string, Candidate>();\n const ids = new WeakMap<Element, number>();\n let next = 0;\n for (const u of uses) {\n let found: NodeListOf<Element>;\n try {\n found = document.querySelectorAll(u.selector);\n } catch {\n continue;\n }\n for (const el of Array.from(found)) {\n if (ignore(el) || !visible(el)) continue;\n if (!ids.has(el)) ids.set(el, next++);\n const key = `${ids.get(el)}|${u.pseudo ?? ''}`;\n const c = candidates.get(key) ?? { el, pseudo: u.pseudo, props: new Set<string>(), roots: new Set<string>() };\n u.props.forEach((p) => c.props.add(p));\n u.roots.forEach((r) => c.roots.add(r));\n candidates.set(key, c);\n }\n }\n // Inline styles and SVG presentation attributes (charts) read tokens too: <path stroke=\"var(--color-...)\">.\n for (const el of Array.from(document.querySelectorAll('[style*=\"var(--\"], [stroke*=\"var(--\"], [fill*=\"var(--\"], [stop-color*=\"var(--\"]'))) {\n if (ignore(el) || !visible(el)) continue;\n const props = new Set<string>();\n const hit = new Set<string>();\n const take = (prop: string, value: string | null) => {\n if (!value) return;\n const from = varsIn(value).filter((v) => roots.has(v));\n if (!from.length) return;\n longhands(prop).forEach((p) => props.add(p));\n from.forEach((v) => roots.get(v)!.forEach((r) => hit.add(r)));\n };\n for (const d of declsOf((el as HTMLElement).style ?? ({ cssText: '' } as CSSStyleDeclaration))) take(d.prop, d.value);\n for (const attr of ['stroke', 'fill', 'stop-color']) take(attr, el.getAttribute(attr));\n if (!props.size) continue;\n if (!ids.has(el)) ids.set(el, next++);\n const key = `${ids.get(el)}|`;\n const c = candidates.get(key) ?? { el, pseudo: null, props: new Set<string>(), roots: new Set<string>() };\n props.forEach((p) => c.props.add(p));\n hit.forEach((r) => c.roots.add(r));\n candidates.set(key, c);\n }\n const list = [...candidates.values()].map((c) => ({ ...c, propList: [...c.props] }));\n const read = () => list.map((c) => {\n const cs = getComputedStyle(c.el, c.pseudo);\n return c.propList.map((p) => cs.getPropertyValue(p));\n });\n // One synchronous task: the browser cannot paint between the two reads, so the page never shows the other side.\n // Transitions are held while it runs: a component that animates its colour would otherwise report its old value\n // mid-transition (links, buttons), and switching back would start a visible transition.\n const still = document.createElement('style');\n still.setAttribute('data-bridge-still', '');\n still.textContent = '*, *::before, *::after { transition: none !important; }';\n document.head.appendChild(still);\n const media = live.media;\n let withLive: string[][] = [];\n let withChange: string[][] = [];\n try {\n getComputedStyle(document.documentElement).color;\n live.media = 'all';\n withLive = read();\n live.media = 'not all';\n withChange = read();\n } finally {\n live.media = media;\n // Settle on the original values before transitions come back, so nothing animates.\n read();\n still.remove();\n }\n // With the combination's sheet on, it is the After side: the two reads swap.\n if (sheetIs === 'after') [withLive, withChange] = [withChange, withLive];\n const elements: ChangedElement[] = [];\n list.forEach((c, i) => {\n const props = c.propList.map((prop, j) => ({ prop, before: withLive[i]![j]!, after: withChange[i]![j]! })).filter((p) => p.before !== p.after);\n if (!props.length) return;\n const roots = [...c.roots];\n const position = getComputedStyle(c.el).position;\n elements.push({\n el: c.el,\n pseudo: c.pseudo,\n roots,\n props,\n label: describe(c.el),\n keys: roots.flatMap((r) => props.map((p) => `${r}|${p.prop}`)),\n floating: position === 'sticky' || position === 'fixed',\n });\n });\n // Every mark of one chart is one surface: the outermost svg, labelled \"Chart\".\n const charts = new Map<Element, ChangedElement>();\n const plain: ChangedElement[] = [];\n for (const e of elements) {\n let svg = e.el.closest('svg');\n while (svg?.parentElement?.closest('svg')) svg = svg.parentElement.closest('svg');\n if (!svg) {\n plain.push(e);\n continue;\n }\n const c: ChangedElement = charts.get(svg) ?? { el: svg, pseudo: null, roots: [], props: [], label: 'Chart', keys: [], floating: false };\n for (const r of e.roots) if (!c.roots.includes(r)) c.roots.push(r);\n for (const p of e.props) if (!c.props.some((x) => x.prop === p.prop)) c.props.push(p);\n for (const k of e.keys) if (!c.keys.includes(k)) c.keys.push(k);\n charts.set(svg, c);\n }\n const surfaces = outermost([...plain, ...charts.values()], (a, b) => a.el !== b.el && a.el.contains(b.el));\n return { elements, surfaces, ms: Math.round((performance.now() - t0) * 10) / 10 };\n}\n","// Runs \"Show what changed\" on demand: once when turned on, again after a route change or a shop or theme switch\n// (the screen re-renders, so it waits for the new content), never in the background otherwise.\nimport { useEffect, useState } from 'react';\nimport { changedElements, type DiffResult } from './outline';\n\nconst IGNORE = '[data-bridge-toolbar], [data-bridge-overlay]';\n\nexport function useChangedElements(on: boolean, live: HTMLLinkElement | HTMLStyleElement | null, vars: string[], screen: string, sheetIs: 'before' | 'after' = 'before'): DiffResult | null {\n const [result, setResult] = useState<DiffResult | null>(null);\n const key = vars.join(',');\n useEffect(() => {\n if (!on || !live || !key) {\n setResult(null);\n return;\n }\n const run = () => setResult(changedElements(key.split(','), live, (el) => Boolean(el.closest(IGNORE)), sheetIs));\n // Now, then once the new screen has rendered its data (ra-core loads it asynchronously).\n const ids = [window.setTimeout(run, 0), window.setTimeout(run, 400), window.setTimeout(run, 1200)];\n return () => ids.forEach((id) => window.clearTimeout(id));\n }, [on, live, key, screen, sheetIs]);\n return result;\n}\n","// The toolbar and the outline layer are Bridge's tool, not the product: they must never take on a change's colours.\n// Their tokens are pinned once, from the live Bridge tokens (production Studio's tokens.css), resolved in an isolated\n// shadow root for the Bridge brand, the theme and compact density, and written as fixed values in one stylesheet that\n// out-ranks both the page's tokens and the live swap. They are not read again after a swap.\nimport { useEffect } from 'react';\n\n/** Marks an element (and what is inside it) as pinned: the toolbar root, the outline layer, their popups. */\nexport const PIN_ATTR = 'data-bridge-pin';\n/** Same, as a class, for popups the DS portals out (Tooltip and Popover accept a className, not attributes). */\nexport const PIN_CLASS = 'bridge-pin';\nconst STYLE_ATTR = 'data-bridge-pinned';\n\nconst cssCache = new Map<string, Promise<string>>();\nconst valueCache = new Map<string, string>();\n\nfunction liveCss(url: string): Promise<string> {\n if (!cssCache.has(url)) cssCache.set(url, fetch(url).then((r) => (r.ok ? r.text() : Promise.reject(new Error(String(r.status))))));\n return cssCache.get(url)!;\n}\n\n/** Every custom property the live tokens declare, resolved for the Bridge brand in one theme. */\nfunction resolve(css: string, theme: string): string {\n const key = `${theme}|${css.length}`;\n const hit = valueCache.get(key);\n if (hit) return hit;\n const names = [...new Set([...css.matchAll(/(--[\\w-]+)\\s*:/g)].map((m) => m[1]!))];\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(css.replace(/:root/g, ':host'));\n const host = document.createElement('div');\n host.style.display = 'none';\n document.body.appendChild(host);\n const shadow = host.attachShadow({ mode: 'open' });\n shadow.adoptedStyleSheets = [sheet];\n const scope = document.createElement('div');\n scope.setAttribute('data-theme', theme);\n scope.setAttribute('data-brand', 'bridge');\n scope.setAttribute('data-density', 'compact');\n shadow.appendChild(scope);\n const cs = getComputedStyle(scope);\n const decls = names\n .map((n) => [n, cs.getPropertyValue(n).trim()] as const)\n .filter(([, v]) => v !== '')\n .map(([n, v]) => `${n}: ${v};`)\n .join('\\n ');\n host.remove();\n valueCache.set(key, decls);\n return decls;\n}\n\n/** Writes the pinned tokens for the current theme. Three-fold selectors out-rank the tokens' attribute rules. */\nexport function usePinnedBridgeTokens(url: string | null, theme: string): void {\n useEffect(() => {\n if (!url) return;\n let live = true;\n liveCss(url)\n .then((css) => {\n if (!live) return;\n const decls = resolve(css, theme);\n let el = document.head.querySelector<HTMLStyleElement>(`style[${STYLE_ATTR}]`);\n if (!el) {\n el = document.createElement('style');\n el.setAttribute(STYLE_ATTR, '');\n }\n el.textContent = `[${PIN_ATTR}][${PIN_ATTR}][${PIN_ATTR}], .${PIN_CLASS}.${PIN_CLASS}.${PIN_CLASS} {\\n ${decls}\\n}`;\n // Last in <head>, after the page's and the live tokens (whose link may be added later: it is re-appended then).\n document.head.appendChild(el);\n })\n .catch(() => {\n // Without the live tokens the toolbar keeps the page's: it still works, it may wear the change's colours.\n });\n return () => {\n live = false;\n };\n }, [url, theme]);\n}\n","// The outlines of \"Show what changed\": one dashed Deep Harbor frame per changed surface (the outermost changed\n// element), with a role chip in its corner, in a fixed layer above the page that takes no pointer events, no focus\n// and no layout. A page-sized surface gets an inset frame so it never reads as browser chrome. Only surfaces with a\n// visible, non-zero box in the viewport are drawn, and only those are counted (onShown).\nimport { useEffect, useLayoutEffect, useState, type ReactNode } from 'react';\nimport { ThemeProvider, Tooltip } from '@bridge-ds/react';\nimport type { Theme } from '@bridge-ds/react';\nimport { shownRect, type ChangedElement } from './outline';\nimport type { Rect } from './session';\nimport { PIN_ATTR, PIN_CLASS } from './pin';\nimport styles from './BridgeToolbar.module.css';\n\n/** Inset of a page-sized frame, so it sits inside the viewport like a selection, not like the window edge. */\nconst INSET = 8;\n\nexport interface Shown {\n /** Visible surfaces, in order. */\n count: number;\n /** Boxes of the visible surfaces that are not page-sized: the toolbar keeps clear of them. */\n obstacles: Rect[];\n}\n\ninterface Box {\n left: number;\n top: number;\n width: number;\n height: number;\n radius: string;\n page: boolean;\n}\n\nfunction boxOf(el: Element): Box | null {\n const r = shownRect(el);\n if (!r) return null;\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n const left = Math.max(r.left, 0);\n const top = Math.max(r.top, 0);\n const right = Math.min(r.right, vw);\n const bottom = Math.min(r.bottom, vh);\n // Page-sized: covers most of the viewport. Drawn as an inset frame with its chip top left.\n const page = (right - left) * (bottom - top) > 0.85 * vw * vh;\n if (page) return { left: INSET, top: INSET, width: vw - 2 * INSET, height: vh - 2 * INSET, radius: '', page };\n return { left, top, width: right - left, height: bottom - top, radius: getComputedStyle(el).borderRadius, page };\n}\n\nexport function ChangeOutlines({\n surfaces,\n theme,\n tip,\n onShown,\n emphasis,\n flash,\n}: {\n surfaces: ChangedElement[];\n theme: Theme;\n /** The surface whose list row is hovered, focused or activated: chip and stronger outline. */\n emphasis: number | null;\n /** Show every chip (the moment outlines turn on). */\n flash: boolean;\n /** Tooltip content for a surface: its role, token and before and after. */\n tip: (s: ChangedElement) => ReactNode;\n onShown: (shown: Shown) => void;\n}) {\n const [tick, setTick] = useState(0);\n const [active, setActive] = useState<number | null>(null);\n\n // Follow the page: re-measure on scroll and resize, one frame at a time.\n useEffect(() => {\n let frame = 0;\n const on = () => {\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(() => setTick((t) => t + 1));\n };\n window.addEventListener('scroll', on, { passive: true, capture: true });\n window.addEventListener('resize', on);\n return () => {\n cancelAnimationFrame(frame);\n window.removeEventListener('scroll', on, { capture: true });\n window.removeEventListener('resize', on);\n };\n }, []);\n\n const boxes = surfaces.map((s) => boxOf(s.el));\n\n // Count only what is drawn; hand the toolbar the boxes to keep clear of.\n const shownKey = boxes.map((b) => (b ? `${Math.round(b.left)},${Math.round(b.top)},${Math.round(b.width)},${Math.round(b.height)}` : '-')).join('|');\n useLayoutEffect(() => {\n onShown({\n count: boxes.filter(Boolean).length,\n obstacles: boxes.filter((b): b is Box => Boolean(b && !b.page)).map((b) => ({ left: b.left, top: b.top, right: b.left + b.width, bottom: b.top + b.height })),\n });\n }, [shownKey, tick]);\n\n // The smallest visible surface under the pointer (page-sized ones would answer every move), or around the focus.\n useEffect(() => {\n const pick = (match: (el: Element, i: number) => boolean) => {\n let best: number | null = null;\n let area = Infinity;\n surfaces.forEach((s, i) => {\n const b = boxOf(s.el);\n if (!b || b.page || !match(s.el, i)) return;\n if (b.width * b.height < area) {\n area = b.width * b.height;\n best = i;\n }\n });\n return best;\n };\n const move = (e: PointerEvent) =>\n setActive(\n pick((el) => {\n const r = el.getBoundingClientRect();\n return e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom;\n }),\n );\n const focus = (e: FocusEvent) => setActive(e.target instanceof Node ? pick((el) => el.contains(e.target as Node)) : null);\n document.addEventListener('pointermove', move, { passive: true });\n document.addEventListener('focusin', focus);\n return () => {\n document.removeEventListener('pointermove', move);\n document.removeEventListener('focusin', focus);\n };\n }, [surfaces]);\n\n return (\n <ThemeProvider theme={theme} brand=\"bridge\" density=\"compact\" className={styles.overlay} data-bridge-overlay=\"\" {...{ [PIN_ATTR]: '' }} aria-hidden=\"true\">\n {boxes.map((b, i) => {\n if (!b) return null;\n const s = surfaces[i]!;\n // Chips are hidden by default: shown on hover of the surface, on its list row, and briefly when outlines turn on.\n const showChip = flash || active === i || emphasis === i;\n const chip = (\n <span className={styles.chip} data-page={b.page || undefined} data-shown={showChip || undefined}>\n {s.label}\n </span>\n );\n return (\n <span\n key={i}\n className={styles.box}\n data-page={b.page || undefined}\n data-inside={(!b.page && b.top < 24) || undefined}\n data-emphasis={emphasis === i || undefined}\n style={{ left: b.left, top: b.top, width: b.width, height: b.height, borderRadius: b.radius }}\n >\n <span className={styles.tint} />\n {active === i || emphasis === i ? (\n // Above the chip when there is room, else below it: never over the toolbar, which keeps clear of boxes.\n <Tooltip open content={tip(s)} side={b.top < 64 ? 'bottom' : 'top'} align=\"start\" className={PIN_CLASS}>\n {chip}\n </Tooltip>\n ) : (\n chip\n )}\n </span>\n );\n })}\n </ThemeProvider>\n );\n}\n","// Changes tried together, in the toolbar: reads the changes (github.ts loadTogetherChange), loads the combination\n// module on demand (together.ts with @bridge-ds/core) and the latest library from the product (its `together` option:\n// the token files its own tokens.css was built from), keeps which changes are switched on,\n// and paints the combination as one stylesheet that switches sides like the live tokens do for one change. Changes\n// that edit code are listed but stay off: they cannot be applied live.\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { ChangeEdits } from '@bridge-ds/core';\nimport { loadTogetherChange, type TogetherFacts } from './github';\nimport { toggleIncluded, type BridgeBuild, type NoDifference } from './session';\nimport type { TogetherBase, TogetherPair, TogetherResult } from './together';\n\ntype Mod = typeof import('./together');\n\nexport interface Together {\n /** The changes in Studio's order, once read (null while reading). */\n list: TogetherFacts[] | null;\n error: boolean;\n /** Switched on, in Studio's order. */\n included: number[];\n toggle: (n: number, on: boolean) => void;\n result: TogetherResult | null;\n /** Tokens each change edits (by path), whether or not its value is the one applied. */\n editedBy: Map<number, string[]>;\n pairs: TogetherPair[];\n /** Nothing differs where the page is, but it does in another theme (or brand): say so, never a silent \"After\". */\n noDiff: NoDifference | null;\n /** The stylesheet with the combination, once in the page; its media switches sides. */\n sheet: HTMLStyleElement | null;\n}\n\n/** The combination's stylesheet: before the pinned toolbar tokens, so the toolbar never wears the changes' colours. */\nfunction useSheet(css: string | null, applied: boolean): HTMLStyleElement | null {\n const [el, setEl] = useState<HTMLStyleElement | null>(null);\n const ref = useRef<HTMLStyleElement | null>(null);\n useEffect(() => {\n if (css === null) return;\n if (!ref.current) {\n const s = document.createElement('style');\n // Same mark as the live tokens: \"Show what changed\" reads the page's own rules without it.\n s.setAttribute('data-bridge-live', '');\n s.setAttribute('data-bridge-together', '');\n const pinned = document.head.querySelector('style[data-bridge-pinned]');\n document.head.insertBefore(s, pinned);\n ref.current = s;\n setEl(s);\n }\n ref.current.textContent = css;\n ref.current.media = applied ? 'all' : 'not all';\n }, [css, applied]);\n useEffect(() => () => ref.current?.remove(), []);\n return el;\n}\n\nexport function useTogether(\n build: BridgeBuild,\n latest: (() => Promise<TogetherBase>) | null,\n changes: number[] | null,\n use: string | null,\n here: { theme: string; brand: string; density: string },\n applied: boolean,\n): Together | null {\n const [mod, setMod] = useState<{ m: Mod; base: TogetherBase } | null>(null);\n const [list, setList] = useState<TogetherFacts[] | null>(null);\n const [error, setError] = useState(false);\n const [included, setIncluded] = useState<number[]>([]);\n const key = changes?.join(',') ?? '';\n\n useEffect(() => {\n if (!key) return;\n let live = true;\n const numbers = key.split(',').map(Number);\n // Without the latest library (a product that did not pass it) the combination cannot be painted: say so.\n const base = latest ? latest() : Promise.reject(new Error('This product does not try changes together.'));\n Promise.all([import('./together'), base, Promise.all(numbers.map((n) => loadTogetherChange(build, n)))]).then(\n ([m, b, facts]) => {\n if (!live) return;\n setMod({ m, base: b });\n setList(facts);\n setIncluded(facts.filter((f) => f.mode === 'tokens' && f.source).map((f) => f.number));\n },\n () => live && setError(true),\n );\n return () => {\n live = false;\n };\n }, [build, key, latest]);\n\n const edits = useMemo<ChangeEdits[]>(() => (mod && list ? list.filter((f) => f.source).map((f) => mod.m.changeEdits(f.source!)) : []), [mod, list]);\n const result = useMemo(() => (mod && list ? mod.m.together(mod.base, edits, mod.m.decodePicks(use), included) : null), [mod, list, edits, use, included]);\n const { theme, brand, density } = here;\n const pairs = useMemo(() => (mod && result ? mod.m.togetherPairs(mod.base, result, { theme, brand, density }) : []), [mod, result, theme, brand, density]);\n const sheet = useSheet(key ? (result?.css ?? null) : null, applied);\n const noDiff = useMemo<NoDifference | null>(() => {\n if (!mod || !result || !result.tokens.length || pairs.length) return null;\n const other = mod.base.modes.themes.find((t) => t !== theme && mod.m.togetherPairs(mod.base, result, { theme: t, brand, density }).length);\n if (other) return { kind: 'theme', here: theme, touched: other };\n const brandElse = mod.base.modes.brands.find((b) => b !== brand && mod.m.togetherPairs(mod.base, result, { theme, brand: b, density }).length);\n return brandElse ? { kind: 'brand', here: brand, touched: brandElse } : null;\n }, [mod, result, pairs.length, theme, brand, density]);\n\n if (!key) return null;\n return {\n list,\n error,\n included,\n toggle: (n, on) => setIncluded((cur) => toggleIncluded(list?.map((f) => f.number) ?? [], cur, n, on)),\n result,\n editedBy: new Map(edits.map((e) => [e.number, [...new Set(e.edits.map((x) => x.path))]])),\n pairs,\n noDiff,\n sheet,\n };\n}\n","// The Bridge toolbar: opened from Bridge Studio (\"Try it in the product\") with `?bridge=<change>`, it lets a designer\n// browse the real product and flip between the live product and this change. Token changes swap the live tokens in\n// without a reload; code changes move between the product in production and the change's preview on the same screen.\n// Production renders nothing on its own. It opens collapsed, bottom right of the content column, and moves away from\n// the page's primary and submit buttons. Several token changes tried together (`?bridge=101,118,120`, from Studio's\n// Changes list) run on the product in production: their combined tokens are applied live (useTogether), each change can\n// be switched off, and Before/After and \"Show what changed\" work on what is switched on.\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent } from 'react';\nimport { Badge, Button, ButtonGroup, Checkbox, Icon, IconButton, Link, Popover, PopoverContent, PopoverTrigger, ThemeProvider, Tooltip } from '@bridge-ds/react';\nimport { Check, ChevronUp, GripVertical, Info, ListChecks, Minimize2, ScanSearch } from 'lucide-react';\nimport { loadChange, type ChangeFacts } from './github';\nimport { loadBuild } from './config';\nimport type { BridgeToolbarProps } from './BridgeToolbar';\nimport { useDocumentScope, type ToolbarScope, type ToolbarShop } from './scope';\nimport type { TogetherBase } from './together';\nimport {\n changeSummary,\n DOCK_KEY,\n dockAt,\n isFlipKey,\n liveTokensUrl,\n noVisibleDifference,\n OPEN_KEY,\n PARAM,\n placeToolbar,\n readChanges,\n readDock,\n readReturn,\n readScroll,\n readUse,\n sameScreenOn,\n SCROLL_PARAM,\n shouldRender,\n stepDock,\n studioChangeUrl,\n studioChangesUrl,\n fromText,\n TOGETHER_EMPTY_LINE,\n TOGETHER_HINT,\n togetherLabel,\n contrastRatio,\n isSubtle,\n toHex,\n whereAmI,\n type BridgeBuild,\n type Dock,\n type NoDifference,\n type Rect,\n type Screen,\n type TokenChange,\n} from './session';\nimport { EMPTY_LINE, isKey, outOfView, surfaceLine } from './diff';\nimport { shownRect } from './outline';\nimport { useChangedElements } from './useChangedElements';\nimport { ChangeOutlines, type Shown } from './ChangeOutlines';\nimport { PIN_ATTR, PIN_CLASS, usePinnedBridgeTokens } from './pin';\nimport { useTogether } from './useTogether';\nimport styles from './BridgeToolbar.module.css';\n\ntype Side = 'before' | 'after';\ntype TokenState = 'idle' | 'loading' | 'ready' | 'error';\n\n/** The two sides, in the words designers use. */\nconst SIDE_LABEL: Record<Side, string> = { before: 'Live product', after: 'This change' };\n/** Token pairs shown on the toolbar; the rest is \"+N\". */\nconst MAX_PAIRS = 3;\n\nfunction session(): Storage | null {\n try {\n return window.sessionStorage;\n } catch {\n return null;\n }\n}\n\nfunction remember(key: string, value: string) {\n try {\n window.sessionStorage.setItem(key, value);\n } catch {\n // Storage blocked: the choice lasts for this page only.\n }\n}\n\n/** The toolbar once a change is asked for: its facts from the build, else from the design system's config. */\nexport default function ToolbarRoot(props: BridgeToolbarProps) {\n const { ds, product, studio, production, preview, deployEnv, proxy } = props;\n // The proxy prop wins over the one a build carries (default: production Bridge, reads.ts).\n const given = useMemo(() => (props.build && proxy !== undefined ? { ...props.build, proxy } : props.build), [props.build, proxy]);\n const [build, setBuild] = useState<BridgeBuild | null>(given ?? null);\n useEffect(() => {\n if (given || !ds || !product) return;\n let live = true;\n loadBuild(ds, product, { studio, production, preview, deployEnv, ...(proxy !== undefined ? { proxy } : {}) }).then(\n (b) => live && setBuild(b),\n (err: Error) => console.warn(`Bridge toolbar: ${err.message}`),\n );\n return () => {\n live = false;\n };\n }, [given, ds, product, studio, production, preview, deployEnv, proxy]);\n if (!build) return null;\n return <Decide build={build} useScope={props.scope ?? useDocumentScope} shops={props.shops ?? []} together={props.together ?? null} />;\n}\n\n/** Decides on first render whether there is anything to show. */\nfunction Decide({ build: given, useScope, shops, together: latest }: { build: BridgeBuild; useScope: () => ToolbarScope; shops: ToolbarShop[]; together: (() => Promise<TogetherBase>) | null }) {\n const [setup] = useState(() => {\n const build = given;\n const store = session();\n const changes = readChanges(window.location.search, store);\n const where = whereAmI(window.location.host, build);\n const returnTo = where === 'production' ? readReturn(window.location.search, store, build.preview) : null;\n // 2 to 4 changes tried together: their tokens are applied live on whatever this admin is (production from Studio).\n const together = changes.length > 1 ? { changes, use: readUse(window.location.search, store) } : null;\n return { build, change: changes[0] ?? null, where, returnTo, together };\n });\n if (!shouldRender({ ...setup, together: Boolean(setup.together) })) return null;\n return <Toolbar build={setup.build} change={setup.change!} onProduction={setup.where === 'production'} returnTo={setup.returnTo} together={setup.together} useScope={useScope} shops={shops} latest={latest} />;\n}\n\n/**\n * The live tokens: one stylesheet after the bundled one, loaded on demand (the live side, or \"Show what changed\") and\n * switched by its media (\"all\" applies it, \"not all\" keeps it loaded but off), so flipping is instant and the\n * comparison can switch it inside one task without a visible flash.\n */\nfunction useLiveSheet(url: string | null, need: boolean, applied: boolean): { state: TokenState; link: HTMLLinkElement | null } {\n const [state, setState] = useState<TokenState>('idle');\n const link = useRef<HTMLLinkElement | null>(null);\n useEffect(() => {\n if (!url) return;\n if (link.current) {\n link.current.media = applied ? 'all' : 'not all';\n return;\n }\n if (!need && !applied) return;\n const el = document.createElement('link');\n el.rel = 'stylesheet';\n el.href = url;\n el.media = applied ? 'all' : 'not all';\n el.referrerPolicy = 'no-referrer';\n el.setAttribute('data-bridge-live', '');\n el.onload = () => setState('ready');\n el.onerror = () => {\n el.remove();\n link.current = null;\n setState('error');\n };\n link.current = el;\n setState('loading');\n document.head.appendChild(el);\n }, [url, need, applied]);\n useEffect(() => () => link.current?.remove(), []);\n return { state, link: state === 'ready' ? link.current : null };\n}\n\ninterface Pair {\n token: TokenChange;\n before: string;\n after: string;\n color: boolean;\n}\n\n/** Resolves each token in a scope (theme, brand) on a probe: its colour as rgb, or its raw value. */\nfunction probe(root: Node, tokens: TokenChange[], scope: { theme: string; brand: string }): string[] {\n const host = document.createElement('div');\n host.setAttribute('data-theme', scope.theme);\n host.setAttribute('data-brand', scope.brand);\n host.setAttribute('data-density', 'comfortable');\n host.style.display = 'none';\n const spans = tokens.map((t) => {\n const s = document.createElement('span');\n s.style.backgroundColor = `var(${t.cssVar})`;\n host.appendChild(s);\n return s;\n });\n root.appendChild(host);\n const out = tokens.map((t, i) => (t.type === 'color' ? getComputedStyle(spans[i]!).backgroundColor : getComputedStyle(host).getPropertyValue(t.cssVar).trim()));\n host.remove();\n return out;\n}\n\n/**\n * Before and after of every changed token, in the theme and brand where it shows: after from this page's own\n * tokens (read while the live tokens are off), before from the live tokens.css applied in an isolated shadow root.\n */\nfunction usePairs(facts: ChangeFacts | null, liveUrl: string | null, brand: string, liveOn: boolean): Pair[] {\n const [pairs, setPairs] = useState<Pair[]>([]);\n const afterCache = useRef(new Map<string, string[]>());\n useEffect(() => {\n const tokens = facts?.tokens ?? [];\n if (!tokens.length || !liveUrl) return;\n let live = true;\n const scopeOf = (t: TokenChange) => ({ theme: t.theme ?? 'light', brand: t.brand ?? brand });\n const key = `${brand}`;\n // After: only readable while the live stylesheet is off; kept per brand.\n if (!afterCache.current.has(key) && !liveOn) afterCache.current.set(key, tokens.map((t) => probe(document.body, [t], scopeOf(t))[0]!));\n const after = afterCache.current.get(key);\n if (!after) return;\n fetch(liveUrl)\n .then((r) => (r.ok ? r.text() : Promise.reject(new Error(String(r.status)))))\n .then((css) => {\n if (!live) return;\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(css.replace(/:root/g, ':host'));\n const host = document.createElement('div');\n host.style.display = 'none';\n document.body.appendChild(host);\n const shadow = host.attachShadow({ mode: 'open' });\n shadow.adoptedStyleSheets = [sheet];\n const before = tokens.map((t) => probe(shadow, [t], scopeOf(t))[0]!);\n host.remove();\n setPairs(tokens.map((t, i) => ({ token: t, before: before[i]!, after: after[i]!, color: t.type === 'color' })).filter((p) => p.before !== p.after));\n })\n .catch(() => live && setPairs([]));\n return () => {\n live = false;\n };\n }, [facts, liveUrl, brand, liveOn]);\n return pairs;\n}\n\n/** What the active side shows, after its bold name. */\nfunction modeDetail(facts: ChangeFacts | null, side: Side, tokens: TokenState): string {\n if (!facts) return 'Reading the change.';\n if (side === 'before') {\n if (tokens === 'loading') return 'loading what customers see today.';\n if (tokens === 'error') return 'could not load it. Check your connection, then press B again.';\n return 'what customers see today.';\n }\n return changeSummary(facts.title);\n}\n\nconst brandName = (shops: ToolbarShop[], brand: string) => shops.find((t) => t.brand === brand)?.name ?? brand;\n\n/** \"Light mode only. Nothing changes in dark.\" */\nfunction noDifferenceText(d: NoDifference, shops: ToolbarShop[]): string {\n const cap = (t: string) => t.charAt(0).toUpperCase() + t.slice(1);\n return d.kind === 'theme' ? `${cap(d.touched)} mode only. Nothing changes in ${d.here}.` : `${brandName(shops, d.touched)} only. Nothing changes in ${brandName(shops, d.here)}.`;\n}\n\n/** Primary and submit buttons of the page, in the viewport: the toolbar never covers them. */\nfunction pageObstacles(own: HTMLElement | null): Rect[] {\n const probeEl = document.createElement('span');\n probeEl.style.backgroundColor = 'var(--color-action-primary-bg)';\n probeEl.hidden = true;\n document.body.appendChild(probeEl);\n const primary = getComputedStyle(probeEl).backgroundColor;\n probeEl.remove();\n const out: Rect[] = [];\n for (const el of document.querySelectorAll<HTMLElement>('button, a[href], [role=\"button\"]')) {\n if (own?.contains(el) || el.closest('[data-bridge-toolbar], [role=\"dialog\"], [role=\"menu\"], [role=\"listbox\"]')) continue;\n const isSubmit = el instanceof HTMLButtonElement && el.type === 'submit';\n if (!isSubmit && getComputedStyle(el).backgroundColor !== primary) continue;\n const r = el.getBoundingClientRect();\n if (!r.width || !r.height || r.bottom <= 0 || r.top >= window.innerHeight) continue;\n out.push({ left: r.left, top: r.top, right: r.right, bottom: r.bottom });\n }\n return out;\n}\n\nfunction Toolbar({\n build,\n change,\n onProduction,\n returnTo,\n together: tg,\n useScope,\n shops,\n latest,\n}: {\n build: BridgeBuild;\n change: number;\n onProduction: boolean;\n returnTo: string | null;\n together: { changes: number[]; use: string | null } | null;\n useScope: () => ToolbarScope;\n shops: ToolbarShop[];\n latest: (() => Promise<TogetherBase>) | null;\n}) {\n const scope = useScope();\n const { theme, density, brand } = scope;\n const tenantId = scope.shop ?? '';\n const setPrefs = scope.set;\n const isTenantId = (id: string) => shops.some((t) => t.id === id);\n const [oneFacts, setFacts] = useState<ChangeFacts | null>(null);\n const [oneError, setError] = useState(false);\n // On production the toolbar only exists for the live side of a code change, or for changes tried together (which\n // open on the combination).\n const [side, setSide] = useState<Side>(onProduction && !tg ? 'before' : 'after');\n const T = useTogether(build, latest, tg?.changes ?? null, tg?.use ?? null, { theme, brand, density }, side === 'after');\n const titleOf = (n: number) => T?.list?.find((f) => f.number === n)?.title ?? null;\n // Changes tried together read as one token change: the tokens of what is switched on, the files they edit.\n const togetherFacts = useMemo<ChangeFacts | null>(() => {\n if (!T?.list || !T.result) return null;\n const on = T.list.filter((f) => T.included.includes(f.number));\n const names = on.map((f) => f.title);\n return {\n number: change,\n title: names.length ? (names.length <= 2 ? names.join(' and ') : `${names.slice(0, 2).join(', ')} and ${names.length - 2} more`) : 'No change switched on',\n url: '',\n sha: '',\n mode: 'tokens',\n files: [...new Set(on.flatMap((f) => f.source?.files ?? []))],\n behind: null,\n tokens: T.result.tokens,\n screens: null,\n };\n }, [T?.list, T?.result, T?.included, change]);\n const facts = tg ? togetherFacts : oneFacts;\n const error = tg ? Boolean(T?.error) : oneError;\n const [open, setOpen] = useState(() => {\n try {\n return window.sessionStorage.getItem(OPEN_KEY) === '1';\n } catch {\n return false;\n }\n });\n const [dock, setDock] = useState<Dock>(() => readDock(session()));\n const [place, setPlace] = useState<{ dock: Dock; lift: number }>({ dock, lift: 0 });\n const [drag, setDrag] = useState<number | null>(null);\n // Set when the toolbar moved the page to the only theme the change touches: \"Shown in light...\".\n const [shownIn, setShownIn] = useState<string | null>(null);\n const dragStart = useRef(0);\n const root = useRef<HTMLDivElement>(null);\n const hash = useHash();\n\n useEffect(() => {\n if (tg) return;\n let live = true;\n loadChange(build, change).then(\n (f) => live && setFacts(f),\n () => live && setError(true),\n );\n return () => {\n live = false;\n };\n }, [build, change, tg]);\n\n // One change: the live tokens.css switches the preview to Before. Changes tried together: this page is the live\n // product already, and the combination's sheet (useTogether) switches it to After.\n const liveUrl = !tg && facts?.mode === 'tokens' ? liveTokensUrl(build) : null;\n const [outlines, setOutlines] = useState(false);\n const canOutline = facts?.mode === 'tokens' && (facts.tokens.length ?? 0) > 0;\n const live = useLiveSheet(liveUrl, outlines && canOutline, side === 'before' && facts?.mode === 'tokens');\n const onePairs = usePairs(tg ? null : facts, liveUrl, brand, side === 'before');\n const pairs: Pair[] = tg ? (T?.pairs ?? []) : onePairs;\n // Changes tried together: measured on the combination's own values where the page is.\n const noDiff = tg ? (T?.noDiff ?? null) : facts?.mode === 'tokens' ? noVisibleDifference(facts.files, { theme, brand: brand }) : null;\n // Outlines run only where the change can show: muted in dark for a light-only change.\n const outlinesOn = outlines && canOutline && !noDiff;\n const diff = useChangedElements(\n outlinesOn,\n tg ? (T?.sheet ?? null) : live.link,\n (facts?.tokens ?? []).map((t) => t.cssVar),\n // Switching a change on or off repaints the combination: the outlines are measured again.\n `${hash}|${theme}|${tenantId}|${tg ? (T?.included.join(',') ?? '') : ''}`,\n tg ? 'after' : 'before',\n );\n const nameOf = (v: string) => facts?.tokens.find((t) => t.cssVar === v)?.name ?? v;\n // What the outlines draw (visible surfaces) and where: the count and the boxes the toolbar keeps clear of.\n const [shown, setShown] = useState<Shown>({ count: 0, obstacles: [] });\n const setShownStable = useCallback((next: Shown) => setShown((p) => (JSON.stringify(p) === JSON.stringify(next) ? p : next)), []);\n const outlineBoxes = useRef<Rect[]>([]);\n outlineBoxes.current = outlinesOn ? shown.obstacles : [];\n // The list row a person points at (its surface shows its chip and a stronger outline), the brief chip flash when\n // outlines turn on (none with reduced motion), and the Changes sheet.\n const [emphasis, setEmphasis] = useState<number | null>(null);\n const [flash, setFlash] = useState(false);\n const [sheetOpen, setSheetOpen] = useState(false);\n const phone = useMedia('(max-width: 760px)');\n const reduced = useMedia('(prefers-reduced-motion: reduce)');\n usePinnedBridgeTokens(liveTokensUrl(build), theme);\n useEffect(() => {\n if (!outlinesOn || reduced) {\n setFlash(false);\n return;\n }\n setFlash(true);\n const id = window.setTimeout(() => setFlash(false), 1500);\n return () => window.clearTimeout(id);\n }, [outlinesOn, reduced]);\n useEffect(() => {\n if (!sheetOpen) setEmphasis(null);\n }, [sheetOpen]);\n\n // A change that only touches one theme opens in that theme, once, and says so.\n const autoTheme = useRef(false);\n useEffect(() => {\n if (autoTheme.current || !facts) return;\n autoTheme.current = true;\n if (noDiff?.kind === 'theme' && (noDiff.touched === 'light' || noDiff.touched === 'dark')) {\n setPrefs({ theme: noDiff.touched });\n setShownIn(noDiff.touched);\n }\n }, [facts, noDiff, setPrefs]);\n // The note holds while the page stays in that theme.\n useEffect(() => {\n if (shownIn && theme !== shownIn) setShownIn(null);\n }, [theme, shownIn]);\n\n // A side switch carried the scroll position: restore it once the screen has its height, then tidy the address.\n useEffect(() => {\n const y = readScroll(window.location.search);\n if (y === null) return;\n const url = new URL(window.location.href);\n url.searchParams.delete(SCROLL_PARAM);\n window.history.replaceState(window.history.state, '', url);\n let tries = 0;\n const id = window.setInterval(() => {\n tries += 1;\n if (document.documentElement.scrollHeight - window.innerHeight >= y || tries > 20) {\n window.scrollTo({ top: y });\n window.clearInterval(id);\n }\n }, 150);\n return () => window.clearInterval(id);\n }, []);\n\n const choose = useCallback(\n (next: Side) => {\n if (next === side || !facts) return;\n if (facts.mode === 'tokens') {\n setSide(next);\n return;\n }\n const here = { search: window.location.search, hash: window.location.hash };\n if (next === 'before' && build.production) {\n window.location.assign(sameScreenOn(build.production, here, { change, returnTo: window.location.origin, scroll: window.scrollY }));\n } else if (next === 'after' && returnTo) {\n window.location.assign(sameScreenOn(returnTo, here, { change, scroll: window.scrollY }));\n }\n },\n [side, facts, build, change, returnTo],\n );\n\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => {\n if (canOutline && !noDiff && isKey(e, 'c')) {\n e.preventDefault();\n setOutlines((o) => !o);\n return;\n }\n if (!isFlipKey(e)) return;\n e.preventDefault();\n choose(side === 'after' ? 'before' : 'after');\n };\n window.addEventListener('keydown', onKey);\n return () => window.removeEventListener('keydown', onKey);\n }, [choose, side, canOutline, noDiff]);\n\n // Stay clear of the page's primary and submit buttons: on open, resize, scroll, route change and size change.\n useLayoutEffect(() => {\n const el = root.current;\n const anchor = el?.parentElement;\n if (!el || !anchor) return;\n let frame = 0;\n const measure = () => {\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(() => {\n const box = el.getBoundingClientRect();\n const area = anchor.getBoundingClientRect();\n const gutter = window.innerWidth <= 760 ? (open ? 0 : 8) : 16;\n const next = placeToolbar({ left: area.left, right: area.right, vh: window.innerHeight, w: box.width, h: box.height, gutter, preferred: dock, obstacles: [...pageObstacles(el), ...outlineBoxes.current] });\n setPlace((p) => (p.dock === next.dock && p.lift === next.lift ? p : next));\n // While open the page gets room for the toolbar, so its end is never hidden under it.\n document.body.style.paddingBottom = open ? `${box.height + 2 * gutter}px` : '';\n });\n };\n measure();\n const later = window.setTimeout(measure, 600);\n const ro = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure);\n ro?.observe(el);\n ro?.observe(document.body);\n window.addEventListener('resize', measure);\n window.addEventListener('scroll', measure, { passive: true });\n window.addEventListener('hashchange', measure);\n return () => {\n cancelAnimationFrame(frame);\n window.clearTimeout(later);\n ro?.disconnect();\n window.removeEventListener('resize', measure);\n window.removeEventListener('scroll', measure);\n window.removeEventListener('hashchange', measure);\n document.body.style.paddingBottom = '';\n };\n }, [dock, open, facts, shown, outlinesOn]);\n\n const toggleOpen = (next: boolean) => {\n setOpen(next);\n remember(OPEN_KEY, next ? '1' : '0');\n };\n const moveTo = (next: Dock) => {\n setDock(next);\n remember(DOCK_KEY, next);\n };\n const onGripKey = (e: ReactKeyboardEvent) => {\n if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {\n e.preventDefault();\n moveTo(stepDock(dock, e.key === 'ArrowLeft' ? -1 : 1));\n }\n };\n const onGripDown = (e: ReactPointerEvent<HTMLButtonElement>) => {\n e.currentTarget.setPointerCapture(e.pointerId);\n dragStart.current = e.clientX;\n setDrag(0);\n };\n const onGripMove = (e: ReactPointerEvent<HTMLButtonElement>) => {\n if (drag !== null) setDrag(e.clientX - dragStart.current);\n };\n const onGripUp = (e: ReactPointerEvent<HTMLButtonElement>) => {\n if (drag === null) return;\n const box = root.current?.getBoundingClientRect();\n setDrag(null);\n if (box && Math.abs(e.clientX - dragStart.current) > 4) moveTo(dockAt(box.left + box.width / 2, window.innerWidth));\n };\n\n // Moving to another screen or theme from the toolbar keeps it open.\n const goTo = (s: Screen) => (e: ReactMouseEvent) => {\n e.preventDefault();\n toggleOpen(true);\n if (isTenantId(s.tenant) && (s.tenant !== tenantId || s.theme !== theme)) setPrefs({ shop: s.tenant, theme: s.theme === 'dark' ? 'dark' : 'light' });\n window.location.hash = s.route;\n };\n const fixNoDiff = () => {\n if (!noDiff) return;\n toggleOpen(true);\n if (noDiff.kind === 'theme') setPrefs({ theme: noDiff.touched === 'dark' ? 'dark' : 'light' });\n else {\n const t = shops.find((x) => x.brand === noDiff.touched);\n if (t) setPrefs({ shop: t.id });\n }\n };\n\n const sideLabel = (x: Side) => (x === 'after' && tg ? togetherLabel(T?.included.length ?? tg.changes.length) : SIDE_LABEL[x]);\n const label = sideLabel(side);\n const title = facts?.title ?? (tg ? `${tg.changes.length} changes together` : `Change ${change}`);\n const screens = facts?.screens ?? null;\n const canFlip = Boolean(facts) && (facts!.mode === 'tokens' || (side === 'after' ? Boolean(build.production) : Boolean(returnTo)));\n const studio = tg ? studioChangesUrl(build) : studioChangeUrl(build, change);\n const behind = facts?.behind ? 'Live has new changes since this change started.' : null;\n // Screens share one shop and theme most of the time: say it once in the sheet's header.\n const shared = screens?.length && screens.every((s) => s.tenant === screens[0]!.tenant && s.theme === screens[0]!.theme) ? screens[0]! : null;\n const shopOf = (t: string) => shops.find((x) => x.id === t)?.name ?? t;\n const surfaces = outlinesOn ? (diff?.surfaces ?? []) : [];\n const shownCount = outlinesOn && diff ? shown.count : null;\n\n // Changes tried together: how many of the switched-on ones show anything in this theme and brand.\n const activeHere = new Set((T?.pairs ?? []).flatMap((p) => p.token.from)).size;\n const note = shownIn ? (\n <p className={styles.note} role=\"status\">\n Shown in {shownIn}. {tg ? 'These changes only affect' : 'This change only affects'} {shownIn}.\n </p>\n ) : noDiff ? (\n <p className={styles.note} role=\"status\">\n <span>{noDifferenceText(noDiff, shops)}</span>\n <Button variant=\"ghost\" size=\"md\" onClick={fixNoDiff} className={styles.noteAction}>\n {noDiff.kind === 'theme' ? `Switch to ${noDiff.touched}` : `Switch to ${brandName(shops, noDiff.touched)}`}\n </Button>\n </p>\n ) : (outlinesOn || side === 'before') && live.state === 'error' ? (\n <p className={styles.note} role=\"status\">\n Could not load the live product. Check your connection, then try again.\n </p>\n ) : shownCount === 0 ? (\n <p className={styles.note} role=\"status\">\n {diff?.surfaces.length ? outOfView(diff.surfaces.length) : tg ? TOGETHER_EMPTY_LINE : EMPTY_LINE}\n </p>\n ) : tg && T && side === 'after' && activeHere < T.included.length ? (\n <p className={styles.note} role=\"status\">\n {activeHere} of these {T.included.length} changes {activeHere === 1 ? 'shows' : 'show'} in {theme}. Changes lists what each one does here.\n </p>\n ) : null;\n\n // The colour pair of each changed token: one split swatch (before half, after half); values in its tooltip only.\n // Most visible first: a ramp change lists its strong steps before its near-white ones.\n const visiblePairs = (noDiff ? [] : pairs).slice().sort((a, b) => (contrastRatio(b.before, b.after) ?? 0) - (contrastRatio(a.before, a.after) ?? 0));\n const hexPair = (before: string, after: string) => `${toHex(before).toUpperCase()} → ${toHex(after).toUpperCase()}`;\n // Changes tried together: each token says which change its value comes from.\n const fromOf = (p: Pair | null | undefined) => {\n const from = (p?.token as { from?: number[] } | undefined)?.from;\n return tg && from?.length ? fromText(from, titleOf) : null;\n };\n const pairTip = (p: Pair) => `${p.token.name}${p.token.step ? ` (${p.token.step})` : ''}${fromOf(p) ? `, ${fromOf(p)}` : ''}: ${p.color ? hexPair(p.before, p.after) : `${p.before} → ${p.after}`}`;\n const splitOf = (before: string, after: string) => (\n <span className={styles.split} aria-hidden=\"true\">\n <span style={{ backgroundColor: before }} />\n <span style={{ backgroundColor: after }} />\n </span>\n );\n const subtleOf = (before: string, after: string) => (isSubtle(before, after) ? <span className={styles.subtle}>Subtle change</span> : null);\n const shownPairs = visiblePairs.filter((p) => p.color).slice(0, MAX_PAIRS);\n // One row per role in the sheet (\"Brand primary\", \"Link\"), its most visible step's swatch first.\n const roleGroups = [...visiblePairs.reduce((m, p) => m.set(p.token.name, [...(m.get(p.token.name) ?? []), p]), new Map<string, Pair[]>())].map(([name, list]) => ({ name, pairs: list }));\n const swatches = visiblePairs.length ? (\n <Tooltip className={PIN_CLASS} content={visiblePairs.slice(0, 6).map(pairTip).join('. ') + (visiblePairs.length > 6 ? `. And ${visiblePairs.length - 6} more.` : '')}>\n <span className={styles.swatches} tabIndex={0} aria-label={`Tokens this change edits: ${visiblePairs.map(pairTip).join('. ')}`}>\n {shownPairs.map((p) => (\n <span key={p.token.path}>{splitOf(p.before, p.after)}</span>\n ))}\n {visiblePairs.length > shownPairs.length && <span className={styles.more}>+{visiblePairs.length - shownPairs.length} more {visiblePairs.length - shownPairs.length === 1 ? 'token' : 'tokens'}</span>}\n {shownPairs[0] ? subtleOf(shownPairs[0].before, shownPairs[0].after) : null}\n </span>\n </Tooltip>\n ) : null;\n\n // Show what changed: token changes only. A code change's live side is another origin (the production admin), whose\n // styles this page cannot read, so there is nothing reliable to compare: the toggle is not offered. Muted where the\n // change shows nothing (dark for a light-only change).\n const tokenNames = (facts?.tokens ?? []).map((t) => t.name);\n const summary = shownCount === null ? null : surfaceLine(diff!.surfaces.flatMap((s) => s.roots.map(nameOf)), shownCount);\n const toggleTip = `${summary ?? `Outline what ${tokenNames.length === 1 ? tokenNames[0] : 'this change'} changes on this screen.`} Press C.`;\n const toggleLabel = shownCount === null ? 'Show what changed' : `Show what changed · ${shownCount}`;\n const outlineToggle = canOutline ? (\n <Tooltip className={PIN_CLASS} content={toggleTip}>\n <Button variant=\"secondary\" size=\"md\" pressed={outlinesOn} aria-keyshortcuts=\"C\" disabled={Boolean(noDiff)} onClick={() => setOutlines((o) => !o)}>\n {toggleLabel}\n </Button>\n </Tooltip>\n ) : null;\n const outlineIcon = canOutline ? (\n <IconButton\n icon={ScanSearch}\n size=\"md\"\n variant=\"ghost\"\n pressed={outlinesOn}\n disabled={Boolean(noDiff)}\n label={shownCount === null ? 'Show what changed' : `Show what changed, ${shownCount} ${shownCount === 1 ? 'surface' : 'surfaces'}`}\n className={styles.phoneOnly}\n onClick={() => setOutlines((o) => !o)}\n />\n ) : null;\n const shownSurfaces = surfaces.map((s, i) => ({ s, i })).filter(({ s }) => shownRect(s.el));\n const focusSurface = (i: number) => {\n const el = surfaces[i]?.el;\n if (!el) return;\n el.scrollIntoView({ block: 'center', behavior: reduced ? 'auto' : 'smooth' });\n setEmphasis(i);\n };\n const tokensOf = (x: { roots: string[] }) => [...new Set(x.roots.map(nameOf))].join(', ');\n\n const sides = (\n <ButtonGroup appearance=\"attached\" aria-label=\"Compare\" className={styles.sides}>\n {(['before', 'after'] as const).map((s) => (\n <Tooltip className={PIN_CLASS} key={s} content={`${sideLabel(s)}: ${s === 'before' ? 'what customers see today.' : modeDetail(facts, 'after', 'idle')} Press B to flip.`}>\n <Button\n variant=\"secondary\"\n size=\"md\"\n pressed={side === s}\n aria-keyshortcuts=\"B\"\n disabled={!canFlip && side !== s}\n onClick={() => choose(s)}\n >\n {sideLabel(s)}\n </Button>\n </Tooltip>\n ))}\n </ButtonGroup>\n );\n\n return (\n <ThemeProvider\n theme={theme}\n brand=\"bridge\"\n density=\"compact\"\n className={styles.anchor}\n data-bridge-toolbar=\"\"\n {...{ [PIN_ATTR]: '' }}\n data-open={open || undefined}\n data-dock={place.dock}\n style={place.lift ? { paddingBottom: `${place.lift}px` } : undefined}\n >\n <div\n ref={root}\n className={open ? styles.panel : styles.pill}\n role=\"region\"\n aria-label={`Bridge: ${label}, ${title}`}\n data-side={side}\n data-diff-ms={outlinesOn ? diff?.ms : undefined}\n data-diff-count={shownCount ?? undefined}\n data-diff-elements={outlinesOn ? diff?.elements.length : undefined}\n data-note={note ? '' : undefined}\n style={drag ? { transform: `translateX(${drag}px)` } : undefined}\n data-dragging={drag !== null || undefined}\n >\n {open ? (\n <>\n <Tooltip className={PIN_CLASS} content=\"Drag, or use the arrow keys, to move the toolbar\">\n <IconButton\n icon={GripVertical}\n size=\"md\"\n label={`Move the toolbar, now ${dock === 'start' ? 'left' : dock === 'end' ? 'right' : 'centred'}. Use the left and right arrow keys.`}\n className={styles.grip}\n onKeyDown={onGripKey}\n onPointerDown={onGripDown}\n onPointerMove={onGripMove}\n onPointerUp={onGripUp}\n onPointerCancel={() => setDrag(null)}\n />\n </Tooltip>\n <p className={styles.title}>\n <span className={styles.brand}>Bridge</span>\n <span className={styles.name} title={title}>\n {title}\n </span>\n </p>\n {outlineIcon}\n <div className={styles.actions}>\n {sides}\n <span className={styles.desktopOnly}>{swatches}</span>\n <Popover open={sheetOpen} onOpenChange={setSheetOpen}>\n <PopoverTrigger\n render={\n phone ? (\n <IconButton icon={ListChecks} size=\"md\" variant=\"ghost\" label={shownCount ? `Changes, ${shownCount} changed here` : 'Changes'} />\n ) : (\n <Button variant=\"ghost\" size=\"md\" iconEnd={ChevronUp} />\n )\n }\n >\n {phone ? null : (\n <>\n Changes{shownCount ? <span className={styles.count}>{shownCount}</span> : null}\n </>\n )}\n </PopoverTrigger>\n <PopoverContent side=\"top\" align=\"center\" className={`${styles.sheet} ${PIN_CLASS}`} aria-label=\"Changes\">\n {tg && T?.list ? (\n <section className={styles.sheetSection} aria-label=\"Changes tried together\">\n <p className={styles.sectionTitle}>Changes tried together</p>\n <p className={styles.note}>{TOGETHER_HINT}</p>\n <ul className={styles.list}>\n {T.list.map((f) => {\n const can = f.mode === 'tokens' && Boolean(f.source);\n const on = T.included.includes(f.number);\n // Its tokens; those another change sets here (a pick in Studio) say which; and whether any shows in\n // this theme and brand (a light-only change shows nothing in dark).\n const paths = T.editedBy.get(f.number) ?? [];\n const byOther = [...new Set(paths.flatMap((p) => T.result?.tokens.find((t) => t.path === p && !t.from.includes(f.number))?.from ?? []))];\n const used = paths.length - paths.filter((p) => T.result?.tokens.some((t) => t.path === p && !t.from.includes(f.number))).length;\n const showsHere = T.pairs.some((p) => p.token.from.includes(f.number));\n const what = !on\n ? `#${f.number}, switched off`\n : used === 0 && byOther.length\n ? `#${f.number}, ${paths.length === 1 ? 'its token is' : `its ${paths.length} tokens are`} set by ${byOther.map((x) => `#${x}`).join(' and ')} here (your pick)`\n : `#${f.number}, ${used} of ${paths.length} ${paths.length === 1 ? 'token' : 'tokens'} used${byOther.length ? `, the rest set by ${byOther.map((x) => `#${x}`).join(' and ')} (your pick)` : ''}${showsHere ? '' : `. Nothing of it shows in ${theme}`}`;\n return (\n <li key={f.number} className={styles.item}>\n <Checkbox\n label={f.title}\n description={can ? what : `#${f.number}. It changes code, so it can't be applied here.`}\n checked={T.included.includes(f.number)}\n disabled={!can}\n onCheckedChange={(on) => T.toggle(f.number, on)}\n />\n </li>\n );\n })}\n </ul>\n {T.result?.unpicked.length ? (\n <p className={styles.note}>\n {T.result.unpicked.join(', ')}: the change you picked in Studio is off, so the first one listed sets {T.result.unpicked.length === 1 ? 'it' : 'them'}.\n </p>\n ) : null}\n </section>\n ) : null}\n {outlinesOn && shownSurfaces.length ? (\n <section className={styles.sheetSection} aria-label={`Changed here, ${shownSurfaces.length}`}>\n <p className={styles.sectionTitle}>Changed here · {shownSurfaces.length}</p>\n <ul className={styles.rows}>\n {shownSurfaces.map(({ s: x, i }) => (\n <li key={i}>\n <Button\n variant=\"ghost\"\n size=\"md\"\n fullWidth\n className={styles.row}\n data-emphasis={emphasis === i || undefined}\n onMouseEnter={() => setEmphasis(i)}\n onMouseLeave={() => setEmphasis((e) => (e === i ? null : e))}\n onFocus={() => setEmphasis(i)}\n onBlur={() => setEmphasis((e) => (e === i ? null : e))}\n onClick={() => focusSurface(i)}\n >\n <span className={styles.rowText}>\n <span className={styles.rowName}>{x.label}</span>\n <span className={styles.rowMeta}>{tokensOf(x)}</span>\n </span>\n </Button>\n </li>\n ))}\n </ul>\n </section>\n ) : null}\n {screens && screens.length ? (\n <section className={styles.sheetSection} aria-label=\"Screens this change affects\">\n <p className={styles.sectionTitle}>Screens this change affects</p>\n {shared ? (\n <p className={styles.note}>\n {shopOf(shared.tenant)}, {shared.theme}\n </p>\n ) : null}\n <ul className={styles.list}>\n {screens.map((sc) => {\n const current = sc.route === hash && sc.tenant === tenantId && sc.theme === theme;\n const where = shared ? null : <span className={styles.meta}> {shopOf(sc.tenant)}, {sc.theme}</span>;\n return (\n <li key={`${sc.route}|${sc.tenant}|${sc.theme}`} className={styles.item} aria-current={current ? 'page' : undefined}>\n {current ? (\n <span className={styles.here}>\n <Icon icon={Check} size=\"sm\" />\n {sc.label}\n {where}\n </span>\n ) : (\n <Link\n variant=\"standalone\"\n href={`?${PARAM}=${change}&tenant=${encodeURIComponent(sc.tenant)}&theme=${encodeURIComponent(sc.theme)}#${sc.route}`}\n onClick={goTo(sc)}\n className={styles.screenLink}\n >\n {sc.label}\n {where}\n </Link>\n )}\n <span className={styles.meta}>{current ? 'You are here' : `${Math.max(1, Math.round(sc.percent))}% changed`}</span>\n </li>\n );\n })}\n </ul>\n </section>\n ) : null}\n {visiblePairs.length ? (\n <section className={`${styles.sheetSection} ${styles.sheetPhone}`} aria-label=\"Tokens this change edits\">\n <p className={styles.sectionTitle}>Tokens</p>\n <ul className={styles.list}>\n {roleGroups.map((g) => (\n <li key={g.name} className={styles.item}>\n <span className={styles.rowText}>\n <span>{g.name}</span>\n <span className={styles.rowMeta}>\n {g.pairs.length === 1 ? (g.pairs[0]!.token.step ?? '') : `${g.pairs.length} steps`}\n {isSubtle(g.pairs[0]!.before, g.pairs[0]!.after) ? ', subtle change' : ''}\n </span>\n </span>\n {g.pairs[0]!.color ? splitOf(g.pairs[0]!.before, g.pairs[0]!.after) : null}\n </li>\n ))}\n </ul>\n </section>\n ) : null}\n {behind ? (\n <p className={styles.notice} role=\"note\">\n <Icon icon={Info} size=\"sm\" />\n {behind}\n </p>\n ) : null}\n <div className={styles.sheetPhone}>\n <Link variant=\"standalone\" href={studio} className={styles.back}>\n Back to Studio\n </Link>\n </div>\n {screens === null ? (\n <p className={`${styles.note} ${styles.sheetFoot}`}>\n {tg\n ? facts\n ? 'Screens are measured per change, not for this mix. Show what changed outlines this screen.'\n : 'Reading the changes.'\n : facts\n ? 'The screens this change affects are not measured yet.'\n : 'Reading the change.'}\n </p>\n ) : screens.length === 0 ? (\n <p className={`${styles.note} ${styles.sheetFoot}`}>No admin screen changes. Component examples may still change: Studio lists them.</p>\n ) : null}\n </PopoverContent>\n </Popover>\n <span className={styles.desktopOnly}>{outlineToggle}</span>\n <Button variant=\"ghost\" size=\"md\" render={<a href={studio} />} className={styles.studio}>\n Back to Studio\n </Button>\n </div>\n <Tooltip className={PIN_CLASS} content=\"Collapse\">\n <IconButton icon={Minimize2} size=\"md\" label=\"Collapse the Bridge toolbar\" className={styles.collapse} onClick={() => toggleOpen(false)} />\n </Tooltip>\n {error ? (\n <p className={styles.noteRow} role=\"status\">\n {tg ? 'Could not read these changes. Reload the page to try again.' : 'Could not read this change. Reload the page to try again.'}\n </p>\n ) : null}\n </>\n ) : (\n <>\n <span className={styles.brand}>Bridge</span>\n <span className={styles.pillTitle} title={title}>\n {title}\n </span>\n <Badge size=\"sm\">{label}</Badge>\n <Tooltip className={PIN_CLASS} content=\"Open the toolbar\">\n <IconButton icon={ChevronUp} size=\"md\" label={`Open the Bridge toolbar. Showing ${label.toLowerCase()}. Press B to flip.`} onClick={() => toggleOpen(true)} />\n </Tooltip>\n </>\n )}\n {note && <div className={styles.noteRow}>{note}</div>}\n </div>\n {outlinesOn && surfaces.length ? (\n <ChangeOutlines\n surfaces={surfaces}\n theme={theme}\n emphasis={emphasis}\n flash={flash}\n onShown={setShownStable}\n tip={(s) => {\n // This surface's own before and after (its computed colour), and the token whose value it now shows.\n const prop = s.props.find((p) => /^rgb/.test(p.before) && /^rgb/.test(p.after));\n const token = prop ? visiblePairs.find((p) => p.color && toHex(p.after) === toHex(prop.after) && toHex(p.before) === toHex(prop.before)) : null;\n // The role leads (\"Brand primary\"), the palette step comes second (\"Primary 700\").\n const name = token?.token.name ?? [...new Set(s.roots.map(nameOf))].slice(0, 2).join(', ');\n // Changes tried together: the change the value comes from, by the matched token, else by the surface's roots.\n const rootsFrom = [...new Set(s.roots.flatMap((r) => (facts?.tokens.find((t) => t.cssVar === r) as { from?: number[] } | undefined)?.from ?? []))];\n const fromLine = fromOf(token) ?? (tg && rootsFrom.length ? fromText(rootsFrom, titleOf) : null);\n return (\n <span className={styles.tip}>\n {prop ? splitOf(prop.before, prop.after) : null}\n <span className={styles.tipText}>\n <span>\n {s.label}: {name}\n {prop ? `, ${hexPair(prop.before, prop.after)}` : ''}\n </span>\n {token?.token.step ? <span className={styles.tipStep}>{token.token.step}</span> : null}\n {fromLine ? <span className={styles.tipStep}>{fromLine.charAt(0).toUpperCase() + fromLine.slice(1)}</span> : null}\n </span>\n {prop ? subtleOf(prop.before, prop.after) : null}\n </span>\n );\n }}\n />\n ) : null}\n </ThemeProvider>\n );\n}\n\n/** A media query, kept in sync. */\nfunction useMedia(query: string): boolean {\n const get = () => (typeof window !== 'undefined' && window.matchMedia ? window.matchMedia(query).matches : false);\n const [match, setMatch] = useState(get);\n useEffect(() => {\n const m = window.matchMedia(query);\n const on = () => setMatch(m.matches);\n m.addEventListener('change', on);\n return () => m.removeEventListener('change', on);\n }, [query]);\n return match;\n}\n\n/** The product's hash route (\"/orders/12\"), kept in sync. */\nfunction useHash(): string {\n const read = () => window.location.hash.replace(/^#/, '').split('?')[0] || '/';\n const [hash, setHash] = useState(read);\n useEffect(() => {\n const on = () => setHash(read());\n window.addEventListener('hashchange', on);\n return () => window.removeEventListener('hashchange', on);\n }, []);\n return hash;\n}\n"],"names":["session","name","list","sheet","roots","tip","chip","here","brand","studio","live","anchor","box","title","note","swatches","sides","on"],"mappings":";;;;;;AAwBA,MAAM,gBAAgB;AACtB,MAAM,WAAW,CAAC,MAAc,yBAAyB,CAAC;AAE1D,SAASA,YAA0B;AACjC,MAAI;AACF,WAAO,OAAO;AAAA,EAChB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,QAAQ,OAAoE;AAC1F,SAAO,YAAY,EAAE,MAAM,MAAM,MAAM,GAAG,MAAM,KAAK,IAAI,MAAM,IAAI,IAAI,OAAO,MAAM,UAAU,SAAY,gBAAgB,MAAM,OAAO;AACzI;AAKA,eAAe,aAAa,IAAW,OAA4C,GAAW,GAAW,KAAyD;AAChK,QAAM,OAAO,MAAM,GAAG,IAAU,GAAG,CAAC,cAAc,aAAa,EAAE,EAAE,MAAM,MAAM,IAAI;AACnF,QAAM,KAAK,MAAM,KAAK,KAAK,CAAC,MAAM,EAAE,SAAS,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM;AAC3E,MAAI,CAAC,GAAI,QAAO;AAChB,QAAM,UAAU,MAAM,GAAG,IAAU,GAAG,CAAC,cAAc,GAAG,GAAG,EAAE,EAAE,MAAM,MAAM,IAAI;AAC/E,MAAI,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,EAAE,SAAS,OAAO,EAAE,SAAS,MAAM,EAAG,QAAO;AAC5E,SAAO,GACJ,KAAK,MAAM,OAAO,MAAM,MAAM,eAAe,MAAM,CAAC,IAAI,GAAG,gBAAgB,EAC3E,KAAK,CAAC,MAAM,KAAK,MAAM,CAAC,CAA+B,EACvD,MAAM,MAAM,IAAI;AACrB;AAEA,eAAsB,WAAW,OAA6D,GAAW,KAAY,QAAQ,KAAK,GAAyB;AAC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AO,IAAI,SAAS,IAAI;AACrC,YAAU,MAAM;AACd,UAAM,KAAK,MAAM,QAAQ,MAAM;AAC/B,WAAO,iBAAiB,cAAc,EAAE;AACxC,WAAO,MAAM,OAAO,oBAAoB,cAAc,EAAE;AAAA,EAC1D,GAAG,CAAA,CAAE;AACL,SAAO;AACT;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"session-CzlIsFDY.js","sources":["../src/session.ts"],"sourcesContent":["// The Bridge toolbar's pure logic: when it shows, which change it follows, what Before and After mean for that\n// change, and the screens it lists. A product opens it only when Bridge Studio links here with `?bridge=<change>`;\n// production renders nothing, except the Before side of a code change, which arrives with a handoff from a preview.\n\nexport interface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\n/**\n * What the toolbar knows about the product and its design system: from bridge.config.json (the product's entry in\n * products[] and previews), read at build time (the Admin demo) or from the design system repository at run time.\n */\nexport interface BridgeBuild {\n /** The repository whose pull requests `?bridge=<n>` names: the product's own repository, else the design system's. */\n owner: string;\n repo: string;\n /** Production Studio (previews.production.docs): the link back and the shipped tokens.css. */\n studio: string | null;\n /** The product in production (products[].production, else previews.production.<key>): Before of a code change. */\n production: string | null;\n /** The product's preview template (products[].preview): only these hosts may hand a code change over to production. */\n preview: string | null;\n /** VERCEL_ENV of the build ('production', 'preview', 'development'), null when unknown. */\n deployEnv: string | null;\n /** The library branch (repo.defaultBranch) and the token files' root (tokens.root): changes tried together. */\n defaultBranch?: string;\n tokensRoot?: string;\n /** The product's key (products[].key) and the design system repository (\"owner/name\"), for the way back to Studio. */\n product?: string;\n ds?: string;\n /** Bridge's origin for GitHub reads (its read proxy); default production Bridge, null to read GitHub directly. */\n proxy?: string | null;\n}\n\nexport const PARAM = 'bridge';\n/** Where After lives for a code change, carried to production on Before. */\nexport const RETURN_PARAM = 'bridge-return';\n/** Scroll position carried across a Before/After navigation. */\nexport const SCROLL_PARAM = 'bridge-scroll';\nexport const SESSION_KEY = 'bridge-admin:change';\nexport const RETURN_KEY = 'bridge-admin:return';\nexport const DOCK_KEY = 'bridge-admin:toolbar-dock';\nexport const OPEN_KEY = 'bridge-admin:toolbar-open';\n/** Changes tried together: the picks of the tokens they set differently (core encodePicks), from Studio. */\nexport const USE_PARAM = 'bridge-use';\nexport const USE_KEY = 'bridge-admin:use';\n/** At most this many changes are tried together. */\nexport const MAX_TOGETHER = 4;\n\nconst safe = <T>(fn: () => T, fallback: T): T => {\n try {\n return fn();\n } catch {\n return fallback;\n }\n};\n\n/**\n * The change the toolbar follows: `?bridge=<n>` wins and is kept for the session (the admin's hash router keeps the\n * query, a reload or a new path does not need it again); `?bridge=off` forgets it. Blocked storage only loses the\n * memory, never the toolbar of the current page.\n */\nexport function readChange(search: string, storage: StorageLike | null): number | null {\n return readChanges(search, storage)[0] ?? null;\n}\n\n/**\n * The change numbers in \"101\" or \"101,118,120\" (an encoded comma too): positive, at most 7 digits, no repeats, at\n * most MAX_TOGETHER. Anything else in the list makes it unreadable (empty), never a guess.\n */\nexport function parseChanges(raw: string | null | undefined): number[] {\n const parts = (raw ?? '').trim().split(/,|%2C/i).map((p) => p.trim());\n if (!parts.every((p) => /^\\d{1,7}$/.test(p) && Number(p) > 0)) return [];\n return [...new Set(parts.map(Number))].slice(0, MAX_TOGETHER);\n}\n\n/**\n * The changes the toolbar follows: one from \"Try it in the product\", 2 to 4 from \"Try them together\". Same memory as\n * one change: `?bridge=` wins and is kept for the session, `?bridge=off` forgets it, blocked storage only loses the\n * memory. The picks (`bridge-use`) travel with the list and are kept, or forgotten, with it.\n */\nexport function readChanges(search: string, storage: StorageLike | null): number[] {\n const params = new URLSearchParams(search);\n if (params.has(PARAM)) {\n const list = parseChanges(params.get(PARAM));\n if (!list.length) {\n if (storage) safe(() => (storage.removeItem(SESSION_KEY), storage.removeItem(USE_KEY)), undefined);\n return [];\n }\n if (storage) {\n safe(() => storage.setItem(SESSION_KEY, list.join(',')), undefined);\n const use = params.get(USE_PARAM);\n safe(() => (use && list.length > 1 ? storage.setItem(USE_KEY, use) : storage.removeItem(USE_KEY)), undefined);\n }\n return list;\n }\n return storage ? parseChanges(safe(() => storage.getItem(SESSION_KEY), null)) : [];\n}\n\n/** The picks that came with the list: from the address, else the session. */\nexport function readUse(search: string, storage: StorageLike | null): string | null {\n const params = new URLSearchParams(search);\n if (params.has(PARAM)) return params.get(USE_PARAM);\n return storage ? safe(() => storage.getItem(USE_KEY), null) : null;\n}\n\n/** A host that matches the product's preview template (`bridge-admin-git-{branch}-team.vercel.app`), https only. */\nexport function isPreviewUrl(raw: string | null | undefined, template: string | null): boolean {\n if (!raw || !template) return false;\n let url: URL;\n let tpl: URL;\n try {\n url = new URL(raw);\n tpl = new URL(template.replace(/\\{[a-z]+\\}/gi, 'x'));\n } catch {\n return false;\n }\n if (url.protocol !== 'https:' || url.username || url.password || url.port) return false;\n const tplHost = /^https?:\\/\\/([^/?#]+)/i.exec(template)?.[1]?.toLowerCase();\n if (!tplHost || tpl.protocol !== 'https:') return false;\n const pattern = new RegExp(`^${tplHost.split(/\\{[a-z]+\\}/i).map((p) => p.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')).join('[a-z0-9-]+')}$`);\n return pattern.test(url.hostname.toLowerCase());\n}\n\n/** The preview to return to from production, from `?bridge-return=` or the session. Only a preview host counts. */\nexport function readReturn(search: string, storage: StorageLike | null, template: string | null): string | null {\n const raw = new URLSearchParams(search).get(RETURN_PARAM);\n if (raw !== null) {\n if (isPreviewUrl(raw, template)) {\n const origin = new URL(raw).origin;\n if (storage) safe(() => storage.setItem(RETURN_KEY, origin), undefined);\n return origin;\n }\n return null;\n }\n const stored = storage ? safe(() => storage.getItem(RETURN_KEY), null) : null;\n return isPreviewUrl(stored, template) ? new URL(stored!).origin : null;\n}\n\nexport type Where = 'production' | 'preview' | 'local';\n\n/** Which deployment this page is: the product in production by host or by build, a preview, or a local build. */\nexport function whereAmI(host: string, build: Pick<BridgeBuild, 'production' | 'deployEnv'>): Where {\n const prodHost = build.production ? safe(() => new URL(build.production!).host, null) : null;\n if (build.deployEnv === 'production' || (prodHost && host.toLowerCase() === prodHost.toLowerCase())) return 'production';\n if (build.deployEnv === 'preview') return 'preview';\n return 'local';\n}\n\n/**\n * Whether the toolbar renders. Never without a change from Studio. In production only for the Before side of a code\n * change, that is with a preview to return to: production on its own renders nothing.\n */\nexport function shouldRender(input: { change: number | null; where: Where; returnTo: string | null; together?: boolean }): boolean {\n if (input.change === null) return false;\n // Changes tried together run on production: no preview holds all of them.\n if (input.together) return true;\n if (input.where === 'production') return input.returnTo !== null;\n return true;\n}\n\n/** \"These 3 changes\": the After side of changes tried together, counting the ones switched on. */\nexport const togetherLabel = (n: number) => (n === 1 ? 'This change' : `These ${n} changes`);\n\n/** The one hint line of changes tried together: where they run and why. */\nexport const TOGETHER_HINT = \"The live product, with these changes' tokens applied in your browser only. No preview has all of them together.\";\n\n/** Show what changed found nothing on this screen for changes tried together. */\nexport const TOGETHER_EMPTY_LINE = \"These changes don't touch this screen. Try another screen.\";\n\n/** Switches one change on or off, keeping the order Studio listed them in. */\nexport function toggleIncluded(all: number[], included: number[], n: number, on: boolean): number[] {\n const next = new Set(included);\n if (on) next.add(n);\n else next.delete(n);\n return all.filter((x) => next.has(x));\n}\n\n/** Studio's Changes list, where changes are tried together (and the way back). */\nexport function studioChangesUrl(build: Pick<BridgeBuild, 'studio' | 'owner' | 'repo'>): string {\n return build.studio ? `${build.studio.replace(/\\/$/, '')}/studio/changes/` : `https://github.com/${build.owner}/${build.repo}/pulls`;\n}\n\nexport type ChangeMode = 'tokens' | 'code';\n\n/** Token files (DTCG and the contrast gate) and changesets only: Before swaps tokens live. Anything else is code. */\nexport function changeMode(files: string[]): ChangeMode {\n const tokenOnly = files.length > 0 && files.every((f) => f.endsWith('.tokens.json') || /contrast\\.checks\\.json$/.test(f) || f.startsWith('.changeset/'));\n return tokenOnly ? 'tokens' : 'code';\n}\n\n/** The live tokens (main's build, served by production Studio at `/tokens.css`), or null when not configured. */\nexport function liveTokensUrl(build: Pick<BridgeBuild, 'studio'>): string | null {\n return build.studio ? safe(() => new URL('tokens.css', build.studio!.replace(/\\/?$/, '/')).href, null) : null;\n}\n\n/**\n * Studio's page for the change. A change in a product's own repository (an exploration there) opens as\n * `?exploration=<n>&product=<key>`; a change of the design system repository as `?pr=<n>`.\n */\nexport function studioChangeUrl(build: Pick<BridgeBuild, 'studio' | 'owner' | 'repo' | 'product' | 'ds'>, change: number): string {\n if (!build.studio) return `https://github.com/${build.owner}/${build.repo}/pull/${change}`;\n const studio = build.studio.replace(/\\/$/, '');\n const own = build.product && build.ds && build.ds.toLowerCase() !== `${build.owner}/${build.repo}`.toLowerCase();\n return own ? `${studio}/studio/changes/?exploration=${change}&product=${encodeURIComponent(build.product!)}` : `${studio}/studio/changes/?pr=${change}`;\n}\n\n/** Shape of a visual impact manifest that the toolbar reads (written by @bridge-ds/visual). */\nexport interface ManifestShot {\n kind: 'story' | 'route';\n label: string;\n route?: string;\n tenant?: string;\n theme: string;\n status: string;\n percent: number;\n}\n\nexport interface Screen {\n label: string;\n route: string;\n tenant: string;\n theme: string;\n percent: number;\n}\n\n/** The product screens the change alters, most changed first, one entry per screen, shop and theme. */\nexport function changedScreens(shots: ManifestShot[] | null | undefined): Screen[] {\n if (!Array.isArray(shots)) return [];\n const seen = new Set<string>();\n return shots\n .filter((s) => s.kind === 'route' && s.route && s.tenant && (s.status === 'changed' || s.status === 'added'))\n .sort((a, b) => b.percent - a.percent)\n .filter((s) => {\n const key = `${s.route}|${s.tenant}|${s.theme}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n })\n .map((s) => ({ label: s.label, route: s.route!, tenant: s.tenant!, theme: s.theme, percent: s.percent }));\n}\n\n/**\n * The same page on another deployment (code changes: production for Before, the preview for After), with the\n * change, the way back and the scroll position in the query. The hash route (ra-core) is kept.\n */\nexport function sameScreenOn(target: string, here: { search: string; hash: string }, extra: { change: number; returnTo?: string | null; scroll?: number }): string {\n const url = new URL(target);\n const params = new URLSearchParams(here.search);\n params.delete(RETURN_PARAM);\n params.delete(SCROLL_PARAM);\n params.set(PARAM, String(extra.change));\n if (extra.returnTo) params.set(RETURN_PARAM, extra.returnTo);\n if (extra.scroll && extra.scroll > 0) params.set(SCROLL_PARAM, String(Math.round(extra.scroll)));\n url.pathname = '/';\n url.search = params.toString();\n url.hash = here.hash;\n return url.href;\n}\n\n/** The scroll position a Before/After navigation carried, once: the caller removes it from the address. */\nexport function readScroll(search: string): number | null {\n const raw = new URLSearchParams(search).get(SCROLL_PARAM);\n return raw && /^\\d{1,7}$/.test(raw) ? Number(raw) : null;\n}\n\nexport type Dock = 'start' | 'center' | 'end';\nconst DOCKS: Dock[] = ['start', 'center', 'end'];\n\n/** Bottom right by default: the corner a back office leaves free most often. */\nexport function readDock(storage: StorageLike | null): Dock {\n const v = storage ? safe(() => storage.getItem(DOCK_KEY), null) : null;\n return DOCKS.includes(v as Dock) ? (v as Dock) : 'end';\n}\n\n/** One step left (-1) or right (+1), stopping at the edges. */\nexport function stepDock(dock: Dock, step: -1 | 1): Dock {\n return DOCKS[Math.min(DOCKS.length - 1, Math.max(0, DOCKS.indexOf(dock) + step))]!;\n}\n\n/** The dock nearest to where a drag ended: thirds of the viewport width. */\nexport function dockAt(x: number, width: number): Dock {\n if (width <= 0) return 'center';\n const r = x / width;\n return r < 1 / 3 ? 'start' : r > 2 / 3 ? 'end' : 'center';\n}\n\n/** Title of a change as people read it: conventional prefixes (\"tokens: \") dropped, first letter up. */\nexport function readableTitle(title: string): string {\n const t = title.replace(/^\\s*[a-z]+(\\([^)]*\\))?!?:\\s*/i, '').trim() || title.trim();\n return t.charAt(0).toUpperCase() + t.slice(1);\n}\n\n/** The B shortcut flips Before and After, unless the person is typing or holds a modifier. */\nexport function isFlipKey(e: { key: string; altKey: boolean; ctrlKey: boolean; metaKey: boolean; target: unknown }): boolean {\n if (e.altKey || e.ctrlKey || e.metaKey || e.key.toLowerCase() !== 'b') return false;\n const t = e.target as { tagName?: string; isContentEditable?: boolean; closest?: (s: string) => unknown } | null;\n if (!t) return true;\n if (t.isContentEditable) return false;\n const tag = (t.tagName ?? '').toLowerCase();\n if (tag === 'input' || tag === 'textarea' || tag === 'select') return false;\n return !(t.closest && t.closest('[role=\"combobox\"], [role=\"textbox\"], [role=\"searchbox\"]'));\n}\n\nexport interface Rect {\n left: number;\n top: number;\n right: number;\n bottom: number;\n}\n\nconst overlaps = (a: Rect, b: Rect, margin: number) => a.left < b.right + margin && a.right > b.left - margin && a.top < b.bottom + margin && a.bottom > b.top - margin;\n\n/**\n * Where the toolbar goes so it never covers a primary or submit button of the page: the chosen dock if it is free,\n * else the opposite corner, else the centre, else the chosen dock lifted just above the buttons it would cover. The\n * docks sit inside the area [left, right] (the content column, so it never sits over the sidebar).\n */\nexport function placeToolbar(input: { left: number; right: number; vh: number; w: number; h: number; gutter: number; preferred: Dock; obstacles: Rect[]; margin?: number }): { dock: Dock; lift: number } {\n const { left: areaLeft, right: areaRight, vh, w, h, gutter, preferred, obstacles } = input;\n const margin = input.margin ?? 8;\n const rectAt = (dock: Dock, lift = 0): Rect => {\n const left = dock === 'start' ? areaLeft : dock === 'end' ? areaRight - w : (areaLeft + areaRight - w) / 2;\n const bottom = vh - gutter - lift;\n return { left, right: left + w, top: bottom - h, bottom };\n };\n const opposite: Dock = preferred === 'start' ? 'end' : 'start';\n const order: Dock[] = [preferred, opposite, ...DOCKS.filter((d) => d !== preferred && d !== opposite)];\n for (const dock of order) {\n const r = rectAt(dock);\n if (!obstacles.some((o) => overlaps(r, o, margin))) return { dock, lift: 0 };\n }\n // Every dock covers something: stay put and rise above the highest button in the way.\n const base = rectAt(preferred);\n const inWay = obstacles.filter((o) => o.left < base.right + margin && o.right > base.left - margin && o.bottom > base.top - margin);\n const top = Math.min(...inWay.map((o) => o.top));\n const lift = Math.max(0, Math.ceil(base.bottom - (top - margin)));\n return { dock: preferred, lift: Math.min(lift, Math.max(0, vh - h - 2 * gutter)) };\n}\n\n/** What one token file can change on screen: a theme and a brand, or every one of them (null). */\nfunction fileScope(file: string): { theme: string | null; brand: string | null } | 'none' {\n if (file.startsWith('.changeset/')) return 'none';\n let m = /(?:^|\\/)semantic\\/([a-z0-9-]+)\\.tokens\\.json$/i.exec(file);\n if (m && m[1] !== 'base') return { theme: m[1]!, brand: null };\n m = /(?:^|\\/)brands\\/([a-z0-9-]+)\\.([a-z0-9-]+)\\.tokens\\.json$/i.exec(file);\n if (m) return { theme: m[2]!, brand: m[1]! };\n m = /(?:^|\\/)brands\\/([a-z0-9-]+)\\.tokens\\.json$/i.exec(file);\n if (m) return { theme: null, brand: m[1]! };\n // Primitives, base, density, components and anything else: could change every theme and brand.\n return { theme: null, brand: null };\n}\n\nexport type NoDifference = { kind: 'theme'; here: string; touched: string } | { kind: 'brand'; here: string; touched: string };\n\n/**\n * Whether a token change shows nothing in this theme and brand, from the token files it edits (DTCG layers named\n * semantic/<theme>, brands/<brand>.<theme>, brands/<brand>). Null when it may show, or when that cannot be told:\n * never claims \"no difference\" on a guess.\n */\nexport function noVisibleDifference(files: string[], here: { theme: string; brand: string }): NoDifference | null {\n const scopes = files.map(fileScope).filter((s): s is { theme: string | null; brand: string | null } => s !== 'none');\n if (!scopes.length) return null;\n const hits = (theme: string, brand: string) => scopes.some((s) => (s.theme === null || s.theme === theme) && (s.brand === null || s.brand === brand));\n if (hits(here.theme, here.brand)) return null;\n const theme = scopes.find((s) => s.theme !== null && s.theme !== here.theme && (s.brand === null || s.brand === here.brand))?.theme;\n if (theme) return { kind: 'theme', here: here.theme, touched: theme };\n const brand = scopes.find((s) => s.brand !== null && s.brand !== here.brand)?.brand;\n return brand ? { kind: 'brand', here: here.brand, touched: brand } : null;\n}\n\n/** \"darker default background.\" The change title as a short phrase after \"This change:\". */\nexport function changeSummary(title: string): string {\n const t = readableTitle(title).replace(/[.\\s]+$/, '');\n if (!t) return '';\n const lower = /^[A-Z][a-z]/.test(t) ? t.charAt(0).toLowerCase() + t.slice(1) : t;\n return `${lower}.`;\n}\n\nexport interface TokenChange {\n /** Token path, \"color.bg.default\". */\n path: string;\n /** CSS variable the token builds to, \"--color-bg-default\". */\n cssVar: string;\n /** The role it plays, what designers call it: \"Page canvas\" (its description), \"Brand primary\" (a palette role). */\n name: string;\n /** The exact step, second: \"Primary 700\" for a palette step, null for a semantic token. */\n step: string | null;\n type: string | null;\n /** The theme and brand its file applies to (null: every one). */\n theme: string | null;\n brand: string | null;\n}\n\ntype TokenNode = { $value?: unknown; $type?: string; $description?: string; [k: string]: unknown };\ntype Leaf = { value: string; type: string | null; description: string | null };\n\nfunction leaves(node: unknown, path: string[] = [], inheritedType: string | null = null, out = new Map<string, Leaf>()): Map<string, Leaf> {\n if (!node || typeof node !== 'object') return out;\n const n = node as TokenNode;\n const type = typeof n.$type === 'string' ? n.$type : inheritedType;\n if ('$value' in n) {\n out.set(path.join('.'), { value: JSON.stringify(n.$value), type, description: typeof n.$description === 'string' ? n.$description : null });\n return out;\n }\n for (const [k, v] of Object.entries(n)) if (!k.startsWith('$')) leaves(v, [...path, k], type, out);\n return out;\n}\n\n/** Palette roles a brand re-points (brands/<brand>.tokens.json), in designers' words. */\nconst PALETTE_ROLES: Record<string, string> = { primary: 'Brand primary', link: 'Link', neutral: 'Neutral', accent: 'Accent', success: 'Success', warning: 'Warning', danger: 'Danger', info: 'Info', categorical: 'Chart colours' };\n\n/** The role a token plays: its description's first phrase, a palette role (\"Brand primary\"), else its path in words. */\nexport function roleOfToken(path: string, description: string | null): string {\n const first = description?.split(/[.:;(]/)[0]?.trim();\n if (first && first.length <= 40) return first;\n const m = /^palette\\.([a-z-]+)\\./.exec(path);\n if (m) return PALETTE_ROLES[m[1]!] ?? designerName(`palette.${m[1]}`, null);\n return designerName(path, null);\n}\n\n/** The palette step, shown second: \"palette.primary.700\" -> \"Primary 700\"; null for other tokens. */\nexport function stepOfToken(path: string): string | null {\n return path.startsWith('palette.') ? designerName(path, null) : null;\n}\n\n/** Designer name of a token: the first phrase of its description, else its path in words (\"Bg default\"). */\nexport function designerName(path: string, description: string | null): string {\n const first = description?.split(/[.:;(]/)[0]?.trim();\n if (first && first.length <= 40) return first;\n const words = path.replace(/^(color|palette)\\./, '').split('.').join(' ');\n return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\n/**\n * The tokens one file changes between two versions of it (parsed DTCG JSON, null when the file is added or removed):\n * every leaf whose $value differs, with the theme and brand its layer applies to.\n */\nexport function tokenChanges(file: string, before: unknown, after: unknown): TokenChange[] {\n const scope = fileScope(file);\n if (scope === 'none') return [];\n const a = leaves(before);\n const b = leaves(after);\n const out: TokenChange[] = [];\n for (const path of new Set([...a.keys(), ...b.keys()])) {\n const x = a.get(path);\n const y = b.get(path);\n if (x?.value === y?.value) continue;\n out.push({\n path,\n cssVar: `--${path.split('.').join('-')}`,\n name: roleOfToken(path, y?.description ?? x?.description ?? null),\n step: stepOfToken(path),\n type: y?.type ?? x?.type ?? null,\n theme: scope.theme,\n brand: scope.brand,\n });\n }\n return out;\n}\n\n/** WCAG contrast ratio between two rgb() colours, or null when either is not rgb (a non-colour value). */\nexport function contrastRatio(a: string, b: string): number | null {\n const lum = (c: string) => {\n const m = /^rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)/.exec(c.trim());\n if (!m) return null;\n const [r, g, bl] = [m[1], m[2], m[3]].map((n) => {\n const v = Number(n) / 255;\n return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;\n }) as [number, number, number];\n return 0.2126 * r + 0.7152 * g + 0.0722 * bl;\n };\n const x = lum(a);\n const y = lum(b);\n if (x === null || y === null) return null;\n return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);\n}\n\n/** Two colours under 1.1:1 read as the same at a glance: the swatch says \"Subtle change\" so it does not look broken. */\nexport const isSubtle = (a: string, b: string): boolean => {\n const r = contrastRatio(a, b);\n return r !== null && r < 1.1;\n};\n\n/** rgb(245, 247, 249) -> #f5f7f9; anything else as is. */\nexport function toHex(color: string): string {\n const m = /^rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*([\\d.]+))?\\)$/.exec(color.trim());\n if (!m) return color;\n const hex = [m[1], m[2], m[3]].map((n) => Number(n).toString(16).padStart(2, '0')).join('');\n return m[4] !== undefined && Number(m[4]) < 1 ? `#${hex}${Math.round(Number(m[4]) * 255).toString(16).padStart(2, '0')}` : `#${hex}`;\n}\n\n/** \"from Darker default background\", \"from #101 and #118\": which change a token's value comes from (changes tried together). */\nexport function fromText(from: number[], titleOf: (n: number) => string | null): string {\n const names = from.map((n) => titleOf(n) ?? `#${n}`);\n return `from ${names.length <= 2 ? names.join(' and ') : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`}`;\n}\n"],"names":["lift","theme","brand"],"mappings":"AAoCO,MAAM,QAAQ;AAEd,MAAM,eAAe;AAErB,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,aAAa;AACnB,MAAM,WAAW;AACjB,MAAM,WAAW;AAEjB,MAAM,YAAY;AAClB,MAAM,UAAU;AAEhB,MAAM,eAAe;AAE5B,MAAM,OAAO,CAAI,IAAa,aAAmB;AAC/C,MAAI;AACF,WAAO,GAAA;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAeO,SAAS,aAAa,KAA0C;AACrE,QAAM,SAAS,OAAO,IAAI,KAAA,EAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM;AACpE,MAAI,CAAC,MAAM,MAAM,CAAC,MAAM,YAAY,KAAK,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,UAAU,CAAA;AACtE,SAAO,CAAC,GAAG,IAAI,IAAI,MAAM,IAAI,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,YAAY;AAC9D;AAOO,SAAS,YAAY,QAAgB,SAAuC;AACjF,QAAM,SAAS,IAAI,gBAAgB,MAAM;AACzC,MAAI,OAAO,IAAI,KAAK,GAAG;AACrB,UAAM,OAAO,aAAa,OAAO,I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