DataTable
Added in alpha.11
Included in Mavis 0.1.0-alpha.11 for Vue + Vite, Nuxt and NativeScript iOS/Android. Keep core and renderers on the same version.
<MDataTable
:items="rows"
:columns="columns"
v-model:sort="sort"
v-model:selected="selected"
label="Collections"
selectable
/>| Prop | Type | Default | Description |
|---|---|---|---|
items / itemKey | readonly object[] / string or function | required / id | Current page and stable identity. |
columns | readonly DataColumn[] | required | Key, label, width, alignment and optional value accessor. |
sort / v-model:sort | DataSort or null | null | Cycles ascending, descending and unsorted; the application sorts the data. |
selected / v-model:selected | readonly ChoiceValue[] | [] | Selected keys; selection on other pages is preserved. |
selectable / rowDisabled / rowLabel | boolean / function / function | false / — / — | Optional selection, row availability and accessible row label. |
disabled / loading | boolean | false | Prevent changes; loading presents a progress indicator. |
selectionLabel | (count) => string | — | Words for how many rows are selected, shown beside the title of a selectable table. |
The table receives the current page. Sorting, filtering, requests and pagination belong to the application; place MPagination in footer. Slots cell and cell:key receive item, itemKey, column, value and index; actions and empty are also available. Web uses an HTML table with headers and aria-sort. Native columns scroll horizontally and cells retain their column labels. Numeric and string identities remain distinct. Cells become editable one column at a time (see Editing cells); this is not a spreadsheet or a virtualized list: paginate large datasets.
Rows keep their identity, so a new sort moves each row to its place instead of redrawing the table. The sort arrow flips with a spring when the direction changes and pops in on the column that just became the key; aria-sort and the button name change at once. On Web a selected row's background fades in, and the count from selectionLabel gives a small bump on every change. The count is plain text, not a live region: the checkboxes already report each change. Reduced motion keeps every state and drops the movement.
<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 { ChoiceValue, DataColumn, DataSort } from '@getcortexlabs/mavis-core'
const query = ref('')
const sort = ref<DataSort | null>(null)
const selected = ref<ChoiceValue[]>([])
const page = ref(1)
const items = [
{ id: 'atlas', name: 'Atlas', kind: 'Design', members: 12 },
{ id: 'bloom', name: 'Bloom', kind: 'Research', members: 8 },
{ id: 'cove', name: 'Cove', kind: 'Product', members: 24 },
{ id: 'drift', name: 'Drift', kind: 'Design', members: 6 },
{ id: 'ember', name: 'Ember', kind: 'Product', members: 16 },
{ id: 'fern', name: 'Fern', kind: 'Research', members: 4 },
]
const columns = computed<DataColumn[]>(() => [
{ key: 'name', label: t('Collection', 'Coleção'), sortable: true, width: 180 },
{ key: 'kind', label: t('Discipline', 'Disciplina'), width: 160 },
{ key: 'members', label: t('Members', 'Membros'), sortable: true, align: 'end', width: 144 },
])
const filtered = computed(() => {
const result = items.filter((item) => item.name.toLowerCase().includes(query.value.toLowerCase()))
if (sort.value) {
const { key, direction } = sort.value
result.sort(
(a, b) =>
(key === 'members' ? a.members - b.members : a.name.localeCompare(b.name)) *
(direction === 'ascending' ? 1 : -1),
)
}
return result
})
const visible = computed(() => filtered.value.slice((page.value - 1) * 3, page.value * 3))
</script>
<template>
<MColumn gap="lg">
<MText variant="overline" :text="t('YOUR WORKSPACE', 'SEU ESPAÇO')" tone="primary" />
<MInput
v-model="query"
:label="t('Find a collection', 'Encontrar coleção')"
@update:modelValue="page = 1"
/>
<MDataTable
:label="t('A place for every idea', 'Um lugar para cada ideia')"
:items="visible"
:columns="columns"
v-model:sort="sort"
v-model:selected="selected"
selectable
:rowLabel="(item) => String(item.name)"
:selectionLabel="
(count) =>
count
? t(`${count} selected`, `${count} ${count === 1 ? 'selecionada' : 'selecionadas'}`)
: t('None selected', 'Nenhuma selecionada')
"
>
<template #cell="{ column, value }"
><MBadge v-if="column.key === 'kind'" :text="String(value)" tone="primary" /><MText
v-else
:text="String(value)"
:weight="column.key === 'name' ? '600' : '400'"
/></template>
<template #footer
><MPagination
v-model="page"
:total="filtered.length"
:pageSize="3"
:label="t('Collection pages', 'Páginas de coleções')"
/></template>
</MDataTable>
<MText
id="table-selection"
:text="selected.join(', ') || t('Nothing selected', 'Nenhuma seleção')"
tone="muted"
variant="caption"
/>
</MColumn>
</template>Editing cells
Give a column an editor and the table a commitCell function. The table keeps the draft of one cell at a time, keyed by the row key and the column key; the rows stay yours. commitCell stores the value, updates your rows and answers with what happened.
Open the editable orders screen ↗
const columns = computed<DataColumn<Order>[]>(() => [
{ key: 'id', label: t('Order', 'Pedido'), width: 104, sortable: true },
{
key: 'customer',
label: t('Customer', 'Cliente'),
width: 200,
sortable: true,
editor: {
type: 'text',
maxLength: 60,
validate: (value) =>
String(value ?? '').trim() ? undefined : t('Enter a customer name.', 'Informe o cliente.'),
},
},
{
key: 'total',
label: 'Total',
width: 160,
align: 'end',
sortable: true,
value: (order) => money(order.total),
editor: {
type: 'number',
min: 0,
step: 0.01,
locale: pt.value ? 'pt-BR' : 'en-US',
validate: (value) => (value === null ? t('Enter a total.', 'Informe o total.') : undefined),
},
},
{
key: 'status',
label: 'Status',
width: 180,
value: (order) => statusLabels.value[order.status],
editor: {
type: 'choice',
options: (Object.keys(statusLabels.value) as OrderStatus[]).map((value) => ({
value,
label: statusLabels.value[value],
})),
// Delivered and cancelled orders are settled: their status is read-only.
readonly: (order) => order.status === 'delivered' || order.status === 'cancelled',
},
},
{
key: 'note',
label: t('Note', 'Observação'),
width: 220,
editor: { type: 'text', multiline: true, maxLength: 140 },
},
])async function commitCell(change: DataCellChange<Order>): Promise<DataCellResult> {
const result = await service.save(
String(change.itemKey),
change.column.key as OrderField,
change.value,
change.signal,
)
failNext.value = service.options.failNext
if (result.status === 'saved') orders.value = service.list()
outcome.value = `${change.itemKey} · ${change.column.label} · ${result.status}`
return result
}| Editor | Options | The draft is |
|---|---|---|
text | multiline, maxLength, placeholder | the text, as typed |
number | min, max, step, locale | text read like MNumberInput; empty is null |
choice | options (as in MSelect) | the chosen value; choosing it commits |
Every editor also takes value(item) (where the editor starts; by default the field named by the column key, not the display value of the column), readonly(item) (that row's cell stays plain text) and validate(value, item) (a message refuses the draft before commitCell is called).
commitCell(change) receives item, itemKey, column, value, previous (what the cell showed when editing began), current (what the row holds now) and signal. It returns, or resolves to:
| Result | The table |
|---|---|
{ status: 'saved' } | closes the editor and shows your rows; update them before you answer |
{ status: 'rejected', message } | keeps the draft in an invalid field with the message |
{ status: 'failed', message? } | keeps the draft, shows the message (or failedLabel) with Retry and Cancel |
| anything else, or a thrown error | is a failed save, never a saved one |
Keyboard and touch
| Key or gesture | Where | What it does |
|---|---|---|
| Enter, Space, F2, tap | an editable cell | opens its editor |
| Enter (return key) | a text or number field | saves; the keyboard goes back to the cell |
| Mod+Enter | a multiline field | saves; Enter adds a line |
| Tab, Shift+Tab | an editor (Web, desktop) | saves, then moves to the next or previous editable cell without opening it |
| Escape | an editor | cancels; while a save is in flight it aborts signal instead |
Keys that an input method is composing with belong to the input method: Enter and Tab during composition neither save nor move. Selection and the arrow keys inside a field are untouched. The Save and Cancel buttons beside the field are always there, for the pointer and for touch screens.
What happens to a draft
- One cell at a time. Opening another cell closes an untouched editor; an editor with changes, a refused draft or a save in flight stays, and the keyboard goes back to it.
- No duplicate saves. While a save is in flight the field is read-only and Enter, Tab and Save do nothing.
- Sort and filter. The draft follows its row key, not its position. On Web the field keeps the keyboard and the selection after the row moves.
- Outside updates. When the value of the edited cell changes in your rows, an untouched editor follows it; a draft with changes stays and says
changedLabel: <new value>, andcommitCellgets bothpreviousandcurrentso you can decide. - Removed rows and columns. If the row leaves (filter, page change, deletion) or the column loses its editor, the draft is dropped, a pending save's
signalis aborted and its answer is ignored. The keyboard goes to the same column in the row that took its place, or to the table. - Cancel during a save.
signalaborts, and the table waits for your answer:savedmeans the write landed, so the cell shows it; anything else discards the draft. Cancelling never pretends to undo a write that was stored. - Unmount. Pending saves are aborted and their answers ignored.
- Selection, sort and paging are not touched by editing. While
disabledorloading, cells show their values without the edit button and an open editor cannot save.
An editable cell is a button named by its value and described by editLabel; its editor is named by the column and the row label (Total, Order 1041), reports an invalid draft and is read-only while saving (the cell is aria-busy on Web). A status line beside the title says savingLabel, savedLabel or the reason a save did not land (role="status" on Web, a polite live region on Android). Cells of columns without an editor, and every cell of a table without one, render as before.
A check pops beside a value that was saved and an alert mark shakes beside a refused draft. The field and the focused cell never move or scale, the text outcome is in place before the motion plays, and reduced motion skips it.
The first delivery edits one cell of a bounded page. Bulk selection, clipboard ranges, formulas, offline sync and virtualized rows are outside it. On iOS and Android a hardware keyboard's Tab and Escape are not mapped; the return key saves single-line fields and the buttons do the rest.
On Web, iOS and Android, filtering or deleting a keyed row lets the remaining rows close the gap. The empty and loading states also transition when one replaces the other. Under reduced motion the table shows the new state immediately.
Desktop
On the Mac and on Windows the header stays above the rows, which scroll when the table gets less height than it needs; a sortable column is a native button, and dragging the edge of a column resizes it for the session. In a selectable table the row check boxes take Up, Down, Home and End to move between rows, and Space or Enter to select. Every row is mounted (there is no windowing), and a width set by dragging is not reported to the application. See Desktop components.
Filtering or removing a row lets it fade while its neighbours close the gap.
An editable cell is a native button with the edit hint as its tooltip; Return, Space, F2 or a click opens a native field in its place (an NSTextField on the Mac, a TextBox on Windows; a choice opens the desktop select). Return saves a one-line field, Command-Return (Control-Enter on Windows) saves a multiline one, Tab and Shift-Tab save and move to the next or previous editable cell, and Escape cancels. The window reports Tab, Escape and the modified Return to the table before the field, so the field never sees them; keys an input method is composing with stay with it on the Mac. The rest of the contract (one cell at a time, the results, retry, cancel during a save, rows that move or leave) is the same as on Web and mobile.
Recordings
The Orders example edits a single cell in place. Watch the editor open inside the table and the saved value return to its row.
Web
iOS Simulator
Android emulator