Skip to content

Commit da4ad13

Browse files
fix(css): replace a @value named in an at-rule prelude only once (#22036)
* fix(css): replace a @value named in an at-rule prelude only once An ident that `@keyframes` / `@counter-style` / `@container` / `@scope` localizes in its own prelude was rewritten a second time by the generic ICSS value walk, and two dependencies over one range concatenate, so `@value animName: pulseAnim` emitted `@keyframes <scoped>pulseAnimpulseAnim` while the animation reference read `<scoped>pulseAnim`. Mark the prelude idents an at-rule's own handler already replaced and skip them in the value walk, leaving every other prelude ident (a `@container` condition, a `@media` query) substituted as before. Closes #22030 * test(css): cover repeated @value animation names in one stylesheet An overriding second `animation` declaration, a comma-separated `animation-name` list (with the same value twice), a shorthand list and a second `@keyframes` block naming the same `@value` each still substitute per occurrence — the dedupe is keyed by the ident's source offset, so it suppresses a second dependency over one range, never a later occurrence. Also reword the changeset: "once" read as once per file. * test(css): cover an imported @value naming another module's @Keyframes Raised on the issue thread: `@value imported from "./values.module.css"` where the other module declares `@keyframes imported`. Resolving the `@value` first and interpolating second lands the animation shorthand, the `animation-name` and the local `@keyframes` prelude on the defining module's scoped name; before the fix the prelude doubled it. * fix(css): localize a @value standing in for a class or id selector `@value sel: .globalThing;` used as `sel { }` substituted the text and stopped there, so the class escaped scoping while every other position resolved and then hashed. Resolve first and localize the class / id the value names, as CSS Modules would had the author written it. A value naming anything else — a type selector, a compound or descendant selector — has no single localizable ident and is still substituted verbatim. * chore(changeset): cover the selector case too The entry named only the at-rule prelude; the fix now spans both. * refactor(css): avoid control-character escapes in the @value selector regex ESLint rejects `[^\x00-\x7F]` under no-control-regex and unicorn/no-hex-escape. Spell the non-ASCII ident code point as the positive range CSS Syntax 3 defines it as (>= U+0080), matching the existing spelling in lib/css/syntax.js. Behaviour is unchanged. * test(css): cover an imported @value used as a selector The only line of the new selector path with no case: an imported value keeps its plain textual substitution, since the defining module owns the scoped name. Brings the patch to full line coverage. * fix(css): localize a @value that resolves to a custom property or grid name Two more positions where a `@value` was resolved but never localized, so the name it produced could not match the same identifier spelled directly. A `@value` naming a dashed ident is now scoped like the ident it resolves to, in `var()` and in the dashed-ident value properties (`anchor-name`, `view-timeline-name`, `font-palette`, `position-try-fallbacks`, …). Previously `var(--foo)` scoped and `var(v)` did not, so the two never referred to the same property. A grid line's readable suffix now follows the `@value` to its resolved name, so `[v]` and `[resolved]` select the same line rather than two different ones. * test(css): cover an imported @value used as a grid line name The one line of the grid change with no case. An imported value keeps the written suffix, since the defining module owns the name; what the case pins is that declaring and referencing the line still agree.
1 parent df72840 commit da4ad13

20 files changed

Lines changed: 1330 additions & 18 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Resolve a `@value` once and then localize it, wherever it names an identifier.

‎lib/css/CssParser.js‎

Lines changed: 144 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,10 @@ const VALUE_AS_ALIAS = /\s+as\s+/;
207207
// `@value name value`: end of the name run (first non-space followed by space).
208208
const VALUE_NAME_BOUNDARY = /\S\s/;
209209
const ONLY_WHITESPACE = /^\s+$/;
210+
// A `@value` whose whole value is one `.class` / `#id`, the only shape whose
211+
// localizable ident is knowable without re-parsing the substitution.
212+
const SIMPLE_CLASS_OR_ID_VALUE =
213+
/^([.#])(-?(?:[A-Za-z_]|[\u0080-\uFFFF])(?:[\w-]|[\u0080-\uFFFF])*)$/;
210214
// Relative request prefix (`./` or `../`) — `isSelfReferenceRequest` per `from`.
211215
const RELATIVE_REQUEST = /^\.{1,2}\//;
212216

@@ -994,6 +998,19 @@ class CssParser extends Parser {
994998
d.entries.push(cssExportEntries.length);
995999
};
9961000

1001+
// Start offsets of the idents an at-rule's own prelude handler already
1002+
// replaced: two deps over one range concatenate rather than the later winning.
1003+
/** @type {Set<number>} */
1004+
const handledPreludeIdents = new Set();
1005+
// Only a prelude is walked by both a handler and the value visitors, so
1006+
// nothing outside one pays for the bookkeeping.
1007+
let trackingPreludeIdents = false;
1008+
1009+
// Start offsets of `@value`-named dashed idents a `var()` handler already
1010+
// scoped; only those are walked twice, so plain dashed idents cost nothing.
1011+
/** @type {Set<number>} */
1012+
const handledDashedValueIdents = new Set();
1013+
9971014
// All `:export`-style exports are collected into a single
9981015
// `CssIcssExportDependency` per module (emitted at parse end) instead of one
9991016
// `Dependency` per export — far fewer retained objects on CSS-heavy builds.
@@ -1024,6 +1041,7 @@ class CssParser extends Parser {
10241041
exportMode = CssIcssExportDependency.EXPORT_MODE.REPLACE,
10251042
exportType = CssIcssExportDependency.EXPORT_TYPE.NORMAL
10261043
) => {
1044+
if (trackingPreludeIdents && range) handledPreludeIdents.add(range[0]);
10271045
// Flat location numbers — the nested loc objects were the parser's
10281046
// hottest allocation (3 objects per exported name).
10291047
cssExportEntries.push({
@@ -1556,13 +1574,15 @@ class CssParser extends Parser {
15561574
};
15571575

15581576
/**
1559-
* Emit a `CssIcssSymbolDependency` rewrite for an ident resolving to an `@value`-defined ICSS symbol (source-order semantics hold since the walker handles each `@value` before later references).
1577+
* Emit a `CssIcssSymbolDependency` rewrite for an ident resolving to an `@value`-defined ICSS symbol (source-order semantics hold since the walker handles each `@value` before later references). A no-op for an ident an at-rule's own prelude handler already replaced.
15601578
* @param {string} name ICSS symbol name
15611579
* @param {number} start start position
15621580
* @param {number} end end position
15631581
* @returns {number} `end` of the rewritten ident range
15641582
*/
15651583
const emitICSSSymbol = (name, start, end) => {
1584+
if (handledPreludeIdents.has(start)) return end;
1585+
if (trackingPreludeIdents) handledPreludeIdents.add(start);
15661586
const def =
15671587
/** @type {IcssDefinition} */
15681588
(icssDefinitions.get(name));
@@ -1580,6 +1600,37 @@ class CssParser extends Parser {
15801600
return end;
15811601
};
15821602

1603+
/**
1604+
* The `.class` / `#id` a locally defined `@value` stands for, when its whole value is exactly one of those. Undefined for an imported value or any richer selector, which stay a plain textual substitution.
1605+
* @param {string} name `@value` name used where a selector is expected
1606+
* @returns {["." | "#", string] | undefined} the selector's prefix and the ident to localize
1607+
*/
1608+
const localizableSelectorValue = (name) => {
1609+
const def = icssDefinitions.get(name);
1610+
if (!def || def.importName || typeof def.value !== "string") {
1611+
return undefined;
1612+
}
1613+
const match = SIMPLE_CLASS_OR_ID_VALUE.exec(def.value.trim());
1614+
return match
1615+
? [/** @type {"." | "#"} */ (match[1]), match[2]]
1616+
: undefined;
1617+
};
1618+
1619+
/**
1620+
* The dashed ident a locally defined `@value` stands for, without its `--` prefix, when its whole value is exactly one. Undefined for an imported value or any richer value, which stay a plain textual substitution.
1621+
* @param {string} name `@value` name used where a dashed ident is expected
1622+
* @returns {string | undefined} the name to localize, sans `--`
1623+
*/
1624+
const localizableDashedValue = (name) => {
1625+
if (icssDefinitions.size === 0) return undefined;
1626+
const def = icssDefinitions.get(name);
1627+
if (!def || def.importName || typeof def.value !== "string") {
1628+
return undefined;
1629+
}
1630+
const value = def.value.trim();
1631+
return isDashedIdentifier(value) ? value.slice(2) : undefined;
1632+
};
1633+
15831634
/**
15841635
* Process a `local(...)` / `global(...)` pseudo-function: strip the call (and a leading legacy `:`) via a presentational dep, then emit `local()`'s inner top-level idents as ICSS exports.
15851636
* @param {FunctionNode} fn parsed local/global function node
@@ -1740,12 +1791,12 @@ class CssParser extends Parser {
17401791
: unescapeRange(identStart, identEnd).slice(2);
17411792

17421793
/**
1743-
* Emit the ICSS export declaring this module exports the given custom property.
1744-
* @param {number} identStart start of the `--<name>` ident
1794+
* Emit the ICSS export declaring this module exports the given custom property, naming it explicitly rather than reading it back from the replaced range. A `@value` standing in for a dashed ident is scoped under the name it resolves to, not the name written at the use site.
1795+
* @param {string} identifier custom property name, sans `--`
1796+
* @param {number} identStart start of the replaced ident
17451797
* @param {number} identEnd end of the ident (exclusive)
17461798
*/
1747-
const emitDashedIdentExport = (identStart, identEnd) => {
1748-
const identifier = dashedIdentName(identStart, identEnd);
1799+
const emitNamedDashedIdentExport = (identifier, identStart, identEnd) => {
17491800
const { line: sl, column: sc } = locConverter.get(identStart);
17501801
const { line: el, column: ec } = locConverter.get(identEnd);
17511802
recordDeclaration(identifier, "custom property", sl, sc);
@@ -1763,6 +1814,19 @@ class CssParser extends Parser {
17631814
);
17641815
};
17651816

1817+
/**
1818+
* Emit the ICSS export declaring this module exports the given custom property.
1819+
* @param {number} identStart start of the `--<name>` ident
1820+
* @param {number} identEnd end of the ident (exclusive)
1821+
*/
1822+
const emitDashedIdentExport = (identStart, identEnd) => {
1823+
emitNamedDashedIdentExport(
1824+
dashedIdentName(identStart, identEnd),
1825+
identStart,
1826+
identEnd
1827+
);
1828+
};
1829+
17661830
/**
17671831
* Emit `--<name> from "<path>"` as an ICSS import + export, stripping ` from "<path>"` so the runtime sees just `--<name>` (dep ranges end at `sourceEnd - 1`, the closing quote).
17681832
* @param {number} identStart start of the `--<name>` ident
@@ -1846,7 +1910,16 @@ class CssParser extends Parser {
18461910

18471911
const identStart = A.start(identNode);
18481912
const identEnd = A.end(identNode);
1849-
if (!rangeIsDashedIdentifier(input, identStart, identEnd)) return;
1913+
if (!rangeIsDashedIdentifier(input, identStart, identEnd)) {
1914+
// `var(v)` where `@value v: --foo` names the same property `var(--foo)`
1915+
// does, so it is scoped here rather than substituted verbatim.
1916+
const dashedName = localizableDashedValue(A.value(identNode));
1917+
if (dashedName !== undefined) {
1918+
handledDashedValueIdents.add(identStart);
1919+
emitNamedDashedIdentExport(dashedName, identStart, identEnd);
1920+
}
1921+
return;
1922+
}
18501923

18511924
let j = identIdx + 1;
18521925
while (j < fv.length && A.type(fv[j]) === NodeType.Whitespace) {
@@ -2351,12 +2424,52 @@ class CssParser extends Parser {
23512424
break;
23522425
}
23532426
case NodeType.Ident: {
2354-
// ICSS rewrite for a bare `@value`-defined ident used as a type-style selector; only worth the slice when definitions exist.
2427+
// A bare `@value`-defined ident stands in for a selector; only worth the slice when definitions exist.
23552428
if (icssDefinitions.size === 0) break;
23562429
const ident = A.value(v);
2357-
if (!isDashedIdentifier(ident) && icssDefinitions.has(ident)) {
2358-
emitICSSSymbol(ident, A.start(v), A.end(v));
2430+
if (isDashedIdentifier(ident) || !icssDefinitions.has(ident)) {
2431+
break;
2432+
}
2433+
const identStart = A.start(v);
2434+
const identEnd = A.end(v);
2435+
// A value naming one class / id is localized like the selector the
2436+
// author would have written; anything else is substituted verbatim.
2437+
const localizable =
2438+
segmentMode === "local"
2439+
? localizableSelectorValue(ident)
2440+
: undefined;
2441+
if (localizable === undefined) {
2442+
emitICSSSymbol(ident, identStart, identEnd);
2443+
break;
2444+
}
2445+
const [prefix, localName] = localizable;
2446+
const { line: sl, column: sc } = locConverter.get(identStart);
2447+
const { line: el, column: ec } = locConverter.get(identEnd);
2448+
module.addPresentationalDependency(
2449+
new ConstDependency(prefix, [identStart, identStart])
2450+
);
2451+
recordDeclaration(
2452+
localName,
2453+
prefix === "." ? "class" : "id",
2454+
sl,
2455+
sc
2456+
);
2457+
addCssExport(
2458+
sl,
2459+
sc,
2460+
el,
2461+
ec,
2462+
localName,
2463+
getReexport(localName),
2464+
[identStart, identEnd],
2465+
true,
2466+
CssIcssExportDependency.EXPORT_MODE.ONCE
2467+
);
2468+
if (prefix === ".") {
2469+
currentRule.hasLocalAnchor = true;
2470+
currentRule.localIdentifiers.push(localName);
23592471
}
2472+
pure.markLocal();
23602473
break;
23612474
}
23622475
default:
@@ -4074,6 +4187,10 @@ class CssParser extends Parser {
40744187
// truncates back to this length (no per-rule copy).
40754188
const savedLocalIdentifierCount = currentRule.localIdentifiers.length;
40764189
const name = `@${toLowerCaseIfNeeded(A.unescapedName(at))}`;
4190+
// The dispatch below is the only place a prelude is rewritten ahead
4191+
// of the value visitors, so the marks live exactly as long as it.
4192+
if (handledPreludeIdents.size !== 0) handledPreludeIdents.clear();
4193+
trackingPreludeIdents = true;
40774194
switch (name) {
40784195
case "@namespace": {
40794196
this._emitWarning(
@@ -4173,6 +4290,7 @@ class CssParser extends Parser {
41734290
)
41744291
);
41754292
}
4293+
trackingPreludeIdents = false;
41764294

41774295
// Prelude value-visitor context; AST-handled at-rules emit their own deps so they're excluded from the local() / global() / ICSS walks.
41784296
const effectiveLocalMode = isEffectivelyLocal();
@@ -4777,9 +4895,24 @@ class CssParser extends Parser {
47774895
if (dashed.counterArgs) return;
47784896
// Deferred: only the ICSS probe needs the ident's string value.
47794897
const identValue = A.value(node);
4780-
if (icssDefinitions.has(identValue)) {
4781-
emitICSSSymbol(identValue, identStart, identEnd);
4898+
if (!icssDefinitions.has(identValue)) return;
4899+
// Already scoped by the enclosing `var()` handler.
4900+
if (
4901+
handledDashedValueIdents.size !== 0 &&
4902+
handledDashedValueIdents.has(identStart)
4903+
) {
4904+
return;
4905+
}
4906+
// A `@value` resolving to a dashed ident sits where `--foo` would be
4907+
// scoped, so it is localized rather than substituted verbatim.
4908+
if (dashedActive && dashed.emit) {
4909+
const dashedName = localizableDashedValue(identValue);
4910+
if (dashedName !== undefined) {
4911+
emitNamedDashedIdentExport(dashedName, identStart, identEnd);
4912+
return;
4913+
}
47824914
}
4915+
emitICSSSymbol(identValue, identStart, identEnd);
47834916
}
47844917
};
47854918
// `as` selects the top-level production (§5.3): a `style` attribute is a

‎lib/dependencies/CssIcssExportDependency.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -916,7 +916,13 @@ CssIcssExportDependency.Template = class CssIcssExportDependencyTemplate extends
916916
}
917917

918918
if (entry.exportType === EXPORT_TYPE.GRID_CUSTOM_IDENTIFIER) {
919-
value += `-${entry.name}`;
919+
// The suffix names what the identifier was built from, so it follows a
920+
// `@value` to its resolved name — both spellings select the same line.
921+
value += `-${
922+
isReference
923+
? /** @type {string[]} */ (entry.value)[0]
924+
: /** @type {string} */ (entry.value)
925+
}`;
920926
}
921927

922928
if (isJs && entry.exportMode !== EXPORT_MODE.NONE) {

0 commit comments

Comments
 (0)