Skip to content

Commit f84f3fa

Browse files
federico-fioriniquantizorclaude
authored
fix: Shadow DOM SSR Hydration Support (#5656)
* fix style tag selector target * refactor * bump maxSize * fix tests * rehydrate only when target container changes * add changeset * better type safety * fix: support Shadow DOM in global style cleanup and getSheet fallback - Pass insertion target to removeGlobalStyleTag so it queries the correct container (ShadowRoot or document) when cleaning up SSR-rendered global style tags on unmount - Use tag.getRootNode() in getSheet fallback so the Firefox quirk path checks the shadow root's styleSheets instead of only document.styleSheets - Add tests for both fixes and getSheet/makeStyleTag in shadow DOM Co-Authored-By: Claude Opus 4.6 <[email protected]> --------- Co-authored-by: Evan Jacobs <[email protected]> Co-authored-by: Evan Jacobs <[email protected]> Co-authored-by: Claude Opus 4.6 <[email protected]>
1 parent 43a5b4b commit f84f3fa

8 files changed

Lines changed: 550 additions & 9 deletions

File tree

‎.changeset/hip-mirrors-design.md‎

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+
Fix SSR styles hydration and global style cleanup in Shadow DOM

‎packages/styled-components/src/constructors/createGlobalStyle.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ export default function createGlobalStyle<Props extends object>(
7979

8080
return () => {
8181
globalStyle.removeStyles(instance, ssc.styleSheet);
82-
removeGlobalStyleTag(styledComponentId);
82+
removeGlobalStyleTag(styledComponentId, ssc.styleSheet.options.target);
8383
};
8484
}, [instance, props, ssc.styleSheet, theme, ssc.stylis]);
8585
}

‎packages/styled-components/src/sheet/Rehydration.ts‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,52 @@
11
import { SC_ATTR, SC_ATTR_ACTIVE, SC_ATTR_VERSION, SC_VERSION, SPLITTER } from '../constants';
2+
import { InsertionTarget } from '../types';
23
import { getIdForGroup, setGroupForId } from './GroupIDAllocator';
34
import { Sheet } from './types';
45

56
const SELECTOR = `style[${SC_ATTR}][${SC_ATTR_VERSION}="${SC_VERSION}"]`;
67
const MARKER_RE = new RegExp(`^${SC_ATTR}\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)`);
78

9+
/**
10+
* Type guard to check if a node is a ShadowRoot.
11+
* Uses instanceof when available, with duck-typing fallback for cross-realm scenarios.
12+
*/
13+
const isShadowRoot = (node: InsertionTarget | Node): node is ShadowRoot => {
14+
return (
15+
(typeof ShadowRoot !== 'undefined' && node instanceof ShadowRoot) ||
16+
('host' in node &&
17+
// https://dom.spec.whatwg.org/#dom-node-document_fragment_node
18+
node.nodeType === 11)
19+
);
20+
};
21+
22+
/**
23+
* Extract the container (Document or ShadowRoot) from an InsertionTarget.
24+
* If the target is a ShadowRoot, return it directly.
25+
* If the target is an HTMLElement, return its root node if it's a ShadowRoot, otherwise return document.
26+
*/
27+
export const getRehydrationContainer = (
28+
target?: InsertionTarget | undefined
29+
): Document | ShadowRoot => {
30+
if (!target) {
31+
return document;
32+
}
33+
34+
// Check if target is a ShadowRoot
35+
if (isShadowRoot(target)) {
36+
return target;
37+
}
38+
39+
// Check if target is an HTMLElement inside a ShadowRoot
40+
if ('getRootNode' in target) {
41+
const root = (target as HTMLElement).getRootNode();
42+
if (isShadowRoot(root)) {
43+
return root;
44+
}
45+
}
46+
47+
return document;
48+
};
49+
850
export const outputSheet = (sheet: Sheet) => {
951
const tag = sheet.getTag();
1052
const { length } = tag;
@@ -79,7 +121,8 @@ const rehydrateSheetFromTag = (sheet: Sheet, style: HTMLStyleElement) => {
79121
};
80122

81123
export const rehydrateSheet = (sheet: Sheet) => {
82-
const nodes = document.querySelectorAll(SELECTOR);
124+
const container = getRehydrationContainer(sheet.options.target);
125+
const nodes = container.querySelectorAll(SELECTOR);
83126

84127
for (let i = 0, l = nodes.length; i < l; i++) {
85128
const node = nodes[i] as any as HTMLStyleElement;

‎packages/styled-components/src/sheet/Sheet.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { EMPTY_OBJECT } from '../utils/empties';
44
import { setToString } from '../utils/setToString';
55
import { makeGroupedTag } from './GroupedTag';
66
import { getGroupForId } from './GroupIDAllocator';
7-
import { outputSheet, rehydrateSheet } from './Rehydration';
7+
import { getRehydrationContainer, outputSheet, rehydrateSheet } from './Rehydration';
88
import { makeTag } from './Tag';
99
import { GroupedTag, Sheet, SheetOptions } from './types';
1010

@@ -69,11 +69,25 @@ export default class StyleSheet implements Sheet {
6969
}
7070

7171
reconstructWithOptions(options: SheetConstructorArgs, withNames = true) {
72-
return new StyleSheet(
72+
const newSheet = new StyleSheet(
7373
{ ...this.options, ...options },
7474
this.gs,
7575
(withNames && this.names) || undefined
7676
);
77+
78+
// If we're reconstructing with a new target on the client, check if the container changed
79+
// This handles the case where StyleSheetManager's target prop changes (e.g., from undefined to shadowRoot)
80+
// We only rehydrate if the container (Document or ShadowRoot) actually changes
81+
if (!this.server && IS_BROWSER && options.target !== this.options.target) {
82+
const oldContainer = getRehydrationContainer(this.options.target);
83+
const newContainer = getRehydrationContainer(options.target);
84+
85+
if (oldContainer !== newContainer) {
86+
rehydrateSheet(newSheet);
87+
}
88+
}
89+
90+
return newSheet;
7791
}
7892

7993
allocateGSInstance(id: string) {

‎packages/styled-components/src/sheet/dom.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,11 @@ export const getSheet = (tag: HTMLStyleElement): CSSStyleSheet => {
3636
return tag.sheet as any as CSSStyleSheet;
3737
}
3838

39-
// Avoid Firefox quirk where the style element might not have a sheet property
40-
const { styleSheets } = document;
39+
// Avoid Firefox quirk where the style element might not have a sheet property.
40+
// Use the tag's root node to find styleSheets — document.styleSheets doesn't
41+
// include sheets inside shadow roots.
42+
const root = tag.getRootNode() as Document | ShadowRoot;
43+
const styleSheets = root.styleSheets ?? document.styleSheets;
4144
for (let i = 0, l = styleSheets.length; i < l; i++) {
4245
const sheet = styleSheets[i];
4346
if (sheet.ownerNode === tag) {
@@ -49,9 +52,10 @@ export const getSheet = (tag: HTMLStyleElement): CSSStyleSheet => {
4952
};
5053

5154
/** Remove a GlobalStyle's SSR-rendered inline style tag(s) from the DOM */
52-
export const removeGlobalStyleTag = (componentId: string): void => {
55+
export const removeGlobalStyleTag = (componentId: string, target?: InsertionTarget): void => {
5356
if (typeof document === 'undefined') return;
5457

55-
const styleTags = document.querySelectorAll(`style[data-styled-global="${componentId}"]`);
58+
const container = target ?? document;
59+
const styleTags = container.querySelectorAll(`style[data-styled-global="${componentId}"]`);
5660
styleTags.forEach(tag => tag.remove());
5761
};

‎packages/styled-components/src/sheet/test/Rehydration.test.tsx‎

Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,4 +143,237 @@ data-styled.g23[id=\"sc-kqxcKS\"]{content:\"a,\"}/*!sc*/
143143
const sheet = new StyleSheet({ isServer: true });
144144
rehydrateSheet(sheet);
145145
});
146+
147+
describe('Shadow DOM support', () => {
148+
it('rehydrates from Shadow DOM when container is provided', () => {
149+
// Create a host element and attach a shadow root
150+
const hostElement = document.createElement('div');
151+
document.body.appendChild(hostElement);
152+
const shadowRoot = hostElement.attachShadow({ mode: 'open' });
153+
154+
// Add server-rendered styles to the shadow root
155+
shadowRoot.innerHTML = `
156+
<style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}">
157+
.shadow-a {}/*!sc*/
158+
${SC_ATTR}.g11[id="shadowIdA"]{content:"shadowNameA,"}/*!sc*/
159+
</style>
160+
`;
161+
162+
const styleInShadow = shadowRoot.querySelector('style');
163+
expect(styleInShadow).not.toBeNull();
164+
expect(styleInShadow!.parentNode).toBe(shadowRoot);
165+
166+
// Create sheet with shadow root as target
167+
const sheet = new StyleSheet({ isServer: true, target: shadowRoot });
168+
169+
// Rehydrate from the shadow root
170+
rehydrateSheet(sheet);
171+
172+
// Verify the styles were rehydrated
173+
expect(GroupIDAllocator.getIdForGroup(11)).toBe('shadowIdA');
174+
expect(sheet.hasNameForId('shadowIdA', 'shadowNameA')).toBe(true);
175+
expect(sheet.getTag().tag.length).toBe(1);
176+
expect(sheet.getTag().getGroup(11)).toBe('.shadow-a {}/*!sc*/\n');
177+
178+
// Verify the old tag was removed from shadow root
179+
expect(styleInShadow!.parentNode).toBe(null);
180+
181+
// Cleanup
182+
document.body.removeChild(hostElement);
183+
});
184+
185+
it('does not find styles in Shadow DOM when searching document', () => {
186+
// Create a host element and attach a shadow root
187+
const hostElement = document.createElement('div');
188+
document.body.appendChild(hostElement);
189+
const shadowRoot = hostElement.attachShadow({ mode: 'open' });
190+
191+
// Add server-rendered styles to the shadow root
192+
shadowRoot.innerHTML = `
193+
<style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}">
194+
.shadow-b {}/*!sc*/
195+
${SC_ATTR}.g12[id="shadowIdB"]{content:"shadowNameB,"}/*!sc*/
196+
</style>
197+
`;
198+
199+
// Create sheet without target (defaults to document)
200+
const sheet = new StyleSheet({ isServer: true });
201+
202+
// Rehydrate from document (default) - should NOT find shadow DOM styles
203+
rehydrateSheet(sheet);
204+
205+
// Verify the styles were NOT rehydrated
206+
expect(GroupIDAllocator.getIdForGroup(12)).toBe(undefined);
207+
expect(sheet.hasNameForId('shadowIdB', 'shadowNameB')).toBe(false);
208+
expect(sheet.getTag().tag.length).toBe(0);
209+
210+
// Cleanup
211+
document.body.removeChild(hostElement);
212+
});
213+
214+
it('removes global style tags inside Shadow DOM when target is provided', async () => {
215+
const { removeGlobalStyleTag } = await import('../dom');
216+
217+
// Create a host element and attach a shadow root
218+
const hostElement = document.createElement('div');
219+
document.body.appendChild(hostElement);
220+
const shadowRoot = hostElement.attachShadow({ mode: 'open' });
221+
222+
// Simulate SSR-rendered global style tag inside shadow root
223+
const globalStyleTag = document.createElement('style');
224+
globalStyleTag.setAttribute('data-styled-global', 'sc-global-test');
225+
globalStyleTag.textContent = 'body { margin: 0; }';
226+
shadowRoot.appendChild(globalStyleTag);
227+
228+
// Also add one to the document
229+
const docStyleTag = document.createElement('style');
230+
docStyleTag.setAttribute('data-styled-global', 'sc-global-test');
231+
docStyleTag.textContent = 'body { margin: 0; }';
232+
document.head.appendChild(docStyleTag);
233+
234+
// With target, removeGlobalStyleTag finds the shadow DOM tag
235+
removeGlobalStyleTag('sc-global-test', shadowRoot);
236+
expect(globalStyleTag.parentNode).toBe(null);
237+
238+
// Without target, it cleans up document-level tags
239+
removeGlobalStyleTag('sc-global-test');
240+
expect(docStyleTag.parentNode).toBe(null);
241+
242+
// Cleanup
243+
document.body.removeChild(hostElement);
244+
});
245+
246+
it('rehydrates from both document and Shadow DOM separately', () => {
247+
// Add styles to document
248+
document.head.innerHTML = `
249+
<style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}">
250+
.doc-style {}/*!sc*/
251+
${SC_ATTR}.g10[id="docId"]{content:"docName,"}/*!sc*/
252+
</style>
253+
`;
254+
255+
// Create shadow root with styles
256+
const hostElement = document.createElement('div');
257+
document.body.appendChild(hostElement);
258+
const shadowRoot = hostElement.attachShadow({ mode: 'open' });
259+
shadowRoot.innerHTML = `
260+
<style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}">
261+
.shadow-style {}/*!sc*/
262+
${SC_ATTR}.g20[id="shadowId"]{content:"shadowName,"}/*!sc*/
263+
</style>
264+
`;
265+
266+
// First sheet rehydrates from document
267+
const docSheet = new StyleSheet({ isServer: true });
268+
rehydrateSheet(docSheet);
269+
expect(docSheet.hasNameForId('docId', 'docName')).toBe(true);
270+
expect(docSheet.hasNameForId('shadowId', 'shadowName')).toBe(false);
271+
272+
// Second sheet rehydrates from shadow root
273+
const shadowSheet = new StyleSheet({ isServer: true, target: shadowRoot });
274+
rehydrateSheet(shadowSheet);
275+
expect(shadowSheet.hasNameForId('shadowId', 'shadowName')).toBe(true);
276+
expect(shadowSheet.hasNameForId('docId', 'docName')).toBe(false);
277+
278+
// Cleanup
279+
document.body.removeChild(hostElement);
280+
});
281+
});
282+
});
283+
284+
describe('rehydrateSheet with different target types', () => {
285+
it('rehydrates from document when no target is provided', () => {
286+
document.head.innerHTML = `
287+
<style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}">
288+
.doc-no-target {}/*!sc*/
289+
${SC_ATTR}.g30[id="docNoTargetId"]{content:"docNoTargetName,"}/*!sc*/
290+
</style>
291+
`;
292+
293+
const sheet = new StyleSheet({ isServer: true });
294+
rehydrateSheet(sheet);
295+
296+
expect(sheet.hasNameForId('docNoTargetId', 'docNoTargetName')).toBe(true);
297+
});
298+
299+
it('rehydrates from document when target is undefined', () => {
300+
document.head.innerHTML = `
301+
<style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}">
302+
.doc-undefined {}/*!sc*/
303+
${SC_ATTR}.g31[id="docUndefinedId"]{content:"docUndefinedName,"}/*!sc*/
304+
</style>
305+
`;
306+
307+
const sheet = new StyleSheet({ isServer: true, target: undefined });
308+
rehydrateSheet(sheet);
309+
310+
expect(sheet.hasNameForId('docUndefinedId', 'docUndefinedName')).toBe(true);
311+
});
312+
313+
it('rehydrates from ShadowRoot when target is a ShadowRoot', () => {
314+
const hostElement = document.createElement('div');
315+
document.body.appendChild(hostElement);
316+
const shadowRoot = hostElement.attachShadow({ mode: 'open' });
317+
318+
shadowRoot.innerHTML = `
319+
<style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}">
320+
.shadow-root-target {}/*!sc*/
321+
${SC_ATTR}.g32[id="shadowRootId"]{content:"shadowRootName,"}/*!sc*/
322+
</style>
323+
`;
324+
325+
const sheet = new StyleSheet({ isServer: true, target: shadowRoot });
326+
rehydrateSheet(sheet);
327+
328+
expect(sheet.hasNameForId('shadowRootId', 'shadowRootName')).toBe(true);
329+
330+
// Cleanup
331+
document.body.removeChild(hostElement);
332+
});
333+
334+
it('rehydrates from ShadowRoot when target is an HTMLElement inside a ShadowRoot', () => {
335+
const hostElement = document.createElement('div');
336+
document.body.appendChild(hostElement);
337+
const shadowRoot = hostElement.attachShadow({ mode: 'open' });
338+
339+
// Add styles first
340+
shadowRoot.innerHTML = `
341+
<style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}">
342+
.shadow-inner-element {}/*!sc*/
343+
${SC_ATTR}.g33[id="shadowInnerId"]{content:"shadowInnerName,"}/*!sc*/
344+
</style>
345+
`;
346+
347+
// Then create and append the inner div (so it's not lost)
348+
const innerDiv = document.createElement('div');
349+
shadowRoot.appendChild(innerDiv);
350+
351+
const sheet = new StyleSheet({ isServer: true, target: innerDiv });
352+
rehydrateSheet(sheet);
353+
354+
expect(sheet.hasNameForId('shadowInnerId', 'shadowInnerName')).toBe(true);
355+
356+
// Cleanup
357+
document.body.removeChild(hostElement);
358+
});
359+
360+
it('rehydrates from document when target is a regular HTMLElement', () => {
361+
const regularDiv = document.createElement('div');
362+
document.body.appendChild(regularDiv);
363+
364+
document.head.innerHTML = `
365+
<style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}">
366+
.regular-element {}/*!sc*/
367+
${SC_ATTR}.g34[id="regularId"]{content:"regularName,"}/*!sc*/
368+
</style>
369+
`;
370+
371+
const sheet = new StyleSheet({ isServer: true, target: regularDiv });
372+
rehydrateSheet(sheet);
373+
374+
expect(sheet.hasNameForId('regularId', 'regularName')).toBe(true);
375+
376+
// Cleanup
377+
document.body.removeChild(regularDiv);
378+
});
146379
});

0 commit comments

Comments
 (0)