Skip to content

Commit

Permalink
chore: fix hydration warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisvxd committed Mar 27, 2024
1 parent 3aa30ae commit 204f5e4
Showing 1 changed file with 51 additions and 42 deletions.
93 changes: 51 additions & 42 deletions packages/core/components/Puck/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,53 +99,11 @@ export function Puck<UserConfig extends Config = Config>({
const [initialAppState] = useState<AppState>(() => {
const initial = { ...defaultAppState.ui, ...initialUi };

let clientUiState: Partial<AppState["ui"]> = {};

if (typeof window !== "undefined") {
const viewportWidth = window.innerWidth;

const viewportDifferences = Object.entries(viewports)
.map(([key, value]) => ({
key,
diff: Math.abs(viewportWidth - value.width),
}))
.sort((a, b) => (a.diff > b.diff ? 1 : -1));

const closestViewport = viewportDifferences[0].key;

if (iframe.enabled) {
clientUiState = {
// Hide side bars on mobile
...(window.matchMedia("(min-width: 638px)").matches
? {}
: {
leftSideBarVisible: false,
rightSideBarVisible: false,
}),
viewports: {
...initial.viewports,

current: {
...initial.viewports.current,
height:
initialUi?.viewports?.current?.height ||
viewports[closestViewport].height ||
"auto",
width:
initialUi?.viewports?.current?.width ||
viewports[closestViewport].width,
},
},
};
}
}

return {
...defaultAppState,
data: initialData,
ui: {
...initial,
...clientUiState,
// Store categories under componentList on state to allow render functions and plugins to modify
componentList: config.categories
? Object.entries(config.categories).reduce(
Expand All @@ -167,6 +125,57 @@ export function Puck<UserConfig extends Config = Config>({
};
});

useEffect(() => {
const initial = { ...defaultAppState.ui, ...initialUi };

let clientUiState: Partial<AppState["ui"]> = {};

// Hide side bars on mobile
if (window.matchMedia("(max-width: 638px)").matches) {
clientUiState = {
...clientUiState,
leftSideBarVisible: false,
rightSideBarVisible: false,
};
}

const viewportWidth = window.innerWidth;

const viewportDifferences = Object.entries(viewports)
.map(([key, value]) => ({
key,
diff: Math.abs(viewportWidth - value.width),
}))
.sort((a, b) => (a.diff > b.diff ? 1 : -1));

const closestViewport = viewportDifferences[0].key;

if (iframe.enabled) {
clientUiState = {
...clientUiState,
viewports: {
...initial.viewports,

current: {
...initial.viewports.current,
height:
initialUi?.viewports?.current?.height ||
viewports[closestViewport].height ||
"auto",
width:
initialUi?.viewports?.current?.width ||
viewports[closestViewport].width,
},
},
};
}

dispatch({
type: "setUi",
ui: clientUiState,
});
}, []);

const [appState, dispatch] = useReducer<StateReducer>(
reducer,
flushZones(initialAppState)
Expand Down

0 comments on commit 204f5e4

Please sign in to comment.