/** * A headless virtual list that renders items near the viewport and leaves * space for unmounted items, so the scroll covers the whole list. * * `VirtualList` is a headless component on the same core as `VirtualList` in * `effect/ui/kit` (`effect/ui/Virtualizer`). They share windowing props * and the `Scrolled` event. Your view draws a `scroll` and one * element for each index in `items`. * * **Anatomy** * * | Part | Element | * | :-- | :-- | * | `list` | `scroll`, the view that scrolls | * | `item` | `view`, one item | * * `item` takes `{ element, index }`. Draw one for each index in `items`, in * order, as children of `list`, and key each element by the item's own id. * Other children of `list`, such as a header, a footer, an empty state or a * `RefreshControl`, stay where they're written. The list adds keyed empty * views among its children that stand in for the items left out. * * **Sizes** * * An item is `itemSize` points along the scroll axis, or `sizes[index]`, * until its `layout` reports its size. With `measure: false` those sizes are * exact and the list sets each item's `height`, or `width` when it's * `horizontal`. Put the space between items in their padding or in a child: * an item's margin isn't measured. * * **Scrolling** * * The list renders the first `initialCount` items, 10 when omitted, until * the scroll has laid out, or the items around a `scrollTo` target. * `scrollTo` jumps to its target after layout and as measured sizes move * the target, until the user drags. While items are measured or `keys` are * passed, `maintainVisibleContentPosition` keeps the first visible item in * place as preceding items change. `followEnd` jumps to the end when content * grows while the user is there. Both ignore `behavior`. * * `scrolling` turns `true` when a drag begins and `false` when the * momentum after it ends, or 100ms after a drag that has none. * * `sticky` keeps the header of the section on screen mounted, and the one * before it. In a vertical list the native `EffectUIStickyHeader` view pins * it to the viewport until the next sticky item pushes it away. That needs a * build with `@effect/ui-native`'s native code, such as a development build. * In Expo Go headers scroll with their rows, and development builds warn. * * **Example** (A list of rows) * * ```ts * import { Native } from "@effect/ui-native" * import { VirtualList } from "@effect/ui-native/kit" * import { Schema } from "effect" * * const rows = Array.from({ length: 10_000 }, (_, i) => "Row " + i) * * const Rows = Native.component({ * name: "Rows", * model: Schema.Struct({}), * message: Schema.Never * }).make({ * init: () => ({}), * update: ($) => $.model, * view: (h) => * VirtualList(h, { * props: { keys: rows, itemSize: 48 }, * view: (list) => * list.list(h.scroll.style({ flex: 1 })).children( * list.items.map((index) => * list.item({ element: h.view.key(rows[index]!), index }).children( * h.text.children(rows[index]!) * ) * ) * ) * }) * }) * ``` * * @stability experimental * @since 4.2.0 */ import * as dev from "#dev" import * as Effect from "effect/Effect" import * as Option from "effect/Option" import * as Schema from "effect/Schema" import * as Stream from "effect/Stream" import * as Command from "effect/ui/Command" import * as Component from "effect/ui/Component" import * as Renderer from "effect/ui/Renderer" import * as Subscription from "effect/ui/Subscription" import * as UiSchema from "effect/ui/UiSchema" import * as View from "effect/ui/View" import * as Virtualizer from "effect/ui/Virtualizer" import * as Native from "../Native.ts" import type { NativeNode } from "../NativeHost.ts" const scrollEndDelay = 100 const { layout: _layout, ...coreFields } = Virtualizer.Props.fields /** * `Virtualizer.Props` in points, excluding `layout`. * * @stability experimental * @category models * @since 4.2.0 */ export const VirtualListProps = Schema.Struct(coreFields) /** * The props of `VirtualList`. * * @stability experimental * @category models * @since 4.2.0 */ export type VirtualListProps = typeof VirtualListProps.Type /** * The events of `VirtualList`, as `Virtualizer.Events` describes them. The * list is at its start while the scroll offset is within a point of 0, and at * its end while the content's end is within the `followEnd` threshold of the * viewport's, or a point. * * @stability experimental * @category models * @since 4.2.0 */ export const VirtualListEvents = Virtualizer.Events /** * The events of `VirtualList`. * * @stability experimental * @category models * @since 4.2.0 */ export type VirtualListEvents = Virtualizer.Events const Measurement = Schema.Struct({ epoch: Schema.Number, index: Schema.Number, key: Schema.NullOr(Schema.String), at: Schema.Number, size: Schema.Number, first: Schema.Boolean }) const Model = Schema.Struct({ ...Virtualizer.Model.fields, scrollOffset: Schema.Number, viewport: Schema.Number, // -1 until native reports the content size. content: Schema.Number, cross: Schema.Number, // Where the leading spacer starts in the content. spacer: Schema.Number, // The row from `placedOf`, and where native last laid out its start. placed: Schema.NullOr( Schema.Struct({ index: Schema.Number, key: Schema.String, at: Schema.Number }) ), // The offset the list last scrolled to, -1 for the end, and the content's // size then. aimed: Schema.NullOr( Schema.Struct({ to: Schema.Number, content: Schema.Number }) ), pending: Schema.Array(Measurement), momentum: Schema.Boolean, // Pixels per point, the grid native lands a scroll on. scale: Schema.Number }) type Model = typeof Model.Type const Message = UiSchema.TaggedEnum({ LaidOutViewport: { size: Schema.Number, cross: Schema.Number }, Scrolled: { offset: Schema.Number, viewport: Schema.Number, content: Schema.Number }, ResizedContent: { content: Schema.Number }, PlacedSpacer: { at: Schema.Number }, LaidOutItem: Measurement.fields, Measured: {}, Requested: { scrollTo: Virtualizer.ScrollTo }, Resolved: {}, Fixed: {}, DragBegan: {}, DragEnded: {}, MomentumBegan: {}, MomentumEnded: {}, Settled: {}, Scaled: { scale: Schema.Number } }) type Message = typeof Message.Type // Read once, which keeps `Dimensions` out of the bundle. Copied from // `deviceScale` in `internal/asset.ts`, as sharing it costs `Image` apps more. const scaled = Subscription.make( "VirtualList.scale", Stream.fromEffect(Native.Device.useSync((device) => { const dimensions = device.module("DeviceInfo")?.getConstants().Dimensions return Message.Scaled({ scale: (dimensions?.window ?? dimensions?.windowPhysicalPixels)?.scale ?? 1 }) })) ) const Root = Native.ref("VirtualList") const withRoot = ( f: (host: Native.Host["Service"], node: NativeNode) => void ) => Effect.flatMap( Renderer.Refs.use((refs) => refs.lookup(Root)), (node) => Native.Host.useSync((host) => { if (Option.isSome(node)) f(host, node.value) return Component.noop }) ) const ScrollList = Command.make( "VirtualList.scrollTo", { args: { offset: Schema.Number, horizontal: Schema.Boolean } }, ({ horizontal, offset }) => withRoot((host, node) => horizontal ? host.scrollTo(node, offset, 0, false) : host.scrollTo(node, 0, offset, false) ) ) const ScrollEnd = Command.make( "VirtualList.scrollToEnd", { args: {} }, () => withRoot((host, node) => host.scrollToEnd(node, false)) ) // Waits a tick, so layouts native reports in separate passes apply together. const Measure = Command.make( "VirtualList.measure", { args: {} }, () => Effect.as(Effect.sleep(0), Message.Measured()) ) // Allows momentum to begin before marking a drag as settled. const Settle = Command.make( "VirtualList.settle", { args: {}, mode: "switch" }, () => Effect.as(Effect.sleep(scrollEndDelay), Message.Settled()) ) const withDefaults = (props: VirtualListProps): VirtualListProps => ({ ...props, initialCount: props.initialCount ?? 10, // At least one row before the viewport, so the leading spacer never // becomes the view the scroll keeps in place. overscan: Math.max(1, Math.floor(props.overscan ?? 3)) }) const reserveOf = (props: VirtualListProps): number => Math.max(0, props.reserveStart ?? 0) const originOf = (model: Model, props: VirtualListProps): number => model.spacer + reserveOf(props) const atEndOf = ( at: Pick, props: VirtualListProps ): boolean => at.content >= 0 && at.content - at.scrollOffset - at.viewport <= (Virtualizer.endThreshold(props) ?? Virtualizer.edgeThreshold) const following = (model: Model, props: VirtualListProps): boolean => Virtualizer.endThreshold(props) !== null && model.atEnd // Whether native keeps the first visible item in place as the content // above it changes. const anchoredOf = (props: VirtualListProps): boolean => props.measure !== false || props.keys !== undefined // Whether native landed on the pixel it rounds `target` to. Android converts // the target and reports the landing in float32. const landed = ({ scale }: Model, offset: number, target: number): boolean => Math.round(offset * scale) === Math.round(Math.fround(Math.fround(target) * scale)) // The row whose native placement maps the core's layout to native's: a // waiting request's target, so a jump aims from its own pixel, or else the // window's first row. const placedOf = ({ request, window }: Virtualizer.Plan): number => request?.index ?? window[0] // Whether a layout report is current, not a late one from before a dataset // or key change. const currentOf = ( plan: Virtualizer.Plan, props: VirtualListProps, { epoch, index, key }: typeof Measurement.Type ): boolean => epoch === plan.epoch && index < plan.count && key === Virtualizer.keyOf(props, index) // Where native has the start of the core's layout, from where it placed the // `placedOf` row. Estimates above that row can change before native lays out // their spacer. const shiftOf = ( model: Model, props: VirtualListProps, given?: Virtualizer.Plan ): number => { const { placed } = model const fallback = originOf(model, props) // Native lays fixed rows out as planned, also before `Fixed` arrives. if (placed === null || props.measure === false) { return fallback } const plan = given ?? Virtualizer.plan(model, props) const [from, to] = plan.window let index = placed.index if (Virtualizer.sizeKey(props, index) !== placed.key) { index = from while (index < to && Virtualizer.sizeKey(props, index) !== placed.key) { index++ } } return index >= from && index < to ? placed.at - plan.offsetOf(index) : fallback } // The start of a viewport scrolled to `offset`, in the core's layout. const startOf = ( model: Model, props: VirtualListProps, offset = model.scrollOffset, given?: Virtualizer.Plan ): number => offset - shiftOf(model, props, given) // After a content change, the stored offset can precede native's anchor // adjustment. Keep the same visible item until the next scroll event. const moved = ( model: Model, props: VirtualListProps, kept = false ): Virtualizer.Updated => { if (model.viewport === 0) return { model, events: [] } const origin = originOf(model, props) return Virtualizer.update( model, props, Virtualizer.Message.MovedViewport({ start: kept ? model.scrollOffset - origin : startOf(model, props), height: model.viewport, anchor: kept && anchoredOf(props) ? model.position : null, atStart: model.scrollOffset <= Virtualizer.edgeThreshold, atEnd: atEndOf(model, props), overflowing: model.content > model.viewport + 0.5, length: Math.max(0, model.content - origin), scrolled: null }) ) } // The scroll the model asks for: to a waiting request's target, or to the // end when the content grew under a list that follows it. const aim = ( model: Model, props: VirtualListProps, follow: boolean ): { readonly model: Model readonly command: | ReturnType | ReturnType | null } => { if (model.viewport === 0) return { model, command: null } let to = follow ? -1 : null const waiting = Virtualizer.waitingOf(model, props) if (waiting !== null) { const target = Virtualizer.targetOf(model, props, waiting) if (target !== null && waiting.target._tag === "End") to = -1 else if (target !== null) { // Far down a list native's float layout drifts from the plan by under // a point, so aim from where native put the row. A larger shift is a // layout native hasn't applied yet. const origin = originOf(model, props) const shift = shiftOf(model, props) // Unrounded: native rounds it to its pixels. to = Math.max(0, (Math.abs(shift - origin) < 1 ? shift : origin) + target) } } if (to === null) return { model, command: null } const reached = to === -1 ? atEndOf(model, props) : landed(model, model.scrollOffset, to) if ( model.aimed !== null && model.aimed.to === to && (reached || Virtualizer.same(model.aimed.content, model.content)) ) return { model, command: null } return { model: { ...model, aimed: { to, content: model.content } }, command: to === -1 ? ScrollEnd.make() : ScrollList.make({ offset: to, horizontal: props.horizontal === true }) } } type Update = Component.Update< Model, Message, VirtualListEvents, VirtualListProps > const finish = ( $: Update, props: VirtualListProps, { events, model }: Virtualizer.Updated, follow = false ) => { const { command, model: next } = aim(model, props, follow) const step = next === $.model ? $ : $.set(next) const emitted = events.length === 0 ? step : step.emit(...events) return command === null ? emitted : emitted.run(command) } const scrolling = ( model: Model, props: VirtualListProps, on: boolean ): Virtualizer.Updated => model.scrolling === on ? { model, events: [] } : Virtualizer.update( model, props, Virtualizer.Message.ScrolledViewport({ offset: model.offset, height: model.height, length: model.length, scrolling: on }) ) type ItemOf> = ReturnType /** * A headless virtual list. Call it with the consumer's `h`, its `props`, and * a `view` closure that applies `list` to a `scroll` and `item` to the * element of each index in `items`. * * **Details** * * The parts object also carries `items`, the indices to render in order, * `count`, `atStart`, `atEnd` and `scrolling`. * * `list` sets the scroll's `layout`, `scroll`, `contentSizeChange` and drag * and momentum handlers, `horizontal`, and `maintainVisibleContentPosition` * while items are measured or `keys` are passed. * `item` sets a `layout` handler, or with `measure: false` the item's size. * * @stability experimental * @category components * @since 4.2.0 */ export const VirtualList = Native.component({ name: "VirtualList", props: VirtualListProps, model: Model, message: Message, events: VirtualListEvents, restore: false }).make({ init: ($) => ({ ...Virtualizer.init(withDefaults($.props)), // Native reports layout only when it changes. Keep the core's width // fixed to retain measurements that native will not report again; // cross-size changes invalidate only unmounted items. width: 1, scrollOffset: 0, viewport: 0, content: -1, cross: 0, spacer: 0, placed: null, aimed: null, pending: [], momentum: false, scale: 1 }), update: ($, message) => { const { model } = $ const props = withDefaults($.props) switch (message._tag) { case "LaidOutViewport": { let sizes = model.sizes if ( model.cross !== 0 && !Virtualizer.same(model.cross, message.cross) ) { const rendered = new Set( Virtualizer.plan(model, props).items.map((i) => Virtualizer.sizeKey(props, i)) ) sizes = Object.fromEntries( Object.entries(sizes).filter(([key]) => rendered.has(key)) ) } return finish( $, props, moved( { ...model, sizes, viewport: message.size, cross: message.cross }, props ) ) } case "Scrolled": { // Wheel and scrollbar input can move away from a completed jump // without a drag-start event. Let the window follow the viewport. const aimed = model.aimed const end = Math.max(0, message.content - message.viewport) const target = aimed?.to === -1 ? end : Math.min(aimed?.to ?? -1, end) const away = target >= 0 && !landed(model, message.offset, target) const leftTarget = away && Virtualizer.same(model.content, message.content) && Virtualizer.same(model.viewport, message.viewport) && landed(model, model.scrollOffset, target) // Short of a waiting target, aim again: Android can run the scroll // before its mount, then anchor the mount's shift on top. const missed = away && !leftTarget && Virtualizer.waitingOf(model, props) !== null const current = leftTarget ? Virtualizer.update( model, props, Virtualizer.Message.ScrolledByUser() ).model : model return finish( $, props, moved( { ...current, aimed: leftTarget || missed ? null : current.aimed, scrollOffset: message.offset, viewport: message.viewport, content: message.content }, props ) ) } case "ResizedContent": { const next = { ...model, content: message.content } // Following the end, the list stays at it until the scroll gets there. return following(model, props) ? finish($, props, { model: next, events: [] }, true) : finish($, props, moved(next, props, true)) } case "PlacedSpacer": return finish( $, props, moved( { ...model, spacer: message.at }, props, !model.atStart && model.scrollOffset >= originOf(model, props) ) ) case "LaidOutItem": { const { at, first, index, key, size } = message const id = key ?? String(index) // Native reports a mount's layouts before its scroll adjustment, such // as for a prepend, so move the placed row now. const placed = model.placed?.key === id && currentOf(Virtualizer.plan(model, props), props, message) ? { ...model.placed, index, at } : model.placed if (model.pending.length === 0) { const known = model.sizes[id] if ( known !== undefined && Virtualizer.same(known, size) && (!first || (model.placed?.index === index && Virtualizer.same(model.placed.at, at))) ) { return placed === model.placed ? $ : finish($, props, { model: { ...model, placed }, events: [] }) } } const step = $.set({ ...model, placed, pending: [...model.pending, message] }) return model.pending.length === 0 ? step.run(Measure.make()) : step } case "Measured": { const plan = Virtualizer.plan(model, props) const items = new Map() let placed = model.placed for (const measurement of model.pending) { if (!currentOf(plan, props, measurement)) continue const { first, index, key, at, size } = measurement if (first && index === placedOf(plan)) { placed = { index, key: key ?? String(index), at } } items.set(index, { index, key, top: at, left: 0, size }) } const next = { ...model, placed, pending: [] } // Positions from separate layout passes don't imply a grid gap. return finish( $, props, Virtualizer.update( next, { ...props, layout: "absolute" }, Virtualizer.Message.MeasuredItems({ epoch: plan.epoch, width: model.width, items: Array.from(items.values()) }) ), following(model, props) ) } case "Requested": return finish( $, props, Virtualizer.update( model, props, Virtualizer.Message.RequestedScroll({ scrollTo: message.scrollTo }) ) ) case "Resolved": return finish($, props, { model, events: [] }) case "Fixed": return $.set({ ...model, placed: null }) case "DragBegan": { const dropped = Virtualizer.update( model, props, Virtualizer.Message.ScrolledByUser() ).model return finish( $, props, scrolling({ ...dropped, aimed: null }, props, true) ).run(Command.interrupt(Settle)) } case "DragEnded": return model.momentum ? $ : $.run(Settle.make()) case "MomentumBegan": return $.set({ ...model, momentum: true }) .run(Command.interrupt(Settle)) case "MomentumEnded": return finish( $, props, scrolling({ ...model, momentum: false }, props, false) ) case "Settled": return model.momentum ? $ : finish($, props, scrolling(model, props, false)) case "Scaled": return $.set({ ...model, scale: message.scale }) } }, subscriptions: ({ model, props }) => { const fresh = Virtualizer.freshOf(model, props) // A key can appear without a native event. Resolve waiting requests // on props changes too, so the list scrolls to the new target. const held = fresh !== null || model.viewport === 0 ? null : Virtualizer.waitingOf(model, props) const target = held === null ? null : Virtualizer.targetOf(model, withDefaults(props), held) return [ fresh !== null && Subscription.make( "VirtualList.scrollTo", JSON.stringify(fresh), () => Stream.make(Message.Requested({ scrollTo: fresh })) ), target !== null && Subscription.make( "VirtualList.resolved", String(target), () => Stream.make(Message.Resolved()) ), // Fixed rows can move without a scroll or content-size event. Drop // the old placement on entry to fixed mode, before measuring resumes. props.measure === false && model.placed !== null && Subscription.make( "VirtualList.fixed", "", () => Stream.make(Message.Fixed()) ), scaled ] }, parts: (p, model) => { const props = withDefaults(p.props) const plan = Virtualizer.plan(model, props) const horizontal = props.horizontal === true const axis = horizontal ? "width" : "height" const anchored = anchoredOf(props) const anchor = placedOf(plan) const main = (rect: Native.Rect) => horizontal ? rect.x : rect.y const length = ( rect: { readonly width: number; readonly height: number } ) => horizontal ? rect.width : rect.height const docks: boolean = !horizontal && (globalThis as any).__nativeComponentRegistry__hasComponent?.("EffectUIStickyHeader") if (!horizontal && !docks && props.sticky?.length) dev.unpinnedSticky() const onScroll = (event: Native.ScrollPayload): Message | undefined => { const offset = horizontal ? event.x : event.y const viewport = length(event) const content = horizontal ? event.contentWidth : event.contentHeight const start = startOf(model, props, offset, plan) // Most scroll events leave the same items visible and send nothing. // A waiting request's plan is around its target, not the viewport, so // the scroll that reaches the target is sent. return props.trackScroll !== true && plan.request === null && Virtualizer.same(viewport, model.viewport) && Virtualizer.same(content, model.content) && Virtualizer.within(plan.first, start) && Virtualizer.within(plan.last, start + viewport) && (offset <= Virtualizer.edgeThreshold) === model.atStart && atEndOf({ scrollOffset: offset, viewport, content }, props) === model.atEnd ? undefined : Message.Scrolled({ offset, viewport, content }) } const spacerPart = p.part( "view", (b) => b.on( "layout", ({ layout }) => Virtualizer.same(main(layout), model.spacer) ? undefined : Message.PlacedSpacer({ at: main(layout) }) ) ) const spacer = (name: string, size: number, placed = false) => { const element = new Native.ViewElement< never, never, Native.ViewEvents, "view" >("view") .key("virtual-list:" + name) .style({ [axis]: Math.max(0, size) }) return View.toNode(placed ? spacerPart(element) : element) } const itemPart = p.part("view", (b, index: number) => { if (docks && props.sticky?.includes(index)) { b = b.forward((node) => ({ ...View.build( node.style({ zIndex: 10 }).prop("collapsable", false), [] ), tag: "virtualListStickyHeader" })) } if (props.measure === false) { const size = props.sizes?.[index] ?? props.itemSize return b.forward((node) => node.style({ [axis]: size })) } const key = Virtualizer.keyOf(props, index) const first = index === anchor return b.on("layout", ({ layout }) => Message.LaidOutItem({ epoch: plan.epoch, index, key, at: main(layout), size: length(layout), first })) }) const withSpacers = ( children: ReadonlyArray>, owner: View.Owner | undefined ) => { const out: Array> = [] const before = spacer("before", plan.before + reserveOf(props), true) let k = 0 for (const child of children) { const item = child._tag === "Element" && child.owned?.some((layer) => layer.owner === owner) === true if (item) { const index = plan.items[k]! const gap = plan.gaps.get(index) if (k === 0) out.push(before) else if (gap !== undefined) out.push(spacer("between:" + index, gap)) k++ } out.push(child) if (item && k === plan.items.length) { out.push(spacer("after", plan.after)) } } if (k === 0) out.push(before, spacer("after", plan.after)) return out } return { items: plan.items, count: plan.count, atStart: model.position !== null && model.atStart, atEnd: model.position !== null && model.atEnd, scrolling: model.scrolling, list: p.part("scroll", (b) => b.ref(Root) .on("layout", ({ layout }) => Virtualizer.same(length(layout), model.viewport) && Virtualizer.same( horizontal ? layout.height : layout.width, model.cross ) ? undefined : Message.LaidOutViewport({ size: length(layout), cross: horizontal ? layout.height : layout.width })) .on("scroll", onScroll) .on("contentSizeChange", (size) => Virtualizer.same(length(size), model.content) ? undefined : Message.ResizedContent({ content: length(size) })) .on("scrollBeginDrag", Message.DragBegan()) .on("scrollEndDrag", Message.DragEnded()) .on("momentumScrollBegin", Message.MomentumBegan()) .on("momentumScrollEnd", Message.MomentumEnded()) .forward((node) => { let scroll = horizontal ? node.horizontal() : node if (anchored) { scroll = scroll.prop("maintainVisibleContentPosition", { minIndexForVisible: 0 }) } const built = View.build(scroll, []) const owner = built.owned?.find((layer) => layer.handlers.scroll === onScroll)?.owner return { ...built, children: withSpacers(built.children, owner) } })), item: View.wrapPart( itemPart, >( { element, index }: { readonly element: B; readonly index: number } ): ItemOf => itemPart(element, index) as ItemOf ) } } })