fix: remove re-creating new shadow-dom on page change

This commit is contained in:
Bilawal Hameed
2020-07-03 16:18:34 +02:00
parent 52f4d37b8e
commit a662bc1639
3 changed files with 12 additions and 32 deletions
@@ -69,7 +69,7 @@ export const Reader = () => {
const location = useLocation();
const { componentId, '*': path } = useParams();
const [ref, shadowRoot] = useShadowDom(componentId, path);
const [ref, shadowRoot] = useShadowDom();
const navigate = useNavigate();
const normalizedUrl = new URLFormatter(
`${docStorageURL}${location.pathname.replace('/docs', '')}`,
@@ -23,7 +23,7 @@ const ComponentWithoutHook = () => {
};
const ComponentWithHook = () => {
const [ref] = useShadowDom('mkdocs', 'about/license/');
const [ref] = useShadowDom();
return <div data-testid="root" ref={ref} />;
};
@@ -31,19 +31,14 @@ describe('useShadowDom', () => {
it('does not create a Shadow DOM instance', async () => {
const rendered = await renderWithEffects(<ComponentWithoutHook />);
const outerDivElement = rendered.getByTestId('root');
expect(outerDivElement.shadowRoot).not.toBeInstanceOf(ShadowRoot);
expect(outerDivElement.children.length).toBe(0);
const divElement = rendered.getByTestId('root');
expect(divElement.shadowRoot).not.toBeInstanceOf(ShadowRoot);
});
it('create a Shadow DOM instance', async () => {
const rendered = await renderWithEffects(<ComponentWithHook />);
const outerDivElement = rendered.getByTestId('root');
expect(outerDivElement.shadowRoot).not.toBeInstanceOf(ShadowRoot);
expect(outerDivElement.children.length).toBe(1);
const innerDivElement = outerDivElement.children[0];
expect(innerDivElement.shadowRoot).toBeInstanceOf(ShadowRoot);
const divElement = rendered.getByTestId('root');
expect(divElement.shadowRoot).toBeInstanceOf(ShadowRoot);
});
});
+6 -21
View File
@@ -17,30 +17,15 @@
import { useEffect, useRef } from 'react';
import type { RefObject } from 'react';
type IUseShadowDOM = (
componentId: string,
path: string,
) => [RefObject<HTMLDivElement>, ShadowRoot?];
type IUseShadowDOM = () => [RefObject<HTMLDivElement>, ShadowRoot?];
export const useShadowDom: IUseShadowDOM = (componentId, path) => {
export const useShadowDom: IUseShadowDOM = () => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const innerDivElement = document.createElement('div');
innerDivElement.attachShadow({ mode: 'open' });
const divElement = ref.current;
divElement?.attachShadow({ mode: 'open' });
}, []);
const outerDivElement = ref.current;
outerDivElement?.appendChild(innerDivElement);
return function cancel() {
outerDivElement?.removeChild(innerDivElement);
};
}, [componentId, path]);
const shadowRoot =
ref.current?.children && ref.current?.children[0].shadowRoot
? ref.current?.children[0].shadowRoot
: undefined;
return [ref, shadowRoot];
return [ref, ref.current?.shadowRoot || undefined];
};