@bazariodev/porthole
v0.1.0
Published
A fixed-size list window for React and Web Components.
Maintainers
Readme
@bazariodev/porthole
Porthole renders only the rows in and near the viewport of a long list. All rows must have the same
height. A spacer keeps the scroll height of the full list. Use the React hook or the
<porthole-list> Web Component.
Install
pnpm add @bazariodev/portholeThe React hook needs React 18 or 19. React is an optional peer dependency. The Web Component does not use React. The package has no runtime dependencies.
Usage
import { usePorthole } from '@bazariodev/porthole';
const ROW_SIZE = 48;
function List({ items }) {
const list = usePorthole({ count: items.length, itemSize: ROW_SIZE });
return (
<div
ref={list.scrollContainerRef}
style={{ height: 600, overflowY: 'auto', overflowAnchor: 'none' }}
>
<div style={{ display: 'flow-root' }}>
<div ref={list.listRef} style={{ height: list.totalSize, overflowY: 'clip' }}>
<div style={{ transform: `translateY(${list.offset}px)` }}>
{items.slice(list.start, list.end).map((item) => (
<div
key={item.id}
style={{ boxSizing: 'border-box', display: 'flow-root', height: ROW_SIZE }}
>
{item.label}
</div>
))}
</div>
</div>
</div>
</div>
);
}items is your array. Each item has an id and a label.
| Element | Hook field | Necessary styles |
| --- | --- | --- |
| Scroll container | scrollContainerRef | A fixed height, overflow-y: auto, overflow-anchor: none |
| Wrapper | — | display: flow-root |
| Spacer | listRef, totalSize | height: totalSize, overflow-y: clip |
| Row group | offset | transform: translateY(offset) |
| Row | — | height: itemSize, box-sizing: border-box, display: flow-root |
- Make the spacer the last child of the wrapper.
- Put leading content in the wrapper before the spacer. Put trailing content and variable bottom padding after the wrapper.
- Keep the padding and border of the scroll container fixed.
- Do not put gaps or vertical margins between rows. Keep a row element when its content is empty.
- Do not scale or rotate the scroll container, the spacer, or their ancestors. A translation is permitted.
Leading content and row size changes
import { useCallback, useRef } from 'react';
import { usePorthole } from '@bazariodev/porthole';
function List({ items, pinned, isCompact }) {
const itemSize = isCompact ? 64 : 80;
const list = usePorthole({ count: items.length, itemSize });
const viewportRef = useRef(null);
const setViewport = useCallback(
(element) => {
viewportRef.current = element;
list.scrollContainerRef(element);
},
[list.scrollContainerRef],
);
return (
<div ref={setViewport} style={{ height: 600, overflowY: 'auto', overflowAnchor: 'none' }}>
<div style={{ display: 'flow-root' }}>
<PinnedRows items={pinned} />
<div ref={list.listRef} style={{ height: list.totalSize, overflowY: 'clip' }}>
<div role="list" style={{ transform: `translateY(${list.offset}px)` }}>
{items.slice(list.start, list.end).map((item, index) => (
<div
key={item.id}
role="listitem"
aria-posinset={list.start + index + 1}
aria-setsize={items.length}
style={{ boxSizing: 'border-box', display: 'flow-root', height: itemSize }}
>
<Row item={item} />
</div>
))}
</div>
</div>
</div>
<button type="button" onClick={() => viewportRef.current.scrollTo({ top: 0 })}>
Back to top
</button>
</div>
);
}PinnedRows and Row are your components. isCompact comes from your breakpoint state.
- Use the same
itemSizefor the hook and the row height in one render. - When
itemSizechanges, the top visible row stays at the same fraction of its height. For example, 40 px into an 80 px row becomes 32 px into a 64 px row. - To keep your own ref to the scroll container, call
scrollContainerReffrom your callback ref. - For a semantic list, set
aria-setsizeand a one-basedaria-posinseton each row.
Fixed-position descendants
The transform makes the row group the containing block of position: fixed descendants. To
prevent this, use padding in place of the transform:
<div role="list" style={{ paddingBlockStart: list.offset }}>Web Component
<porthole-list style="height: 600px">
<h2 slot="leading">Messages</h2>
<p slot="trailing">End of list</p>
</porthole-list>import { definePortholeElement } from '@bazariodev/porthole/web-components';
definePortholeElement();
const list = document.querySelector('porthole-list');
list.configure({
count: items.length,
itemSize: 48,
renderRow: (index) => items[index].label,
});items is your array. To show elements, return a new element from renderRow. To change the data,
call configure again. list is the element from the previous example.
let items = [];
function renderRow(index) {
const label = document.createElement('strong');
label.textContent = items[index].label;
return label;
}
function showItems(nextItems) {
items = nextItems;
list.configure({ count: items.length, itemSize: 48, renderRow });
}porthole-list::part(row) {
border-block-end: 1px solid #ddd;
padding-inline: 12px;
}- Call
definePortholeElement()beforeconfigure. - The element is the scroll container. Set its height. Its default styles set
display: block,overflow-y: auto, andoverflow-anchor: none. renderRow(index)returns a new detachedNode, a string,null, orundefined. A string becomes text.nullandundefinedgive an empty row.- Each row is
itemSizeCSS px high and clips vertical overflow. - Each
configurecall renders all rows in the range again. A scroll renders only the rows that enter the range. - You can call
configurebefore you connect the element. Rows render after connection. - Do not call
configurefromrenderRowor from a row lifecycle callback during an update. This call throws anError. - If
renderRowthrows duringconfigure, the element keeps its previous configuration and rows. Thenconfigurethrows the error. - If
renderRowdisconnects the element, the render stops. On reconnection, the element uses the latest valid configuration. - To move a list to another window, call
definePortholeElement()in that window and create a new list there. A moved element can stop updates when you remove its source iframe.
Behavior
- The range contains the visible rows and
overscanrows on each side. The defaultoverscanis 4. - Before the first measurement, the range contains the first 20 rows or fewer. This is also true for a server render, a scroll container with no height, and a document without a window.
- With a measured
height, at mostceil(height / itemSize) + 1 + 2 × overscanrows are in the DOM. - During a scroll, Porthole reads only
scrollTop. It measures the layout on attachment, after a resize of the scroll container or the wrapper, and after acountoritemSizechange. - After an
itemSizechange, Porthole does not keep the top row in these conditions:countalso changes.- The top of the viewport is outside the list, or the scroll container had no height.
- The user or the browser moved the position after the last measurement.
- Hook only: the scroll container or the spacer also changes, or the old position is at or after the new end of the scroll range.
count, order, and leading content changes keep the scroll position in CSS px. The browser limits the position to the new scroll range. One row of added leading height moves the list down one row.- Rows outside the range are not in the DOM. Browser Find cannot find them. A focused row can unmount. Your code must move the focus.
- The tested limit for the full scroll content is 8,000,000 CSS px. Porthole does not enforce it. Use bounded pages for larger lists.
- Porthole does not support the document scroll container, horizontal lists, grids, rows of different heights, or sticky rows.
API
usePorthole(options)
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| count | number | — | Necessary. Item count: a safe integer, 0 or more. |
| itemSize | number | — | Necessary. Row border-box height in CSS px: a finite number more than 0. |
| overscan | number | 4 | Rows before and after the visible rows: a safe integer, 0 or more. |
| Field | Type | Description |
| --- | --- | --- |
| start | number | First index to render. |
| end | number | Index after the last item to render. |
| totalSize | number | Spacer height in CSS px: count × itemSize. |
| offset | number | Row group offset in CSS px: start × itemSize. |
| scrollContainerRef | (element: HTMLElement \| null) => void | Stable callback ref for the scroll container. |
| listRef | (element: HTMLElement \| null) => void | Stable callback ref for the spacer. |
definePortholeElement()
Import it from @bazariodev/porthole/web-components. It registers <porthole-list> and returns the
constructor. Each later call returns the same constructor. The import does not use the DOM.
element.configure(options) accepts count, itemSize, and overscan as usePorthole does. It
also accepts the necessary function renderRow(index). The element has the named slots leading
and trailing and the part row.
Errors
| Error | Message |
| --- | --- |
| RangeError | count must be a nonnegative safe integer |
| RangeError | itemSize must be a positive finite number |
| RangeError | overscan must be a nonnegative safe integer |
| RangeError | count times itemSize must be finite |
| TypeError | renderRow must be a function |
| Error | configure cannot run during rendering |
| Error | porthole-list is already defined |
The hook throws during render. The element throws from configure. A configure call that throws
keeps the previous configuration and rows. definePortholeElement() throws when a different
constructor has the porthole-list name.
TypeScript
Both entries include ESM and CommonJS declarations. Root types: PortholeOptions and
PortholeResult. Web Components types: PortholeElementOptions, PortholeElement, and
PortholeElementConstructor. The Web Components entry adds porthole-list to
HTMLElementTagNameMap. Thus document.querySelector('porthole-list') returns
PortholeElement | null.
License
MIT. See LICENSE.
