Skip to content

Commit

Permalink
useWindowInnerSize actually ServerSideReady
Browse files Browse the repository at this point in the history
  • Loading branch information
garronej committed Jul 8, 2023
1 parent 670258c commit b6ed437
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 13 deletions.
38 changes: 28 additions & 10 deletions src/tools/useWindowInnerSize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,33 @@ import { useState } from "react";
import { Evt } from "evt";
import { useEvt } from "evt/hooks/useEvt";
import { isBrowser } from "./isBrowser";

/** Returns 0 values on the server side */
export function useWindowInnerSize() {

const [dimensions, setDimensions] = useState(() => ({
"windowInnerWidth": !isBrowser ? 0 : window.innerWidth,
"windowInnerHeight": !isBrowser ? 0 : window.innerHeight
}));
import { assert } from "tsafe/assert";
import { symToStr } from "tsafe/symToStr";

export function useWindowInnerSize<P extends { isSsrSetup: boolean; }>(
/** Default: { isSsrSetup: false }, We assume we are in a SPA */
params?: P
): P extends { isSsrSetup: true; } ? {
windowInnerWidth: number | undefined;
windowInnerHeight: number | undefined;
}: {
windowInnerWidth: number;
windowInnerHeight: number;
} {

const { isSsrSetup = false } = params ?? {};

const [dimensions, setDimensions] = useState(() =>
isSsrSetup ?
{
"windowInnerWidth": undefined,
"windowInnerHeight": undefined
} :
(assert(isBrowser, `${symToStr({ useWindowInnerSize })} should be used in SSR mode`), {
"windowInnerWidth": window.innerWidth,
"windowInnerHeight": window.innerHeight
})
);

useEvt(ctx =>
Evt.from(ctx, window, "resize")
Expand All @@ -22,8 +41,7 @@ export function useWindowInnerSize() {
[]
);

//@ts-expect-error
return dimensions;



}
14 changes: 11 additions & 3 deletions src/useWindowInnerSize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,19 @@
import { useWindowInnerSize as useRealWindowInnerSize } from "./tools/useWindowInnerSize";
import { useViewPortState } from "./ViewPortAdapter";

/** Returns 0 values on the server side */
export function useWindowInnerSize() {
export function useWindowInnerSize<P extends { isSsrSetup: boolean; }>(
/** Default: { isSsrSetup: false }, We assume we are in a SPA */
params?: P
): P extends { isSsrSetup: true; } ? {
windowInnerWidth: number | undefined;
windowInnerHeight: number | undefined;
} : {
windowInnerWidth: number;
windowInnerHeight: number;
} {

const { viewPortState } = useViewPortState();
const { windowInnerWidth, windowInnerHeight } = useRealWindowInnerSize();
const { windowInnerWidth, windowInnerHeight } = useRealWindowInnerSize(params);

return viewPortState !== undefined ?
{
Expand Down

0 comments on commit b6ed437

Please sign in to comment.