FilePicker
MFilePicker opens the platform document selector and presents selected names, optional previews, progress and actions. On Web, files can also be dropped on its zone or pasted while focus is inside the picker. The application supplies upload transport. Selecting, dropping or pasting a file never starts an upload.
Available in alpha.5
Available in Mavis alpha.5.
Shared selection
<script setup lang="ts">
import { useFileSelection } from '@getcortexlabs/mavis-core/vue'
const selection = useFileSelection({
multiple: true,
accept: ['image/*', '.pdf'],
maxCount: 3,
maxSize: 5 * 1024 * 1024,
})
</script>
<template>
<m-file-picker :selection="selection" label="Trip documents" />
</template>useFileSelection creates a controller owned by the current Vue component. Unmount cancels operations and releases resources. Deactivation pauses operations and retains files for explicit retry. Keep the owner above a conditional MFilePicker if its selection should survive hiding the control. Hiding, unloading or disabling the picker pauses its work; remounting does not resume uploads automatically.
The framework-neutral createFileSelection(options) from @getcortexlabs/mavis-core has the same state and actions; its owner must call dispose(). Create one per owner/request, never a server module singleton.
| Option | Default | Meaning |
|---|---|---|
multiple | false | Single selection replaces the prior file after validation. Multiple selection appends. |
accept | [] | Extensions, exact MIME types or families such as image/*. |
maxCount | 1, or 10 when multiple | Maximum selected descriptors. Single mode always accepts at most one. |
maxSize | unset | Per-file byte limit. A provider with unknown size cannot be checked locally. |
initial | [] | Serializable existing descriptors; no local handles or previews are created. |
upload | unset | Host callback for explicit upload/retry. No callback means selection-only UI. |
Cancelling preserves the previous selection. Invalid batches are rejected as a whole and their new resources are released. Reselecting the same file is allowed; each accepted selection gets a new ID. Multiple mode does not deduplicate separate selections. Accept/type/size checks help the UI; the server still owns authoritative validation. Unknown file types require a matching extension hint when MIME metadata is unavailable.
State and transport
selection.state contains items, picking and an optional selection error with code picker, type, size or count. Use subscribe(listener) for external observation; it returns an unsubscribe function. Snapshots are immutable. Each FileItem contains only id, name, optional size/type, status, optional progress and error. Status is selected, uploading, uploaded, failed or cancelled.
The injected upload({ item, handle, cancellation, progress }) returns a promise. Fulfilment marks success; rejection marks failure. progress(loaded, total?) reports bytes, with a positive total for known progress. Omitting total displays indeterminate progress. Reaching 100% does not complete the promise. Connect cancellation.onCancel(callback) to the host request's abort mechanism and release that subscription when the request settles.
The controller exposes upload(id), retry(id), cancel(id), remove(id), clear(), pause() and dispose(). Retry calls the same host callback with the retained local handle and begins a new attempt. It does not imply resumable transfer or server idempotency. Cancel retains the local file; remove/clear/dispose release it. Completion and progress from cancelled, removed or replaced attempts are ignored, including transports that fail to abort. Successful local files remain available for preview until released by their owner.
For example, the Web host can translate the opaque handle into a browser File:
import { getWebFile } from '@getcortexlabs/mavis-web'
import type { FileUpload } from '@getcortexlabs/mavis-core'
// uploadURL comes from application configuration; authentication stays in the host.
const upload: FileUpload = async ({ handle, cancellation }) => {
const abort = new AbortController()
const unsubscribe = cancellation.onCancel(() => abort.abort())
try {
const body = new FormData()
body.append('file', getWebFile(handle))
const response = await fetch(uploadURL, { method: 'POST', body, signal: abort.signal })
if (!response.ok) throw new Error('Upload failed. Try again.')
} finally {
unsubscribe()
}
}This example has indeterminate progress because fetch does not report uploaded bytes here. Endpoints, credentials, request headers, timeouts, storage, retention and resumable upload policy remain application concerns. Mavis supplies no background transfer service.
Platform resources and previews
Web uses a fresh <input type="file"> created during button activation. Images may get an object URL preview; the URL is revoked on resource release. A broken preview leaves the name and actions intact. The normal button supports Tab, Enter and Space. Focus returns to the selector after selection/cancellation and before a selected item is removed.
iOS uses UIDocumentPickerViewController with copy/import mode on iOS 14+. The system makes a temporary private copy, which Mavis deletes on release; the original document is untouched. Quick Look requests a bounded thumbnail. Android uses ACTION_OPEN_DOCUMENT and transient read access to the selected content URI. It does not request broad storage permissions or take persistent URI grants. Provider thumbnails are available on Android API 29+ when supported. The Activity pause caused by opening the system picker keeps that selection request alive; leaving or unmounting its Vue owner cancels it. These are document pickers that can select images; there is no camera capture or dedicated Photos-library picker. Cloud providers may download their selected document or thumbnail. See Apple document picker, Quick Look thumbnails and Android document access.
Native hosts import getNativeFile(handle) from @getcortexlabs/mavis/vue. It returns { platform, native, openRead }: native is an Android content Uri or iOS NSURL; openRead() returns { native, close }, containing a java.io.InputStream or opened NSInputStream. Native objects have type unknown at this boundary; narrow/cast them with the host's platform typings. Close streams after use; removing/disposal also closes streams opened through this accessor. Accessors reject released handles. Raw paths and URI strings are not a portable file API. Handles belong to the current process/selection and cannot be saved for a later launch.
Preview failure does not reject selection. selection.preview(id) is renderer-specific client state, separate from serializable descriptors. Use hasFile(id) to distinguish local resources from metadata-only entries. SSR renders initial names/statuses and placeholders without activating a picker or allocating object URLs. Initial descriptors never restore local upload/retry capability; the user must select a file again. Serialize only selection.state.items, never the controller, handles, previews, File, Blob or native resources.
Component props
| Prop | Purpose |
|---|---|
selection | Required FileSelectionController. |
label | Required nonempty visible/accessibility label. |
disabled | Blocks actions and pauses active work; defaults to false. |
chooseLabel / uploadLabel / cancelLabel / retryLabel / removeLabel | Translate action text; defaults are English. File action names include the filename. |
dropLabel / dropActiveLabel | Web only. The invitation beside the Choose action and its replacement while files hover the zone; defaults are or drop them here and Release to add. The invitation is hidden where the device has no hovering pointer. |
hint | Optional constraints in the application's words, such as accepted types and the size limit. |
emptyLabel / pendingLabel | Translate empty and indeterminate states. |
formatSize | Optional (bytes) => string. The default is fileSizeText from core: binary units, one decimal at most, a period as separator. |
celebrate | Opt-in confetti when the last pending file finishes uploading; defaults to false. Skipped under reduced motion and where the renderer has no confetti. |
statusLabels | Optional mapping for all five status names. |
errorLabels | Optional mapping for selection error codes. Host transport owns its error messages. |
There are no component events or slots. The controller owns the state, and can be used independently of forms. Names wrap and actions wrap onto additional rows at narrow widths. Previews are decorative; the visible filename remains the content label.
Drop, paste and motion
The Web zone accepts dropped files and files pasted from the clipboard while focus is inside the picker. Both go through the same controller as the selector, so accept, maxCount and maxSize apply and an invalid batch is refused as a whole. Dropped folders are ignored. The zone responds while files are dragged anywhere over the page and again when they hover it; a refused batch shakes the zone and shows the usual error. Clicking the zone opens the selector; the Choose button remains the only keyboard and assistive-technology control, so the zone adds no tab stop. A drop outside the zone is left to the browser. NativeScript has no drop or paste: its zone shows the Choose action, the hint and the empty state.
In a container at least 520 CSS pixels wide the Web zone centers its content; below that it lays the artwork beside the action. Each file is one row with a thumbnail or an icon for its kind, a size in readable units and its actions. Rows arrive with a short stagger, a finished upload pops a check on its thumbnail and a failure shakes its row once. On NativeScript a failure also asks for a light haptic. These moments use the theme's motion tokens through Jolt and are skipped or shortened under reduced motion; status text and announcements never wait for them.
fileSizeText(bytes, decimal?), fileKind(file) and fileKindIcons are exported from @getcortexlabs/mavis-core for applications that render their own list. fileKind chooses artwork only; it never decides whether a file is accepted. The shared demonstration source simulates transfer locally and sends no files.
A component ref exposes the portable InputHandle methods focus() and blur(). Focus targets the Choose action without opening the platform selector; it does nothing while disabled or a selection is pending. Blur releases that action's focus without cancelling selection or upload. This supports form error targets and focus after a step transition:
import { ref } from 'vue'
import type { InputHandle } from '@getcortexlabs/mavis-core'
const attachmentPicker = ref<InputHandle>() // bind ref="attachmentPicker" on MFilePicker
// After the control is mounted:
attachmentPicker.value?.focus()
attachmentPicker.value?.blur()On Web, iOS and Android, a removed file can leave a fading visual copy as the remaining rows close the gap. Its upload and retry actions leave with the live row.
Desktop
On the desktop the choose button opens the file dialog of the system, and files dropped on the field join the same selection. There is no confetti there, so celebrate has no effect; see Desktop components.
Removing a file fades its row and moves the remaining files into place.
Full example
<script setup lang="ts">
import { useCatalogLocale } from '../locale'
import { computed, ref } from 'vue'
import { useFileSelection } from '@getcortexlabs/mavis-core/vue'
import { fileSizeText, type InputHandle } from '@getcortexlabs/mavis-core'
const { t, locale } = useCatalogLocale(() => props.lang)
const props = withDefaults(defineProps<{ lang?: 'en' | 'pt' }>(), { lang: undefined })
const picker = ref<InputHandle>()
defineExpose({
focus: () => picker.value?.focus(),
blur: () => picker.value?.blur(),
} satisfies InputHandle)
const failNext = ref(false)
const copy = computed(() =>
(props.lang ?? locale.value) === 'pt'
? {
title: 'Documentos para a sua próxima viagem.',
label: 'Documentos e imagens',
choose: 'Escolher arquivos',
drop: 'ou solte-os aqui',
dropActive: 'Solte para adicionar',
hint: 'Até três imagens ou PDFs, 5 MB cada. Você também pode colar.',
decimal: ',',
upload: 'Simular envio',
cancel: 'Cancelar',
retry: 'Tentar novamente',
remove: 'Remover',
empty: 'Nenhum arquivo selecionado',
pending: 'Preparando',
description: 'O envio é uma simulação local; nenhum arquivo sai do dispositivo.',
failure: 'O envio simulado falhou. Tente novamente.',
fail: 'Falhar no próximo envio',
statuses: {
selected: 'Pronto',
uploading: 'Enviando',
uploaded: 'Concluído',
failed: 'Falhou',
cancelled: 'Cancelado',
},
errors: {
picker: 'Não foi possível abrir os arquivos.',
type: 'Escolha uma imagem ou um PDF.',
count: 'Escolha no máximo três arquivos.',
size: 'Um arquivo ultrapassa 5 MB.',
},
}
: {
title: 'Documents for your next journey.',
label: 'Documents and images',
choose: 'Choose files',
drop: 'or drop them here',
dropActive: 'Release to add',
hint: 'Up to three images or PDFs, 5 MB each. Pasting works too.',
decimal: '.',
upload: 'Simulate upload',
cancel: 'Cancel',
retry: 'Retry',
remove: 'Remove',
empty: 'No files selected',
pending: 'Preparing',
description: 'Upload is a local simulation; no file leaves the device.',
failure: 'The simulated upload failed. Try again.',
fail: 'Fail the next upload',
statuses: {
selected: 'Ready',
uploading: 'Uploading',
uploaded: 'Uploaded',
failed: 'Failed',
cancelled: 'Cancelled',
},
errors: {
picker: 'Could not open the files.',
type: 'Choose an image or PDF.',
count: 'Choose at most three files.',
size: 'A file exceeds 5 MB.',
},
},
)
const selection = useFileSelection({
multiple: true,
maxCount: 3,
maxSize: 5 * 1024 * 1024,
accept: ['image/*', '.pdf'],
// Demonstration transport only. A real application injects its own request here.
upload: ({ progress, cancellation }) =>
new Promise<void>((resolve, reject) => {
const shouldFail = failNext.value
failNext.value = false
let step = 0
const timer = setInterval(() => {
step++
if (step > 2) progress(step - 2, 8)
if (shouldFail && step === 4) {
clearInterval(timer)
unsubscribe()
reject(new Error(copy.value.failure))
} else if (step === 10) {
clearInterval(timer)
unsubscribe()
resolve()
}
}, 250)
const unsubscribe = cancellation.onCancel(() => {
clearInterval(timer)
resolve()
})
}),
})
</script>
<template>
<m-column gap="lg" id="file-picker-demo">
<m-text variant="heading">{{ t(copy.title) }}</m-text>
<m-text tone="muted">{{ t(copy.description) }}</m-text>
<m-file-picker
ref="picker"
:selection="selection"
:label="t(copy.label)"
:chooseLabel="copy.choose"
:dropLabel="copy.drop"
:dropActiveLabel="copy.dropActive"
:hint="t(copy.hint)"
:formatSize="(bytes: number) => fileSizeText(bytes, copy.decimal)"
celebrate
:uploadLabel="copy.upload"
:cancelLabel="copy.cancel"
:retryLabel="copy.retry"
:removeLabel="copy.remove"
:emptyLabel="t(copy.empty)"
:pendingLabel="copy.pending"
:statusLabels="copy.statuses"
:errorLabels="copy.errors"
/>
<m-switch v-model="failNext" :label="t(copy.fail)" />
</m-column>
</template>