Repository: facebook/stylex
Pull request #898: feat: create media query transformer to ensure last query wins
Author: login: mellyeliu
Labels: name: CLA Signed
description: This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.
Created: 2025-02-22T12:23:26Z | Merged: 2025-04-11T04:01:22Z

create media query transformer to ensure “last query wins” logic

## Context  
Now that we have a usable media query parser in https://github.com/facebook/stylex/pull/743, we can finally implement last media query wins logic. 

## Implementation
High level approach: traverse through styles, search for media queries, do two passes at each node - one to build up a list of negations for each query, and another to apply the negation. 

1. traverse nested styles with dfs
   - dfs to find all nested media queries
   - extract and flatten all media queries per into list for easier transformation

2. iterate media queries in reverse order
   - loop through the extracted media queries from last to first 

3. accumulate negations
   -backwards, for single pass
-  build up a list of negations from previous queries during reverse iteration
   - apply these negations to prevent earlier media queries from overriding more specific ones defined later

4. construct updated media queries
   - forwards order, because we need to reassign the object keys in the same order we see them to avoid breaking js object keys order
   - for each media query: use `MediaQuery.parser.parseToEnd` to convert query string into object representation
 - append all accumulated negations to queries
   - stringify media query using`MediaQuery.toString()`
   - append current queries to negations

5. return updated styles object with negated media queries


## Testing

Use `json.stringify` to ensure object key order is maintained

Scenarios like:
- basic usage: multiple widths 
- basic usage: complex styles object 
- basic usage: lots and lots of widths 
- nested queries
- handles comma-separated (or) media queries
- handles and media queries 
- keywords
- combination of keywords and > rules

Missing: 
- Nested not cases blocked on parsing issues

## Pre-flight checklist

- [x] I have read the contributing guidelines
      [Contribution Guidelines](https://github.com/facebook/stylex/blob/main/.github/CONTRIBUTING.md)
- [x] Performed a self-review of my code


Diff:
diff --git a/packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js b/packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
new file mode 100644
index 000000000..a7691d92e
--- /dev/null
+++ b/packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
@@ -0,0 +1,339 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            '1 / 4',
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: nested query', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': {
+            '@media (max-width: 1024px)': '1 / 3',
+            '@media (max-width: 768px)': '1 / -1',
+          },
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            {
+              '@media (max-width: 1024px) and (not (max-width: 768px))':
+                '1 / 3',
+              '@media (max-width: 768px)': '1 / -1',
+            },
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: nested query', () => {
+    const originalStyles = {
+      table: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': {
+            '@media (max-width: 1024px)': '1 / 3',
+            '@media (max-width: 768px)': '1 / -1',
+          },
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      table: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            {
+              '@media (max-width: 1024px) and (not (max-width: 768px))':
+                '1 / 3',
+              '@media (max-width: 768px)': '1 / -1',
+            },
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        padding: '10px',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: complex object', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        grid: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+        },
+        gridRow: {
+          default: '1 / 2',
+          padding: '10px',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            '1 / 4',
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        grid: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+        },
+        gridRow: {
+          default: '1 / 2',
+          padding: '10px',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: lots and lots of widths', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+          '@media (max-width: 458px)': '1 / -1',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px)) and (not (max-width: 458px))':
+            '1 / 4',
+          '@media (max-width: 1024px) and (not (max-width: 768px)) and (not (max-width: 458px))':
+            '1 / 3',
+          '@media (max-width: 768px) and (not (max-width: 458px))': '1 / -1',
+          '@media (max-width: 458px)': '1 / -1',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('single word condition', () => {
+    const originalStyles = stylex.create({
+      colorMode: {
+        mode: {
+          default: 'normal',
+          '@media (color)': 'colorful',
+          '@media (monochrome)': 'grayscale',
+        },
+      },
+    });
+
+    const expectedStyles = {
+      colorMode: {
+        mode: {
+          default: 'normal',
+          '@media (color) and (not (monochrome))': 'colorful',
+          '@media (monochrome)': 'grayscale',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('handles comma-separated (or) media queries', () => {
+    const originalStyles = stylex.create({
+      container: {
+        width: {
+          default: '100%',
+          '@media screen, (max-width: 800px)': '80%',
+          '@media (max-width: 500px)': '60%',
+        },
+      },
+    });
+
+    const expectedStyles = {
+      container: {
+        width: {
+          default: '100%',
+          '@media screen and (not (max-width: 500px)), (max-width: 800px) and (not (max-width: 500px))':
+            '80%',
+          '@media (max-width: 500px)': '60%',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test.skip('handles and media queries', () => {
+    const originalStyles = stylex.create({
+      container: {
+        width: {
+          default: '100%',
+          '@media (min-width: 900px)': '80%',
+          '@media (min-width: 500px) and (max-width: 899px) and (max-height: 300px)':
+            '50%',
+        },
+      },
+    });
+
+    const expectedStyles = {
+      container: {
+        width: {
+          default: '100%',
+          '@media (min-width: 900px) and (not ((min-width: 500px) and (max-width: 899px) and (max-height: 300px)))':
+            '80%',
+          '@media (min-width: 500px) and (max-width: 899px) and (max-height: 300px)':
+            '50%',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test.skip('combination of keywords and rules', () => {
+    const originalStyles = stylex.create({
+      container: {
+        width: {
+          default: '100%',
+          '@media screen and (min-width: 900px)': '80%',
+          '@media print and (max-width: 500px)': '50%',
+        },
+      },
+    });
+
+    const expectedStyles = {
+      container: {
+        width: {
+          default: '100%',
+          '@media screen and (min-width: 900px) and (not (print and (max-width: 500px)))':
+            '80%',
+          '@media print and (max-width: 500px)': '50%',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: does not modify single queries', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('ignores legacy media query syntax', () => {
+    const originalStyles = {
+      root: {
+        width: '100%',
+        '@media (min-width: 600px)': {
+          width: '50%',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      root: {
+        width: '100%',
+        '@media (min-width: 600px)': {
+          width: '50%',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+});
diff --git a/packages/style-value-parser/src/at-queries-from-tokens/media-query-transform.js b/packages/style-value-parser/src/at-queries-from-tokens/media-query-transform.js
new file mode 100644
index 000000000..002fe15ec
--- /dev/null
+++ b/packages/style-value-parser/src/at-queries-from-tokens/media-query-transform.js
@@ -0,0 +1,106 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict
+ */
+
+import { MediaQuery } from './media-query.js';
+
+export function lastMediaQueryWinsTransform(styles: Object): Object {
+  return dfsProcessQueries(styles, 0);
+}
+
+function combineMediaQueryWithNegations(
+  current: MediaQuery,
+  negations: MediaQuery[],
+): MediaQuery {
+  if (negations.length === 0) {
+    return current;
+  }
+
+  let combinedAst;
+
+  if (current.queries.type === 'or') {
+    combinedAst = {
+      type: 'or',
+      rules: current.queries.rules.map((rule) => ({
+        type: 'and',
+        rules: [
+          rule,
+          ...negations.map((mq) => ({ type: 'not', rule: mq.queries })),
+        ],
+      })),
+    };
+  } else {
+    combinedAst = {
+      type: 'and',
+      rules: [
+        current.queries,
+        ...negations.map((mq) => ({ type: 'not', rule: mq.queries })),
+      ],
+    };
+  }
+
+  return new MediaQuery(combinedAst);
+}
+
+function dfsProcessQueries(
+  obj: { [key: string]: any },
+  depth: number,
+): {
+  [key: string]: any,
+} {
+  const result: { [key: string]: any } = {};
+
+  Object.entries(obj).forEach(([key, value]) => {
+    if (typeof value === 'object' && value !== null) {
+      result[key] = dfsProcessQueries(value, depth + 1);
+    } else {
+      result[key] = value;
+    }
+  });
+
+  if (
+    depth >= 2 &&
+    Object.keys(result).some((key) => key.startsWith('@media '))
+  ) {
+    const mediaKeys = Object.keys(result).filter((key) =>
+      key.startsWith('@media '),
+    );
+
+    const negations = [];
+    const accumulatedNegations = [];
+
+    for (let i = mediaKeys.length - 1; i > 0; i--) {
+      // Skip last iteration
+      const mediaQuery = MediaQuery.parser.parseToEnd(mediaKeys[i]);
+      negations.push(mediaQuery);
+      accumulatedNegations.push([...negations]); // Clone array before pushing
+    }
+    accumulatedNegations.reverse();
+    accumulatedNegations.push([]);
+
+    for (let i = 0; i < mediaKeys.length; i++) {
+      const currentKey = mediaKeys[i];
+      const currentValue = result[currentKey];
+
+      const baseMediaQuery = MediaQuery.parser.parseToEnd(currentKey);
+      const reversedNegations = [...accumulatedNegations[i]].reverse();
+
+      const combinedQuery = combineMediaQueryWithNegations(
+        baseMediaQuery,
+        reversedNegations,
+      );
+
+      const newMediaKey = combinedQuery.toString();
+
+      delete result[currentKey];
+      result[newMediaKey] = currentValue;
+    }
+  }
+
+  return result;
+}
diff --git a/packages/style-value-parser/src/at-queries-from-tokens/media-query.js b/packages/style-value-parser/src/at-queries-from-tokens/media-query.js
index a4646f300..33771d70e 100644
--- a/packages/style-value-parser/src/at-queries-from-tokens/media-query.js
+++ b/packages/style-value-parser/src/at-queries-from-tokens/media-query.js
@@ -43,7 +43,7 @@ type MediaRulePair = {
   key: string,
   value: MediaRuleValue,
 };
-type MediaNotRule = { type: 'not', rule: MediaRulePair | MediaWordRule };
+type MediaNotRule = { type: 'not', rule: MediaQueryRule };
 type MediaAndRules = { type: 'and', rules: $ReadOnlyArray<MediaQueryRule> };
 type MediaOrRules = { type: 'or', rules: $ReadOnlyArray<MediaQueryRule> };
 


Reviews:
user: login: necolas
body: What does "last wins" mean exactly in this context? FWIW, the "last wins" approach to property merging in StyleX is only true for properties with the same name. The way we handle short/long form merging (inc within a single style object) is really problematic and something we're trying to undo. So if last-wins for MQ is a local concern within a style, I'm concerned that will also be problematic. Anything that relies on order of keys in authored code is going to have those problems
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-02-27T16:42:25Z
user: login: nmn
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-02-28T01:04:59Z
user: login: mellyeliu
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-02-28T01:15:24Z
user: login: nmn
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-02-28T01:17:13Z
user: login: nmn
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-02-28T01:20:40Z
user: login: mellyeliu
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-02-28T01:40:22Z
user: login: necolas
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-02-28T04:35:31Z
user: login: nmn
body: Please remove the console.logs at least before merging.

Further code improvements can be made later.
state: APPROVED
author_association: COLLABORATOR
submitted_at: 2025-04-11T03:08:36Z
user: login: mellyeliu
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-11T03:44:32Z
user: login: mellyeliu
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-11T03:59:55Z

Review comments:
diff_hunk: @@ -0,0 +1,217 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: necolas
body: We should be concerned at how bloated generated code gets with this approach
created_at: 2025-02-27T16:34:26Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,217 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(result).toEqual(expectedStyles);
+  });
+
+  test('basic usage: complex object', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+      gridRow: {
+        default: '1 / 2',
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: necolas
body: This is an example of where I think this approach breaks down. Let's say some conditional applies this MQ to the same element as the MQs above - non of the negations apply and you go back to having non deterministic rendering results
created_at: 2025-02-27T16:37:37Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,217 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: nmn
body: This is a bit of a work in progress where we will be simplifying the media queries as well.
created_at: 2025-02-28T01:04:59Z
author_association: COLLABORATOR
diff_hunk: @@ -0,0 +1,217 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: mellyeliu
body: the doc here provides a bit more context - https://docs.google.com/document/d/1KlMnWz__zVBNcH_HQmd64sPEFf6AdaXeG46rL_eU5ec/edit?tab=t.uwqdsvafq1l7#heading=h.m5zrpmurwti 

the plan is to eventually rewrite the media query parser to do the simplification step for us, or to pass this return to another fn to do a second round of parsing 
created_at: 2025-02-28T01:15:24Z
author_association: MEMBER
diff_hunk: @@ -0,0 +1,217 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(result).toEqual(expectedStyles);
+  });
+
+  test('basic usage: complex object', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+      gridRow: {
+        default: '1 / 2',
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: nmn
body: I think there's some misunderstanding of how the media queries work and what this PR is fixing.

All that this PR does, is that if you have multiple "conditions" in a single value (`{default: A, ...}`) then you no longer have to manually ensure that the conditions don't overlap and we do that for you automatically.

This removes the main source of non-determinism which is that we cannot guarantee that the media queries in the generated CSS will be in the same order as defined in the source.

When talking about media queries *within* multiple keys, such as a shorthand and a longhand, there is no non-determinism there. Based on the config options, either the "the last applied property" (`application-order`) will win, OR, the longhand property will win (`property-specificity`). 

Whichever "value" wins, this PR is only about making the "conditions" within the "value" deterministic and predictable.
created_at: 2025-02-28T01:17:09Z
author_association: COLLABORATOR
diff_hunk: @@ -0,0 +1,217 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(result).toEqual(expectedStyles);
+  });
+
+  test('basic usage: complex object', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+      gridRow: {
+        default: '1 / 2',
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: nmn
body: To further clarify, the generated CSS order is:
```
<shorthands>
<Media Queries around shorthands>
<Pseudo Classes on shorthands>
<Media Queries and Pseudo Classes around shorthands>

<longhands>
<Media Queries around longhands>
<Pseudo Classes on longhands>
<Media Queries and Pseudo Classes around longhands>
```

i.e., the longhand property *always* has higher specificity regardless of the media query applied on the shorthand and this makes the styles deterministic.

created_at: 2025-02-28T01:20:34Z
author_association: COLLABORATOR
diff_hunk: @@ -0,0 +1,217 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(result).toEqual(expectedStyles);
+  });
+
+  test('basic usage: complex object', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+      gridRow: {
+        default: '1 / 2',
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: mellyeliu
body: Hmm, maybe my example in the test cases is not be the most illustrative in how it's used in stylex. 

The object containing `default` and MQs is effectively a single value assigned to a style property, not a nested style declaration.

An example of how this would resolve in stylex:
```tsx
const styles = stylex.create({
  foo: {
    paddingTop: {
      default: 50,
      '@media (max-width: 1440px)': 10px,
      '@media (max-width: 768px)': 15px,
    }
  },
  foo2: {
    padding: {
      default: 500,
      '@media (max-width: 1280px)': 20px, 
      '@media (max-width: 480px)': '40px',
    }
  }
});
```

Which would be used in an element like:
```tsx
// application-order 
stylex.props(styles.foo, styles.foo2) 
// is equivalent to stylex.props(styles.foo2)
// because padding overrides padding-top in application order


// property-specificity 
stylex.props(styles.foo, styles.foo2) 
// which would have padding-top from foo
// and padding from foo2 in the other directions


stylex.props(styles.foo2, styles.foo) 
// for both config options, element has padding-top from foo
// and padding from foo2 in the other directions
```

created_at: 2025-02-28T01:40:22Z
author_association: MEMBER
diff_hunk: @@ -0,0 +1,217 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(result).toEqual(expectedStyles);
+  });
+
+  test('basic usage: complex object', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+      gridRow: {
+        default: '1 / 2',
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: necolas
body: Ah yes that's right. Thanks
created_at: 2025-02-28T04:35:31Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,281 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: nested query', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': {
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          {
+            '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+            '@media (max-width: 768px)': '1 / -1',
+          },
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: nested query', () => {
+    const originalStyles = {
+      table: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': {
+            '@media (max-width: 1024px)': '1 / 3',
+            '@media (max-width: 768px)': '1 / -1',
+          },
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      table: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            {
+              '@media (max-width: 1024px) and (not (max-width: 768px))':
+                '1 / 3',
+              '@media (max-width: 768px)': '1 / -1',
+            },
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        padding: '10px',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: complex object', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+      gridRow: {
+        default: '1 / 2',
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+      gridRow: {
+        default: '1 / 2',
+        padding: '10px',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: lots and lots of widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+        '@media (max-width: 458px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px)) and (not (max-width: 458px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px)) and (not (max-width: 458px))':
+          '1 / 3',
+        '@media (max-width: 768px) and (not (max-width: 458px))': '1 / -1',
+        '@media (max-width: 458px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('single word condition', () => {
+    const originalStyles = stylex.create({
+      colorMode: {
+        '@media (color)': 'colorful',
+        '@media (monochrome)': 'grayscale',
+      },
+    });
+
+    const expectedStyles = {
+      colorMode: {
+        '@media (color) and (not (monochrome))': 'colorful',
+        '@media (monochrome)': 'grayscale',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('handles comma-separated (or) media queries', () => {
+    const originalStyles = stylex.create({
+      container: {
+        default: 'width: 100%',
+        '@media screen, (max-width: 800px)': 'width: 80%',
+        '@media (max-width: 500px)': 'width: 60%',
+      },
+    });
+
+    const expectedStyles = {
+      container: {
+        default: 'width: 100%',
+        '@media screen and (not (max-width: 500px)), (max-width: 800px) and (not (max-width: 500px))':
+          'width: 80%',
+        '@media (max-width: 500px)': 'width: 60%',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('handles and media queries', () => {
+    const originalStyles = stylex.create({
+      container: {
+        default: 'width:100%',
+        '@media (min-width: 900px)': 'width:80%',
+        '@media (min-width: 500px) and (max-width: 899px) and (max-height: 300px)':
+          'width:50%',
+      },
+    });
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: nmn
body: ```suggestion
    const originalStyles = stylex.create({
      container: {
        width: {
          default: '100%',
          '@media (min-width: 900px)': '80%',
          '@media (min-width: 500px) and (max-width: 899px) and (max-height: 300px)': '50%',
        },
      },
    });
```
created_at: 2025-04-10T01:27:40Z
author_association: COLLABORATOR
diff_hunk: @@ -0,0 +1,281 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: nested query', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': {
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          {
+            '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+            '@media (max-width: 768px)': '1 / -1',
+          },
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: nested query', () => {
+    const originalStyles = {
+      table: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': {
+            '@media (max-width: 1024px)': '1 / 3',
+            '@media (max-width: 768px)': '1 / -1',
+          },
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      table: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            {
+              '@media (max-width: 1024px) and (not (max-width: 768px))':
+                '1 / 3',
+              '@media (max-width: 768px)': '1 / -1',
+            },
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        padding: '10px',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: complex object', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+      gridRow: {
+        default: '1 / 2',
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+      },
+      grid: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+      },
+      gridRow: {
+        default: '1 / 2',
+        padding: '10px',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: lots and lots of widths', () => {
+    const originalStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px)': '1 / 4',
+        '@media (max-width: 1024px)': '1 / 3',
+        '@media (max-width: 768px)': '1 / -1',
+        '@media (max-width: 458px)': '1 / -1',
+      },
+    };
+
+    const expectedStyles = {
+      gridColumn: {
+        default: '1 / 2',
+        '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px)) and (not (max-width: 458px))':
+          '1 / 4',
+        '@media (max-width: 1024px) and (not (max-width: 768px)) and (not (max-width: 458px))':
+          '1 / 3',
+        '@media (max-width: 768px) and (not (max-width: 458px))': '1 / -1',
+        '@media (max-width: 458px)': '1 / -1',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('single word condition', () => {
+    const originalStyles = stylex.create({
+      colorMode: {
+        '@media (color)': 'colorful',
+        '@media (monochrome)': 'grayscale',
+      },
+    });
+
+    const expectedStyles = {
+      colorMode: {
+        '@media (color) and (not (monochrome))': 'colorful',
+        '@media (monochrome)': 'grayscale',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('handles comma-separated (or) media queries', () => {
+    const originalStyles = stylex.create({
+      container: {
+        default: 'width: 100%',
+        '@media screen, (max-width: 800px)': 'width: 80%',
+        '@media (max-width: 500px)': 'width: 60%',
+      },
+    });
+
+    const expectedStyles = {
+      container: {
+        default: 'width: 100%',
+        '@media screen and (not (max-width: 500px)), (max-width: 800px) and (not (max-width: 500px))':
+          'width: 80%',
+        '@media (max-width: 500px)': 'width: 60%',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('handles and media queries', () => {
+    const originalStyles = stylex.create({
+      container: {
+        default: 'width:100%',
+        '@media (min-width: 900px)': 'width:80%',
+        '@media (min-width: 500px) and (max-width: 899px) and (max-height: 300px)':
+          'width:50%',
+      },
+    });
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: nmn
body: Any media queries at the top-level, AKA, legacy media queries should not be transformed at all as they are used as keys when merging styles and they should never be changed.
created_at: 2025-04-10T01:28:16Z
author_association: COLLABORATOR
diff_hunk: @@ -0,0 +1,339 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            '1 / 4',
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: nested query', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': {
+            '@media (max-width: 1024px)': '1 / 3',
+            '@media (max-width: 768px)': '1 / -1',
+          },
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            {
+              '@media (max-width: 1024px) and (not (max-width: 768px))':
+                '1 / 3',
+              '@media (max-width: 768px)': '1 / -1',
+            },
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: nested query', () => {
+    const originalStyles = {
+      table: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': {
+            '@media (max-width: 1024px)': '1 / 3',
+            '@media (max-width: 768px)': '1 / -1',
+          },
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      table: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            {
+              '@media (max-width: 1024px) and (not (max-width: 768px))':
+                '1 / 3',
+              '@media (max-width: 768px)': '1 / -1',
+            },
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        padding: '10px',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: complex object', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        grid: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+        },
+        gridRow: {
+          default: '1 / 2',
+          padding: '10px',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            '1 / 4',
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        grid: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+        },
+        gridRow: {
+          default: '1 / 2',
+          padding: '10px',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: lots and lots of widths', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+          '@media (max-width: 458px)': '1 / -1',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px)) and (not (max-width: 458px))':
+            '1 / 4',
+          '@media (max-width: 1024px) and (not (max-width: 768px)) and (not (max-width: 458px))':
+            '1 / 3',
+          '@media (max-width: 768px) and (not (max-width: 458px))': '1 / -1',
+          '@media (max-width: 458px)': '1 / -1',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('single word condition', () => {
+    const originalStyles = stylex.create({
+      colorMode: {
+        mode: {
+          default: 'normal',
+          '@media (color)': 'colorful',
+          '@media (monochrome)': 'grayscale',
+        },
+      },
+    });
+
+    const expectedStyles = {
+      colorMode: {
+        mode: {
+          default: 'normal',
+          '@media (color) and (not (monochrome))': 'colorful',
+          '@media (monochrome)': 'grayscale',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('handles comma-separated (or) media queries', () => {
+    const originalStyles = stylex.create({
+      container: {
+        width: {
+          default: '100%',
+          '@media screen, (max-width: 800px)': '80%',
+          '@media (max-width: 500px)': '60%',
+        },
+      },
+    });
+
+    const expectedStyles = {
+      container: {
+        width: {
+          default: '100%',
+          '@media screen and (not (max-width: 500px)), (max-width: 800px) and (not (max-width: 500px))':
+            '80%',
+          '@media (max-width: 500px)': '60%',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test.skip('handles and media queries', () => {
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: nmn
body: Why is this one skipped? An issue with the parser?
created_at: 2025-04-11T03:05:42Z
author_association: COLLABORATOR
diff_hunk: @@ -0,0 +1,111 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict
+ */
+
+import { MediaQuery } from './media-query.js';
+
+export function lastMediaQueryWinsTransform(styles: Object): Object {
+  return dfsProcessQueries(styles, 0);
+}
+
+function combineMediaQueryWithNegations(
+  current: MediaQuery,
+  negations: MediaQuery[],
+): MediaQuery {
+  if (negations.length === 0) {
+    return current;
+  }
+
+  let combinedAst;
+
+  if (current.queries.type === 'or') {
+    combinedAst = {
+      type: 'or',
+      rules: current.queries.rules.map((rule) => ({
+        type: 'and',
+        rules: [
+          rule,
+          ...negations.map((mq) => ({ type: 'not', rule: mq.queries })),
+        ],
+      })),
+    };
+  } else {
+    combinedAst = {
+      type: 'and',
+      rules: [
+        current.queries,
+        ...negations.map((mq) => ({ type: 'not', rule: mq.queries })),
+      ],
+    };
+  }
+
+  return new MediaQuery(combinedAst);
+}
+
+function dfsProcessQueries(
+  obj: { [key: string]: any },
+  depth: number,
+): {
+  [key: string]: any,
+} {
+  const result: { [key: string]: any } = {};
+
+  Object.entries(obj).forEach(([key, value]) => {
+    if (typeof value === 'object' && value !== null) {
+      result[key] = dfsProcessQueries(value, depth + 1);
+    } else {
+      result[key] = value;
+    }
+  });
+
+  if (
+    depth >= 2 &&
+    Object.keys(result).some((key) => key.startsWith('@media '))
+  ) {
+    const mediaKeys = Object.keys(result).filter((key) =>
+      key.startsWith('@media '),
+    );
+
+    const negations = [];
+    const accumulatedNegations = [];
+
+    for (let i = mediaKeys.length - 1; i > 0; i--) {
+      // Skip last iteration
+      const mediaQuery = MediaQuery.parser.parseToEnd(mediaKeys[i]);
+      negations.push(mediaQuery);
+      accumulatedNegations.push([...negations]); // Clone array before pushing
+    }
+    accumulatedNegations.reverse();
+    accumulatedNegations.push([]);
+    console.log('accumulatedNegations', accumulatedNegations);
path: packages/style-value-parser/src/at-queries-from-tokens/media-query-transform.js
user: login: nmn
body: remove console.log
created_at: 2025-04-11T03:06:51Z
author_association: COLLABORATOR
diff_hunk: @@ -0,0 +1,111 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict
+ */
+
+import { MediaQuery } from './media-query.js';
+
+export function lastMediaQueryWinsTransform(styles: Object): Object {
+  return dfsProcessQueries(styles, 0);
+}
+
+function combineMediaQueryWithNegations(
+  current: MediaQuery,
+  negations: MediaQuery[],
+): MediaQuery {
+  if (negations.length === 0) {
+    return current;
+  }
+
+  let combinedAst;
+
+  if (current.queries.type === 'or') {
+    combinedAst = {
+      type: 'or',
+      rules: current.queries.rules.map((rule) => ({
+        type: 'and',
+        rules: [
+          rule,
+          ...negations.map((mq) => ({ type: 'not', rule: mq.queries })),
+        ],
+      })),
+    };
+  } else {
+    combinedAst = {
+      type: 'and',
+      rules: [
+        current.queries,
+        ...negations.map((mq) => ({ type: 'not', rule: mq.queries })),
+      ],
+    };
+  }
+
+  return new MediaQuery(combinedAst);
+}
+
+function dfsProcessQueries(
+  obj: { [key: string]: any },
+  depth: number,
+): {
+  [key: string]: any,
+} {
+  const result: { [key: string]: any } = {};
+
+  Object.entries(obj).forEach(([key, value]) => {
+    if (typeof value === 'object' && value !== null) {
+      result[key] = dfsProcessQueries(value, depth + 1);
+    } else {
+      result[key] = value;
+    }
+  });
+
+  if (
+    depth >= 2 &&
+    Object.keys(result).some((key) => key.startsWith('@media '))
+  ) {
+    const mediaKeys = Object.keys(result).filter((key) =>
+      key.startsWith('@media '),
+    );
+
+    const negations = [];
+    const accumulatedNegations = [];
+
+    for (let i = mediaKeys.length - 1; i > 0; i--) {
+      // Skip last iteration
+      const mediaQuery = MediaQuery.parser.parseToEnd(mediaKeys[i]);
+      negations.push(mediaQuery);
+      accumulatedNegations.push([...negations]); // Clone array before pushing
+    }
+    accumulatedNegations.reverse();
+    accumulatedNegations.push([]);
+    console.log('accumulatedNegations', accumulatedNegations);
+
+    for (let i = 0; i < mediaKeys.length; i++) {
+      const currentKey = mediaKeys[i];
+      const currentValue = result[currentKey];
+
+      const baseMediaQuery = MediaQuery.parser.parseToEnd(currentKey);
+      const reversedNegations = [...accumulatedNegations[i]].reverse();
+      console.log('start');
+      console.dir(baseMediaQuery, { depth: null });
+      console.dir(reversedNegations, { depth: null });
path: packages/style-value-parser/src/at-queries-from-tokens/media-query-transform.js
user: login: nmn
body: remove
created_at: 2025-04-11T03:07:03Z
author_association: COLLABORATOR
diff_hunk: @@ -0,0 +1,111 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict
+ */
+
+import { MediaQuery } from './media-query.js';
+
+export function lastMediaQueryWinsTransform(styles: Object): Object {
+  return dfsProcessQueries(styles, 0);
+}
+
+function combineMediaQueryWithNegations(
+  current: MediaQuery,
+  negations: MediaQuery[],
+): MediaQuery {
+  if (negations.length === 0) {
+    return current;
+  }
+
+  let combinedAst;
+
+  if (current.queries.type === 'or') {
+    combinedAst = {
+      type: 'or',
+      rules: current.queries.rules.map((rule) => ({
+        type: 'and',
+        rules: [
+          rule,
+          ...negations.map((mq) => ({ type: 'not', rule: mq.queries })),
+        ],
+      })),
+    };
+  } else {
+    combinedAst = {
+      type: 'and',
+      rules: [
+        current.queries,
+        ...negations.map((mq) => ({ type: 'not', rule: mq.queries })),
+      ],
+    };
+  }
+
+  return new MediaQuery(combinedAst);
+}
+
+function dfsProcessQueries(
+  obj: { [key: string]: any },
+  depth: number,
+): {
+  [key: string]: any,
+} {
+  const result: { [key: string]: any } = {};
+
+  Object.entries(obj).forEach(([key, value]) => {
+    if (typeof value === 'object' && value !== null) {
+      result[key] = dfsProcessQueries(value, depth + 1);
+    } else {
+      result[key] = value;
+    }
+  });
+
+  if (
+    depth >= 2 &&
+    Object.keys(result).some((key) => key.startsWith('@media '))
+  ) {
+    const mediaKeys = Object.keys(result).filter((key) =>
+      key.startsWith('@media '),
+    );
+
+    const negations = [];
+    const accumulatedNegations = [];
+
+    for (let i = mediaKeys.length - 1; i > 0; i--) {
+      // Skip last iteration
+      const mediaQuery = MediaQuery.parser.parseToEnd(mediaKeys[i]);
+      negations.push(mediaQuery);
+      accumulatedNegations.push([...negations]); // Clone array before pushing
+    }
+    accumulatedNegations.reverse();
+    accumulatedNegations.push([]);
+    console.log('accumulatedNegations', accumulatedNegations);
+
+    for (let i = 0; i < mediaKeys.length; i++) {
+      const currentKey = mediaKeys[i];
+      const currentValue = result[currentKey];
+
+      const baseMediaQuery = MediaQuery.parser.parseToEnd(currentKey);
+      const reversedNegations = [...accumulatedNegations[i]].reverse();
+      console.log('start');
+      console.dir(baseMediaQuery, { depth: null });
+      console.dir(reversedNegations, { depth: null });
+
+      const combinedQuery = combineMediaQueryWithNegations(
+        baseMediaQuery,
+        reversedNegations,
+      );
+      console.dir(combinedQuery, { depth: null });
+
+      const newMediaKey = combinedQuery.toString();
+
+      delete result[currentKey];
path: packages/style-value-parser/src/at-queries-from-tokens/media-query-transform.js
user: login: nmn
body: Refactor this function a bit to improve readability and to not need to rely on key deletion.
created_at: 2025-04-11T03:08:01Z
author_association: COLLABORATOR
diff_hunk: @@ -0,0 +1,339 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ */
+
+import { lastMediaQueryWinsTransform } from '../media-query-transform.js';
+
+const stylex = {
+  create: (styles) => styles,
+};
+
+describe('Media Query Transformer', () => {
+  test('basic usage: multiple widths', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            '1 / 4',
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: nested query', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': {
+            '@media (max-width: 1024px)': '1 / 3',
+            '@media (max-width: 768px)': '1 / -1',
+          },
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            {
+              '@media (max-width: 1024px) and (not (max-width: 768px))':
+                '1 / 3',
+              '@media (max-width: 768px)': '1 / -1',
+            },
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: nested query', () => {
+    const originalStyles = {
+      table: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': {
+            '@media (max-width: 1024px)': '1 / 3',
+            '@media (max-width: 768px)': '1 / -1',
+          },
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        padding: '10px',
+      },
+    };
+
+    const expectedStyles = {
+      table: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            {
+              '@media (max-width: 1024px) and (not (max-width: 768px))':
+                '1 / 3',
+              '@media (max-width: 768px)': '1 / -1',
+            },
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        padding: '10px',
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: complex object', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        grid: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+        },
+        gridRow: {
+          default: '1 / 2',
+          padding: '10px',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px))':
+            '1 / 4',
+          '@media (max-width: 1024px) and (not (max-width: 768px))': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+        },
+        grid: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+        },
+        gridRow: {
+          default: '1 / 2',
+          padding: '10px',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('basic usage: lots and lots of widths', () => {
+    const originalStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px)': '1 / 4',
+          '@media (max-width: 1024px)': '1 / 3',
+          '@media (max-width: 768px)': '1 / -1',
+          '@media (max-width: 458px)': '1 / -1',
+        },
+      },
+    };
+
+    const expectedStyles = {
+      foo: {
+        gridColumn: {
+          default: '1 / 2',
+          '@media (max-width: 1440px) and (not (max-width: 1024px)) and (not (max-width: 768px)) and (not (max-width: 458px))':
+            '1 / 4',
+          '@media (max-width: 1024px) and (not (max-width: 768px)) and (not (max-width: 458px))':
+            '1 / 3',
+          '@media (max-width: 768px) and (not (max-width: 458px))': '1 / -1',
+          '@media (max-width: 458px)': '1 / -1',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('single word condition', () => {
+    const originalStyles = stylex.create({
+      colorMode: {
+        mode: {
+          default: 'normal',
+          '@media (color)': 'colorful',
+          '@media (monochrome)': 'grayscale',
+        },
+      },
+    });
+
+    const expectedStyles = {
+      colorMode: {
+        mode: {
+          default: 'normal',
+          '@media (color) and (not (monochrome))': 'colorful',
+          '@media (monochrome)': 'grayscale',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test('handles comma-separated (or) media queries', () => {
+    const originalStyles = stylex.create({
+      container: {
+        width: {
+          default: '100%',
+          '@media screen, (max-width: 800px)': '80%',
+          '@media (max-width: 500px)': '60%',
+        },
+      },
+    });
+
+    const expectedStyles = {
+      container: {
+        width: {
+          default: '100%',
+          '@media screen and (not (max-width: 500px)), (max-width: 800px) and (not (max-width: 500px))':
+            '80%',
+          '@media (max-width: 500px)': '60%',
+        },
+      },
+    };
+
+    const result = lastMediaQueryWinsTransform(originalStyles);
+    expect(JSON.stringify(result)).toBe(JSON.stringify(expectedStyles));
+  });
+
+  test.skip('handles and media queries', () => {
path: packages/style-value-parser/src/at-queries-from-tokens/__tests__/media-query-transform-test.js
user: login: mellyeliu
body: yeppp see edge cases in https://github.com/facebook/stylex/pull/943
created_at: 2025-04-11T03:44:32Z
author_association: MEMBER
diff_hunk: @@ -0,0 +1,111 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict
+ */
+
+import { MediaQuery } from './media-query.js';
+
+export function lastMediaQueryWinsTransform(styles: Object): Object {
+  return dfsProcessQueries(styles, 0);
+}
+
+function combineMediaQueryWithNegations(
+  current: MediaQuery,
+  negations: MediaQuery[],
+): MediaQuery {
+  if (negations.length === 0) {
+    return current;
+  }
+
+  let combinedAst;
+
+  if (current.queries.type === 'or') {
+    combinedAst = {
+      type: 'or',
+      rules: current.queries.rules.map((rule) => ({
+        type: 'and',
+        rules: [
+          rule,
+          ...negations.map((mq) => ({ type: 'not', rule: mq.queries })),
+        ],
+      })),
+    };
+  } else {
+    combinedAst = {
+      type: 'and',
+      rules: [
+        current.queries,
+        ...negations.map((mq) => ({ type: 'not', rule: mq.queries })),
+      ],
+    };
+  }
+
+  return new MediaQuery(combinedAst);
+}
+
+function dfsProcessQueries(
+  obj: { [key: string]: any },
+  depth: number,
+): {
+  [key: string]: any,
+} {
+  const result: { [key: string]: any } = {};
+
+  Object.entries(obj).forEach(([key, value]) => {
+    if (typeof value === 'object' && value !== null) {
+      result[key] = dfsProcessQueries(value, depth + 1);
+    } else {
+      result[key] = value;
+    }
+  });
+
+  if (
+    depth >= 2 &&
+    Object.keys(result).some((key) => key.startsWith('@media '))
+  ) {
+    const mediaKeys = Object.keys(result).filter((key) =>
+      key.startsWith('@media '),
+    );
+
+    const negations = [];
+    const accumulatedNegations = [];
+
+    for (let i = mediaKeys.length - 1; i > 0; i--) {
+      // Skip last iteration
+      const mediaQuery = MediaQuery.parser.parseToEnd(mediaKeys[i]);
+      negations.push(mediaQuery);
+      accumulatedNegations.push([...negations]); // Clone array before pushing
+    }
+    accumulatedNegations.reverse();
+    accumulatedNegations.push([]);
+    console.log('accumulatedNegations', accumulatedNegations);
+
+    for (let i = 0; i < mediaKeys.length; i++) {
+      const currentKey = mediaKeys[i];
+      const currentValue = result[currentKey];
+
+      const baseMediaQuery = MediaQuery.parser.parseToEnd(currentKey);
+      const reversedNegations = [...accumulatedNegations[i]].reverse();
+      console.log('start');
+      console.dir(baseMediaQuery, { depth: null });
+      console.dir(reversedNegations, { depth: null });
+
+      const combinedQuery = combineMediaQueryWithNegations(
+        baseMediaQuery,
+        reversedNegations,
+      );
+      console.dir(combinedQuery, { depth: null });
+
+      const newMediaKey = combinedQuery.toString();
+
+      delete result[currentKey];
path: packages/style-value-parser/src/at-queries-from-tokens/media-query-transform.js
user: login: mellyeliu
body: i'll revisit this in the next PR when integrating with rules
created_at: 2025-04-11T03:59:55Z
author_association: MEMBER

PR comments:
user: login: github-actions[bot]
created_at: 2025-02-22T12:28:21Z
body: <!-- workflow-benchmarks-size-data -->
### workflow: benchmarks/size
Comparison of minified (terser) and compressed (brotli) size results, measured in bytes. Smaller is better.

> benchmarks@0.11.1 compare
> node ./compare.js /tmp/tmp.YE2LaIJ6Uz /tmp/tmp.cZHeGXE0mI

| **Results** | **Base** | **Patch** | **Ratio** |  |
| :--- | ---: | ---: | ---: | ---: |
|  |  |  |  |
| **stylex/lib/stylex.js** |  |  |  |  |
| &middot; compressed | 985 | 985 | 1.00 |  |
| &middot; minified | 3,154 | 3,154 | 1.00 |  |
|  |  |  |  |
| **stylex/lib/StyleXSheet.js** |  |  |  |  |
| &middot; compressed | 1,266 | 1,266 | 1.00 |  |
| &middot; minified | 3,776 | 3,776 | 1.00 |  |
|  |  |  |  |
| **benchmarks/size/.build/bundle.js** |  |  |  |  |
| &middot; compressed | 537,611 | 537,611 | 1.00 |  |
| &middot; minified | 7,435,904 | 7,435,904 | 1.00 |  |
|  |  |  |  |
| **benchmarks/size/.build/stylex.css** |  |  |  |  |
| &middot; compressed | 100,609 | 100,609 | 1.00 |  |
| &middot; minified | 755,721 | 755,721 | 1.00 |  |
author_association: NONE
user: login: mellyeliu
created_at: 2025-03-17T17:28:47Z
body: updated implementation to ensure object key ordering is preserved
author_association: MEMBER
user: login: github-actions[bot]
created_at: 2025-04-10T05:35:22Z
body: <!-- workflow-benchmarks-perf-data -->
### workflow: benchmarks/perf
Comparison of performance test results, measured in operations per second. Larger is better.

> benchmarks@0.11.1 compare
> node ./compare.js /tmp/tmp.mOaO0JYlzi /tmp/tmp.c7c8WZQj4U

| **Results** | **Base** | **Patch** | **Ratio** |  |
| :--- | ---: | ---: | ---: | ---: |
|  |  |  |  |
| **babel-plugin: stylex.create** |  |  |  |  |
| &middot; basic create | 537 | 540 | 1.01 | + |
| &middot; complex create | 198 | 197 | 0.99 | - |
|  |  |  |  |
| **babel-plugin: stylex.createTheme** |  |  |  |  |
| &middot; basic themes | 464 | 462 | 1.00 | - |
| &middot; complex themes | 43 | 41 | 0.95 | - |
author_association: NONE
user: login: mellyeliu
created_at: 2025-04-10T05:36:21Z
body: ignore legacy media query syntax by checking dfs depth (>2) 
ping @nmn pls review 👻
author_association: MEMBER