Skip to content

Commit

Permalink
Include scrollbar width in media calculation (#698)
Browse files Browse the repository at this point in the history
Turns out that the difference in the returned values was due to the fact
that CSS includes the scrollbar width in the media size calculation, and
the hook wasn't doing that.

Should not impact the app in any negative way, but it is worth a quick
check.
  • Loading branch information
danielfdsilva authored Oct 13, 2023
2 parents a52e077 + 84e13f2 commit 1bb5c5e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
7 changes: 6 additions & 1 deletion app/scripts/utils/use-media-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useEffect, useMemo } from 'react';
import { useTheme } from 'styled-components';
import useDimensions from 'react-cool-dimensions';
import { DevseedUIThemeMediaRanges } from '@devseed-ui/theme-provider';
import { getScrollbarWidth } from './use-scrollbar-width-css';

interface MediaBreakpointStatus {
current: keyof DevseedUIThemeMediaRanges;
Expand Down Expand Up @@ -82,11 +83,15 @@ export function useMediaQuery() {
observe(document.body);
}, [observe]);

// Account for the scrollbar width because the css media queries will.
const scrollbarWidth = getScrollbarWidth();

// On first mount react-cool-dimension will return a width of 0, which breaks
// the media queries styles because there's a mismatch between the css media
// queries and the js.
const width =
calculatedWidth || (typeof window !== 'undefined' ? window.innerWidth : 0);
calculatedWidth + scrollbarWidth ||
(typeof window !== 'undefined' ? window.innerWidth + scrollbarWidth : 0);

const rangeBooleans = useMemo(
() =>
Expand Down
25 changes: 18 additions & 7 deletions app/scripts/utils/use-scrollbar-width-css.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import { useEffect } from 'react';

let scrollbarWidthCache;
export function getScrollbarWidth() {
if (scrollbarWidthCache !== undefined) {
return scrollbarWidthCache;
}

const el = document.createElement('div');
el.style.cssText = 'overflow:scroll; visibility:hidden; position:absolute;';
document.body.appendChild(el);
const width = el.offsetWidth - el.clientWidth;
el.remove();

scrollbarWidthCache = width;
return width;
}

export function useScrollbarWidthAsCssVar(varName = '--scrollbar-width') {
useEffect(() => {
const el = document.createElement('div');
el.style.cssText = 'overflow:scroll; visibility:hidden; position:absolute;';
document.body.appendChild(el);
const width = el.offsetWidth - el.clientWidth;
el.remove();

const width = getScrollbarWidth();
document.documentElement.style.setProperty(varName, width + 'px');

() => {
return () => {
document.documentElement.style.removeProperty(varName);
};
}, [varName]);
Expand Down

0 comments on commit 1bb5c5e

Please sign in to comment.