Skip to content

Commit

Permalink
next: body scroll padding/margin (#514)
Browse files Browse the repository at this point in the history
  • Loading branch information
huntabyte authored Apr 26, 2024
1 parent f605ff7 commit 7486b06
Showing 1 changed file with 20 additions and 15 deletions.
35 changes: 20 additions & 15 deletions packages/bits-ui/src/lib/internal/useBodyScrollLock.svelte.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Map } from "svelte/reactivity";
import { onDestroy } from "svelte";
import { onDestroy, untrack } from "svelte";
import { box } from "runed";
import type { Fn } from "./types.js";
import { isBrowser, isIOS } from "./is.js";
Expand All @@ -16,7 +16,6 @@ export type ScrollBodyOption = {

const useBodyLockStackCount = createSharedHook(() => {
const map = new Map<string, boolean>();
let initialOverflow = $state<string | undefined>();

const locked = $derived.by(() => {
for (const value of map.values()) {
Expand All @@ -27,15 +26,17 @@ const useBodyLockStackCount = createSharedHook(() => {
return false;
});

let initialBodyStyle: Partial<CSSStyleDeclaration> = $state<Partial<CSSStyleDeclaration>>({});

let stopTouchMoveListener: Fn | null = null;

function resetBodyStyle() {
if (!isBrowser) return;
document.body.style.paddingRight = "";
document.body.style.marginRight = "";
document.body.style.pointerEvents = "";
document.body.style.paddingRight = initialBodyStyle.paddingRight ?? "";
document.body.style.marginRight = initialBodyStyle.marginRight ?? "";
document.body.style.pointerEvents = initialBodyStyle.pointerEvents ?? "";
document.body.style.removeProperty("--scrollbar-width");
document.body.style.overflow = initialOverflow ?? "";
document.body.style.overflow = initialBodyStyle.overflow ?? "";
isIOS && stopTouchMoveListener?.();
}

Expand All @@ -49,18 +50,22 @@ const useBodyLockStackCount = createSharedHook(() => {
return;
}

if (initialOverflow === undefined) {
initialOverflow = document.body.style.overflow;
}
untrack(() => {
const bodyStyle = getComputedStyle(document.body);
initialBodyStyle.overflow = bodyStyle.overflow;
initialBodyStyle.paddingRight = bodyStyle.paddingRight;
initialBodyStyle.marginRight = bodyStyle.marginRight;
initialBodyStyle.pointerEvents = bodyStyle.pointerEvents;
});

// TODO: account for RTL direction, etc.
const verticalScrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
const defaultConfig = {
padding: verticalScrollbarWidth,
margin: 0,
};
const paddingRight = Number.parseInt(initialBodyStyle.paddingRight ?? "0", 10);

// TODO: give user ability to customize the config via global context
const config = defaultConfig;
const config = {
padding: paddingRight + verticalScrollbarWidth,
margin: Number.parseInt(initialBodyStyle.marginRight ?? "0", 10),
};

if (verticalScrollbarWidth > 0) {
document.body.style.paddingRight = `${config.padding}px`;
Expand Down

0 comments on commit 7486b06

Please sign in to comment.