Skip to content

Commit b932154

Browse files
authored
feat: account for scroll margin (#906)
* feat: account for scroll margin * feat: rename vars
1 parent 9e7f63d commit b932154

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

src/index.ts

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,16 @@ const getParentElement = (element: Node): Element | null => {
274274
return parent
275275
}
276276

277+
const getScrollMargins = (target: Element) => {
278+
const computedStyle = window.getComputedStyle(target)
279+
return {
280+
top: parseFloat(computedStyle.scrollMarginTop) || 0,
281+
right: parseFloat(computedStyle.scrollMarginRight) || 0,
282+
bottom: parseFloat(computedStyle.scrollMarginBottom) || 0,
283+
left: parseFloat(computedStyle.scrollMarginLeft) || 0,
284+
}
285+
}
286+
277287
/** @public */
278288
export const compute = (target: Element, options: Options): ScrollAction[] => {
279289
if (typeof document === 'undefined') {
@@ -342,20 +352,26 @@ export const compute = (target: Element, options: Options): ScrollAction[] => {
342352
bottom: targetBottom,
343353
left: targetLeft,
344354
} = target.getBoundingClientRect()
355+
const {
356+
top: marginTop,
357+
right: marginRight,
358+
bottom: marginBottom,
359+
left: marginLeft,
360+
} = getScrollMargins(target)
345361

346362
// These values mutate as we loop through and generate scroll coordinates
347363
let targetBlock: number =
348364
block === 'start' || block === 'nearest'
349-
? targetTop
365+
? targetTop - marginTop
350366
: block === 'end'
351-
? targetBottom
352-
: targetTop + targetHeight / 2 // block === 'center
367+
? targetBottom + marginBottom
368+
: targetTop + targetHeight / 2 - marginTop + marginBottom // block === 'center
353369
let targetInline: number =
354370
inline === 'center'
355-
? targetLeft + targetWidth / 2
371+
? targetLeft + targetWidth / 2 - marginLeft + marginRight
356372
: inline === 'end'
357-
? targetRight
358-
: targetLeft // inline === 'start || inline === 'nearest
373+
? targetRight + marginRight
374+
: targetLeft - marginLeft // inline === 'start || inline === 'nearest
359375

360376
// Collect new scroll positions
361377
const computations: ScrollAction[] = []

0 commit comments

Comments
 (0)