VirtualList
Alpha.10
Available in Mavis alpha.11 for Vue Web and NativeScript. Keep core and renderer versions aligned.
<MVirtualList
:items="items"
itemKey="id"
:rowHeight="72"
:height="360"
label="Collections"
><template #default="{ item }">…</template></MVirtualList>| Property | Type | Default | Description |
|---|---|---|---|
items | readonly T[] | required | Collection owned by the app. |
itemKey | keyof T / (item: T) => string or number | id | Unique stable identity; index keys are unsuitable for reorder. |
rowHeight | number / 'auto' | required | Fixed positive row height in CSS px / DIP, or auto to measure. |
estimatedRowHeight | number | — | Height assumed for a row not measured yet. Required with auto. |
height | number | required | Finite scroll viewport height. |
overscan | number | 3 | Extra Web rows; native owns recycling buffers. |
initialIndex | number | 0 | Initial scroll destination. |
animated | boolean | true | Animate keyed data changes on Web/NativeScript. |
label / emptyLabel | string | required / No items | List name and empty fallback. |
A vertical, fixed-row-height collection. Web renders only the viewport plus overscan; NativeScript uses its recycled ListView. The typed default slot receives { item, index, itemKey }; empty replaces the empty fallback. scrollToIndex(index) scrolls through a public handle and rejects an invalid index. scrollToKey(key, { align }) brings a row to the start (default), center or end of the viewport and returns false, without scrolling, when no item has that key. Use immutable array replacement or reactive items. Duplicate/missing keys fail early, and numeric/string keys stay distinct. Insertions, removals, sorting and filtering preserve the first visible key and its offset inside the row on Web and NativeScript. If that key is removed, the nearest surviving index becomes the anchor; the result is clamped to the scrollable range.
Keep drafts, selection and loading state in the item or an external store keyed by identity. Cell-local state is not retained after unmount; native cells reset their keyed child when reused. Web keeps a focused row mounted while scrolling and returns focus to the list if that item is removed. Arbitrary native editor focus across offscreen recycling is not promised. With a fixed rowHeight, choose a height that fits the actual text and accessibility font size, or measure the rows. Paging, drag reorder and automatic scroll restoration across route unmounts are outside this contract. Give the list its own bounded viewport; avoid placing it inside another vertical scroller. SSR renders the same bounded initial window and hydrates its initial scroll position.
Keyed changes with Jolt
The upcoming release uses Jolt RC.15 listChanges for data changes. Retained visible rows move into their new positions, newly inserted visible items enter, and removed visible items can leave through bounded, noninteractive presentation copies. Rows entering the viewport through ordinary scrolling do not replay an entrance. MVirtualList owns this work: do not also animate its rows with animateLayout or another listChanges controller.
Use :animated="false" for immediate visual updates while retaining key and scroll anchoring. Reduced motion also settles immediately. Recycling clears the previous item's motion before the row is rebound; hiding/unmounting the list releases its controller and any exit copies. State that must survive remains in your keyed data or store.
For a keyed shared-photo return, call realizeKey({ key, tag, signal }) on the mounted list. It resolves to true when the current row for that key has a stable tagged surface, and to false on removal, interruption or timeout. Both finite numeric and string item keys are supported. Photo collection example.
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useCatalogLocale } from '../locale'
const props = defineProps<{ lang?: 'en' | 'pt' }>()
const { locale } = useCatalogLocale(() => props.lang)
const pt = computed(() => (props.lang ?? locale.value) === 'pt')
const t = (en: string, br: string) => (pt.value ? br : en)
import type { VirtualListHandle } from '@getcortexlabs/mavis-core'
const list = ref<VirtualListHandle>()
const items = ref(
Array.from({ length: 1000 }, (_, i) => ({
id: i + 1,
title: `Collection ${i + 1}`,
saved: false,
})),
)
function reverse() {
items.value = [...items.value].reverse()
}
</script>
<template>
<MColumn gap="md">
<MRow gap="sm" wrap
><MButton
:text="t('Last item', 'Último item')"
@click="list?.scrollToIndex(items.length - 1)" /><MButton
:text="t('Reverse', 'Inverter')"
variant="secondary"
@click="reverse"
/></MRow>
<MVirtualList
ref="list"
:items="items"
itemKey="id"
:rowHeight="72"
:height="360"
:label="t('A thousand collections', 'Mil coleções')"
>
<template #default="{ item }"
><MRow :height="72" paddingX="sm" gap="md"
><MText :text="`${t('Collection', 'Coleção')} ${item.id}`" :grow="1" /><MButton
:text="item.saved ? t('Saved', 'Salvo') : t('Save', 'Salvar')"
:icon="item.saved ? 'heart' : 'plus'"
:accessibilityLabel="`${t('Save', 'Salvar')} ${item.id}`"
variant="ghost"
@click="item.saved = !item.saved" /></MRow
></template>
</MVirtualList>
<MText
:text="
t(
'Saved state belongs to each item and survives cell reuse.',
'O estado pertence a cada item e acompanha a reciclagem das células.',
)
"
variant="caption"
tone="muted"
/>
</MColumn>
</template>Rows of different heights
With rowHeight="auto" each row takes the height of its content: text that wraps, a picture whose size is known only once it loads, replies that open. Give estimatedRowHeight the height of a typical row; rows not measured yet count at that height, so the scroll bar can change length as you scroll. On WebKit, a jump to a measured row uses the nearest scroll position the browser can represent, including when the preceding rows have fractional heights.
<MVirtualList
ref="list"
:items="posts"
itemKey="id"
rowHeight="auto"
:estimatedRowHeight="96"
:height="420"
label="Posts"
><template #default="{ item }">…</template></MVirtualList>list.value?.scrollToKey(7777, { align: 'center' })Only the rows in view, plus overscan on the Web, exist, whatever their heights. The list keeps the row you are reading where it is:
- When rows are inserted, removed, reordered or filtered above it, the first visible row keeps its key and the distance between its top and the top of the list.
- When a row above it grows or shrinks, because a picture loaded, text was edited or replies opened, the rows you see do not move.
- When the list changes width or the text size changes, every row is measured again and the first visible row stays put.
- If that row is removed, another row that was visible takes its place; if none of them is left, the next row of the previous order goes to the top, then the previous one.
- While you are scrolling, the list never writes the scroll position. New heights move the rows instead, and the position is corrected once you let go.
scrollToKey and scrollToIndex reach rows that were never on screen: the row is placed from the estimate, then placed again as it and its neighbours are measured, until you scroll.
Heights are kept by key. They are forgotten when the key leaves the list or when its item changes to another object, and all of them when the width changes. A recycled row never shows the height, drafts or motion of the key it showed before: keep drafts and open sections in your data or a store keyed by identity, as in the example below. Hiding the list, a KeepAlive and reduced motion work as with fixed rows.
On iOS a new width or text size can show the previous heights for one frame before the first row is put back. On Android center and end take a second frame to land once the row is measured. A measured list on iOS and Android does not accept motionScroll: the Web follows its scroll, native platforms need fixed rows.
Open the ten-thousand-post example.
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import type { VirtualAlign, VirtualListHandle } from '@getcortexlabs/mavis-core'
import { cropQuadrants } from '../assets/crop-quadrants'
defineProps<{ mode?: string }>()
/** One post of a feed whose rows grow with their text, a picture and opened replies. */
interface Post {
id: number
author: string
text: string
/** Width over height, known only once the picture has loaded. */
ratio?: number
replies: readonly string[]
}
const authors = ['Ada', 'Grace', 'Alan', 'Barbara', 'Edsger', 'Margaret', 'Donald']
const sentences = [
'Shipped the new build.',
'The review notes are in the shared folder, with the open questions at the end.',
'Lunch is moving to the terrace on Friday if the weather holds.',
'Anyone else seeing the staging deploy take twice as long since this morning? The logs show the cache being rebuilt on every step.',
'Thanks!',
]
const ratios = [4 / 3, 3 / 4, 16 / 9, 1]
function post(id: number): Post {
const length = 1 + ((Math.abs(id) * 7) % 5)
return {
id,
author: authors[Math.abs(id) % authors.length]!,
text: Array.from({ length }, (_, index) => sentences[(Math.abs(id) + index) % 5]).join(' '),
ratio:
Math.abs(id) % 4 === 0 ? ratios[Math.floor(Math.abs(id) / 4) % ratios.length] : undefined,
replies: Array.from({ length: 1 + (Math.abs(id) % 3) }, (_, index) => `Reply ${index + 1}`),
}
}
const fresh = () => Array.from({ length: 10_000 }, (_, id) => post(id))
const list = ref<VirtualListHandle>()
const posts = ref<Post[]>(fresh())
// Everything a row shows besides the post itself belongs to the page, by key: a row that is
// recycled or realized again finds it here.
const loaded = reactive(new Set<number>())
const opened = reactive(new Set<number>())
const replies = reactive(new Map<number, string>())
const narrow = ref(false)
const large = ref(false)
const visible = ref(true)
const reached = ref('none')
let added = 0
function prepend(count: number) {
posts.value = [...Array.from({ length: count }, () => post(-++added)), ...posts.value]
}
function rapid() {
for (let step = 0; step < 10; step++) setTimeout(() => prepend(1), step * 30)
}
function reorderTop() {
posts.value = [...posts.value.slice(0, 50).reverse(), ...posts.value.slice(50)]
}
function jump(key: number, align: VirtualAlign) {
reached.value = `${key}:${align}:${list.value?.scrollToKey(key, { align }) ?? false}`
}
function toggle(id: number) {
if (opened.has(id)) opened.delete(id)
else opened.add(id)
}
function reset() {
posts.value = fresh()
loaded.clear()
opened.clear()
replies.clear()
list.value?.scrollToIndex(0)
}
const state = computed(
() =>
`${posts.value.length}|${opened.size}|${loaded.size}|${reached.value}|${replies.get(7778) ?? ''}`,
)
</script>
<template>
<MScreen>
<MColumn padding="md" gap="sm">
<MText text="Measured feed" variant="title" as="h1" />
<MRow v-if="mode !== 'reader'" gap="sm" wrap>
<MButton
size="sm"
variant="secondary"
id="feed-prepend"
text="Prepend 3"
@click="prepend(3)"
/>
<MButton
size="sm"
variant="secondary"
id="feed-remove-top"
text="Remove first 10"
@click="posts = posts.slice(10)"
/>
<MButton
size="sm"
variant="secondary"
id="feed-reorder-top"
text="Reverse first 50"
@click="reorderTop"
/>
<MButton
size="sm"
variant="secondary"
id="feed-rapid"
text="Rapid prepends"
@click="rapid"
/>
<MButton
size="sm"
variant="secondary"
id="feed-filter"
text="Hide every third"
@click="posts = posts.filter((item) => item.id % 3 !== 0)"
/>
<MButton
size="sm"
variant="secondary"
id="feed-remove-anchor"
text="Remove 7777"
@click="posts = posts.filter((item) => item.id !== 7777)"
/>
<MButton size="sm" variant="secondary" id="feed-reset" text="Reset" @click="reset" />
</MRow>
<MRow v-if="mode !== 'reader'" gap="sm" wrap>
<MButton
size="sm"
variant="secondary"
id="feed-jump-start"
text="7777 at start"
@click="jump(7777, 'start')"
/>
<MButton
size="sm"
variant="secondary"
id="feed-jump-center"
text="7777 centred"
@click="jump(7777, 'center')"
/>
<MButton
size="sm"
variant="secondary"
id="feed-jump-end"
text="7777 at end"
@click="jump(7777, 'end')"
/>
<MButton
size="sm"
variant="secondary"
id="feed-jump-missing"
text="Missing key"
@click="jump(-99_999, 'start')"
/>
<MButton
size="sm"
variant="secondary"
id="feed-narrow"
:text="narrow ? 'Full width' : 'Narrow'"
@click="narrow = !narrow"
/>
<MButton
size="sm"
variant="secondary"
id="feed-large"
:text="large ? 'Regular text' : 'Larger text'"
@click="large = !large"
/>
<MButton
size="sm"
variant="secondary"
id="feed-hide"
:text="visible ? 'Hide list' : 'Show list'"
@click="visible = !visible"
/>
</MRow>
<MRow v-if="mode === 'reader'" gap="xs">
<MButton id="reader-jump" size="sm" text="Jump to post 7777" @click="jump(7777, 'start')" />
<MButton id="reader-edit" size="sm" text="Edit 7778" @click="jump(7778, 'start')" />
<MButton id="reader-prepend" size="sm" text="Prepend 3" @click="prepend(3)" />
</MRow>
<MBox :width="narrow ? 280 : '100%'">
<MVirtualList
v-if="visible"
id="virtual-feed"
ref="list"
:items="posts"
itemKey="id"
rowHeight="auto"
:estimatedRowHeight="96"
:height="400"
label="Ten thousand posts"
>
<template #default="{ item }">
<MColumn :id="`feed-row-${item.id}`" paddingX="sm" paddingY="xs" gap="xs">
<MText :text="`${item.author} · #${item.id}`" variant="caption" tone="muted" />
<MText
:id="`feed-text-${item.id}`"
:text="item.text"
:variant="large ? 'heading' : 'body'"
/>
<MImage
v-if="item.ratio"
:id="`feed-picture-${item.id}`"
:src="cropQuadrants"
:alt="`Picture of post ${item.id}`"
:aspectRatio="loaded.has(item.id) ? item.ratio : 4"
@load="loaded.add(item.id)"
/>
<MButton
:id="`feed-expand-${item.id}`"
variant="ghost"
:text="opened.has(item.id) ? 'Hide replies' : `Show ${item.replies.length} replies`"
@click="toggle(item.id)"
/>
<MColumn v-if="opened.has(item.id)" gap="xs">
<MText v-for="reply in item.replies" :key="reply" :text="reply" />
<MInput
:id="`feed-reply-${item.id}`"
:label="`Reply to ${item.id}`"
:modelValue="replies.get(item.id) ?? ''"
@update:modelValue="(value: string) => replies.set(item.id, value)"
/>
</MColumn>
</MColumn>
</template>
</MVirtualList>
</MBox>
<MText id="virtual-feed-state" :text="state" variant="caption" />
</MColumn>
</MScreen>
</template>Linking scroll to a surface
Pass a reference from createMotionScrollSource() to a fixed-row list through its motionScroll prop. A declared surface can follow the scrolling distance in CSS pixels on Web or DIP on native. Changing the row height or item count refreshes the bounds. On iOS and Android the fixed-row list requires Jolt’s native vertical source. Requesting the scheduler for that list throws. A scrolling MScreen also accepts scrollAxis="x" for horizontal scrolling. Use axis: "x" on a numeric link to that screen.
const indicator = marker.scrollLinked(listSource, { x: [0, 96] }, { range: [0, 240] })Open the scroll sources example.
Simulator and emulator checks
In the 10,000-post catalog, after the jump and scroll sequence, the iPhone 15 Pro simulator (iOS 17.5) retained eight row views and 53–54 cached heights across two runs. The Android emulator (API 36) retained six to seven row views. These counts describe this fixture and viewport. The 26 checks per platform include alignment of an unvisited row, ten consecutive prepends and preservation of a draft across recycling.
In the 10,000-post catalog, entering the list with VoiceOver on the iOS 27 simulator read the three prepended posts in order and then the previous first post. Starting on post 7777 with TalkBack on Android API 36 and swiping right reached 7778 and 7779, including the text and reply controls between them. Typing into an expanded reply on each platform and prepending more posts preserved the draft under its original key. These checks used simulator and emulator keyboards. Physical keyboard layouts and third-party IME composition are still unverified.
Reordering a thousand rows on the Web
On the Web renderer, pass a stable reorder object and update your list in onCommit. The event contains key, beforeKey (or null at the end), fromIndex and toIndex. The dragged row stays mounted while other rows enter and leave the window. Keyboard and pointer input use the same logical order, including measured rows.
<MVirtualList
:items="stops"
itemKey="id"
rowHeight="auto"
:height="300"
label="Stops"
:reorder="sort"
>
<template #default="{ item }">
<span>{{ item.name }}</span>
<button class="grip" :aria-label="item.name">↕</button>
</template>
</MVirtualList>Define sort = { handle: ".grip", onCommit }. Hold a handle to drag. On a keyboard, Space picks up the row, arrows or Home/End move it, and Escape cancels. The Web ref exposes moveUp(key), moveDown(key) and cancelReorder(). An offscreen item can move without being mounted. Try the thousand-stop list.
Desktop
On the Mac and Windows hosts only the rows in view, plus overscan, exist as native views. Each row keeps its identity by key while the list scrolls, a row whose control has the keyboard stays until the focus leaves it, and scrollToIndex and scrollToKey move the native scroll view. With rowHeight="auto" a row takes the height Mavis's layout gives its content, and the row you are reading stays in place through changes above it and a new width, as on the Web. animated and motionScroll are accepted with no effect yet: rows are placed at once. See Desktop components.
Recordings
The same feed has 10,000 posts. Jump to a distant post, prepend rows and resize the content while watching the first visible post.
Web
iOS Simulator
Android emulator