Skip to content

Commit 4bfc2cb

Browse files
authored
fix: component selectors for memo, function wrappers and Preact, server manager options, prerelease job (#5867)
* ci: declare the packages the prerelease notes script imports * fix: component selectors for memo and Preact, server manager options with empty plugins * fix: one brand check for component selectors, and reuse the server manager's stylis instance * refactor: resolve the server manager's stylis once, and share the brand check * style: format the basic test * test: assert the reused server stylis instance is the manager's own
1 parent 1ddadee commit 4bfc2cb

14 files changed

Lines changed: 234 additions & 83 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
Referring to another component in a style (`${Box}:hover { ... }`) produces that component's selector for any styled component under `preact/compat`, and for a `React.memo` or function wrapper that has the styled component's statics hoisted onto it.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
A `StyleSheetManager` in a server component honors `namespace` and `enableVendorPrefixes` when they are passed together with `stylisPlugins={[]}`, matching client components.

‎docs/rsc-style-injection.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,10 @@ The override carries exactly four things: `shouldForwardProp`, `styleSheet`, `st
147147
`stylisPlugins`. A nested manager inherits `stylisPlugins` and `shouldForwardProp` from its parent
148148
when it omits them, which is what lets an inner manager set `namespace` or `enableVendorPrefixes`
149149
while keeping the outer plugins. Passing `stylisPlugins={[]}` explicitly opts out and falls back to
150-
the default stylis instance. When neither a custom stylis instance nor a `shouldForwardProp` survives
151-
resolution, the override is cleared to `null` rather than set to a redundant object.
150+
the default stylis instance, or to a plugin-free instance that keeps a `namespace` or
151+
`enableVendorPrefixes` passed with it. When neither a custom stylis instance nor a
152+
`shouldForwardProp` survives resolution, the override is cleared to `null` rather than set to a
153+
redundant object.
152154

153155
The compiled stylis instance is memoized at module level, because the manager reads and writes it in
154156
one synchronous call. A memoized instance is reused only by a manager with the same plugins array

‎package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
"packageManager": "[email protected]",
2626
"devDependencies": {
2727
"@changesets/cli": "^2.27.7",
28-
"husky": "9.1.7"
28+
"@changesets/read": "0.6.7",
29+
"husky": "9.1.7",
30+
"semver": "7.7.4"
2931
}
3032
}

‎packages/styled-components/src/constructors/test/styled.rsc.test.tsx‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,11 @@ import { mainSheet } from '../../models/StyleSheetManager';
3838
import { resetGroupIds } from '../../sheet/GroupIDAllocator';
3939
import { resetIdentifiers } from '../../models/StyledComponent';
4040
import styled, { css, keyframes } from '../../index';
41-
import { StyleSheetManager } from '../../models/StyleSheetManager';
41+
import {
42+
mainStylis,
43+
StyleSheetManager,
44+
useStyleSheetContext,
45+
} from '../../models/StyleSheetManager';
4246
import stylisPluginRSC from '../../utils/stylisPluginRSC';
4347

4448
/** Extract all CSS rule text from <style> tags in rendered HTML */
@@ -1714,6 +1718,54 @@ describe('styled RSC mode', () => {
17141718
expect(allCSS).toMatchInlineSnapshot(`".dnGtrT:first-child{color:red;}"`);
17151719
expect(allCSS).not.toContain(':not(style');
17161720
});
1721+
1722+
it.each<[string, Record<string, unknown>, string]>([
1723+
['nothing else', {}, '.CLASS{user-select:none;}'],
1724+
['a namespace', { namespace: '#ns' }, '#ns .CLASS{user-select:none;}'],
1725+
[
1726+
'enableVendorPrefixes',
1727+
{ enableVendorPrefixes: true },
1728+
'.CLASS{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;}',
1729+
],
1730+
])('applies an empty stylisPlugins list together with %s', (_label, props, expected) => {
1731+
mockUseRequest(new Map());
1732+
const Item = styled.li`
1733+
user-select: none;
1734+
`;
1735+
1736+
const html = ReactDOMServer.renderToString(
1737+
<StyleSheetManager stylisPlugins={[]} {...props}>
1738+
<Item />
1739+
</StyleSheetManager>
1740+
);
1741+
1742+
expect(extractStyleContents(html).replace(/\.[a-zA-Z0-9]+/g, '.CLASS')).toBe(expected);
1743+
});
1744+
1745+
it.each<[string, Record<string, unknown>]>([
1746+
['a namespace', { namespace: '#ns' }],
1747+
['enableVendorPrefixes', { enableVendorPrefixes: true }],
1748+
])('reuses one stylis instance across requests for stable plugins with %s', (_label, props) => {
1749+
const plugins = [stylisPluginRSC];
1750+
const seen: unknown[] = [];
1751+
const ReadStylis = () => {
1752+
seen.push(useStyleSheetContext().stylis);
1753+
return null;
1754+
};
1755+
1756+
for (let request = 0; request < 3; request++) {
1757+
mockUseRequest(new Map());
1758+
ReactDOMServer.renderToString(
1759+
<StyleSheetManager stylisPlugins={plugins} {...props}>
1760+
<ReadStylis />
1761+
</StyleSheetManager>
1762+
);
1763+
}
1764+
1765+
expect(seen).toHaveLength(3);
1766+
expect(seen[0]).not.toBe(mainStylis);
1767+
expect(new Set(seen).size).toBe(1);
1768+
});
17171769
});
17181770

17191771
describe('StyleSheetManager settings are scoped per request', () => {

‎packages/styled-components/src/models/StyleSheetManager.tsx‎

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -132,19 +132,18 @@ export function StyleSheetManager(props: IStyleSheetManager): React.JSX.Element
132132
// Merge with existing override: inherit parent values when props are omitted.
133133
const parentOverride = slot.override || defaultContextValue;
134134

135-
// Build a stylis instance when any stylis-related prop is provided.
136-
// Cache it when the plugins array ref is stable.
137-
const hasStylisProps =
138-
props.stylisPlugins !== undefined ||
139-
props.namespace !== undefined ||
140-
props.enableVendorPrefixes !== undefined;
135+
const hasStylisOptions =
136+
props.namespace !== undefined || props.enableVendorPrefixes !== undefined;
137+
let resolvedStylis = parentOverride.stylis;
141138

142-
if (hasStylisProps) {
139+
if (props.stylisPlugins && !props.stylisPlugins.length && !hasStylisOptions) {
140+
resolvedStylis = mainStylis;
141+
} else if (props.stylisPlugins) {
142+
// Memoized while the plugins array ref and options stay the same.
143143
if (
144-
props.stylisPlugins &&
145-
(props.stylisPlugins !== rscLastPlugins ||
146-
props.namespace !== rscLastNamespace ||
147-
props.enableVendorPrefixes !== rscLastPrefix)
144+
props.stylisPlugins !== rscLastPlugins ||
145+
props.namespace !== rscLastNamespace ||
146+
props.enableVendorPrefixes !== rscLastPrefix
148147
) {
149148
rscLastPlugins = props.stylisPlugins;
150149
rscLastNamespace = props.namespace;
@@ -153,24 +152,21 @@ export function StyleSheetManager(props: IStyleSheetManager): React.JSX.Element
153152
options: { namespace: props.namespace, prefix: props.enableVendorPrefixes },
154153
plugins: props.stylisPlugins,
155154
});
156-
} else if (props.namespace !== undefined || props.enableVendorPrefixes !== undefined) {
157-
// Namespace or prefix changed without new plugins - create fresh instance
158-
// using inherited plugins from parent.
159-
rscCachedStylis = createStylisInstance({
160-
options: { namespace: props.namespace, prefix: props.enableVendorPrefixes },
161-
plugins: props.stylisPlugins ?? parentOverride.stylisPlugins,
162-
});
163-
rscLastPlugins = undefined;
164-
rscLastNamespace = undefined;
165-
rscLastPrefix = undefined;
166155
}
156+
157+
resolvedStylis = rscCachedStylis;
158+
} else if (hasStylisOptions) {
159+
// Options without plugins of its own: build on the parent's plugins.
160+
rscCachedStylis = createStylisInstance({
161+
options: { namespace: props.namespace, prefix: props.enableVendorPrefixes },
162+
plugins: parentOverride.stylisPlugins,
163+
});
164+
rscLastPlugins = undefined;
165+
rscLastNamespace = undefined;
166+
rscLastPrefix = undefined;
167+
resolvedStylis = rscCachedStylis;
167168
}
168169

169-
const resolvedStylis = hasStylisProps
170-
? props.stylisPlugins !== undefined && !props.stylisPlugins.length
171-
? mainStylis
172-
: rscCachedStylis
173-
: parentOverride.stylis;
174170
const resolvedShouldForwardProp =
175171
'shouldForwardProp' in props ? props.shouldForwardProp : parentOverride.shouldForwardProp;
176172

‎packages/styled-components/src/test/basic.test.tsx‎

Lines changed: 43 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,27 @@
11
import '@testing-library/jest-dom';
22
import { render } from '@testing-library/react';
33
import React, { Component, CSSProperties, StrictMode } from 'react';
4-
import { AnyComponent } from '../types';
4+
import { AnyComponent, IStyledComponent } from '../types';
55
import hoist from '../utils/hoist';
66
import { getRenderedCSS, resetStyled } from './utils';
77

88
let styled: ReturnType<typeof resetStyled>;
99

10+
/** Runs `fn` with `React.forwardRef` returning a function, the shape preact/compat gives it. */
11+
const withFunctionForwardRef = (fn: () => void) => {
12+
const spy = jest.spyOn(React, 'forwardRef').mockImplementation((renderFn =>
13+
Object.assign((props: object) => renderFn(props, null), {
14+
$$typeof: Symbol.for('react.forward_ref'),
15+
render: renderFn,
16+
})) as typeof React.forwardRef);
17+
18+
try {
19+
fn();
20+
} finally {
21+
spy.mockRestore();
22+
}
23+
};
24+
1025
describe('basic', () => {
1126
beforeEach(() => {
1227
styled = resetStyled();
@@ -384,21 +399,11 @@ describe('basic', () => {
384399
expect(Outer.componentStyle).not.toEqual(Inner.componentStyle);
385400
});
386401

387-
it("folds chains when forwardRef returns a function (Preact's react-compat shape, #5736)", () => {
388-
// Preact's react-compat shims React.forwardRef to return a function with
389-
// $$typeof = Symbol.for('react.forward_ref'), where React returns an
390-
// object. styled-components must accept both as styled-component carriers
391-
// so extended-chain folding still happens (and intermediate styles
392-
// continue to apply when `as` overrides the rendered tag).
393-
const originalForwardRef = React.forwardRef;
394-
// @ts-expect-error monkey-patching for the test
395-
React.forwardRef = (renderFn: any) => {
396-
const fn = (props: any) => renderFn(props, null);
397-
fn.$$typeof = Symbol.for('react.forward_ref');
398-
fn.render = renderFn;
399-
return fn;
400-
};
401-
try {
402+
it("folds chains when forwardRef returns a function (preact/compat's shape, #5736)", () => {
403+
// styled-components must accept both carriers so extended-chain folding
404+
// still happens (and intermediate styles continue to apply when `as`
405+
// overrides the rendered tag).
406+
withFunctionForwardRef(() => {
402407
const Box = styled.div`
403408
color: red;
404409
`;
@@ -414,10 +419,28 @@ describe('basic', () => {
414419
expect(Box2.foldedComponentIds).toBe(Box.styledComponentId + ' ' + Box1.styledComponentId);
415420
expect(Box2.target).toBe('div');
416421
expect(Box2.componentStyle.baseStyle).toBeDefined();
417-
} finally {
418-
// @ts-expect-error restore
419-
React.forwardRef = originalForwardRef;
420-
}
422+
});
423+
});
424+
425+
it.each<[string, (fn: () => void) => void, (Box: IStyledComponent<'web'>) => object]>([
426+
['the styled component under preact/compat', withFunctionForwardRef, Box => Box],
427+
['a memo HOC that hoists its statics', fn => fn(), Box => hoist(React.memo(Box), Box)],
428+
])('uses %s as a selector', (_label, run, wrap) => {
429+
run(() => {
430+
const Box = styled.div``;
431+
const Parent = styled.div`
432+
${wrap(Box)}:hover {
433+
color: blue;
434+
}
435+
`;
436+
437+
const { container } = render(<Parent />);
438+
const generatedClass = (container.firstChild as HTMLElement).classList[1];
439+
440+
expect(getRenderedCSS()).toBe(
441+
`.${generatedClass} .${Box.styledComponentId}:hover {\n color: blue;\n}`
442+
);
443+
});
421444
});
422445

423446
it('should not fold components if there is an interim HOC', () => {

‎packages/styled-components/src/utils/flatten.ts‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import {
44
Dict,
55
ExecutionContext,
66
Interpolation,
7-
IStyledComponent,
87
RuleSet,
98
Stringifier,
109
} from '../types';
@@ -16,7 +15,7 @@ import isFunction from './isFunction';
1615
import isKeyframes from './isKeyframes';
1716
import isPlainObject from './isPlainObject';
1817
import isStatelessFunction from './isStatelessFunction';
19-
import isStyledComponent from './isStyledComponent';
18+
import { hasStyledComponentBrand } from './isStyledComponent';
2019

2120
/**
2221
* It's falsish not falsy because 0 is allowed.
@@ -81,19 +80,23 @@ export default function flatten<Props extends object>(
8180
return result;
8281
}
8382

84-
const t = typeof chunk;
85-
86-
if (t === 'string') {
87-
result.push(chunk as string);
83+
if (typeof chunk === 'string') {
84+
result.push(chunk);
8885
return result;
8986
}
9087

91-
if (t === 'function') {
88+
if (typeof chunk === 'function') {
9289
if (isClientReference(chunk)) {
9390
if (process.env.NODE_ENV !== 'production') warnClientReference(chunk);
9491
return result;
9592
}
9693

94+
// preact/compat's forwardRef and function HOCs both carry the brand on a function.
95+
if (hasStyledComponentBrand(chunk)) {
96+
result.push(`.${chunk.styledComponentId}`);
97+
return result;
98+
}
99+
97100
if (isStatelessFunction(chunk) && executionContext) {
98101
const fnResult = (chunk as Function)(executionContext);
99102

@@ -114,7 +117,7 @@ export default function flatten<Props extends object>(
114117

115118
return flatten<Props>(fnResult, executionContext, styleSheet, stylisInstance, result);
116119
} else {
117-
result.push(chunk as unknown as IStyledComponent<'web'>);
120+
result.push(chunk);
118121
return result;
119122
}
120123
}
@@ -126,8 +129,8 @@ export default function flatten<Props extends object>(
126129
return result;
127130
}
128131

129-
if (isStyledComponent(chunk)) {
130-
result.push(`.${(chunk as unknown as IStyledComponent<'web', any>).styledComponentId}`);
132+
if (typeof chunk === 'object' && hasStyledComponentBrand(chunk)) {
133+
result.push(`.${chunk.styledComponentId}`);
131134
return result;
132135
}
133136

‎packages/styled-components/src/utils/isStaticRules.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,10 @@
11
import { RuleSet } from '../types';
22
import isFunction from './isFunction';
3-
import isStyledComponent from './isStyledComponent';
43

4+
/** A function left in the rules is an interpolation: `css()` has already turned styled components into selectors. */
55
export default function isStaticRules<Props extends object>(rules: RuleSet<Props>) {
66
for (let i = 0; i < rules.length; i += 1) {
7-
const rule = rules[i];
8-
9-
if (isFunction(rule) && !isStyledComponent(rule)) {
10-
// functions are allowed to be static if they're just being
11-
// used to get the classname of a nested styled component
12-
return false;
13-
}
7+
if (isFunction(rules[i])) return false;
148
}
159

1610
return true;

‎packages/styled-components/src/utils/isStyledComponent.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,29 @@ const REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
55
/**
66
* Type guard that returns true if the target is a styled component.
77
*
8-
* Accepts both `object` and `function` carriers because Preact's react-compat
8+
* Accepts both `object` and `function` carriers because preact/compat's
99
* `forwardRef` returns a function while React's returns an object (#5736).
10-
* `$$typeof` is checked alongside the `styledComponentId` brand so that HOCs
11-
* which hoist non-React statics from a styled component (and therefore inherit
12-
* `styledComponentId`) are not mistaken for real styled components - those
13-
* HOCs do not carry the forward-ref `$$typeof`.
10+
* `$$typeof` is checked alongside the `styledComponentId` brand so that function
11+
* and `memo` HOCs which hoist the brand from a styled component are not folded
12+
* into its chain. A `forwardRef` HOC carries both, so it is folded and its own
13+
* render is skipped.
1414
*/
1515
export default function isStyledComponent(target: any): target is StyledComponentBrand {
1616
return (
1717
target != null &&
1818
(typeof target === 'object' || typeof target === 'function') &&
1919
target.$$typeof === REACT_FORWARD_REF_TYPE &&
20-
'styledComponentId' in target
20+
hasStyledComponentBrand(target)
2121
);
2222
}
23+
24+
/**
25+
* True for anything that renders with a styled component's class: the component
26+
* itself, or an HOC that hoisted its statics. For selectors only; chain folding
27+
* needs `isStyledComponent`, since an HOC's own render must still run.
28+
*/
29+
export function hasStyledComponentBrand(
30+
target: object
31+
): target is { readonly styledComponentId: string } {
32+
return 'styledComponentId' in target;
33+
}

0 commit comments

Comments
 (0)