Skip to content

Commit

Permalink
feat: load initial styles via initialContent and remove onStylesLoade…
Browse files Browse the repository at this point in the history
…d API
  • Loading branch information
chrisvxd committed Mar 24, 2024
1 parent 8ba43c5 commit c91ca0c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 31 deletions.
6 changes: 0 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,6 @@ Shares an API with [react-frame-component](https://github.com/ryanseddon/react-f

Print debug messages when mounting styles to the console

### onStylesLoaded

`onStylesLoaded: function`

A callback that triggers when the initial styles [are loaded](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#stylesheet_load_events)

## License

MIT © [Measured Corporation Ltd](https://measured.co)
36 changes: 11 additions & 25 deletions src/AutoFrameComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { ReactNode, useLayoutEffect } from "react";
import React, { ReactNode, useLayoutEffect, useState } from "react";
import Frame, { FrameComponentProps, useFrame } from "react-frame-component";
import hash from "object-hash";

Expand All @@ -14,14 +14,12 @@ const collectStyles = (doc: Document) => {
return collected;
};

const CopyHostStyles = ({
const SyncHostStyles = ({
children,
debug = false,
onStylesLoaded = () => null,
}: {
children: ReactNode;
debug?: boolean;
onStylesLoaded?: () => void;
}) => {
const { document: doc, window: win } = useFrame();

Expand Down Expand Up @@ -133,21 +131,6 @@ const CopyHostStyles = ({

const parentDocument = win!.parent.document;

const collectedStyles = collectStyles(parentDocument);

let mountedCounter = 0;

// Add new style tags
collectedStyles.forEach((styleNode) => {
addEl(styleNode as HTMLElement, () => {
mountedCounter += 1;

if (mountedCounter === collectedStyles.length) {
onStylesLoaded();
}
});
});

observer.observe(parentDocument.head, { childList: true, subtree: true });

return () => {
Expand All @@ -160,18 +143,21 @@ const CopyHostStyles = ({

export type AutoFrameProps = FrameComponentProps & {
debug?: boolean;
onStylesLoaded?: () => void;
};

export default React.forwardRef<HTMLIFrameElement, AutoFrameProps>(function (
{ children, debug, onStylesLoaded, ...props }: AutoFrameProps,
{ children, debug, ...props }: AutoFrameProps,
ref
) {
const [initialStyles] = useState(collectStyles(document));

const initialContent = `<!DOCTYPE html><html><head>${initialStyles
.map((el) => el.outerHTML)
.join("")}</head><body><div></div></body></html>`;

return (
<Frame {...props} ref={ref}>
<CopyHostStyles debug={debug} onStylesLoaded={onStylesLoaded}>
{children}
</CopyHostStyles>
<Frame initialContent={initialContent} {...props} ref={ref}>
<SyncHostStyles debug={debug}>{children}</SyncHostStyles>
</Frame>
);
});

0 comments on commit c91ca0c

Please sign in to comment.