|
| 1 | +import Component from '@ember/component'; |
| 2 | +import { debounce } from '@ember/runloop'; |
| 3 | +import { htmlSafe } from '@ember/string'; |
| 4 | +import { tracked } from '@glimmer/tracking'; |
| 5 | + |
| 6 | +export default class ScrollContainerComponent extends Component { |
| 7 | + attributeBindings = ['style']; |
| 8 | + |
| 9 | + @tracked collection; |
| 10 | + @tracked currentItem; |
| 11 | + @tracked itemHeight; |
| 12 | + |
| 13 | + lastIndex = -1; |
| 14 | + lastItem = undefined; |
| 15 | + |
| 16 | + get style() { |
| 17 | + return htmlSafe(` |
| 18 | + position: relative; |
| 19 | + height: 100%; |
| 20 | + `); |
| 21 | + } |
| 22 | + |
| 23 | + get scrollTargetStyle() { |
| 24 | + let { index, itemHeight } = this; |
| 25 | + |
| 26 | + if (index === -1) { |
| 27 | + return htmlSafe('display: none;'); |
| 28 | + } else { |
| 29 | + return htmlSafe(` |
| 30 | + position: absolute; |
| 31 | + width: 100%; |
| 32 | + height: ${itemHeight || 0}px; |
| 33 | + margin: 0px; |
| 34 | + padding: 0px; |
| 35 | + top: ${index * itemHeight || 0}px; |
| 36 | + left: 0px; |
| 37 | + z-index: -9999; |
| 38 | + pointer-events: none; |
| 39 | + `); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + get index() { |
| 44 | + return this.collection.indexOf(this.currentItem); |
| 45 | + } |
| 46 | + |
| 47 | + get scrollTarget() { |
| 48 | + return this.element.querySelector('.scroll-target'); |
| 49 | + } |
| 50 | + |
| 51 | + didRender() { |
| 52 | + let { index, lastIndex, currentItem, lastItem } = this; |
| 53 | + |
| 54 | + if (index !== lastIndex || currentItem !== lastItem) { |
| 55 | + this.lastIndex = index; |
| 56 | + this.lastItem = currentItem; |
| 57 | + |
| 58 | + debounce(this, this.scrollIntoViewIfNeeded, 50); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + scrollIntoViewIfNeeded() { |
| 63 | + let { element, scrollTarget } = this; |
| 64 | + |
| 65 | + if (needsScroll(element, scrollTarget)) { |
| 66 | + scrollTarget.scrollIntoView({ |
| 67 | + behavior: 'auto', |
| 68 | + block: 'nearest', |
| 69 | + inline: 'nearest' |
| 70 | + }); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +function needsScroll(container, target) { |
| 76 | + let { top: containerTop, bottom: containerBottom } = container.getBoundingClientRect(); |
| 77 | + let { top: targetTop, bottom: targetBottom } = target.getBoundingClientRect(); |
| 78 | + return targetTop < containerTop || targetBottom > containerBottom; |
| 79 | +} |
0 commit comments