diff --git a/chnobli/src/scroll/Scroll.ts b/chnobli/src/scroll/Scroll.ts index a8fb7ab..242b719 100644 --- a/chnobli/src/scroll/Scroll.ts +++ b/chnobli/src/scroll/Scroll.ts @@ -338,9 +338,11 @@ export default class ScrollTimeline { const startY = start.y - height * start.view; const endY = end.y - height * end.view; - if (y >= startY && y < endY) { + // the end is included, at the bottom of the page y can't get + // past the last offset + if (y >= startY && y <= endY) { const dif = endY - startY; - const x = 1 - (endY - y) / dif; + const x = dif === 0 ? 1 : 1 - (endY - y) / dif; return start.position + (end.position - start.position) * x; } diff --git a/chnobli/src/tests/scroll.test.ts b/chnobli/src/tests/scroll.test.ts new file mode 100644 index 0000000..a1aac68 --- /dev/null +++ b/chnobli/src/tests/scroll.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest'; +import ScrollTimeline from '../scroll/Scroll.js'; + +function scrollWith(offsets: [number, number, number][]) { + const s = new ScrollTimeline(); + s.offsets = offsets.map(([y, view, position]) => ({ y, view, position })); + return (y: number) => (s as any).calcPosition({ y, height: 100 }); +} + +describe('scroll', () => { + it('position', () => { + // from 0 to 900, like a page that can't scroll past the end + const pos = scrollWith([ + [0, 0, 0], + [900, 0, 1], + ]); + + expect(pos(-1)).toBe(-1); + expect(pos(0)).toBe(0); + expect(pos(450)).toBe(0.5); + expect(pos(900)).toBe(1); + expect(pos(901)).toBe(2); + }); + + it('position with three offsets', () => { + const pos = scrollWith([ + [0, 0, 0], + [200, 1, 0.5], + [500, 0, 1], + ]); + + expect(pos(100)).toBe(0.5); + expect(pos(300)).toBe(0.75); + expect(pos(500)).toBe(1); + }); +});