Skip to content

Instantly share code, notes, and snippets.

@blasten
Last active August 29, 2015 14:24
Show Gist options
  • Save blasten/8e3de5f497ce323adba6 to your computer and use it in GitHub Desktop.
Save blasten/8e3de5f497ce323adba6 to your computer and use it in GitHub Desktop.
function refresh() {
var SCROLL_DIRECTION_UP = -1;
var SCROLL_DIRECTION_DOWN = 1;
var SCROLL_DIRECTION_NONE = 0;
var direction = SCROLL_DIRECTION_NONE;
var ratio = 0.5;
var delta = this.scrollTop - this.scrollPosition;
this.scrollPosition = this.scrollTop;
if (delta < 0) {
direction = SCROLL_DIRECTION_UP;
} else if (delta > 0) {
direction = SCROLL_DIRECTION_DOWN;
}
var topSpace = this.scrollTop - this.physicalOffset;
var bottomSpace = (this.physicalSize + this.physicalOffset) - this.scrollTop - this.viewportSize;
var totalSpace = topSpace + bottomSpace;
var currentRatio, tileHeight, nth;
var movingUp = [], recycledTiles= 0;
if (direction === SCROLL_DIRECTION_UP) {
var isFirstOne = (this.virtualStart === 0);
currentRatio = topSpace / totalSpace;
if (!isFirstOne && currentRatio < ratio) {
// move tiles from bottom to top
// approximate `currentRatio` to `ratio`
nth = this.physicalEnd;
while (currentRatio < ratio && recycledTiles < this.physicalCount) {
tileHeight = this.physicalSizes[nth];
currentRatio += tileHeight / totalSpace;
movingUp.push(nth);
nth = (nth === 0) ? this.physicalCount - 1 : nth - 1;
recycledTiles++;
}
recycledTiles = -recycledTiles;
}
} else if (direction === SCROLL_DIRECTION_DOWN) {
var isLastOne = (this.virtualStart + this.physicalCount === this.virtualCount);
currentRatio = bottomSpace / totalSpace;
if (!isLastOne && currentRatio < ratio) {
// move tiles from top to bottom
// approximate `currentRatio` to `ratio`
nth = this.physicalStart;
while (currentRatio < ratio && recycledTiles < this.physicalCount) {
tileHeight = this.physicalSizes[nth];
currentRatio += tileHeight / totalSpace;
this.physicalOffset += tileHeight;
nth = (nth + 1) % this.physicalCount;
recycledTiles++;
}
}
}
if (recycledTiles !== 0 || direction === SCROLL_DIRECTION_NONE) {
this.virtualStart = this.virtualStart + recycledTiles;
this.physicalStart = this.virtualStart % this.physicalCount;
this.physicalEnd = (this.physicalStart + this.physicalCount - 1) % this.physicalCount;
this._assignModels();
// measure heights
this._updateMetrics();
// adjust offset after measuring
while (movingUp.length) {
this.physicalOffset -= this.physicalSizes[movingUp.pop()];
}
this._positionItems();
this._updateScrollerSize();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment