From 898992c86b62ba2054c7167c640b579785d93871 Mon Sep 17 00:00:00 2001 From: Lee Date: Sat, 3 Oct 2026 12:38:41 +0000 Subject: [PATCH 1/5] feat: add opt-in logical keyframes and animation references --- .github/workflows/ci.yml | 1 - CHANGELOG.md | 2 + README.md | 29 ++- .../docs/getting-started/introduction.mdx | 2 +- .../src/content/docs/guides/configuration.mdx | 12 ++ docs/src/content/docs/references/api.mdx | 8 +- examples/README.md | 4 + examples/logical-animations/README.md | 11 ++ examples/logical-animations/index.html | 23 +++ examples/logical-animations/input.css | 11 ++ examples/logical-animations/process.ts | 13 ++ package.json | 2 +- scripts/test-browser-animations.mjs | 47 +++++ scripts/test-package.mjs | 5 +- src/animations.ts | 180 ++++++++++++++++++ src/cascade.ts | 2 + src/index.ts | 21 +- test/animations.test.ts | 105 ++++++++++ 18 files changed, 463 insertions(+), 15 deletions(-) create mode 100644 examples/logical-animations/README.md create mode 100644 examples/logical-animations/index.html create mode 100644 examples/logical-animations/input.css create mode 100644 examples/logical-animations/process.ts create mode 100644 scripts/test-browser-animations.mjs create mode 100644 src/animations.ts create mode 100644 test/animations.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 79c0b19..b887482 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [main] pull_request: - branches: [main] jobs: build: diff --git a/CHANGELOG.md b/CHANGELOG.md index 511ccc7..9eecf74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Add opt-in `animations: true` support for direction-specific logical keyframes and static `animation`/`animation-name` references, including prefixed definitions, name collisions and conditional same-name definitions. Preserve original definitions and warn for dynamic references. + - Transform logical names in `transition-property`, keeping static duration, delay, timing-function and behavior lists aligned when a property expands into several physical names. Dynamic or inherited timing lists are retained with a warning when expansion cannot be safely aligned. ## [0.7.0] - 2026-10-03 diff --git a/README.md b/README.md index 8513d8a..0d5a9a8 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,8 @@ Use this plugin when your internationalized application needs both directions in | Your target browsers support the logical properties you use | Native CSS; no transformation is needed | | Compile logical properties for one configured direction or writing mode | [postcss-logical](https://github.com/csstools/postcss-plugins/tree/main/plugins/postcss-logical), also available through [postcss-preset-env](https://github.com/csstools/postcss-plugins/tree/main/plugin-packs/postcss-preset-env) | | Mirror existing physical LTR styles into RTL styles | [RTLCSS](https://github.com/MohammadYounes/rtlcss) or [postcss-rtlcss](https://github.com/elchininet/postcss-rtlcss) | -| Compile logical properties into one stylesheet with horizontal LTR/RTL scopes, including existing direction selectors | **postcss-logical-polyfill** | -| Need logical-property transformations for vertical writing modes or keyframes | Evaluate [postcss-logical-properties-polyfill](https://github.com/erickskrauch/postcss-logical-properties-polyfill), whose documentation lists these features | +| Compile logical properties into one stylesheet with horizontal LTR/RTL scopes, including existing direction selectors and opt-in logical animations | **postcss-logical-polyfill** | +| Need logical-property transformations for vertical writing modes | Evaluate [postcss-logical-properties-polyfill](https://github.com/erickskrauch/postcss-logical-properties-polyfill), whose documentation lists these features | Other tools also generate combined LTR/RTL styles. This plugin focuses on logical-property input, existing direction scopes, common declarations and additional logical values. Check the [supported properties](https://github.com/oe/postcss-logical-polyfill/blob/main/docs/src/content/docs/references/supported-properties.mdx) and limitations below against your application. @@ -150,10 +150,33 @@ These classes must match ancestors of the styled elements. They scope the genera See the [configuration guide](https://github.com/oe/postcss-logical-polyfill/blob/main/docs/src/content/docs/guides/configuration.mdx) for selector lists and integration options. +## Logical keyframes (opt-in) + +```js +logicalPolyfill({ animations: true }); +``` + +The plugin keeps original keyframes and creates LTR/RTL physical-property copies for referenced logical animations. Both `animation-name` and `animation` shorthand references are rewritten. Ordinary animations are unchanged. Generated names avoid existing definitions and static references; same-name definitions retain their original media/supports/layer contexts. + +```css +/* Input */ +@keyframes slide { + from { margin-inline-start: 0; } + to { margin-inline-start: 100px; } +} +.card { animation: slide 1s linear; } +``` + +This generates direction-specific `lp-slide-ltr` and `lp-slide-rtl` keyframes and matching animation rules. Generated names may gain a numeric suffix when needed to avoid collisions. + +Try the [runnable animation example](https://github.com/oe/postcss-logical-polyfill/tree/main/examples/logical-animations). + +Run `postcss-import` before this plugin when definitions and references are in separate files. Runtime names inside `var()` or `env()` cannot be resolved reliably: they remain unchanged with a PostCSS warning, and original definitions remain available for browsers with native logical-property support. They do not gain a physical-property animation fallback. Expand CSS nesting before the plugin. + ## Compatibility and limitations - Transformations assume horizontal writing modes. Vertical writing modes are not inferred. -- Keyframes and certain other at-rules are left untouched. Logical property names in `transition` and `transition-property` are transformed; animation names and keyframe contents are not rewritten. +- Keyframes are left untouched by default. Enable `animations: true` to transform referenced logical keyframes and static animation names. Logical property names in `transition` and `transition-property` are transformed independently of this option. - Expand CSS nesting before this plugin, using a tool such as `postcss-nested` or `postcss-nesting`. Unexpanded nested rules are left intact with a PostCSS warning. - Direction prefixes add selector specificity. Overrides in separate rules should use matching direction scopes. For subtrees with conflicting direction ancestors, write explicit direction-scoped selectors so the plugin can use the rightmost context. - Repeated physical properties within an optimized rule are resolved by `!important` priority, then source order. Overlapping common shorthands are retained in direction rules where needed to preserve their ordering relative to directional longhands. diff --git a/docs/src/content/docs/getting-started/introduction.mdx b/docs/src/content/docs/getting-started/introduction.mdx index 23347b9..73ebe38 100644 --- a/docs/src/content/docs/getting-started/introduction.mdx +++ b/docs/src/content/docs/getting-started/introduction.mdx @@ -21,7 +21,7 @@ Other tools also generate combined LTR/RTL styles. This plugin focuses on logica ## Compatibility -The plugin assumes horizontal writing modes. It transforms logical property names in `transition`, but leaves keyframe contents and animation names untouched. Expand CSS nesting before running the plugin. +The plugin assumes horizontal writing modes. It transforms logical property names in `transition` and `transition-property`. Keyframes and animation references are left untouched by default; enable `animations: true` to compile static references to logical keyframes. Expand CSS nesting before running the plugin. Generated direction prefixes add specificity. Use matching scopes for overrides in separate rules and explicit direction-scoped selectors for subtrees with conflicting direction ancestors. diff --git a/docs/src/content/docs/guides/configuration.mdx b/docs/src/content/docs/guides/configuration.mdx index d9b587a..7a9530b 100644 --- a/docs/src/content/docs/guides/configuration.mdx +++ b/docs/src/content/docs/guides/configuration.mdx @@ -377,3 +377,15 @@ console.log('Transformed CSS:', result.css); ### From Other Logical Property Tools Like `postcss-logical`, this plugin converts logical properties to physical properties. It generates both horizontal LTR and RTL scopes in one stylesheet, rather than mapping all declarations for one configured direction. Review the generated selectors, specificity and supported properties when migrating. + +## Logical keyframes + +Enable animation compilation explicitly: + +```js +logicalPolyfill({ animations: true }); +``` + +The default is `false`. Referenced logical keyframes receive separate physical-property copies for LTR and RTL, with collision-free generated names. Static `animation-name` and `animation` shorthand references use the matching direction copy. Original definitions remain available. Duplicate names in conditional rules retain those conditions. + +Definitions and references must be available in the same PostCSS root; run `postcss-import` first for multi-file animations. Expand CSS nesting first. Dynamic names in `var()`/`env()` remain unchanged with a warning and do not receive an old-browser fallback. diff --git a/docs/src/content/docs/references/api.mdx b/docs/src/content/docs/references/api.mdx index 9206a13..9e03d09 100644 --- a/docs/src/content/docs/references/api.mdx +++ b/docs/src/content/docs/references/api.mdx @@ -446,9 +446,9 @@ The plugin includes TypeScript definitions: ```typescript import postcss from 'postcss' -import logicalPolyfill, { Options } from 'postcss-logical-polyfill' +import logicalPolyfill, { LogicalPolyfillOptions } from 'postcss-logical-polyfill' -const options: Options = { +const options: LogicalPolyfillOptions = { preserve: false, dir: 'ltr', supports: true, @@ -482,3 +482,7 @@ For large projects, consider: 1. Using `preserve: false` in production 2. Enabling `supports: true` for progressive enhancement 3. Processing only relevant CSS files + +## Animation compilation + +`animations?: boolean` enables logical keyframe and static animation-reference compilation. Its default is `false`. Existing direction selectors and `outputOrder` also apply to the generated animation rules. See the [configuration guide](../../guides/configuration/#logical-keyframes) for limitations. diff --git a/examples/README.md b/examples/README.md index 4a36e6e..728fcfe 100644 --- a/examples/README.md +++ b/examples/README.md @@ -49,3 +49,7 @@ Or run individual examples by navigating to their directories and following the - Nested selectors with logical properties - Complex scenarios with both RTL and LTR rules - Difference between scoped and unscoped logical properties + +## Logical animations + +[Logical keyframes](./logical-animations/) demonstrates opt-in animation compilation and a browser direction toggle. diff --git a/examples/logical-animations/README.md b/examples/logical-animations/README.md new file mode 100644 index 0000000..089e41e --- /dev/null +++ b/examples/logical-animations/README.md @@ -0,0 +1,11 @@ +# Logical keyframes + +After installing repository dependencies, run from this directory: + +```sh +pnpm exec tsx process.ts +``` + +Open `index.html` in a browser. The generated `output.css` contains separate LTR and RTL keyframes. Switching the root `dir` attribute changes the active animation without rebuilding CSS. + +Animation compilation requires `animations: true`; the default remains disabled. This example keeps definitions and static references in one file. For separate files, inline them with `postcss-import` first. Runtime references through `var()` remain native-only and produce a warning. diff --git a/examples/logical-animations/index.html b/examples/logical-animations/index.html new file mode 100644 index 0000000..0f98b52 --- /dev/null +++ b/examples/logical-animations/index.html @@ -0,0 +1,23 @@ + + + + + + Logical keyframes: LTR and RTL + + + +

One stylesheet, two animation directions

+ +

The box moves away from the start edge in both directions.

+
+ + + diff --git a/examples/logical-animations/input.css b/examples/logical-animations/input.css new file mode 100644 index 0000000..559ea0b --- /dev/null +++ b/examples/logical-animations/input.css @@ -0,0 +1,11 @@ +.box { + inline-size: 80px; + block-size: 80px; + background: #38bdf8; + animation: slide 2s linear infinite alternate; +} + +@keyframes slide { + from { margin-inline-start: 0; } + to { margin-inline-start: 160px; } +} diff --git a/examples/logical-animations/process.ts b/examples/logical-animations/process.ts new file mode 100644 index 0000000..46fe9d8 --- /dev/null +++ b/examples/logical-animations/process.ts @@ -0,0 +1,13 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import postcss from 'postcss'; +import plugin from '../../src'; + +(async () => { + const input = path.join(__dirname, 'input.css'); + const output = path.join(__dirname, 'output.css'); + const result = await postcss([plugin({ animations: true })]).process(fs.readFileSync(input, 'utf8'), { from: input, to: output }); + fs.writeFileSync(output, result.css); + for (const warning of result.warnings()) console.warn(warning.toString()); + console.log('Generated output.css. Open index.html and switch direction.'); +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/package.json b/package.json index ebeafcd..433de70 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "test": "vitest", "test:ci": "vitest run", "test:package": "node scripts/test-package.mjs", - "test:browser": "node scripts/test-browser.mjs && node scripts/test-browser-transitions.mjs", + "test:browser": "node scripts/test-browser.mjs && node scripts/test-browser-transitions.mjs && node scripts/test-browser-animations.mjs", "test:coverage": "vitest run --coverage", "test:coverage:watch": "vitest --coverage", "test:coverage:ui": "vitest --coverage --ui", diff --git a/scripts/test-browser-animations.mjs b/scripts/test-browser-animations.mjs new file mode 100644 index 0000000..778c40c --- /dev/null +++ b/scripts/test-browser-animations.mjs @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import { chromium } from 'playwright-core'; +const require = createRequire(import.meta.url); +const postcss = require('postcss'); +const plugin = require('../dist/index.js'); +const frames = '@keyframes slide{from{margin-inline-start:0}to{margin-inline-start:100px}}'; +const cases = [ + frames + '.x{animation:slide 1s linear both}', + frames + '.x{animation-name:slide;animation-duration:1s;animation-timing-function:linear;animation-fill-mode:both}', + frames + '@keyframes fade{from{opacity:0}to{opacity:1}}.x{animation:slide 1s linear both,fade 2s linear both}', + frames + '@media(min-width:1px){@keyframes slide{from{margin-left:0}to{margin-left:20px}}}.x{animation:slide 1s linear both}', + frames.replace(/slide/g, 'linear') + '.x{animation:1s linear "linear" both}', + frames + '@keyframes lp-slide-ltr{from{opacity:0}to{opacity:1}}.x{animation:slide 1s linear both}', + frames + '.x{animation-name:slide!important;animation:none;animation-duration:1s;animation-timing-function:linear}', + frames.replace('@keyframes', '@-webkit-keyframes') + '.x{-webkit-animation:slide 1s linear both}', + frames + '.x{--motion:slide 1s linear both;animation:var(--motion)}' +]; +const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_BIN || '/usr/bin/chromium', args: ['--no-sandbox', '--disable-dev-shm-usage'] }); +try { + const page = await browser.newPage(); + async function sample(css, direction) { + return page.evaluate(async ({ css, direction }) => { + document.body.innerHTML = ''; + const host = document.createElement('div'); + document.body.append(host); + const shadow = host.attachShadow({ mode: 'open' }); + shadow.innerHTML = `
x
`; + const el = shadow.querySelector('.x'); + getComputedStyle(el).marginLeft; + const animations = el.getAnimations(); + for (const animation of animations) { animation.pause(); animation.currentTime = 500; } + await new Promise(requestAnimationFrame); + const styles = getComputedStyle(el); + return { animations: animations.length, left: styles.marginLeft, right: styles.marginRight, opacity: styles.opacity }; + }, { css, direction }); + } + for (const css of cases) { + const compiled = (await postcss([plugin({ animations: true })]).process(css, { from: undefined })).css; + for (const direction of ['ltr', 'rtl']) { + const expected = await sample(css, direction); + assert.ok(expected.animations > 0, 'Native fixture must actually animate'); + assert.deepEqual(await sample(compiled, direction), expected, `${direction}: ${css}`); + } + } + console.log(`Browser animations: ${cases.length * 2} native/compiled intermediate-frame comparisons passed.`); +} finally { await browser.close(); } diff --git a/scripts/test-package.mjs b/scripts/test-package.mjs index 14ea784..9ceebba 100644 --- a/scripts/test-package.mjs +++ b/scripts/test-package.mjs @@ -29,10 +29,13 @@ try { const values = []; result.root.walkDecls(decl => values.push([decl.value, Boolean(decl.important)])); assert.deepEqual(values, [['10px', true], ['10px', true]]); + const animated = await postcss([creator({ animations: true })]).process('@keyframes slide{from{margin-inline-start:0}to{margin-inline-start:10px}}.x{animation:slide 1s}', { from: undefined }); + assert.match(animated.css, /animation:lp-slide-ltr 1s/); + assert.match(animated.css, /animation:lp-slide-rtl 1s/); } const types = join(dirname(entry), '..', manifest.types); assert.match(readFileSync(types, 'utf8'), /LogicalPolyfillOptions/); - writeFileSync(join(directory, 'consumer.ts'), `import plugin, { LogicalPolyfillOptions } from 'postcss-logical-polyfill';\nimport postcss from 'postcss';\nconst options: LogicalPolyfillOptions = { outputOrder: 'rtl-first' };\npostcss([plugin(options)]);\n`); + writeFileSync(join(directory, 'consumer.ts'), `import plugin, { LogicalPolyfillOptions } from 'postcss-logical-polyfill';\nimport postcss from 'postcss';\nconst options: LogicalPolyfillOptions = { outputOrder: 'rtl-first', animations: true };\npostcss([plugin(options)]);\n`); const tsc = createRequire(join(root, 'package.json')).resolve('typescript/bin/tsc'); execFileSync(process.execPath, [tsc, '--noEmit', '--strict', '--skipLibCheck', '--module', 'node16', '--moduleResolution', 'node16', '--target', 'es2020', join(directory, 'consumer.ts')], { cwd: directory, stdio: 'pipe' }); console.log('Packed package: CommonJS, ES module and TypeScript consumers passed.'); diff --git a/src/animations.ts b/src/animations.ts new file mode 100644 index 0000000..7a0a918 --- /dev/null +++ b/src/animations.ts @@ -0,0 +1,180 @@ +import { AnyNode, AtRule, Declaration, Result, Root, Rule } from 'postcss'; +import valueParser, { Node } from 'postcss-value-parser'; +import { applyLogicalTransformation, hasLogicalProperties } from './logical-properties'; + +type Direction = 'ltr' | 'rtl'; +export type AnimationContext = Map>; +const globals = /^(initial|inherit|unset|revert|revert-layer)$/i; +const identifier = /^(?:--|-?(?:[_a-z]|[^\x00-\x7f]|\\[^\n\r\f]))(?:[_a-z0-9-]|[^\x00-\x7f]|\\[^\n\r\f])*$/i; +const keyframes = /^(?:-[a-z]+-)?keyframes$/i; + +// value-parser does not consume whitespace terminating a hexadecimal CSS escape. +function normalizedEscapes(value: string): string { + return value.replace(/\\([\da-f]{1,6})(?:\r\n|[ \n\r\t\f])?/gi, (_, hex: string) => `\\${hex.padStart(6, '0')}`); +} +function decoded(value: string): string { + return value.replace(/\\(?:([\da-f]{1,6})(?:\r\n|[ \n\r\t\f])?|(\r\n|[\n\r\f])|([\s\S]))/gi, (_, hex: string, newline: string, char: string) => { + if (!hex) return newline ? '' : char; + const point = parseInt(hex, 16); + return String.fromCodePoint(!point || point > 0x10ffff || (point >= 0xd800 && point <= 0xdfff) ? 0xfffd : point); + }); +} +function definitionName(atRule: AtRule): string | undefined { + const nodes = valueParser(normalizedEscapes(atRule.params)).nodes.filter(node => !['space', 'comment'].includes(node.type)); + if (nodes.length !== 1 || !['word', 'string'].includes(nodes[0].type)) return; + if (nodes[0].type === 'word' && (!identifier.test(nodes[0].value) || globals.test(decoded(nodes[0].value)) || decoded(nodes[0].value).toLowerCase() === 'none')) return; + return decoded(nodes[0].value); +} + +function referenceNodes(decl: Declaration): { parsed: ReturnType; names: Node[]; dynamic: boolean } { + const parsed = valueParser(normalizedEscapes(decl.value)); + const names: Node[] = []; + let dynamic = false; + parsed.walk(node => { if (node.type === 'function' && /^(var|env)$/i.test(node.value)) dynamic = true; }); + if (dynamic) return { parsed, names, dynamic }; + const groups: Node[][] = [[]]; + for (const node of parsed.nodes) { + if (node.type === 'div' && node.value === ',') groups.push([]); + else if (!['space', 'comment'].includes(node.type)) groups[groups.length - 1].push(node); + } + for (const nodes of groups) { + if (decl.prop.toLowerCase().endsWith('animation-name')) { + if (nodes.length !== 1 || !['string', 'word'].includes(nodes[0].type)) continue; + const node = nodes[0]; + if (node.type === 'string' || (identifier.test(node.value) && !globals.test(decoded(node.value)) && decoded(node.value).toLowerCase() !== 'none')) names.push(node); + continue; + } + const occupied = new Set(); + let name: Node | undefined; + let valid = true; + for (const node of nodes) { + const token = decoded(node.value).toLowerCase(); + let slot: string | undefined; + if (node.type === 'function') { + if (/^(steps|cubic-bezier|linear)$/i.test(token) && !occupied.has('easing')) slot = 'easing'; + else { valid = false; break; } + } else if (node.type === 'word') { + if (globals.test(token)) { valid = false; break; } + if (/^[-+]?(?:\d*\.)?\d+(ms|s)$/.test(token)) { + slot = occupied.has('duration') ? 'delay' : 'duration'; + if (occupied.has(slot) || (slot === 'duration' && token.startsWith('-'))) { valid = false; break; } + } else if (/^(ease|linear|ease-in|ease-out|ease-in-out|step-start|step-end)$/.test(token) && !occupied.has('easing')) slot = 'easing'; + else if ((token === 'infinite' || /^(?:\d*\.)?\d+$/.test(token)) && !occupied.has('iterations')) slot = 'iterations'; + else if (/^(normal|reverse|alternate|alternate-reverse)$/.test(token) && !occupied.has('direction')) slot = 'direction'; + else if (/^(none|forwards|backwards|both)$/.test(token) && !occupied.has('fill')) slot = 'fill'; + else if (/^(running|paused)$/.test(token) && !occupied.has('play')) slot = 'play'; + else if (token === 'none') { valid = false; break; } + } else if (node.type !== 'string') { valid = false; break; } + if (slot) occupied.add(slot); + else if (node.type === 'word' && !identifier.test(node.value)) { valid = false; break; } + else if (!name) name = node; + else { valid = false; break; } + } + if (valid && name) names.push(name); + } + return { parsed, names, dynamic }; +} +function animationDeclaration(decl: Declaration): boolean { + return /^(?:-[a-z]+-)?animation(?:-name)?$/i.test(decl.prop); +} +function flatRule(rule: Rule): boolean { + if (rule.nodes.some(node => node.type === 'rule' || node.type === 'atrule')) return false; + let supported = true; + for (let node: AnyNode | undefined = rule.parent as AnyNode; node; node = node.parent as AnyNode | undefined) { + if (node.type === 'rule' || (node.type === 'atrule' && (keyframes.test(node.name) || /^(page|font-face|counter-style)$/i.test(node.name)))) supported = false; + } + return supported; +} + +/** Keep original definitions for native/dynamic references; clone every same-name definition in its original context. */ +export async function prepareAnimations(root: Root, result: Result, order: 'ltr-first' | 'rtl-first'): Promise { + const definitions = new Map(); + const logical = new Set(); + root.walkAtRules(atRule => { + if (!keyframes.test(atRule.name)) return; + let nested = false; + for (let node: AnyNode | undefined = atRule.parent as AnyNode; node; node = node.parent as AnyNode | undefined) { if (node.type === 'rule') nested = true; } + if (nested) return; + const name = definitionName(atRule); + if (name === undefined) return; + definitions.set(name, [...(definitions.get(name) ?? []), atRule]); + if (atRule.nodes?.some(node => node.type === 'rule' && hasLogicalProperties(node))) logical.add(name); + }); + const needed = new Set(); + const used = new Set(definitions.keys()); + root.walkRules(rule => { + if (!flatRule(rule)) { + if (rule.nodes.some(node => node.type === 'rule' || node.type === 'atrule') && rule.nodes.some(node => node.type === 'decl' && animationDeclaration(node) && referenceNodes(node).names.some(name => logical.has(decoded(name.value))))) { + result.warn('Expand CSS nesting before compiling logical animations; this nested rule was left unchanged.', { node: rule }); + } + return; + } + rule.walkDecls(decl => { + if (!animationDeclaration(decl)) return; + const refs = referenceNodes(decl); + if (refs.dynamic && logical.size) result.warn('Cannot resolve dynamic animation names; the animation declaration and original keyframes were preserved. Inline imports before this plugin for cross-file references.', { node: decl }); + for (const node of refs.names) { + const name = decoded(node.value); + used.add(name); + if (logical.has(name)) needed.add(name); + } + }); + }); + const context: AnimationContext = new Map(); + const directions: Direction[] = order === 'ltr-first' ? ['ltr', 'rtl'] : ['rtl', 'ltr']; + for (const name of needed) { + const generated = {} as Record; + for (const direction of ['ltr', 'rtl'] as const) { + const base = `lp-${name.replace(/[^\w-]/g, '-').slice(0, 48) || 'animation'}-${direction}`; + let unique = base; + for (let suffix = 2; used.has(unique); suffix++) unique = `${base}-${suffix}`; + used.add(unique); + generated[direction] = unique; + } + const pending: Array<{ original: AtRule; clones: AtRule[] }> = []; + let failed = false; + for (const original of definitions.get(name)!) { + const clones: AtRule[] = []; + for (const direction of directions) { + const clone = original.clone({ params: generated[direction] }); + for (const frame of clone.nodes ?? []) { + if (frame.type !== 'rule') continue; + if (frame.nodes.some(node => node.type === 'rule' || node.type === 'atrule')) { failed = true; break; } + if (!hasLogicalProperties(frame)) continue; + const transformed = await applyLogicalTransformation(frame, direction, result); + if (!transformed) { failed = true; break; } + frame.replaceWith(transformed); + } + clones.push(clone); + } + pending.push({ original, clones }); + } + if (failed) { result.warn(`Could not transform keyframes for ${name}; definitions and references were left unchanged.`, { node: definitions.get(name)![0] }); continue; } + for (const { original, clones } of pending) { + let previous: AtRule = original; + for (const clone of clones) { previous.after(clone); previous = clone; } + } + context.set(name, generated); + } + return context; +} + +export function hasAnimationReferences(rule: Rule, context: AnimationContext): boolean { + if (!context.size) return false; + return rule.nodes.some(node => node.type === 'decl' && animationDeclaration(node) && referenceNodes(node).names.some(name => context.has(decoded(name.value)))); +} +export function transformAnimationReferences(rule: Rule, context: AnimationContext, direction: Direction): void { + if (!context.size) return; + rule.walkDecls(decl => { + if (!animationDeclaration(decl)) return; + const refs = referenceNodes(decl); + let changed = false; + for (const node of refs.names) { + const mapped = context.get(decoded(node.value)); + if (!mapped) continue; + node.value = mapped[direction]; + changed = true; + } + if (changed) decl.value = refs.parsed.toString(); + }); +} diff --git a/src/cascade.ts b/src/cascade.ts index a975490..91b3e38 100644 --- a/src/cascade.ts +++ b/src/cascade.ts @@ -12,6 +12,8 @@ for (const family of ['margin', 'padding', 'scroll-margin', 'scroll-padding']) { shorthands.set(family, sides.map(side => `${family}-${side}`)); } shorthands.set('transition', ['property', 'duration', 'timing-function', 'delay', 'behavior'].map(part => `transition-${part}`)); +shorthands.set('animation', ['name', 'duration', 'timing-function', 'delay', 'iteration-count', 'direction', 'fill-mode', 'play-state', 'timeline', 'range-start', 'range-end'].map(part => `animation-${part}`)); +shorthands.set('-webkit-animation', ['name', 'duration', 'timing-function', 'delay', 'iteration-count', 'direction', 'fill-mode', 'play-state'].map(part => `-webkit-animation-${part}`)); shorthands.set('inset', sides); shorthands.set('border', sides.flatMap(side => borderParts.map(part => `border-${side}-${part}`)).concat(borderImage)); for (const side of sides) shorthands.set(`border-${side}`, borderParts.map(part => `border-${side}-${part}`)); diff --git a/src/index.ts b/src/index.ts index 4b88be1..4c965e1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -21,6 +21,7 @@ import { analyzePropertyDifferences, winningDeclarations, } from './logical-properties'; +import { AnimationContext, prepareAnimations, hasAnimationReferences, transformAnimationReferences } from './animations'; import { orderCascadeProperties, retainCascadeDependencies } from './cascade'; // Skip processing of @keyframes and other special at-rules that shouldn't be transformed @@ -70,6 +71,8 @@ export interface LogicalPolyfillOptions { * @default 'ltr-first' */ outputOrder?: 'ltr-first' | 'rtl-first'; + /** Compile referenced logical keyframes and animation names for both directions. Default: false. */ + animations?: boolean; } // Categorize selectors by their direction context @@ -159,7 +162,8 @@ async function processRule( ltrSelector: string, rtlSelector: string, outputOrder: 'ltr-first' | 'rtl-first', - result: Result + result: Result, + animations: AnimationContext ): Promise { const config: DirectionConfig = { ltr: ltrSelector, rtl: rtlSelector }; const results: Rule[] = []; @@ -175,6 +179,9 @@ async function processRule( return []; // Transformation failure } + transformAnimationReferences(ltrTransformed, animations, 'ltr'); + transformAnimationReferences(rtlTransformed, animations, 'rtl'); + // Process unscoped selectors if (noscopeSelectors.length > 0) { if (rulesAreIdentical(ltrTransformed, rtlTransformed)) { @@ -216,19 +223,21 @@ const logicalPolyfill: PluginCreator = (opts = {}) => { const rtlSelector = opts.rtl?.selector?.trim() || DEFAULT_CONFIG.rtlSelector; const ltrSelector = opts.ltr?.selector?.trim() || DEFAULT_CONFIG.ltrSelector; const outputOrder = opts.outputOrder || DEFAULT_CONFIG.outputOrder; + const animationsEnabled = Boolean(opts.animations); return { postcssPlugin: 'postcss-logical-polyfill', async Once(root, { result }) { // Simple approach: process rules and replace them in place - await processAllRules(root, ltrSelector, rtlSelector, outputOrder, result); + const animations = animationsEnabled ? await prepareAnimations(root, result, outputOrder) : new Map(); + await processAllRules(root, ltrSelector, rtlSelector, outputOrder, result, animations); } }; }; // Process all rules recursively, maintaining structure -async function processAllRules(container: Root | AtRule, ltrSelector: string, rtlSelector: string, outputOrder: 'ltr-first' | 'rtl-first', result: Result) { +async function processAllRules(container: Root | AtRule, ltrSelector: string, rtlSelector: string, outputOrder: 'ltr-first' | 'rtl-first', result: Result, animations: AnimationContext) { const rulesToProcess: Rule[] = []; // First pass: collect rules that need processing @@ -242,14 +251,14 @@ async function processAllRules(container: Root | AtRule, ltrSelector: string, rt if (logical) result.warn('Expand CSS nesting before postcss-logical-polyfill; this nested rule was left unchanged.', { node }); return; } - if (hasLogicalProperties(node)) rulesToProcess.push(node); + if (hasLogicalProperties(node) || hasAnimationReferences(node, animations)) rulesToProcess.push(node); } else if (node.type === 'atrule') { // Don't process these at-rules, keep them as is if (SKIP_AT_RULES.includes(node.name.toLowerCase()) || /^(?:-[a-z]+-)?keyframes$/i.test(node.name)) return; // Recursively process regular at-rules like media queries // Store the promise for later awaiting - promises.push(processAllRules(node, ltrSelector, rtlSelector, outputOrder, result)); + promises.push(processAllRules(node, ltrSelector, rtlSelector, outputOrder, result, animations)); } }); @@ -258,7 +267,7 @@ async function processAllRules(container: Root | AtRule, ltrSelector: string, rt // Second pass: process rules for (const rule of rulesToProcess) { - const processedRules = await processRule(rule, ltrSelector, rtlSelector, outputOrder, result); + const processedRules = await processRule(rule, ltrSelector, rtlSelector, outputOrder, result, animations); // Replace the original rule with processed rules if (processedRules.length > 0) { diff --git a/test/animations.test.ts b/test/animations.test.ts new file mode 100644 index 0000000..747016d --- /dev/null +++ b/test/animations.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from 'vitest'; +import postcss, { AtRule, Rule, Declaration } from 'postcss'; +import plugin from '../src'; +const frames = '@keyframes slide{from{margin-inline-start:0}to{margin-inline-start:100px}}'; +const process = (css: string, options = {}) => postcss([plugin({ animations: true, ...options })]).process(css, { from: undefined }); +const refs = (root: postcss.Root, prop = 'animation-name') => { + const found: Array<[string, string]> = []; + root.walkDecls(prop, decl => { if (decl.parent?.type === 'rule') found.push([(decl.parent as Rule).selector, decl.value]); }); + return found; +}; + +describe('opt-in logical animations', () => { + it('keeps the default behavior unchanged', async () => { + const css = frames + '.x{animation-name:slide}'; + expect((await postcss([plugin()]).process(css, { from: undefined })).css).toBe(css); + }); + it('uses a separate keyframe name and correct sides for each direction', async () => { + const result = await process(frames + '.x{animation-name:slide}'); + expect(refs(result.root)).toEqual([ + ['[dir="ltr"] .x', 'lp-slide-ltr'], ['[dir="rtl"] .x', 'lp-slide-rtl'] + ]); + const definitions = result.root.nodes.filter(node => node.type === 'atrule') as AtRule[]; + expect(definitions.map(def => def.params)).toEqual(['slide', 'lp-slide-ltr', 'lp-slide-rtl']); + expect(((definitions[1].first as Rule).first as Declaration).prop).toBe('margin-left'); + expect(((definitions[2].first as Rule).first as Declaration).prop).toBe('margin-right'); + }); + it.each(['slide 1s linear', '1s ease-in 200ms 2 alternate both paused slide', 'slide 1s steps(2, end)'])('rewrites shorthand %s', async value => { + const result = await process(frames + `.x{animation:${value}}`); + expect(refs(result.root, 'animation').map(([, value]) => value)).toEqual([value.replace('slide', 'lp-slide-ltr'), value.replace('slide', 'lp-slide-rtl')]); + }); + it('preserves ordinary names and multiple animations', async () => { + const result = await process(frames + '.x{animation:slide 1s linear, other 2s ease;animation-name:slide,other}'); + expect(refs(result.root).map(([, value]) => value)).toEqual(['lp-slide-ltr,other', 'lp-slide-rtl,other']); + expect(refs(result.root, 'animation').map(([, value]) => value)).toEqual(['lp-slide-ltr 1s linear, other 2s ease', 'lp-slide-rtl 1s linear, other 2s ease']); + }); + it('handles keyword names according to shorthand grammar', async () => { + const css = frames.replace(/slide/g, 'linear') + '.a{animation:linear 1s}.b{animation:linear 1s linear}.c{animation:"linear" 1s}'; + const result = await process(css); + expect(refs(result.root, 'animation')).toContainEqual(['.a', 'linear 1s']); + expect(refs(result.root, 'animation')).toContainEqual(['[dir="rtl"] .b', 'linear 1s lp-linear-rtl']); + expect(refs(result.root, 'animation')).toContainEqual(['[dir="rtl"] .c', '"lp-linear-rtl" 1s']); + }); + it('resolves quoted and escaped names', async () => { + const result = await process(String.raw`@keyframes s\6c ide{from{margin-inline-start:0}to{margin-inline-start:10px}}.a{animation:s\6c ide 1s}.b{animation-name:"s\6c ide"}`); + expect(refs(result.root, 'animation')).toContainEqual(['[dir="rtl"] .a', 'lp-slide-rtl 1s']); + expect(refs(result.root)).toContainEqual(['[dir="rtl"] .b', '"lp-slide-rtl"']); + }); + it('keeps dynamic names and original keyframes with warnings', async () => { + const css = frames + '.a{animation:var(--animation)}.b{animation-name:var(--name)}'; + const result = await process(css); + expect(result.css).toBe(css); + expect(result.warnings()).toHaveLength(2); + }); + it('avoids collisions with existing or externally referenced animation names', async () => { + const result = await process(frames + '@keyframes lp-slide-ltr{from{opacity:0}to{opacity:1}}.a{animation-name:slide}.b{animation-name:lp-slide-rtl}'); + expect(refs(result.root)).toContainEqual(['[dir="ltr"] .a', 'lp-slide-ltr-2']); + expect(refs(result.root)).toContainEqual(['[dir="rtl"] .a', 'lp-slide-rtl-2']); + expect(refs(result.root)).toContainEqual(['.b', 'lp-slide-rtl']); + }); + it('is idempotent after serialization, including generated-name collisions', async () => { + const input = frames + '@keyframes lp-slide-ltr{from{opacity:0}to{opacity:1}}.x{animation:slide 1s}'; + const first = await process(input); + expect((await process(first.css)).css).toBe(first.css); + }); + it('clones all same-name definitions in their conditional contexts', async () => { + const result = await process(frames + '@media(min-width:1px){@keyframes slide{from{margin-left:0}to{margin-left:20px}}}.x{animation-name:slide}'); + const conditional: string[] = []; + result.root.walkAtRules('keyframes', def => { if (def.parent?.type === 'atrule') conditional.push(def.params); }); + expect(conditional).toEqual(['slide', 'lp-slide-ltr', 'lp-slide-rtl']); + }); + it('supports prefixed definitions and declarations', async () => { + const result = await process(frames.replace('@keyframes', '@-webkit-keyframes') + '.x{-webkit-animation:slide 1s}'); + expect(refs(result.root, '-webkit-animation')).toContainEqual(['[dir="rtl"] .x', 'lp-slide-rtl 1s']); + expect(result.css).toContain('@-webkit-keyframes lp-slide-rtl'); + }); + it('uses existing direction scopes, custom markers and configured order', async () => { + const result = await process(frames + '.rtl .x{animation-name:slide}.y{animation-name:slide}', { rtl: { selector: '.rtl' }, ltr: { selector: '.ltr' }, outputOrder: 'rtl-first' }); + expect(refs(result.root)).toEqual([['.rtl .x', 'lp-slide-rtl'], ['.rtl .y', 'lp-slide-rtl'], ['.ltr .y', 'lp-slide-ltr']]); + }); + it('keeps resets and importance when shorthand and name overlap', async () => { + const result = await process(frames + '.x{animation-name:slide!important;animation:none}'); + for (const direction of ['ltr', 'rtl']) { + const rule = result.root.nodes.find(node => node.type === 'rule' && node.selector.includes(`[dir="${direction}"]`)) as Rule; + expect(rule.nodes.filter(node => node.type === 'decl').map(decl => [decl.prop, decl.value, !!decl.important])).toEqual([ + ['animation-name', `lp-slide-${direction}`, true], ['animation', 'none', false] + ]); + } + }); + it('does not scope frame selectors or modify unused logical definitions', async () => { + expect((await process(frames)).css).toBe(frames); + const result = await process(frames + '.x{animation-name:slide}'); + result.root.walkAtRules('keyframes', def => { def.walkRules(rule => { expect(rule.selector).not.toContain('dir='); }); }); + }); + it('does not turn invalid numeric or negative-duration names into valid animations', async () => { + for (const css of [frames + '.x{animation:slide -1s}', '@keyframes "2"{from{margin-inline-start:0}to{margin-inline-start:1px}}.x{animation:2 1s 2}', '@keyframes 2{from{margin-inline-start:0}to{margin-inline-start:1px}}.x{animation-name:"2"}']) { + expect((await process(css)).css).toBe(css); + } + }); + it('keeps unexpanded nesting intact', async () => { + const css = frames + '.x{animation-name:slide;& .child{color:red}}'; + const result = await process(css); + expect(result.css).toBe(css); + expect(result.warnings()).toHaveLength(1); + }); +}); From cdfbc296b72b3ad5d33b069194441ae517674844 Mon Sep 17 00:00:00 2001 From: Lee Date: Sat, 3 Oct 2026 12:44:15 +0000 Subject: [PATCH 2/5] fix: recognize CSS numeric syntax in motion values --- scripts/test-browser-animations.mjs | 1 + scripts/test-browser-transitions.mjs | 3 ++- src/animations.ts | 8 ++++---- test/animations.test.ts | 2 +- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/scripts/test-browser-animations.mjs b/scripts/test-browser-animations.mjs index 778c40c..176d46a 100644 --- a/scripts/test-browser-animations.mjs +++ b/scripts/test-browser-animations.mjs @@ -7,6 +7,7 @@ const plugin = require('../dist/index.js'); const frames = '@keyframes slide{from{margin-inline-start:0}to{margin-inline-start:100px}}'; const cases = [ frames + '.x{animation:slide 1s linear both}', + frames + '.x{animation:slide 1e3ms linear both}', frames + '.x{animation-name:slide;animation-duration:1s;animation-timing-function:linear;animation-fill-mode:both}', frames + '@keyframes fade{from{opacity:0}to{opacity:1}}.x{animation:slide 1s linear both,fade 2s linear both}', frames + '@media(min-width:1px){@keyframes slide{from{margin-left:0}to{margin-left:20px}}}.x{animation:slide 1s linear both}', diff --git a/scripts/test-browser-transitions.mjs b/scripts/test-browser-transitions.mjs index bf84845..6a8a00d 100644 --- a/scripts/test-browser-transitions.mjs +++ b/scripts/test-browser-transitions.mjs @@ -8,7 +8,8 @@ const cases = [ 'transition-property:margin-inline,opacity;transition-duration:1s,2s;transition-timing-function:linear', 'transition:opacity 1s ease 100ms,color 2s linear 200ms;transition-property:margin-inline,opacity', 'transition-duration:1s,2s!important;transition:color 3s;transition-property:margin-inline,opacity', - 'transition-property:margin-inline-start,opacity;transition-duration:1s,2s;transition-delay:100ms,200ms' + 'transition-property:margin-inline-start,opacity;transition-duration:1s,2s;transition-delay:100ms,200ms', + 'transition:opacity 1e3ms linear,color 2e3ms linear;transition-property:margin-inline,opacity' ].map(decls => `.x{margin-inline-start:0;opacity:1;${decls}}.x.end{margin-inline-start:100px;opacity:0}`); const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_BIN || '/usr/bin/chromium', args: ['--no-sandbox', '--disable-dev-shm-usage'] }); try { diff --git a/src/animations.ts b/src/animations.ts index 7a0a918..bbcf1c0 100644 --- a/src/animations.ts +++ b/src/animations.ts @@ -4,7 +4,7 @@ import { applyLogicalTransformation, hasLogicalProperties } from './logical-prop type Direction = 'ltr' | 'rtl'; export type AnimationContext = Map>; -const globals = /^(initial|inherit|unset|revert|revert-layer)$/i; +const globals = /^(initial|inherit|unset|revert|revert-layer|default)$/i; const identifier = /^(?:--|-?(?:[_a-z]|[^\x00-\x7f]|\\[^\n\r\f]))(?:[_a-z0-9-]|[^\x00-\x7f]|\\[^\n\r\f])*$/i; const keyframes = /^(?:-[a-z]+-)?keyframes$/i; @@ -55,11 +55,11 @@ function referenceNodes(decl: Declaration): { parsed: ReturnType { expect(((definitions[1].first as Rule).first as Declaration).prop).toBe('margin-left'); expect(((definitions[2].first as Rule).first as Declaration).prop).toBe('margin-right'); }); - it.each(['slide 1s linear', '1s ease-in 200ms 2 alternate both paused slide', 'slide 1s steps(2, end)'])('rewrites shorthand %s', async value => { + it.each(['slide 1e3ms linear', 'slide +1s +2', 'slide -0s both', 'slide 1s linear', '1s ease-in 200ms 2 alternate both paused slide', 'slide 1s steps(2, end)'])('rewrites shorthand %s', async value => { const result = await process(frames + `.x{animation:${value}}`); expect(refs(result.root, 'animation').map(([, value]) => value)).toEqual([value.replace('slide', 'lp-slide-ltr'), value.replace('slide', 'lp-slide-rtl')]); }); From cb42f54ad84ca77bdc8b12e31fbc3e6b62fb9d1e Mon Sep 17 00:00:00 2001 From: Lee Date: Sat, 3 Oct 2026 12:46:52 +0000 Subject: [PATCH 3/5] fix: ignore invalid transition shorthand resets --- scripts/test-browser-transitions.mjs | 3 ++- src/transition-properties.ts | 9 +++++++++ test/transition-property.test.ts | 6 ++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/scripts/test-browser-transitions.mjs b/scripts/test-browser-transitions.mjs index 6a8a00d..78125a2 100644 --- a/scripts/test-browser-transitions.mjs +++ b/scripts/test-browser-transitions.mjs @@ -9,7 +9,8 @@ const cases = [ 'transition:opacity 1s ease 100ms,color 2s linear 200ms;transition-property:margin-inline,opacity', 'transition-duration:1s,2s!important;transition:color 3s;transition-property:margin-inline,opacity', 'transition-property:margin-inline-start,opacity;transition-duration:1s,2s;transition-delay:100ms,200ms', - 'transition:opacity 1e3ms linear,color 2e3ms linear;transition-property:margin-inline,opacity' + 'transition:opacity 1e3ms linear,color 2e3ms linear;transition-property:margin-inline,opacity', + 'transition-duration:1s,2s;transition:opacity -1s,color -2s;transition-property:margin-inline,opacity' ].map(decls => `.x{margin-inline-start:0;opacity:1;${decls}}.x.end{margin-inline-start:100px;opacity:0}`); const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_BIN || '/usr/bin/chromium', args: ['--no-sandbox', '--disable-dev-shm-usage'] }); try { diff --git a/src/transition-properties.ts b/src/transition-properties.ts index 9b9ceb2..6a5fe00 100644 --- a/src/transition-properties.ts +++ b/src/transition-properties.ts @@ -14,18 +14,26 @@ function shorthand(value: string): Record | null { for (const item of postcss.list.comma(value)) { const values = { ...defaults }; let times = 0; + const assigned = new Set(); for (const node of valueParser(item).nodes) { if (node.type === 'space' || node.type === 'comment') continue; const token = valueParser.stringify(node); if (node.type === 'word' && /^[-+]?(?:\d*\.?\d+|\d+\.)(?:e[-+]?\d+)?(?:ms|s)$/i.test(token)) { if (times > 1) return null; + if (!times && parseFloat(token) < 0) return null; values[times++ ? 'transition-delay' : 'transition-duration'] = token; } else if (/^(ease|ease-in|ease-out|ease-in-out|linear|step-start|step-end)$/i.test(token) || (node.type === 'function' && /^(cubic-bezier|steps|linear)$/i.test(node.value))) { + if (assigned.has('easing')) return null; + assigned.add('easing'); values['transition-timing-function'] = token; } else if (/^(normal|allow-discrete)$/i.test(token)) { + if (assigned.has('behavior')) return null; + assigned.add('behavior'); values['transition-behavior'] = token; } else if (node.type === 'word' && !globalValues.test(token)) { + if (assigned.has('property')) return null; + assigned.add('property'); values['transition-property'] = token; } else return null; } @@ -42,6 +50,7 @@ export async function transformTransitionProperties(rule: Rule, processor: Plugi if (decl.parent !== rule) return; const prop = decl.prop.toLowerCase(); const values = prop === 'transition' ? shorthand(decl.value) : null; + if (prop === 'transition' && !values && !globalValues.test(decl.value) && !/\b(?:var|env)\(/i.test(decl.value)) return; const entries = prop === 'transition' ? Object.keys(defaults).map(key => [key, values?.[key] ?? decl.value]) : [[prop, decl.value]]; for (const [key, value] of entries) { const previous = state.get(key); diff --git a/test/transition-property.test.ts b/test/transition-property.test.ts index 47e0300..7bd81f0 100644 --- a/test/transition-property.test.ts +++ b/test/transition-property.test.ts @@ -52,6 +52,12 @@ describe('transition-property', () => { expect(values(rule)['transition-duration']).toBe('1s, 1s, 2s'); } }); + it('ignores invalid shorthand resets when aligning earlier valid timing lists', async () => { + const result = await process('.x{transition-duration:1s,2s;transition:opacity -1s,color -2s;transition-property:margin-inline,opacity}'); + for (const rule of (result.root.nodes as Rule[]).filter(r => r.selector.includes('dir='))) { + expect(values(rule)['transition-duration']).toBe('1s, 1s, 2s'); + } + }); it('retains a later shorthand reset', async () => { const result = await process('.x{transition-property:margin-inline-start;transition:none}'); expect(result.root.nodes).toHaveLength(1); From 3a6b2c73fac4d0bde85efa5c24294d17c84e8c59 Mon Sep 17 00:00:00 2001 From: Lee Date: Sat, 3 Oct 2026 12:49:34 +0000 Subject: [PATCH 4/5] fix: parse negative delays before motion durations --- scripts/test-browser-animations.mjs | 1 + scripts/test-browser-transitions.mjs | 3 ++- src/animations.ts | 4 ++-- src/transition-properties.ts | 8 ++++---- test/animations.test.ts | 6 +++--- test/transition-property.test.ts | 2 +- 6 files changed, 13 insertions(+), 11 deletions(-) diff --git a/scripts/test-browser-animations.mjs b/scripts/test-browser-animations.mjs index 176d46a..0281475 100644 --- a/scripts/test-browser-animations.mjs +++ b/scripts/test-browser-animations.mjs @@ -8,6 +8,7 @@ const frames = '@keyframes slide{from{margin-inline-start:0}to{margin-inline-sta const cases = [ frames + '.x{animation:slide 1s linear both}', frames + '.x{animation:slide 1e3ms linear both}', + frames + '.x{animation:slide -200ms 1s linear both}', frames + '.x{animation-name:slide;animation-duration:1s;animation-timing-function:linear;animation-fill-mode:both}', frames + '@keyframes fade{from{opacity:0}to{opacity:1}}.x{animation:slide 1s linear both,fade 2s linear both}', frames + '@media(min-width:1px){@keyframes slide{from{margin-left:0}to{margin-left:20px}}}.x{animation:slide 1s linear both}', diff --git a/scripts/test-browser-transitions.mjs b/scripts/test-browser-transitions.mjs index 78125a2..a62188e 100644 --- a/scripts/test-browser-transitions.mjs +++ b/scripts/test-browser-transitions.mjs @@ -10,7 +10,8 @@ const cases = [ 'transition-duration:1s,2s!important;transition:color 3s;transition-property:margin-inline,opacity', 'transition-property:margin-inline-start,opacity;transition-duration:1s,2s;transition-delay:100ms,200ms', 'transition:opacity 1e3ms linear,color 2e3ms linear;transition-property:margin-inline,opacity', - 'transition-duration:1s,2s;transition:opacity -1s,color -2s;transition-property:margin-inline,opacity' + 'transition-duration:1s,2s;transition:opacity 1s 2s 3s;transition-property:margin-inline,opacity', + 'transition:opacity -100ms 1s linear,color -200ms 2s linear;transition-property:margin-inline,opacity' ].map(decls => `.x{margin-inline-start:0;opacity:1;${decls}}.x.end{margin-inline-start:100px;opacity:0}`); const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_BIN || '/usr/bin/chromium', args: ['--no-sandbox', '--disable-dev-shm-usage'] }); try { diff --git a/src/animations.ts b/src/animations.ts index bbcf1c0..8c82048 100644 --- a/src/animations.ts +++ b/src/animations.ts @@ -56,8 +56,8 @@ function referenceNodes(decl: Declaration): { parsed: ReturnType= 0 ? 'duration' : 'delay'; + if (occupied.has(slot)) { valid = false; break; } } else if (/^(ease|linear|ease-in|ease-out|ease-in-out|step-start|step-end)$/.test(token) && !occupied.has('easing')) slot = 'easing'; else if ((token === 'infinite' || /^\+?(?:\d*\.?\d+|\d+\.)(?:e[-+]?\d+)?$/.test(token)) && !occupied.has('iterations')) slot = 'iterations'; else if (/^(normal|reverse|alternate|alternate-reverse)$/.test(token) && !occupied.has('direction')) slot = 'direction'; diff --git a/src/transition-properties.ts b/src/transition-properties.ts index 6a5fe00..f029728 100644 --- a/src/transition-properties.ts +++ b/src/transition-properties.ts @@ -13,15 +13,15 @@ function shorthand(value: string): Record | null { const lists: Record = Object.fromEntries(Object.keys(defaults).map(prop => [prop, []])); for (const item of postcss.list.comma(value)) { const values = { ...defaults }; - let times = 0; const assigned = new Set(); for (const node of valueParser(item).nodes) { if (node.type === 'space' || node.type === 'comment') continue; const token = valueParser.stringify(node); if (node.type === 'word' && /^[-+]?(?:\d*\.?\d+|\d+\.)(?:e[-+]?\d+)?(?:ms|s)$/i.test(token)) { - if (times > 1) return null; - if (!times && parseFloat(token) < 0) return null; - values[times++ ? 'transition-delay' : 'transition-duration'] = token; + const slot = !assigned.has('duration') && parseFloat(token) >= 0 ? 'duration' : 'delay'; + if (assigned.has(slot)) return null; + assigned.add(slot); + values[`transition-${slot}`] = token; } else if (/^(ease|ease-in|ease-out|ease-in-out|linear|step-start|step-end)$/i.test(token) || (node.type === 'function' && /^(cubic-bezier|steps|linear)$/i.test(node.value))) { if (assigned.has('easing')) return null; diff --git a/test/animations.test.ts b/test/animations.test.ts index 4a6dc50..0714808 100644 --- a/test/animations.test.ts +++ b/test/animations.test.ts @@ -24,7 +24,7 @@ describe('opt-in logical animations', () => { expect(((definitions[1].first as Rule).first as Declaration).prop).toBe('margin-left'); expect(((definitions[2].first as Rule).first as Declaration).prop).toBe('margin-right'); }); - it.each(['slide 1e3ms linear', 'slide +1s +2', 'slide -0s both', 'slide 1s linear', '1s ease-in 200ms 2 alternate both paused slide', 'slide 1s steps(2, end)'])('rewrites shorthand %s', async value => { + it.each(['slide -200ms 1s linear', 'slide -1s 2s', 'slide 1e3ms linear', 'slide +1s +2', 'slide -0s both', 'slide 1s linear', '1s ease-in 200ms 2 alternate both paused slide', 'slide 1s steps(2, end)'])('rewrites shorthand %s', async value => { const result = await process(frames + `.x{animation:${value}}`); expect(refs(result.root, 'animation').map(([, value]) => value)).toEqual([value.replace('slide', 'lp-slide-ltr'), value.replace('slide', 'lp-slide-rtl')]); }); @@ -91,8 +91,8 @@ describe('opt-in logical animations', () => { const result = await process(frames + '.x{animation-name:slide}'); result.root.walkAtRules('keyframes', def => { def.walkRules(rule => { expect(rule.selector).not.toContain('dir='); }); }); }); - it('does not turn invalid numeric or negative-duration names into valid animations', async () => { - for (const css of [frames + '.x{animation:slide -1s}', '@keyframes "2"{from{margin-inline-start:0}to{margin-inline-start:1px}}.x{animation:2 1s 2}', '@keyframes 2{from{margin-inline-start:0}to{margin-inline-start:1px}}.x{animation-name:"2"}']) { + it('does not turn invalid numeric names or excess times into valid animations', async () => { + for (const css of [frames + '.x{animation:slide 1s 2s 3s}', '@keyframes "2"{from{margin-inline-start:0}to{margin-inline-start:1px}}.x{animation:2 1s 2}', '@keyframes 2{from{margin-inline-start:0}to{margin-inline-start:1px}}.x{animation-name:"2"}']) { expect((await process(css)).css).toBe(css); } }); diff --git a/test/transition-property.test.ts b/test/transition-property.test.ts index 7bd81f0..e883d0e 100644 --- a/test/transition-property.test.ts +++ b/test/transition-property.test.ts @@ -53,7 +53,7 @@ describe('transition-property', () => { } }); it('ignores invalid shorthand resets when aligning earlier valid timing lists', async () => { - const result = await process('.x{transition-duration:1s,2s;transition:opacity -1s,color -2s;transition-property:margin-inline,opacity}'); + const result = await process('.x{transition-duration:1s,2s;transition:opacity 1s 2s 3s;transition-property:margin-inline,opacity}'); for (const rule of (result.root.nodes as Rule[]).filter(r => r.selector.includes('dir='))) { expect(values(rule)['transition-duration']).toBe('1s, 1s, 2s'); } From 3731fc67023a39f6010d737f99572b990e0abd68 Mon Sep 17 00:00:00 2001 From: Lee Date: Sat, 3 Oct 2026 13:09:57 +0000 Subject: [PATCH 5/5] fix: distinguish literal backslashes in animation names --- scripts/test-browser-animations.mjs | 4 +++- src/animations.ts | 2 +- test/animations.test.ts | 11 +++++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/scripts/test-browser-animations.mjs b/scripts/test-browser-animations.mjs index 0281475..7478a11 100644 --- a/scripts/test-browser-animations.mjs +++ b/scripts/test-browser-animations.mjs @@ -16,7 +16,9 @@ const cases = [ frames + '@keyframes lp-slide-ltr{from{opacity:0}to{opacity:1}}.x{animation:slide 1s linear both}', frames + '.x{animation-name:slide!important;animation:none;animation-duration:1s;animation-timing-function:linear}', frames.replace('@keyframes', '@-webkit-keyframes') + '.x{-webkit-animation:slide 1s linear both}', - frames + '.x{--motion:slide 1s linear both;animation:var(--motion)}' + frames + '.x{--motion:slide 1s linear both;animation:var(--motion)}', + String.raw`@keyframes "s\\31"{from{margin-inline-start:0}to{margin-inline-start:20px}}@keyframes "s\\000031"{from{margin-inline-start:0}to{margin-inline-start:100px}}.x{animation:"s\\31" 1s linear both}`, + String.raw`@keyframes "s\\31"{from{margin-inline-start:0}to{margin-inline-start:20px}}@keyframes "s\\000031"{from{margin-inline-start:0}to{margin-inline-start:100px}}.x{animation:"s\\000031" 1s linear both}` ]; const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_BIN || '/usr/bin/chromium', args: ['--no-sandbox', '--disable-dev-shm-usage'] }); try { diff --git a/src/animations.ts b/src/animations.ts index 8c82048..2564b36 100644 --- a/src/animations.ts +++ b/src/animations.ts @@ -10,7 +10,7 @@ const keyframes = /^(?:-[a-z]+-)?keyframes$/i; // value-parser does not consume whitespace terminating a hexadecimal CSS escape. function normalizedEscapes(value: string): string { - return value.replace(/\\([\da-f]{1,6})(?:\r\n|[ \n\r\t\f])?/gi, (_, hex: string) => `\\${hex.padStart(6, '0')}`); + return value.replace(/\\(?:([\da-f]{1,6})(?:\r\n|[ \n\r\t\f])?|[^\n\r\f])/gi, (escape: string, hex: string) => hex ? `\\${hex.padStart(6, '0')}` : escape); } function decoded(value: string): string { return value.replace(/\\(?:([\da-f]{1,6})(?:\r\n|[ \n\r\t\f])?|(\r\n|[\n\r\f])|([\s\S]))/gi, (_, hex: string, newline: string, char: string) => { diff --git a/test/animations.test.ts b/test/animations.test.ts index 0714808..453a983 100644 --- a/test/animations.test.ts +++ b/test/animations.test.ts @@ -51,6 +51,17 @@ describe('opt-in logical animations', () => { expect(result.css).toBe(css); expect(result.warnings()).toHaveLength(2); }); + it('keeps literal backslashes distinct from hexadecimal escapes in animation names', async () => { + const css = String.raw`@keyframes "s\\31"{from{margin-inline-start:0}to{margin-inline-start:20px}}@keyframes "s\\000031"{from{margin-inline-start:0}to{margin-inline-start:100px}}.a{animation-name:"s\\31"}.b{animation-name:"s\\000031"}`; + const result = await process(css); + const names = refs(result.root).filter(([selector]) => selector.includes('dir="ltr"')).map(([, value]) => value); + expect(new Set(names).size).toBe(2); + const ends: string[] = []; + result.root.walkAtRules('keyframes', def => { + if (names.includes(`"${def.params}"`)) ends.push(((def.last as Rule).first as Declaration).value); + }); + expect(ends).toEqual(['20px', '100px']); + }); it('avoids collisions with existing or externally referenced animation names', async () => { const result = await process(frames + '@keyframes lp-slide-ltr{from{opacity:0}to{opacity:1}}.a{animation-name:slide}.b{animation-name:lp-slide-rtl}'); expect(refs(result.root)).toContainEqual(['[dir="ltr"] .a', 'lp-slide-ltr-2']);