Skip to content
LIBRARYFeedback

RefreshControl ​

Included in RC.12

Available in Mavis 0.1.0-rc.12 for Vue + Vite, Nuxt and NativeScript. Keep the Mavis packages at the same version.

Web preview
Open example ↗
vue
<MRefreshControl label="Your morning edition" :refresh="refreshStories">
  <Stories :items="stories" />
</MRefreshControl>
PropTypeDefaultContract
label / refreshstring / RefreshActionrequiredAccessible region name and application-owned operation.
height / thresholdnumber480 / 80Viewport height and pull threshold in px/DIP.
disabledbooleanfalseCancel pending work and pause refresh interaction.
refreshLabel / refreshingLabel / successLabel / errorLabel / retryLabel / cancelLabelstringEnglish labelsTranslate every state and action.

Pull down at the top, or use the Refresh button. Supply an async refresh(context) callback. context.signal supports cancellation, and context.commit(() => updateState()) guards application updates against stale requests. Apply results inside commit; arbitrary writes performed by the application cannot be undone. Only one request runs at a time. Cancel, disabling, KeepAlive deactivation and teardown invalidate the active request. Error and success labels are configurable. Exposed methods: refresh() and cancel(). RefreshControl owns a bounded scroll region with a compact status header, not a native Page.

Pass stable string keys through itemKeys and render each row in #item="{ itemKey, index }". Use the component handle’s preserveAnchor(change) for prepends. A refresh already preserves the visible row when you update the feed inside context.commit(change). When switching feeds, change sourceKey to cancel the outgoing request and reset the scroll position.

The status line carries a decorative mark for each state: an arrow at rest, a spinning ring while refreshing, a check that pops on success and an alert that shakes on error. On NativeScript this mark is the only refresh indicator, and a screen reader hears refreshingLabel, successLabel or errorLabel when a refresh starts, succeeds or fails. Rows added after the first render, such as fresh stories committed by a refresh or a new feed, arrive in sequence. Reduced motion skips the row arrivals and the travel of the mark.

vue
<script setup lang="ts">
import { computed, ref } from 'vue'
import type { RefreshContext } from '@getcortexlabs/mavis-core'
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)
const edition = ref(1),
  fail = ref(false),
  disabled = ref(false)
const source = ref(1)
const entries = ref(['1', '2', '3', '4', '5'])
function replaceEdition() {
  source.value++
  edition.value = 1
  entries.value = ['1', '2', '3', '4', '5']
}
async function refresh(context: RefreshContext) {
  const shouldFail = fail.value
  await new Promise<void>((resolve) => {
    const timer = setTimeout(resolve, 900)
    context.signal.addEventListener(
      'abort',
      () => {
        clearTimeout(timer)
        resolve()
      },
      { once: true },
    )
  })
  if (context.cancelled) return
  if (shouldFail) throw new Error('Offline')
  await context.commit(() => {
    entries.value = [String(5 + edition.value), ...entries.value]
    edition.value++
  })
}
</script>
<template>
  <MColumn gap="md">
    <MText text="THE DAILY / A FRESH PERSPECTIVE" variant="overline" tone="primary" />
    <MRefreshControl
      :label="t('Your morning edition', 'Sua edição da manhã')"
      :refresh="refresh"
      :sourceKey="source"
      :itemKeys="entries"
      :disabled="disabled"
      :refreshLabel="t('Refresh', 'Atualizar')"
      :refreshingLabel="t('Bringing fresh stories…', 'Buscando novas histórias…')"
      :successLabel="t('You are up to date', 'Tudo em dia')"
      :errorLabel="
        t('Offline. Your stories are still here.', 'Sem conexão. Suas histórias continuam aqui.')
      "
      :retryLabel="t('Try again', 'Tentar novamente')"
      :cancelLabel="t('Cancel refresh', 'Cancelar atualização')"
    >
      <template #default
        ><MColumn padding="md" gap="md">
          <MText
            id="refresh-edition"
            :text="`${t('Edition', 'Edição')} ${edition}`"
            variant="overline"
            tone="primary"
          /> </MColumn
      ></template>
      <template #item="{ itemKey }"
        ><MColumn padding="sm"
          ><MCard :id="'story-' + itemKey" gap="sm"
            ><MText
              :text="`${itemKey.padStart(2, '0')} / JOURNAL`"
              variant="overline"
              tone="muted" /><MText
              :text="
                t(
                  [
                    'A different way to start.',
                    'Small things, noticed.',
                    'Make time for a detour.',
                    'There is more outside.',
                    'Keep your curiosity.',
                  ][(Number(itemKey) - 1) % 5]!,
                  [
                    'Um começo diferente.',
                    'Os detalhes importam.',
                    'Tempo para um desvio.',
                    'Há mais lá fora.',
                    'Guarde a curiosidade.',
                  ][(Number(itemKey) - 1) % 5]!,
                )
              "
              variant="heading"
          /></MCard> </MColumn
      ></template>
    </MRefreshControl>
    <MButton
      variant="secondary"
      :text="t('Switch edition', 'Trocar edição')"
      @click="replaceEdition"
    />
    <MRow gap="sm" wrap
      ><MSwitch v-model="fail" :label="t('Simulate offline', 'Simular offline')" /><MSwitch
        v-model="disabled"
        :label="t('Pause updates', 'Pausar atualizações')"
    /></MRow>
  </MColumn>
</template>
ts
async function refreshStories(context: RefreshContext) {
  const response = await fetch('/api/stories', { signal: context.signal })
  if (!response.ok) throw new Error('Could not refresh')
  const items = await response.json()
  await context.commit(() => {
    stories.value = items
  })
}

Desktop ​

A desktop has no pull gesture. A Refresh button in the toolbar runs the action, and so does mod+R (Command-R on the Mac, Control-R on Windows) while the control is shown; the same button cancels a running refresh and the status line under it names each state. threshold is accepted with no effect, and Windows does not announce the states yet. See Desktop components.

Components for NativeScript and Web. Starting with Vue.