Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include scrollbar width in media calculation #698

Merged
merged 1 commit into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading