Skip to content

Commit

Permalink
refactor & added optional automatic scroll tracking for ancestors
Browse files Browse the repository at this point in the history
  • Loading branch information
Yair Even Or authored and Yair Even Or committed Oct 2, 2021
1 parent 7824de1 commit 045496f
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/position.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
* @param {Array} offset distance (in pixels) from original placement position ("10px 20px" or just "10px" for both horizontal & vertical)
*/

const position = props => {
var {target, ref, offset, placement, prevPlacement, useRaf = true} = props,
const position = props => {
var {target, ref, offset, placement, prevPlacement, useRaf = true, track} = props,
pos = {x:ref.x, y:ref.y, h:0, w:0},
refRect = (ref && ref.x) ? {...ref} : {},
refWindow,
Expand Down Expand Up @@ -74,7 +74,7 @@
target.setAttribute('data-placement', placement.join(' '));
target.setAttribute('data-pos-overflow', Object.entries(overflow).reduce((acc, [k,v]) => v ? `${acc} ${k}` : acc , '').trim());
[
['pos-left', pos.x], // overflow.right ? vpSize.w - targetSize.w : pos.x
['pos-left', overflow.right ? vpSize.w - targetSize.w : pos.x],
['pos-top', pos.y], // pos.y > offset[1] ? pos.y : 0
['pos-target-width', targetSize.w],
['pos-target-height', targetSize.h],
Expand All @@ -87,6 +87,21 @@
].forEach(([k,v]) => target.style.setProperty('--'+k, Math.round(v)))
})

// auto-reposition on any ancestor scroll
if( track?.scroll && !target.position__trackedScroll ){
// mark the node as tracked
target.position__trackedScroll = true;

// if any ancestor of refElement was scrolled, re-position the target
window.addEventListener('scroll', onScroll, true)

function onScroll(e){
// make sure the scrolled element contains the ref element
if( e.target.contains(refElement) )
position(props)
}
}

return {pos, placement}
}

Expand Down

0 comments on commit 045496f

Please sign in to comment.