Skip to content

Commit

Permalink
Fix some CSS sync issues when switching to the iframed mode (tajo#196)
Browse files Browse the repository at this point in the history
* Fix some CSS sync issues when switching to the iframed mode

* Fix some style nodes were missing in sync
  • Loading branch information
tajo authored Jul 19, 2022
1 parent f92e9d8 commit f92ed78
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
5 changes: 5 additions & 0 deletions .changeset/lovely-pillows-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ladle/react": patch
---

Fix some CSS sync issue when switching into iframed version.
24 changes: 13 additions & 11 deletions packages/ladle/lib/app/src/story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import config from "./get-config";
import NoStories from "./no-stories";
import { ModeState, ThemeState } from "../../shared/types";

const frameDefaultHead = `<base target="_parent" />`;

const StoryFrame: React.FC<{
children: React.ReactElement;
active: boolean;
Expand All @@ -23,10 +21,7 @@ const StoryFrame: React.FC<{
return (
<Frame
title={`Story ${story}`}
initialContent={`<!DOCTYPE html><html><head>${document.head.innerHTML.replace(
/<script[\s\S]*?>[\s\S]*?<\/script>/gi,
"",
)}${frameDefaultHead}</head><body style="margin:0"><div id="root"></div></body></html>`}
initialContent={`<!DOCTYPE html><html><head><base target="_parent" /></head><body style="margin:0"><div id="root"></div></body></html>`}
mountTarget="#root"
style={{
height: width ? "calc(100% - 128px)" : "100%",
Expand Down Expand Up @@ -56,11 +51,18 @@ const SynchronizeHead: React.FC<{
const { window: storyWindow } = useFrame();
const syncHead = () => {
if (!storyWindow) return;
storyWindow.document.head.innerHTML =
`${document.head.innerHTML}${frameDefaultHead}`.replace(
/<script[\s\S]*?>[\s\S]*?<\/script>/gi,
"",
);
[...(document.head.children as any)].forEach((child) => {
if (
child.tagName === "STYLE" ||
(child.tagName === "LINK" &&
(child.getAttribute("type") === "text/css" ||
child.getAttribute("rel") === "stylesheet"))
) {
storyWindow.document.head.appendChild(
child.cloneNode(true),
) as HTMLStyleElement;
}
});
};
React.useEffect(() => {
if (active) {
Expand Down

0 comments on commit f92ed78

Please sign in to comment.