---
title: "Primitives"
description: "Functions that return the rectangle, row and column of any item, for ARIA, overlays and custom events."
canonical_url: "https://vvirtual-grid.netlify.app/reference/primitives"
---
# Primitives

> Functions that return the rectangle, row and column of any item, for ARIA, overlays and custom events.

The grid does not add ARIA roles, focus handling or overlays. Instead, it gives you the positions it already computes, so you can build them yourself. Use the primitives to get an item's rectangle, or its row and column, even when the item is not rendered.

## Example grid

The example passes a `pageProvider` to the grid, as in the [VirtualGrid example](https://vvirtual-grid.netlify.app/reference/virtual-grid#example-grid).

```vue
<script setup lang="ts">
import { useTemplateRef } from "vue";
import { VirtualGrid } from "vvirtual-grid/vue";
import { createRectQuery, getItemRect } from "vvirtual-grid/primitives";

const grid = useTemplateRef("grid");
const marker = useTemplateRef("marker");
const query = createRectQuery({ index: 4200 });

function onViewportScroll() {
  query.root = grid.value.$el;
  query.layout = grid.value.measurement;
  if (getItemRect(query)) {
    marker.value.style.translate = `${query.rect.x}px ${query.rect.y}px`;
  }
}
</script>
```

Call the handler from the grid's `viewport-scroll` event. The marker is a fixed element outside the scroll container.

```vue
<template>
  <div class="h-96 overflow-y-auto">
    <VirtualGrid
      ref="grid"
      :length="10000"
      :page-size="40"
      :page-provider="pageProvider"
      @viewport-scroll="onViewportScroll"
      class="grid grid-cols-[repeat(auto-fill,minmax(80px,1fr))] gap-2"
    >
      <template #default="{ item, index, style }">
        <div :style="style" :data-index="index" class="h-12">{{ item.title }}</div>
      </template>

      <template #probe>
        <div class="h-12" />
      </template>
    </VirtualGrid>
  </div>
  <div ref="marker" style="position: fixed; inset: 0 auto auto 0; width: 8px; height: 8px; background: red" />
</template>
```

The marker follows item 4200 while the user scrolls. Item 4200 does not need to be rendered, because its rectangle comes from its index and the grid's measurement.

## Query objects

Each primitive reads its input from a query object and writes its result into the same object. The object holds the input fields (`index`, `layout`, and `root` for rectangles). It also holds the field that receives the result: `rect` for a rectangle, `cell` for a row and column.

The grid emits `viewport-scroll` on every scroll event. If each handler call built a new object, the browser would have to collect all of them while the user scrolls. A query object is created once and reused, so a call creates no object.

C APIs use the same idea with an output parameter: `get_rect(index, &rect)` fills a struct the caller owns, instead of returning a new one.

Create a query with `createRectQuery` or `createCellQuery`. Before each call, set `index`. Set `layout` and `root` from the grid as well, because both change when the grid resizes. The sample in [Get an item's rectangle](#get-an-items-rectangle) sets all three on every scroll.

<field-group>
<field name="index">

Zero-based index of the item. The primitives do not check it against `length`.

</field>

<field name="layout">

The grid's exposed [`measurement`](https://vvirtual-grid.netlify.app/reference/virtual-grid#exposed-values). It is `undefined` until the grid is measured, and the primitives return `false` or `-1` while it is.

</field>

<field name="root">

Rectangle queries only. The grid element, `grid.value.$el`. Leave it `null` for coordinates relative to item 0.

</field>

<field name="rect">

Rectangle queries only. Where `getItemRect` writes `x`, `y`, `width`, `height`, `top`, `right`, `bottom` and `left`.

</field>

<field name="cell">

Cell queries only. Where `getItemCell` writes `row` and `column`, and what `getIndexByCell` reads.

</field>
</field-group>

<note>

`rect` has the fields of a `DOMRect`. A Floating UI virtual element can return it from `getBoundingClientRect()`.

</note>

## Get an item's rectangle

### `createRectQuery`

```ts
createRectQuery(init?: { index?, layout?, root? }): RectQuery
```

Returns a query with a zeroed `rect`. Every field in `init` is optional.

### `getItemRect`

```ts
getItemRect(query: RectQuery): boolean
```

Writes the item's rectangle into `query.rect`. What the numbers are relative to depends on `query.root`:

- With `root` set to `null`, they are relative to the top-left corner of item 0. This is arithmetic, with no DOM read.
- With `root` set to the grid element, they are relative to the viewport, like `getBoundingClientRect()`. This reads the layout of one element.

It returns `false` and leaves `rect` unchanged when `layout` is `undefined`, or when `root` is set and the grid has rendered nothing.

## Get a row and column

With `grid-auto-flow: column`, indexes fill a column before moving to the next one. These functions follow that order.

### `createCellQuery`

```ts
createCellQuery(init?: { index?, layout? }): CellQuery
```

Returns a query with a zeroed `cell`.

### `getItemCell`

```ts
getItemCell(query: CellQuery): boolean
```

Reads `query.index` and writes the zero-based `row` and `column` into `query.cell`. It returns `false` when `layout` is `undefined`.

### `getIndexByCell`

```ts
getIndexByCell(query: CellQuery): number
```

Reads `query.cell` and returns the index at that row and column. It returns `-1` when `layout` is `undefined`.

## Track rendered items

### `createItemTracker`

```ts
createItemTracker({ onBind?, onUnbind? }): (root: Element) => void
```

Returns a function. Call it with the grid element from the `render` event. Each call compares the rendered items with the previous call.

<field-group>
<field name="onBind">

`(index, element) => void`. An element started rendering `index`. It also runs when a loaded item replaces its placeholder.

</field>

<field name="onUnbind">

`(index) => void`. No element renders `index` any more.

</field>
</field-group>

The tracker reuses two internal maps, so a call after the first creates no object.

```vue
<script setup lang="ts">
import { useTemplateRef } from "vue";
import { createItemTracker } from "vvirtual-grid/primitives";

const grid = useTemplateRef("grid");
const anchored = 0; // the item the list marks as current

const track = createItemTracker({
  onBind: (index, element) => element.toggleAttribute("aria-current", index === anchored),
  onUnbind: (index) => console.log("item left the DOM", index),
});
</script>
```

Call the tracker with the grid element on the `render` event.

The grid is the one from [Example grid](#example-grid).

```vue
<template>
  <div class="h-96 overflow-y-auto">
    <VirtualGrid ref="grid" @render="track(grid.$el)">
      <template #default="{ item, index, style }">
        <div :style="style" :data-index="index">{{ item.title }}</div>
      </template>
    </VirtualGrid>
  </div>
</template>
```

## Doing it with the DOM

Set `:data-index="index"` on the root element of the `default` and `placeholder` slots. Three questions then need no primitive.

Which element renders item 42? Select it from the grid element. It is `null` when the item is not rendered.

```ts
const element = grid.value.$el.querySelector(':scope > [data-index="42"]');
```

Which item did an event come from? Find the closest element with the attribute. The result is `-1` outside an item.

```ts
const index = Number(event.target.closest("[data-index]")?.dataset.index ?? -1);
```

How many rows does the list have? Divide the length by the number of columns and round up. This holds in row flow, the default. In column flow, `measurement.rows` is the number of rows.

```ts
const rowCount = Math.ceil(10000 / grid.value.measurement.columns);
```

<warning>

`measurement` is `undefined` until the grid has measured itself. Read it in a `layout-change` handler, which the grid emits each time `measurement` changes, or check that it is set before you use it.

</warning>

## Types

All exported from `vvirtual-grid/primitives`. [`RectQuery` and `CellQuery`](#query-objects) hold the input and output fields, and [`ItemTrackerCallbacks`](#track-rendered-items) holds the tracker callbacks. `ItemRect` has the fields of a `DOMRect`, and `ItemCell` has `row` and `column`.

`ItemLayout` is the part of `measurement` the primitives read: `flow`, `columns`, `rows`, `colGap`, `rowGap`, `itemWidthWithGap` and `itemHeightWithGap`.


## Sitemap

See the full [sitemap](https://vvirtual-grid.netlify.app/sitemap.md) for all pages.
