Skip to content

Chrome DevTools for coding agents

feat: resolve CSS custom variable values inline in `get_css_styles` (#3481)

Samiya Caur8ba2ac945eba
diff --git a/docs/tool-reference.md b/docs/tool-reference.md
index 42d60d1b..842f8e52 100644
--- a/docs/tool-reference.md
+++ b/docs/tool-reference.md
@@ -419,7 +419,7 @@
### `get_css_styles`
**Description:** Retrieve matched CSS rules, inline styles (element.style), inherited styles, custom properties, and cascade wrappers (@layer, @media, @container, @scope) for an element identified by its UID.
-Rules are ordered from highest to lowest cascade precedence and include source line numbers (e.g. index:196). Active (winning) declarations have no prefix tag, while (losing) overridden declarations are prefixed with [overloaded].
+Rules are ordered from highest to lowest cascade precedence and include source line numbers (e.g. index:196). Active (winning) declarations have no prefix tag, while (losing) overridden declarations are prefixed with [overloaded]. Declarations referencing custom properties via var() include their resolved values as inline comments (e.g. color: var(--brand); /* #ff0000 */).
Treat the output as authoritative and complete.
Results are paginated (10 rules per page by default); use pageIdx to page through the remaining rules. Requires a UID from [`take_snapshot`](#take_snapshot).
diff --git a/src/config/cli-options.ts b/src/config/cli-options.ts
index ab95b7cd..bc6cf3cd 100644
--- a/src/config/cli-options.ts
+++ b/src/config/cli-options.ts
@@ -645,7 +645,7 @@ export const commands: Commands = {
},
get_css_styles: {
description:
- 'Retrieve matched CSS rules, inline styles (element.style), inherited styles, custom properties, and cascade wrappers (@layer, @media, @container, @scope) for an element identified by its UID.\nRules are ordered from highest to lowest cascade precedence and include source line numbers (e.g. index:196). Active (winning) declarations have no prefix tag, while (losing) overridden declarations are prefixed with [overloaded].\nTreat the output as authoritative and complete.\nResults are paginated (10 rules per page by default); use pageIdx to page through the remaining rules. Requires a UID from take_snapshot.',
+ 'Retrieve matched CSS rules, inline styles (element.style), inherited styles, custom properties, and cascade wrappers (@layer, @media, @container, @scope) for an element identified by its UID.\nRules are ordered from highest to lowest cascade precedence and include source line numbers (e.g. index:196). Active (winning) declarations have no prefix tag, while (losing) overridden declarations are prefixed with [overloaded]. Declarations referencing custom properties via var() include their resolved values as inline comments (e.g. color: var(--brand); /* #ff0000 */).\nTreat the output as authoritative and complete.\nResults are paginated (10 rules per page by default); use pageIdx to page through the remaining rules. Requires a UID from take_snapshot.',
category: 'Debugging',
args: {
pageId: {
diff --git a/src/formatters/CssFormatter.ts b/src/formatters/CssFormatter.ts
index 330f2ab4..17f3c833 100644
--- a/src/formatters/CssFormatter.ts
+++ b/src/formatters/CssFormatter.ts
@@ -72,6 +72,7 @@ export type AncestorCSSRule =
export interface StructuredCssProperty {
name: string;
value: string;
+ resolvedValue?: string;
status: CssPropertyStatus;
important?: boolean;
}
@@ -467,7 +468,10 @@ function formatPropertyLine(prop: StructuredCssProperty): string {
prop.important && !/\s*!\s*important$/i.test(prop.value)
? ' !important'
: '';
- return `${stateStr}${prop.name}: ${prop.value}${imp};`;
+ const resolved = prop.resolvedValue
+ ? ` /* ${prop.resolvedValue.replaceAll('*/', '*\\/')} */`
+ : '';
+ return `${stateStr}${prop.name}: ${prop.value}${imp};${resolved}`;
}
/**
@@ -1102,6 +1106,30 @@ export class CssFormatter {
);
}
+ static #resolveVariableValue(
+ prop: DevTools.CSSProperty.CSSProperty,
+ value: string,
+ matchedStyles: MatchedStyles,
+ ): string | undefined {
+ if (
+ !prop.parsedOk ||
+ prop.disabled ||
+ !value.includes('var(') ||
+ prop.ownerStyle.parentRule instanceof DevTools.CSSRule.CSSFunctionRule
+ ) {
+ return undefined;
+ }
+ const matching = prop.parseValue(matchedStyles, null);
+ if (!matching || matching.hasUnresolvedSubstitutions(matching.ast.tree)) {
+ return undefined;
+ }
+ const resolved = matching.getComputedPropertyValueText().trim();
+ if (!resolved || resolved === value) {
+ return undefined;
+ }
+ return resolved;
+ }
+
static #formatStructuredProperty(
prop: DevTools.CSSProperty.CSSProperty,
matchedStyles: MatchedStyles,
@@ -1123,10 +1151,16 @@ export class CssFormatter {
if (isImportant) {
value = value.replace(/\s*!\s*important$/i, '').trimEnd();
}
+ const resolvedValue = CssFormatter.#resolveVariableValue(
+ prop,
+ value,
+ matchedStyles,
+ );
return {
name: prop.name,
value,
+ ...(resolvedValue ? {resolvedValue} : {}),
status,
...(isImportant ? {important: true} : {}),
};
diff --git a/src/tools/css.ts b/src/tools/css.ts
index 95771936..a5c2237b 100644
--- a/src/tools/css.ts
+++ b/src/tools/css.ts
@@ -12,7 +12,7 @@ import {definePageTool, type PageToolFactory} from './ToolDefinition.js';
export const getCssStyles: PageToolFactory = definePageTool(() => ({
name: 'get_css_styles',
description: `Retrieve matched CSS rules, inline styles (element.style), inherited styles, custom properties, and cascade wrappers (@layer, @media, @container, @scope) for an element identified by its UID.
-Rules are ordered from highest to lowest cascade precedence and include source line numbers (e.g. index:196). Active (winning) declarations have no prefix tag, while (losing) overridden declarations are prefixed with [overloaded].
+Rules are ordered from highest to lowest cascade precedence and include source line numbers (e.g. index:196). Active (winning) declarations have no prefix tag, while (losing) overridden declarations are prefixed with [overloaded]. Declarations referencing custom properties via var() include their resolved values as inline comments (e.g. color: var(--brand); /* #ff0000 */).
Treat the output as authoritative and complete.
Results are paginated (10 rules per page by default); use pageIdx to page through the remaining rules. Requires a UID from take_snapshot.`,
annotations: {
diff --git a/tests/formatters/CssFormatter.test.js.snapshot b/tests/formatters/CssFormatter.test.js.snapshot
index ff2ec786..75c352af 100644
--- a/tests/formatters/CssFormatter.test.js.snapshot
+++ b/tests/formatters/CssFormatter.test.js.snapshot
@@ -1179,6 +1179,54 @@ Styles for button (uid: "elem-diag"):
}
`;
+exports[`CssFormatter > omits resolved value when var() is unresolved, disabled, or absent toJSON 1`] = `
+{
+ "element": {
+ "uid": "elem-var-omitted",
+ "selector": "button"
+ },
+ "rules": [
+ {
+ "type": "inline",
+ "selector": "element.style",
+ "properties": [
+ {
+ "name": "color",
+ "value": "var(--undefined)",
+ "status": "active"
+ },
+ {
+ "name": "padding",
+ "value": "var(--gap) var(--undefined)",
+ "status": "active"
+ },
+ {
+ "name": "border-width",
+ "value": "var(--gap)",
+ "status": "disabled"
+ },
+ {
+ "name": "background",
+ "value": "red /* brand */",
+ "status": "active"
+ }
+ ]
+ }
+ ]
+}
+`;
+
+exports[`CssFormatter > omits resolved value when var() is unresolved, disabled, or absent toString 1`] = `
+Styles for button (uid: "elem-var-omitted"):
+
+ element.style {
+ color: var(--undefined);
+ padding: var(--gap) var(--undefined);
+ [disabled] border-width: var(--gap);
+ background: red /* brand */;
+ }
+`;
+
exports[`CssFormatter > resolves container queries with node uid toJSON 1`] = `
{
"element": {
@@ -1224,6 +1272,66 @@ Styles for button (uid: "elem-widget"):
}
`;
+exports[`CssFormatter > resolves var() values inline toJSON 1`] = `
+{
+ "element": {
+ "uid": "elem-var",
+ "selector": "button"
+ },
+ "rules": [
+ {
+ "type": "inline",
+ "selector": "element.style",
+ "properties": [
+ {
+ "name": "color",
+ "value": "var(--brand)",
+ "resolvedValue": "#ff0000",
+ "status": "active"
+ },
+ {
+ "name": "padding",
+ "value": "calc(var(--gap) * 2)",
+ "resolvedValue": "calc(8px * 2)",
+ "status": "active"
+ },
+ {
+ "name": "margin",
+ "value": "var(--missing, 12px)",
+ "resolvedValue": "12px",
+ "status": "active"
+ },
+ {
+ "name": "background-color",
+ "value": "var(--accent)",
+ "resolvedValue": "#00ff88",
+ "status": "active",
+ "important": true
+ },
+ {
+ "name": "content",
+ "value": "var(--note)",
+ "resolvedValue": "\\"a */ b\\"",
+ "status": "active"
+ }
+ ]
+ }
+ ]
+}
+`;
+
+exports[`CssFormatter > resolves var() values inline toString 1`] = `
+Styles for button (uid: "elem-var"):
+
+ element.style {
+ color: var(--brand); /* #ff0000 */
+ padding: calc(var(--gap) * 2); /* calc(8px * 2) */
+ margin: var(--missing, 12px); /* 12px */
+ background-color: var(--accent) !important; /* #00ff88 */
+ content: var(--note); /* "a *\\/ b" */
+ }
+`;
+
exports[`CssFormatter > rule subsets > matched rules all 3 rules toJSON 1`] = `
{
"element": {
diff --git a/tests/formatters/CssFormatter.test.ts b/tests/formatters/CssFormatter.test.ts
index d5219177..1c15f081 100644
--- a/tests/formatters/CssFormatter.test.ts
+++ b/tests/formatters/CssFormatter.test.ts
@@ -612,6 +612,7 @@ describe('CssFormatter', () => {
});
const matchedStyles = createMockCSSMatchedStyles({
functionRules: [funcRule],
+ cssVariables: {'--x': '10px'},
});
return new CssFormatter(matchedStyles, {uid: 'elem-func'});
@@ -642,4 +643,45 @@ describe('CssFormatter', () => {
return new CssFormatter(matchedStyles, {uid: 'elem-kf'});
},
);
+
+ formatterTest('resolves var() values inline', () => {
+ const style = createMockCSSInlineStyle([
+ createMockCSSProperty('color', 'var(--brand)'),
+ createMockCSSProperty('padding', 'calc(var(--gap) * 2)'),
+ createMockCSSProperty('margin', 'var(--missing, 12px)'),
+ createMockCSSProperty('background-color', 'var(--accent) !important', {
+ important: true,
+ }),
+ createMockCSSProperty('content', 'var(--note)'),
+ ]);
+ const matchedStyles = createMockCSSMatchedStyles({
+ nodeStyles: [style],
+ cssVariables: {
+ '--brand': '#ff0000',
+ '--gap': '8px',
+ '--accent': '#00ff88',
+ '--note': '"a */ b"',
+ },
+ });
+
+ return new CssFormatter(matchedStyles, {uid: 'elem-var'});
+ });
+
+ formatterTest(
+ 'omits resolved value when var() is unresolved, disabled, or absent',
+ () => {
+ const style = createMockCSSInlineStyle([
+ createMockCSSProperty('color', 'var(--undefined)'),
+ createMockCSSProperty('padding', 'var(--gap) var(--undefined)'),
+ createMockCSSProperty('border-width', 'var(--gap)', {disabled: true}),
+ createMockCSSProperty('background', 'red /* brand */'),
+ ]);
+ const matchedStyles = createMockCSSMatchedStyles({
+ nodeStyles: [style],
+ cssVariables: {'--gap': '8px'},
+ });
+
+ return new CssFormatter(matchedStyles, {uid: 'elem-var-omitted'});
+ },
+ );
});
diff --git a/tests/mocks.ts b/tests/mocks.ts
index 197f960c..7018c34e 100644
--- a/tests/mocks.ts
+++ b/tests/mocks.ts
@@ -659,12 +659,23 @@ export function createMockCSSProperty(
value: string,
options: MockCSSPropertyOptions = {},
): MockCSSProperty {
- const prop = sinon.createStubInstance(DevTools.CSSProperty.CSSProperty);
- prop.name = name;
- prop.value = value;
- prop.important = options.important ?? false;
- prop.parsedOk = options.parsedOk ?? true;
- prop.disabled = options.disabled ?? false;
+ const ownerStyle = sinon.createStubInstance(
+ DevTools.CSSStyleDeclaration.CSSStyleDeclaration,
+ );
+ ownerStyle.parentRule = null;
+ const prop = sinon.stub(
+ new DevTools.CSSProperty.CSSProperty(
+ ownerStyle,
+ 0,
+ name,
+ value,
+ options.important ?? false,
+ options.disabled ?? false,
+ options.parsedOk ?? true,
+ false,
+ ),
+ );
+ prop.parseValue.callThrough();
return prop;
}
@@ -695,6 +706,9 @@ export function createMockCSSStyleDeclaration(
if (options.range) {
Object.assign(style, {range: options.range});
}
+ for (const prop of properties) {
+ prop.ownerStyle = style;
+ }
return style;
}
@@ -1019,6 +1033,7 @@ export interface MockCSSMatchedStylesParams {
>;
propertyStates?: Map<DevTools.CSSProperty.CSSProperty, string>;
matchingSelectorsMap?: Map<unknown, number[]>;
+ cssVariables?: Record<string, string>;
}
export function createMockCSSMatchedStyles(
@@ -1074,6 +1089,18 @@ export function createMockCSSMatchedStyles(
mock.getMatchingSelectors.callsFake(
rule => params.matchingSelectorsMap?.get(rule) ?? [],
);
+ mock.propertyMatchers.callThrough();
+ mock.computeCSSVariable.callsFake((_style, name) => {
+ const value = params.cssVariables?.[name];
+ return value !== undefined
+ ? {
+ value,
+ declaration: new DevTools.CSSMatchedStyles.CSSValueSource(
+ createMockCSSProperty(name, value),
+ ),
+ }
+ : null;
+ });
return mock;
}