Skip to the code

Virtual list with measured heights

Reviews on the tea shop aren't all the same height: a one-line "Lovely" sits next to a long story about a trip to Darjeeling. A virtual list can't know a row's height until it has rendered it, so it starts from an estimate and corrects it as rows are measured. Write a class VirtualRows for that. new VirtualRows(rowCount, estimatedHeight) is a list in which every row is estimatedHeight pixels tall until it's measured.

setHeight(index, px) records row index's measured height, replacing the estimate or an earlier measurement. offsetOf(index) is where row index starts: the sum of the heights of every row before it, measured or estimated, so offsetOf(0) is 0 and offsetOf(rowCount) is the end of the list. totalHeight() is the height of the whole list. Throw a RangeError for an index that isn't a whole number in range (0 to rowCount - 1 for setHeight, 0 to rowCount for offsetOf), and for a height that isn't a finite number above 0, in setHeight and in the constructor, which also throws one for a rowCount that isn't a whole number of 0 or more.

range(scrollTop, viewportHeight, overscan) returns { start, end, offsetTop } the way the fixed-height problem visible-range does, with the heights you have. Clamp scrollTop to between 0 and totalHeight() - viewportHeight (0 when the list is shorter than the box). Each row covers the pixels from its offset up to, but not including, the next row's offset, and the rows in view are the ones that share a pixel with the box, from scrollTop up to, but not including, scrollTop + viewportHeight. Add overscan rows (3 unless given) on each side, within the list; offsetTop is offsetOf(start). An empty list gives { start: 0, end: -1, offsetTop: 0 }.

A virtual list calls these on every scroll, and measures rows all over the list as people jump around it, so setHeight, offsetOf, and range must each take about O(log n) time, never a walk through every row. Keep the heights in a structure with running totals (prefix sums) that you can update, such as a Fenwick tree, and find the first row in view with a binary search over them. The last test makes 20,000 calls on a list of 200,000 rows.

const reviews = new VirtualRows(1000, 50);
reviews.setHeight(2, 120); // the Darjeeling story
reviews.offsetOf(3); // 220: 50 + 50 + 120
reviews.totalHeight(); // 50070
reviews.range(100, 300, 1);
// Rows 2 to 6 are in view (row 6 starts at 370), so: { start: 1, end: 7, offsetTop: 50 }

What the tests check

  1. rows nobody has measured use the estimate
    const rows = new VirtualRows(1000, 50);
    expect(rows.totalHeight()).toBe(50000);
    expect([rows.offsetOf(0), rows.offsetOf(10), rows.offsetOf(1000)]).toEqual([0, 500, 50000]);
    expect(rows.range(0, 400, 0)).toEqual({ start: 0, end: 7, offsetTop: 0 });
    expect(rows.range(125, 400, 0)).toEqual({ start: 2, end: 10, offsetTop: 100 });
    
  2. a measured height moves every row after it, and the total
    const rows = new VirtualRows(1000, 50);
    rows.setHeight(2, 120);
    expect([rows.offsetOf(0), rows.offsetOf(2), rows.offsetOf(3), rows.offsetOf(999)]).toEqual([0, 100, 220, 50020]);
    expect(rows.totalHeight()).toBe(50070);
    
  3. finds the rows in view among measured heights, leaving out a row that starts at the bottom edge
    const rows = new VirtualRows(100, 40);
    [100, 60, 200, 40, 80].forEach((height, index) => rows.setHeight(index, height));
    // Rows start at 0, 100, 160, 360, 400, 480, and then every 40 px.
    expect(rows.range(0, 300, 0)).toEqual({ start: 0, end: 2, offsetTop: 0 });
    expect(rows.range(100, 300, 0)).toEqual({ start: 1, end: 3, offsetTop: 100 });
    expect(rows.range(359, 100, 0)).toEqual({ start: 2, end: 4, offsetTop: 160 });
    
  4. adds overscan, 3 unless given, within the list
    const rows = new VirtualRows(100, 40);
    [100, 60, 200, 40, 80].forEach((height, index) => rows.setHeight(index, height));
    expect(rows.totalHeight()).toBe(4280);
    expect(rows.range(400, 100)).toEqual({ start: 1, end: 8, offsetTop: 100 });
    expect(rows.range(4080, 200)).toEqual({ start: 92, end: 99, offsetTop: 3960 });
    
  5. clamps a scroll position outside the list, and shows every row of a short list
    const rows = new VirtualRows(100, 40);
    [100, 60, 200, 40, 80].forEach((height, index) => rows.setHeight(index, height));
    expect(rows.range(-50, 300, 0)).toEqual({ start: 0, end: 2, offsetTop: 0 });
    expect(rows.range(99999, 200, 0)).toEqual({ start: 95, end: 99, offsetTop: 4080 });
    expect(new VirtualRows(3, 50).range(10, 400, 0)).toEqual({ start: 0, end: 2, offsetTop: 0 });
    
  6. measuring a row again replaces its height
    const rows = new VirtualRows(10, 50);
    rows.setHeight(4, 100);
    rows.setHeight(4, 30);
    expect(rows.totalHeight()).toBe(480);
    expect([rows.offsetOf(4), rows.offsetOf(5)]).toEqual([200, 230]);
    
  7. rejects an index or a height that can't be right
    const rows = new VirtualRows(10, 50);
    for (const [index, px] of [[10, 40], [-1, 40], [1.5, 40], [2, 0], [2, -5], [2, NaN], [2, Infinity], [2, "40"]]) {
      expect(() => rows.setHeight(index, px)).toThrow(RangeError);
    }
    expect(() => rows.offsetOf(11)).toThrow(RangeError);
    expect(() => rows.offsetOf(-1)).toThrow(RangeError);
    expect(rows.offsetOf(10)).toBe(500);
    expect(rows.totalHeight()).toBe(500);
    expect(() => new VirtualRows(10, 0)).toThrow(RangeError);
    expect(() => new VirtualRows(-1, 50)).toThrow(RangeError);
    
  8. an empty list has nothing to render
    const rows = new VirtualRows(0, 50);
    expect(rows.totalHeight()).toBe(0);
    expect(rows.offsetOf(0)).toBe(0);
    expect(rows.range(0, 300)).toEqual({ start: 0, end: -1, offsetTop: 0 });
    
  9. stays fast on 200,000 rows measured all over the list
    const count = 200000;
    const rows = new VirtualRows(count, 40);
    const heights = new Map();
    let total = count * 40;
    for (let call = 0; call < 5000; call++) {
      const index = (call * 7919) % count;
      const height = 20 + (call % 61);
      total += height - (heights.get(index) ?? 40);
      heights.set(index, height);
      rows.setHeight(index, height);
      const end = rows.offsetOf(count);
      const view = rows.range(end / 2, 800, 2);
      rows.totalHeight();
      if (call % 1000 === 0) {
        expect(end).toBe(total);
        expect(rows.offsetOf(view.start)).toBe(view.offsetTop);
        const first = view.start + 2;
        expect(rows.offsetOf(first) <= end / 2 && end / 2 < rows.offsetOf(first + 1)).toBe(true);
      }
    }
    let before = 150000 * 40;
    for (const [index, height] of heights) if (index < 150000) before += height - 40;
    expect(rows.offsetOf(150000)).toBe(before);
    expect(rows.totalHeight()).toBe(total);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).