Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
inokawa committed Jan 13, 2024
1 parent 08ca50b commit a74242d
Showing 1 changed file with 28 additions and 18 deletions.
46 changes: 28 additions & 18 deletions src/core/scroller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,33 @@ export type WindowScroller = {
_fixScrollJump: (jump: number) => void;
};

const calcOffsetToViewport = (
node: HTMLElement,
viewport: HTMLElement,
isHorizontal: boolean,
offset: number = 0
): number => {
// TODO calc offset only when it changes (maybe impossible)
const offsetKey = isHorizontal ? "offsetLeft" : "offsetTop";
const offsetSum =
offset +
(isHorizontal && isRTLDocument()
? window.innerWidth - node[offsetKey] - node.offsetWidth
: node[offsetKey]);

const parent = node.offsetParent;
if (node === viewport || !parent) {
return offsetSum;
}

return calcOffsetToViewport(
parent as HTMLElement,
viewport,
isHorizontal,
offsetSum
);
};

/**
* @internal
*/
Expand All @@ -331,7 +358,6 @@ export const createWindowScroller = (
return {
_observe(container) {
const scrollToKey = isHorizontal ? "scrollX" : "scrollY";
const offsetKey = isHorizontal ? "offsetLeft" : "offsetTop";

const normalizeOffset = (offset: number, diff?: boolean): number => {
if (isHorizontal && isRTLDocument()) {
Expand All @@ -340,29 +366,13 @@ export const createWindowScroller = (
return offset;
};

// TODO calc offset only when it changes (maybe impossible)
const getOffsetToWindow = (node: HTMLElement, offset: number): number => {
const nodeOffset =
offset +
(isHorizontal && isRTLDocument()
? window.innerWidth - node[offsetKey] - node.offsetWidth
: node[offsetKey]);

const parent = node.offsetParent;
if (node === document.body || !parent) {
return nodeOffset;
}

return getOffsetToWindow(parent as HTMLElement, nodeOffset);
};

scrollObserver = createScrollObserver(
store,
window,
isHorizontal,
() =>
normalizeOffset(window[scrollToKey]) -
getOffsetToWindow(container, 0),
calcOffsetToViewport(container, document.body, isHorizontal),
(jump) => {
// TODO support case two window scrollers exist in the same view
window.scrollBy(
Expand Down

0 comments on commit a74242d

Please sign in to comment.