Skip to content
Open
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
4 changes: 2 additions & 2 deletions src/Dom/dynamicCSS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const APPEND_ORDER = 'data-rc-order';
const APPEND_PRIORITY = 'data-rc-priority';
const MARK_KEY = `rc-util-key`;

const containerCache = new Map<ContainerType, Node & ParentNode>();
let containerCache = new WeakMap<ContainerType, Node & ParentNode>();

export type ContainerType = Element | ShadowRoot;
export type Prepend = boolean | 'queue';
Expand Down Expand Up @@ -155,7 +155,7 @@ function syncRealContainer(container: ContainerType, option: Options) {
* manually clear container cache to avoid global cache in unit testes
*/
export function clearContainerCache() {
containerCache.clear();
containerCache = new WeakMap<ContainerType, Node & ParentNode>();
}

export function updateCSS(
Expand Down
43 changes: 43 additions & 0 deletions tests/dynamicCSS.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -235,4 +235,47 @@ describe('dynamicCSS', () => {
expect(targetContainer.contains(SecondStyle)).toBeTruthy();
});
});
describe('ShadowRoot and container cache', () => {
afterEach(() => {
clearContainerCache();
const styles = document.querySelectorAll('style');
styles.forEach(style => {
style.parentNode?.removeChild(style);
});
});

it('injects, updates and clears styles within a ShadowRoot container', () => {
const host = document.createElement('div');
document.body.appendChild(host);
const shadowRoot = host.attachShadow({ mode: 'open' });

const style = updateCSS('.shadow-rule { color: blue; }', 'shadow-key', {
attachTo: shadowRoot,
});

expect(shadowRoot.contains(style)).toBeTruthy();
expect(document.head.querySelector('style')).toBeFalsy();
expect(style.innerHTML).toEqual('.shadow-rule { color: blue; }');

// In-place update within shadowRoot
updateCSS('.shadow-rule { color: red; }', 'shadow-key', {
attachTo: shadowRoot,
});
expect(shadowRoot.querySelectorAll('style')).toHaveLength(1);
expect(style.innerHTML).toEqual('.shadow-rule { color: red; }');

// clearContainerCache should reset WeakMap cache without breaking subsequent operations
clearContainerCache();
updateCSS('.shadow-rule { color: green; }', 'shadow-key', {
attachTo: shadowRoot,
});
expect(shadowRoot.querySelectorAll('style')).toHaveLength(1);
expect(style.innerHTML).toEqual('.shadow-rule { color: green; }');

removeCSS('shadow-key', { attachTo: shadowRoot });
expect(shadowRoot.querySelector('style')).toBeFalsy();

document.body.removeChild(host);
});
});
});