Skip to content
LIBRARYFeedbackUpdated

Toast ​

MToast · Feedback that leaves the rest of the screen available.

Next alpha

Available in 0.1.0-alpha.4.

Web preview
Open example ↗

Usage ​

vue
<script setup lang="ts">
import { useToast } from '@getcortexlabs/mavis-core/vue'

const toast = useToast()
function saved() {
  toast.show({
    title: 'Profile saved',
    message: 'Your changes are ready.',
    tone: 'success',
  })
}
</script>

<template>
  <m-screen>
    <m-button @click="saved">Save</m-button>
    <m-toast :controller="toast" closeLabel="Dismiss notice" />
  </m-screen>
</template>

Call useToast() in Vue setup. Each call creates its own queue, cleaned up with that scope. Connect it to one MToast; NativeScript requires an MScreen ancestor. For notifications across routes, use the application scope described below. Both renderer entry points also export useToast.

Host props ​

PropTypeDefaultBehavior
controllerToastControllerrequiredThe queue returned by useToast(). One host per local controller.
closeLabelstringDismiss notificationAccessible name for the close button. Translate it in the app.
countdownbooleanfalseA thin line that drains with the real remaining time and holds whenever the timer holds. For the app queue, set createMavis({ toast: { countdown: true } }).
swipeablebooleantrueDragging sideways dismisses the notice; a short drag springs back.

The host renders at the top of its viewport. It does not accept content slots or layout props. NativeScript keeps it inside the Screen's safe area; Web clears the host document's safe-area inset. It leaves the keyboard and current focus alone. It has no scrim, focus trap or router back handler.

Messages and controller ​

ToastOptions, ToastTone and ToastController are exported by @getcortexlabs/mavis-core.

OptionTypeDefaultBehavior
messagestringrequiredNon-empty plain text. HTML is not interpreted.
titlestringomittedOptional non-empty heading.
tonesuccess | error | warning | infoinfoSemantic icon and color. The warning color comes from theme.colors.warning.
durationnumber5000Milliseconds after entry completes; 0 keeps the notice until dismissed. Must be finite and between 0 and 2147483647.
  • toast.show(options) copies the options and queues a message. It returns a numeric ID, or undefined after a local host has unloaded or its owner has been disposed.
  • toast.dismiss() closes the current message. toast.dismiss(id) also lets the app remove a queued message; unknown IDs do nothing.
  • toast.clear() discards waiting messages and dismisses the current one.

Messages appear in insertion order, one at a time. The next enters after the current one finishes leaving; its own clock starts after entry. Repeated calls create separate messages, including when the text is the same. Validation, persistence and network requests belong to the app.

Time, interaction and lifecycle ​

The timer preserves remaining time when paused. It waits while a Sheet is open and while the app/document is in the background. On Web, hovering or focusing the toast also pauses it; Escape closes it when focus is inside. Closing a focused Web notice returns focus to its still-mounted opener. It never takes focus just to announce a message.

Native notices keep their close control reachable and allow long copy to scroll. Notices respect reduced motion on entry and dismissal. When a native screen reader is active at entry, automatic dismissal pauses so the notice can be closed manually. This is basic behavior, not a comprehensive assistive-technology audit.

For local queues, unmounting the host clears its queue. Native page unload during navigation also clears it, including pages retained by a router; calls while that page is away are ignored and returning accepts fresh messages. NativeScript also unloads views when the app enters the background; that case keeps the paused queue until the page loads again. A destroyed Vue scope rejects later asynchronous calls. Replacing the host's controller releases the previous queue. Use the application scope for delivery across routes.

Use duration: 0 when the message must remain available. Keep important validation or instructions in the screen as well: a toast is transient feedback, not the only record of an error. Actions such as Undo, promise helpers, custom templates and operating-system notifications are outside this version.

Motion ​

A notice springs down from the top edge and its tone icon pops. Dragging pauses its time like hover does; releasing past a short distance, or with enough speed, sends it out along the gesture and dismisses it. The close button and Escape remain the keyboard and screen-reader path. Under reduced motion the arrival and countdown are immediate and static.

Desktop ​

On the Mac and on Windows the notification appears above the screen, keeps its queue, countdown, pause on hover and swipe, and Escape closes it while the keyboard is in it. The Mac announces each one; Windows does not announce yet. See Desktop components.

Full example ​

View source
vue
<script setup lang="ts">
import { useCatalogLocale } from '../locale'
import { computed, ref } from 'vue'
import { useMavisTheme, useToast } from '@getcortexlabs/mavis-core/vue'
import type { ToastOptions, ToastTone } from '@getcortexlabs/mavis-core'

const { t, locale } = useCatalogLocale(() => props.lang)

const props = withDefaults(defineProps<{ lang?: 'en' | 'pt' }>(), { lang: undefined })

const pt = computed(() => (props.lang ?? locale.value) === 'pt')
const { theme } = useMavisTheme()
const toast = useToast()
const sent = ref(0)
function show(tone: ToastTone) {
  const messages: Record<ToastTone, [string, string, string, string]> = {
    success: [
      'Tudo no lugar.',
      'Suas alterações foram salvas nesta demonstração.',
      'Right where it belongs.',
      'Your changes were saved in this demo.',
    ],
    error: [
      'Não foi dessa vez.',
      'Não conseguimos concluir. Tente novamente.',
      'Something went wrong.',
      'We could not finish. Please try again.',
    ],
    warning: [
      'Mais um detalhe.',
      'Confira o endereço antes de continuar.',
      'One more detail.',
      'Check the address before continuing.',
    ],
    info: [
      'Uma novidade para você.',
      'A coleção de inverno já está disponível.',
      'Something new for you.',
      'The winter collection is now available.',
    ],
  }
  const copy = messages[tone]
  send({ title: copy[pt.value ? 0 : 2], message: copy[pt.value ? 1 : 3], tone })
}
function send(options: ToastOptions) {
  toast.show(options)
  sent.value++
}
function queue() {
  for (const n of [1, 2, 3])
    send({
      title: pt.value ? `Aviso ${n} de 3` : `Notice ${n} of 3`,
      message: pt.value
        ? 'Um de cada vez, sem interromper o que você está fazendo.'
        : 'One at a time, without interrupting what you are doing.',
      tone: n === 3 ? 'success' : 'info',
      duration: 2000,
    })
}
function persistent() {
  send({
    title: pt.value ? 'No seu tempo.' : 'Take your time.',
    message: pt.value
      ? 'Este aviso fica por aqui até você fechar.'
      : 'This notice stays here until you dismiss it.',
    duration: 0,
  })
}
</script>

<template>
  <m-column gap="lg">
    <m-column padding="lg" gap="md" radius="lg" :backgroundColor="theme.colors.primarySoft">
      <m-row justify="between" gap="sm">
        <m-text variant="overline" tone="primary">{{
          t(pt ? 'UM SINAL, SEM PAUSA' : 'A SIGNAL, NOT A PAUSE')
        }}</m-text>
        <m-icon name="sparkles" tone="primary" />
      </m-row>
      <m-text variant="heading">{{ t(pt ? 'No momento certo.' : 'Right on time.') }}</m-text>
      <m-text variant="caption" tone="muted">{{
        t(
          pt
            ? 'Uma confirmação. Um cuidado. Uma novidade. E a vida continua.'
            : 'A confirmation. A heads-up. Something new. Then carry on.',
        )
      }}</m-text>
      <m-row padding="md" gap="sm" radius="md" :backgroundColor="theme.colors.surface">
        <m-icon name="circle-check" tone="success" />
        <m-column gap="xs" :grow="1" :width="0">
          <m-text :style="{ fontWeight: '600' }">{{
            t(pt ? 'Tudo em dia.' : 'All caught up.')
          }}</m-text>
          <m-text variant="caption" tone="muted">{{
            t(pt ? 'Pequenos avisos, bem resolvidos.' : 'Small notices, thoughtfully done.')
          }}</m-text>
        </m-column>
      </m-row>
    </m-column>
    <m-column gap="sm">
      <m-row gap="sm" wrap>
        <m-button :grow="1" :style="{ width: 0 }" icon="circle-check" @click="show('success')">{{
          t(pt ? 'Sucesso' : 'Success')
        }}</m-button>
        <m-button
          :grow="1"
          :style="{ width: 0 }"
          variant="secondary"
          icon="circle-alert"
          @click="show('error')"
          >{{ t(pt ? 'Erro' : 'Error') }}</m-button
        >
      </m-row>
      <m-row gap="sm" wrap>
        <m-button
          :grow="1"
          :style="{ width: 0 }"
          variant="secondary"
          icon="triangle-alert"
          @click="show('warning')"
          >{{ t(pt ? 'Aviso' : 'Warning') }}</m-button
        >
        <m-button
          :grow="1"
          :style="{ width: 0 }"
          variant="secondary"
          icon="info"
          @click="show('info')"
          >{{ t(pt ? 'Informação' : 'Information') }}</m-button
        >
      </m-row>
    </m-column>
    <m-button variant="secondary" @click="queue">{{
      t(pt ? 'Disparar três avisos' : 'Queue three notices')
    }}</m-button>
    <m-button variant="ghost" @click="persistent">{{
      t(pt ? 'Sem fechar sozinho' : 'Keep it open')
    }}</m-button>
    <m-row gap="sm" justify="between" wrap>
      <m-text variant="caption" tone="muted">{{
        t(pt ? `${sent} avisos disparados` : `${sent} notices sent`)
      }}</m-text>
      <m-button variant="ghost" size="sm" @click="toast.clear()">{{
        t(pt ? 'Limpar fila' : 'Clear queue')
      }}</m-button>
    </m-row>
    <m-toast
      :controller="toast"
      :closeLabel="t(pt ? 'Fechar aviso' : 'Dismiss notice')"
      countdown
    />
  </m-column>
</template>

Profile uses Toast after a valid local save; field errors remain beside their inputs.

Notifications across routes ​

useToast() keeps the existing local queue. useToast({ scope: 'app' }) uses one queue per createMavis app, disposed on app unmount. It is not a singleton shared between SSR requests.

ts
const toast = useToast({ scope: 'app' })
toast.show({ message: 'Your space is ready.', tone: 'success' })
navigation.push('/home')

Each MScreen automatically activates a host after the app queue is requested. Do not add another MToast for this queue inside Screen. Web apps without Screen can declare one host at the application root. Local queues still require their own MToast and reject late work after unload/unmount.

Host replacement preserves order and remaining time; the clock pauses without an active host. Old page callbacks cannot affect the new owner. Background/resume also preserves remaining time. The application queue uses the active Screen's theme; local queues keep the theme of their declared host. The queues are independent: choose the scope for each flow.

Customize the automatic close label with createMavis({ toast: { closeLabel: 'Dismiss notification' } }).

During a modal ​

The policy is to defer presentation until the last modal stops covering the screen, without consuming the notification's duration or stealing focus. NativeScript uses Screen's overlay ownership. Web respects actually modal dialogs (:modal), including Sheet/Dialog; a non-modal dialog.show() does not block notifications. The host does not fight the browser top layer with z-index.

Morrow demonstrates login → home with the same notification, and recovery that closes its Sheet before showing feedback. Mavis does not send email or authenticate accounts.

Components for NativeScript and Web. Starting with Vue.