Skip to content

Biblioteca ​

Escolha assuntos de design, desenvolvimento e produto para filtrar uma pequena coleção de leituras. A tela começa com dois assuntos selecionados, deixando o checkbox pai no estado parcial. Selecione todos, escolha assuntos individuais ou limpe a seleção para ver o estado vazio.

Abrir exemplo interativo ↗

A tela controla o array de IDs selecionados, deriva os dois estados do pai e filtra os cartões. MCheckbox apenas solicita mudanças. A coleção é uma demonstração local, sem requisições nem preferências salvas; sair da tela reinicia os filtros.

Os filtros de assuntos usam Chip selecionável. A busca encontra títulos e descrições, ignorando maiúsculas e acentos. EmptyState oferece limpar filtros quando nada combina; os salvos têm um estado vazio próprio e retorno a Explorar. Busca e assuntos não filtram a aba Salvos.

Código ​

vue
<script setup lang="ts">
import { useCatalogLocale } from '../locale'
import { computed, onBeforeUnmount, ref } from 'vue'
import type { ChoiceValue, IconName } from '@getcortexlabs/mavis-core'
import { useMavisTheme } from '@getcortexlabs/mavis-core/vue'
import { useCatalog } from '../context'
import ThemeSwitch from '../ThemeSwitch.vue'
import LibraryDownload from '../LibraryDownload.vue'

const { t, choices } = useCatalogLocale()

const { navigation } = useCatalog()
const { theme } = useMavisTheme()
const topics = [
  { id: 'design', label: 'Design', icon: 'palette' as IconName },
  { id: 'development', label: 'Desenvolvimento', icon: 'code' as IconName },
  { id: 'product', label: 'Produto', icon: 'lightbulb' as IconName },
]
const articles = [
  {
    id: 1,
    topic: 'design',
    title: 'O espaço também fala.',
    description: 'Ritmo e respiro em interfaces que convidam a ficar.',
    time: '6 MIN',
    number: '01',
    accent: false,
  },
  {
    id: 2,
    topic: 'development',
    title: 'Pequenos detalhes. Grande diferença.',
    description: 'Estados e interações que tornam um componente completo.',
    time: '8 MIN',
    number: '02',
    accent: true,
  },
  {
    id: 3,
    topic: 'product',
    title: 'Antes da próxima tela.',
    description: 'Encontre a pergunta certa antes de desenhar a resposta.',
    time: '4 MIN',
    number: '03',
    accent: false,
  },
]
const loading = ref(false)
let loadingTimer: ReturnType<typeof setTimeout> | undefined
function refresh() {
  if (loading.value) return
  loading.value = true
  loadingTimer = setTimeout(() => {
    loading.value = false
    loadingTimer = undefined
  }, 1500)
}
onBeforeUnmount(() => clearTimeout(loadingTimer))
const activeTab = ref<ChoiceValue | null>('explore')
const savedArticles = ref([1])
const tabs = computed(() => [
  { value: 'explore', label: 'Explorar' },
  { value: 'saved', label: `${t('Salvos')} (${savedArticles.value.length})` },
])
function bookmark(id: number) {
  savedArticles.value = savedArticles.value.includes(id)
    ? savedArticles.value.filter((value) => value !== id)
    : [...savedArticles.value, id]
}
const query = ref('')
const search = computed(() => normalize(query.value.trim()))
function normalize(text: string) {
  return text
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .toLocaleLowerCase('pt-BR')
}
function clearFilters() {
  query.value = ''
  toggleAll(true)
}
const selected = ref(['design', 'development'])
const all = computed(() => selected.value.length === topics.length)
const mixed = computed(() => selected.value.length > 0 && !all.value)
const visible = computed(() =>
  articles.filter((article) =>
    activeTab.value === 'saved'
      ? savedArticles.value.includes(article.id)
      : selected.value.includes(article.topic) &&
        normalize(`${article.title} ${article.description}`).includes(search.value),
  ),
)
function toggle(id: string, checked: boolean) {
  selected.value = checked
    ? [...selected.value, id]
    : selected.value.filter((value) => value !== id)
}
function toggleAll(checked: boolean) {
  selected.value = checked ? topics.map((topic) => topic.id) : []
}
</script>

<template>
  <m-screen scroll>
    <m-column padding="lg" gap="lg" class="showcase-container">
      <m-row justify="between" gap="sm">
        <m-button size="sm" variant="ghost" @click="navigation.back('/showcase')">{{
          t('← Showcase')
        }}</m-button>
        <ThemeSwitch />
      </m-row>
      <m-column gap="sm" paddingY="lg">
        <m-text variant="overline" tone="primary">{{ t('MAVIS / BIBLIOTECA') }}</m-text>
        <m-text as="h1" variant="display">{{ t('Boas ideias. Por perto.') }}</m-text>
        <m-text tone="muted">{{
          t('Um lugar para alimentar a curiosidade. Comece pelo que move você.')
        }}</m-text>
      </m-column>
      <LibraryDownload @open="activeTab = 'saved'" />
      <m-button variant="secondary" icon="refresh-cw" :disabled="loading" @click="refresh">{{
        t('Atualizar coleção')
      }}</m-button>
      <m-tabs v-model="activeTab" :tabs="choices(tabs)" :label="t('Biblioteca')">
        <template #default="{ value }">
          <m-column gap="lg">
            <m-card v-if="value === 'explore'" gap="md">
              <m-row justify="between" gap="md">
                <m-text as="h2" variant="heading">{{ t('Seus assuntos') }}</m-text>
                <m-icon name="sliders-horizontal" tone="primary" />
              </m-row>
              <m-checkbox
                :modelValue="all"
                :indeterminate="mixed"
                :label="t('Todos os assuntos')"
                indeterminateLabel="Seleção parcial"
                :helperText="`${selected.length} ${t('de 3 selecionados')}`"
                @update:modelValue="toggleAll"
              />
              <m-box :height="1" :backgroundColor="theme.colors.border" />
              <m-row gap="sm" wrap>
                <m-chip
                  v-for="topic in topics"
                  :key="topic.id"
                  :label="t(topic.label)"
                  :icon="topic.icon"
                  selectable
                  :modelValue="selected.includes(topic.id)"
                  @update:modelValue="toggle(topic.id, $event)"
                />
              </m-row>
              <m-input
                v-model="query"
                :label="t('Buscar leituras')"
                :placeholder="t('Uma ideia, uma palavra…')"
              />
            </m-card>
            <m-row justify="between" gap="md">
              <m-text as="h2" variant="heading">{{
                t(value === 'saved' ? 'Para ler com calma' : 'Para explorar')
              }}</m-text>
              <m-text variant="caption" tone="muted"
                >{{ t(visible.length) }}{{ t(' de 3') }}</m-text
              >
            </m-row>
            <m-column v-if="loading" gap="lg">
              <m-text tone="muted">{{ t('Buscando novas leituras…') }}</m-text>
              <m-card v-for="n in 2" :key="n">
                <m-column gap="lg">
                  <m-row gap="md">
                    <m-skeleton :width="48" :height="48" radius="full" :shrink="0" />
                    <m-column :width="0" :grow="1" gap="sm">
                      <m-skeleton width="70%" />
                      <m-skeleton width="45%" :height="12" />
                    </m-column>
                  </m-row>
                  <m-skeleton :height="28" width="85%" />
                  <m-skeleton />
                  <m-skeleton width="65%" />
                </m-column>
              </m-card>
            </m-column>
            <template v-else>
              <m-column
                v-for="article in visible"
                :key="article.id"
                padding="lg"
                gap="lg"
                radius="lg"
                :backgroundColor="
                  article.accent ? theme.colors.accentSoft : theme.colors.primarySoft
                "
              >
                <m-row justify="between" gap="md">
                  <m-text variant="display" :tone="article.accent ? 'accent' : 'primary'">{{
                    t(article.number)
                  }}</m-text>
                  <m-column gap="xs" align="end">
                    <m-text variant="overline" :tone="article.accent ? 'accent' : 'primary'">{{
                      t(topics.find((topic) => topic.id === article.topic)?.label)
                    }}</m-text>
                    <m-text variant="caption" tone="muted">{{ t(article.time) }}</m-text>
                  </m-column>
                </m-row>
                <m-column gap="sm">
                  <m-text as="h3" variant="title">{{ t(article.title) }}</m-text>
                  <m-text tone="muted">{{ t(article.description) }}</m-text>
                </m-column>
                <m-button
                  variant="ghost"
                  :icon="savedArticles.includes(article.id) ? 'check' : 'bookmark'"
                  @click="bookmark(article.id)"
                  >{{
                    t(savedArticles.includes(article.id) ? 'Remover dos salvos' : 'Salvar leitura')
                  }}</m-button
                >
              </m-column>
              <m-card v-if="!visible.length" padding="none">
                <m-empty-state
                  :title="
                    t(
                      value === 'saved'
                        ? 'Guarde uma boa ideia.'
                        : search
                          ? 'Nenhuma ideia por aqui.'
                          : 'Uma página em branco.',
                    )
                  "
                  :description="
                    t(
                      value === 'saved'
                        ? 'Salve uma leitura em Explorar para encontrá-la aqui.'
                        : search
                          ? 'Tente outra palavra ou abra espaço para todos os assuntos.'
                          : 'Selecione um assunto para encontrar novas ideias.',
                    )
                  "
                  :icon="value === 'saved' ? 'bookmark' : search ? 'search' : 'book-open'"
                  :tone="value === 'saved' ? 'primary' : 'accent'"
                >
                  <template #actions>
                    <m-button
                      v-if="value === 'saved'"
                      variant="secondary"
                      @click="activeTab = 'explore'"
                      >{{ t('Explorar leituras') }}</m-button
                    >
                    <m-button v-else variant="secondary" @click="clearFilters">{{
                      t(search ? 'Limpar filtros' : 'Mostrar todos')
                    }}</m-button>
                  </template>
                </m-empty-state>
              </m-card>
            </template>
          </m-column>
        </template>
      </m-tabs>
      <m-text variant="caption" tone="muted" align="center">{{
        t(
          'Coleção demonstrativa, com carregamento simulado. Os filtros e salvos são locais e reiniciam ao sair da tela.',
        )
      }}</m-text>
    </m-column>
  </m-screen>
</template>

Referência de Checkbox · Temas

MTabs separa Explorar e Salvos. Salvar uma leitura atualiza o contador da aba; filtros e IDs salvos ficam no pai e permanecem ao trocar painéis. A coleção reinicia ao sair da tela. Referência de Tabs.

Atualizar coleção simula uma espera de 1,5 segundo com MSkeleton. Filtros, aba ativa e salvos são preservados; não há requisição de rede.

Feedback do download ​

Baixar coleção demonstra um fluxo local: preparação indeterminada, progresso conhecido, cancelamento, falha e nova tentativa. Simular falha interrompe o timer; o aviso de erro oferece outra tentativa. Ao concluir, a ação Ver salvos abre os itens salvos. Fechar um aviso só esconde a mensagem; filtros e favoritos continuam preservados.

É uma simulação: nenhum arquivo é buscado, armazenado ou disponibilizado offline. O timer é cancelado ao desmontar a tela. O app controla progresso e mensagens; MProgress e MAlert exibem esse estado.

Referência de Progress · Referência de Alert

Código do exemplo de download
vue
<script setup lang="ts">
import { useCatalogLocale } from './locale'
import { computed, onBeforeUnmount, ref } from 'vue'
import { useMavisTheme } from '@getcortexlabs/mavis-core/vue'

const { t } = useCatalogLocale()

defineEmits<{ open: [] }>()
const { theme } = useMavisTheme()
type Phase = 'idle' | 'preparing' | 'downloading' | 'complete' | 'error' | 'cancelled'
const phase = ref<Phase>('idle')
const value = ref(0)
const notice = ref(true)
let timer: ReturnType<typeof setTimeout> | undefined
const busy = computed(() => phase.value === 'preparing' || phase.value === 'downloading')
const caption = computed(
  () =>
    ({
      idle: 'PRONTA PARA IR',
      preparing: 'PREPARANDO',
      downloading: 'BAIXANDO',
      complete: 'CONCLUÍDO',
      error: 'INTERROMPIDO',
      cancelled: 'CANCELADO',
    })[phase.value],
)
function stop() {
  clearTimeout(timer)
  timer = undefined
}
function advance() {
  value.value = Math.min(100, value.value + 10)
  if (value.value === 100) {
    phase.value = 'complete'
    timer = undefined
    return
  }
  timer = setTimeout(advance, 550)
}
function start() {
  stop()
  value.value = 0
  notice.value = true
  phase.value = 'preparing'
  timer = setTimeout(() => {
    phase.value = 'downloading'
    advance()
  }, 900)
}
function interrupt(next: 'error' | 'cancelled') {
  stop()
  phase.value = next
  notice.value = true
}
onBeforeUnmount(stop)
</script>

<template>
  <m-column gap="md" id="library-download">
    <m-card gap="lg" :backgroundColor="theme.colors.accentSoft" :style="{ borderWidth: 0 }">
      <m-row justify="between" gap="sm">
        <m-row gap="sm"
          ><m-icon name="download" tone="accent" /><m-text variant="overline" tone="accent">{{
            t('LEVE COM VOCÊ')
          }}</m-text></m-row
        >
        <m-badge :text="t('03 LEITURAS')" tone="accent" size="sm" />
      </m-row>
      <m-column gap="sm">
        <m-text variant="title">{{ t('Boas ideias também viajam.') }}</m-text>
        <m-text tone="muted">{{ t('Prepare sua coleção para ler no seu tempo.') }}</m-text>
      </m-column>
      <m-column gap="sm">
        <m-row justify="between" gap="md">
          <m-text variant="overline" tone="accent">{{ t(caption) }}</m-text>
          <m-text variant="heading" tone="accent">{{
            t(phase === 'preparing' ? '…' : `${value}%`)
          }}</m-text>
        </m-row>
        <m-progress
          id="library-download-progress"
          :value="value"
          :indeterminate="phase === 'preparing'"
          :label="t('Download da biblioteca')"
          :indeterminateLabel="t('Preparando coleção')"
          tone="accent"
          size="lg"
        />
      </m-column>
      <m-row gap="sm" wrap>
        <m-button v-if="!busy" icon="download" @click="start">{{
          t(phase === 'idle' ? 'Baixar coleção' : 'Baixar novamente')
        }}</m-button>
        <m-button v-if="busy" size="sm" variant="secondary" @click="interrupt('cancelled')">{{
          t('Cancelar download')
        }}</m-button>
        <m-button v-if="busy" size="sm" variant="ghost" @click="interrupt('error')">{{
          t('Simular falha')
        }}</m-button>
      </m-row>
    </m-card>
    <m-alert
      v-if="notice && phase === 'error'"
      :title="t('A conexão foi interrompida.')"
      :description="
        t(
          'Tente novamente para preparar a coleção desde o início. Suas leituras salvas continuam aqui.',
        )
      "
      tone="error"
      announce
      dismissible
      :closeLabel="t('Fechar erro do download')"
      @close="notice = false"
    >
      <template #actions
        ><m-button size="sm" variant="secondary" @click="start">{{
          t('Tentar novamente')
        }}</m-button></template
      >
    </m-alert>
    <m-alert
      v-if="notice && phase === 'complete'"
      :title="t('Coleção preparada.')"
      :description="t('Tudo pronto nesta demonstração. Explore suas leituras salvas.')"
      tone="success"
      announce
      dismissible
      :closeLabel="t('Fechar confirmação do download')"
      @close="notice = false"
    >
      <template #actions
        ><m-button size="sm" variant="secondary" @click="$emit('open')">{{
          t('Ver salvos')
        }}</m-button></template
      >
    </m-alert>
    <m-alert
      v-if="notice && phase === 'cancelled'"
      :title="t('Download cancelado.')"
      :description="t('Você pode começar de novo quando quiser.')"
      tone="warning"
      announce
      dismissible
      :closeLabel="t('Fechar aviso de cancelamento')"
      @close="notice = false"
    />
    <m-text variant="caption" tone="muted">{{
      t('Download simulado. Nenhum arquivo é transferido ou salvo no dispositivo.')
    }}</m-text>
  </m-column>
</template>

Componentes para NativeScript e Web. Começando por Vue.