Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
build:
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 26 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/src/content/docs/getting-started/introduction.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
12 changes: 12 additions & 0 deletions docs/src/content/docs/guides/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 6 additions & 2 deletions docs/src/content/docs/references/api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
4 changes: 4 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
11 changes: 11 additions & 0 deletions examples/logical-animations/README.md
Original file line number Diff line number Diff line change
@@ -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.
23 changes: 23 additions & 0 deletions examples/logical-animations/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Logical keyframes: LTR and RTL</title>
<link rel="stylesheet" href="output.css">
</head>
<body>
<h1>One stylesheet, two animation directions</h1>
<button type="button">Switch to RTL</button>
<p>The box moves away from the start edge in both directions.</p>
<div class="box"></div>
<script>
const button = document.querySelector('button');
button.addEventListener('click', () => {
const root = document.documentElement;
root.dir = root.dir === 'ltr' ? 'rtl' : 'ltr';
button.textContent = root.dir === 'ltr' ? 'Switch to RTL' : 'Switch to LTR';
});
</script>
</body>
</html>
11 changes: 11 additions & 0 deletions examples/logical-animations/input.css
Original file line number Diff line number Diff line change
@@ -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; }
}
13 changes: 13 additions & 0 deletions examples/logical-animations/process.ts
Original file line number Diff line number Diff line change
@@ -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; });
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
51 changes: 51 additions & 0 deletions scripts/test-browser-animations.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
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: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}',
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)}',
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 {
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 = `<style>${css}</style><div dir="${direction}"><div class="x">x</div></div>`;
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(); }
5 changes: 4 additions & 1 deletion scripts/test-package.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
Expand Down
Loading
Loading