feat: home screen and navigation design

This commit is contained in:
fsylvain committed 2026-09-26 17:46:42 +02:00
1 parent 30a4df47b1
commit 930b836241
24 files changed
+1774 -19

No files matched your search

+267 -1
View File
@@ -1,9 +1,275 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import DashboardShell from '@/components/DashboardShell.vue'
import ArticleStatusBadge from '@/components/ArticleStatusBadge.vue'
import NewArticleModal from '@/components/NewArticleModal.vue'
import { useArticles, type Article } from '@/composables/useArticles'
import { useSessionStore } from '@/stores/session'
import { formatRelativeDate } from '@/lib/relativeDate'
const SKELETON_DELAY_MS = 150
const RECENT_LIST_SIZE = 5
type LoadState = 'loading' | 'default' | 'empty' | 'error'
const session = useSessionStore()
const { listArticles } = useArticles()
const loadState = ref<LoadState>('loading')
const articles = ref<Article[]>([])
const showSkeleton = ref(false)
const newArticleModalOpen = ref(false)
let skeletonTimer: ReturnType<typeof setTimeout> | null = null
function greetingForHour(hour: number) {
if (hour < 12) {
return 'Good morning'
}
if (hour < 18) {
return 'Good afternoon'
}
return 'Good evening'
}
const greeting = computed(() => {
const timeOfDayGreeting = greetingForHour(new Date().getHours())
const username = session.session?.username
return username ? `${timeOfDayGreeting}, ${username}` : timeOfDayGreeting
})
const subtitle = computed(() =>
loadState.value === 'empty'
? 'Welcome to RenewCMS.'
: "Here's where things stand on your site.",
)
const stats = computed(() => {
const online = articles.value.filter((article) => article.is_online).length
return {
total: articles.value.length,
online,
drafts: articles.value.length - online,
}
})
const statTiles = computed(() => [
{ label: 'articles', value: stats.value.total },
{ label: 'online', value: stats.value.online },
{ label: 'drafts', value: stats.value.drafts },
])
const recentArticles = computed(() =>
[...articles.value]
.sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime())
.slice(0, RECENT_LIST_SIZE),
)
function clearSkeletonTimer() {
if (skeletonTimer !== null) {
clearTimeout(skeletonTimer)
skeletonTimer = null
}
}
async function loadArticles() {
loadState.value = 'loading'
showSkeleton.value = false
clearSkeletonTimer()
skeletonTimer = setTimeout(() => {
showSkeleton.value = true
}, SKELETON_DELAY_MS)
try {
const result = await listArticles()
articles.value = result
loadState.value = result.length === 0 ? 'empty' : 'default'
} catch {
loadState.value = 'error'
} finally {
clearSkeletonTimer()
showSkeleton.value = false
}
}
function openNewArticleModal() {
newArticleModalOpen.value = true
}
onMounted(loadArticles)
</script>
<template>
<DashboardShell>
<p>Home placeholder.</p>
<template #navbar-right>
<UButton
icon="i-lucide-plus"
color="neutral"
variant="ghost"
class="size-11 justify-center text-highlighted sm:hidden"
:ui="{ leadingIcon: 'size-5' }"
aria-label="New article"
@click="openNewArticleModal"
/>
</template>
<div class="flex max-w-244 flex-col gap-5 lg:gap-7">
<div class="flex flex-wrap items-end gap-4">
<div class="flex min-w-50 flex-1 flex-col gap-1">
<h1 data-testid="greeting" class="text-2xl font-semibold text-highlighted">
{{ greeting }}
</h1>
<p class="text-base/5 text-muted">{{ subtitle }}</p>
</div>
<UButton
icon="i-lucide-plus"
class="hidden px-3 sm:flex"
@click="openNewArticleModal"
>
New article
</UButton>
</div>
<template v-if="(loadState === 'loading' && showSkeleton) || loadState === 'default'">
<div class="grid grid-cols-3 gap-3">
<div
v-for="tile in statTiles"
:key="tile.label"
data-testid="stat-tile"
class="flex flex-col gap-1 border border-default bg-default p-4"
>
<template v-if="loadState === 'loading'">
<USkeleton class="h-7 w-10 rounded-none bg-accented" />
<USkeleton class="h-3 w-17.5 rounded-none bg-accented" />
</template>
<template v-else>
<span class="text-2xl font-semibold text-highlighted">{{
tile.value
}}</span>
<span class="text-muted">{{ tile.label }}</span>
</template>
</div>
</div>
<section class="flex flex-col gap-2.5">
<div class="flex items-baseline justify-between">
<h2 class="text-lg font-semibold text-highlighted">Recently updated</h2>
<RouterLink to="/article" class="text-toned underline underline-offset-3">
All articles
</RouterLink>
</div>
<div
v-if="loadState === 'loading'"
aria-busy="true"
class="border border-default bg-default"
>
<div
v-for="n in RECENT_LIST_SIZE"
:key="n"
class="flex min-h-13 items-center gap-3 border-t border-muted px-3 py-2 lg:min-h-11"
>
<USkeleton class="h-3 max-w-[60%] flex-1 rounded-none bg-accented" />
<USkeleton class="h-5 w-14 rounded-none bg-accented" />
</div>
</div>
<ul v-else data-testid="recent-list" class="border border-default bg-default">
<li v-for="article in recentArticles" :key="article.id">
<RouterLink
:to="`/article/${article.id}/edit`"
class="flex min-h-13 items-center gap-3 border-t border-muted px-3 py-2 lg:min-h-11"
>
<span class="min-w-0 flex-1 truncate font-medium text-highlighted">
{{ article.title }}
</span>
<ArticleStatusBadge :online="article.is_online" />
<span class="hidden w-27.5 text-right text-muted lg:inline">
{{ formatRelativeDate(article.updated_at) }}
</span>
</RouterLink>
</li>
</ul>
</section>
</template>
<UEmpty
v-else-if="loadState === 'empty'"
variant="outline"
icon="i-lucide-file-text"
title="Write your first article"
description="It starts as a draft, so nothing appears on your site until you publish it."
:ui="{
root: 'gap-3 rounded-none border border-default px-6 py-12 ring-0 sm:px-6 sm:py-12 lg:px-6 lg:py-12',
header: 'max-w-none gap-3',
avatar: 'mb-0 size-11 rounded-none bg-elevated text-xl text-toned',
title: 'text-[1.125rem] font-semibold',
description: 'max-w-85 text-base text-wrap text-muted',
body: 'max-w-none',
}"
>
<template #actions>
<UButton
icon="i-lucide-plus"
class="h-11 px-4 lg:h-8"
@click="openNewArticleModal"
>
New article
</UButton>
</template>
</UEmpty>
<UAlert
v-else-if="loadState === 'error'"
role="alert"
color="error"
variant="soft"
orientation="vertical"
:close="false"
icon="i-lucide-circle-x"
title="Couldn't load your articles"
description="Check your connection and try again."
:ui="{
root: 'gap-2.5 px-3.5 py-3',
icon: 'mt-0.5 size-4',
title: 'text-sm font-semibold',
description: 'mt-0.5 text-sm text-toned opacity-100',
actions: 'mt-2',
}"
>
<template #actions>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-rotate-cw"
class="h-7 bg-default px-2.5 text-xs text-highlighted"
:ui="{ leadingIcon: 'size-3.5' }"
@click="loadArticles"
>
Try again
</UButton>
</template>
</UAlert>
<div class="flex items-start gap-3.5 border border-default bg-default p-4">
<div
class="flex size-9 shrink-0 items-center justify-center bg-secondary-200 text-primary-900 dark:bg-secondary-300"
>
<UIcon name="i-lucide-plug" class="size-4.5" />
</div>
<div class="flex flex-1 flex-col gap-1">
<h2 class="text-base/5 font-semibold text-highlighted">Connect your website</h2>
<p class="text-pretty text-muted">
Your site reads published articles from RenewCMS. Share this guide with
whoever builds it.
</p>
<RouterLink
to="/integration"
class="mt-1 self-start font-medium text-highlighted underline underline-offset-3"
>
Open the guide
</RouterLink>
</div>
</div>
</div>
<NewArticleModal v-model:open="newArticleModalOpen" />
</DashboardShell>
</template>
+375
View File
@@ -0,0 +1,375 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import uiPlugin from '@nuxt/ui/vue-plugin'
import router from '@/router'
import { useSessionStore } from '@/stores/session'
import type { Article } from '@/composables/useArticles'
import HomeView from '../HomeView.vue'
function mockResponse(status: number, body: unknown = null, headers: Record<string, string> = {}) {
return {
ok: status >= 200 && status < 300,
status,
headers: { get: (name: string) => headers[name] ?? null },
json: async () => body,
} as unknown as Response
}
function routeFor(url: string, init?: RequestInit) {
const method = init?.method ?? 'GET'
return `${method} ${url}`
}
function fetchRouter(handlers: Record<string, () => Response | Promise<Response>>) {
return vi.fn((url: string, init?: RequestInit) => {
const key = routeFor(url, init)
const handler = handlers[key]
if (!handler) {
throw new Error(`Unexpected fetch call: ${key}`)
}
return handler()
})
}
const sixArticles: Article[] = [
{
id: 1,
title: 'How we price a bathroom renovation',
body: '',
images: [],
is_online: true,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-06T00:00:00Z',
},
{
id: 2,
title: 'Winter checklist for timber windows',
body: '',
images: [],
is_online: true,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-05T00:00:00Z',
},
{
id: 3,
title: 'Choosing tiles for a small bathroom',
body: '',
images: [],
is_online: false,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-04T00:00:00Z',
},
{
id: 4,
title: 'A guide to underfloor heating',
body: '',
images: [],
is_online: true,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-03T00:00:00Z',
},
{
id: 5,
title: 'When to reseal a stone worktop',
body: '',
images: [],
is_online: false,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-02T00:00:00Z',
},
{
id: 6,
title: 'Small bathroom lighting ideas',
body: '',
images: [],
is_online: true,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
},
]
let currentWrapper: Awaited<ReturnType<typeof mount>> | null = null
async function mountHome(handlers: Record<string, () => Response | Promise<Response>>) {
setActivePinia(createPinia())
const session = useSessionStore()
session.session = { verified: true, username: 'marta' }
session.status = 'ready'
global.fetch = fetchRouter(handlers) as unknown as typeof fetch
await router.push('/home')
const wrapper = mount(HomeView, {
attachTo: document.body,
global: {
plugins: [router, uiPlugin],
},
})
currentWrapper = wrapper
await flushPromises()
return wrapper
}
function findButton(wrapper: Awaited<ReturnType<typeof mount>>, label: string) {
return wrapper.findAll('button').find((button) => button.text() === label)
}
afterEach(async () => {
currentWrapper?.unmount()
currentWrapper = null
vi.useRealTimers()
await router.push('/login')
})
describe('Skeletons appear only after 150 ms, never for a fast response', () => {
it('shows no skeleton before 150 ms, a skeleton after, then Default once resolved', async () => {
vi.useFakeTimers()
let resolveList: (() => void) | null = null
const wrapper = await mountHome({
'GET /v1/article/': () =>
new Promise((resolve) => {
resolveList = () => resolve(mockResponse(200, sixArticles))
}),
})
expect(wrapper.find('[aria-busy="true"]').exists()).toBe(false)
await vi.advanceTimersByTimeAsync(150)
expect(wrapper.find('[aria-busy="true"]').exists()).toBe(true)
resolveList?.()
await vi.advanceTimersByTimeAsync(0)
await flushPromises()
expect(wrapper.find('[aria-busy="true"]').exists()).toBe(false)
expect(wrapper.text()).toContain('6')
expect(wrapper.text()).toContain('articles')
})
it('never shows a skeleton when the response resolves in under 150 ms', async () => {
vi.useFakeTimers()
const wrapper = await mountHome({
'GET /v1/article/': () => Promise.resolve(mockResponse(200, sixArticles)),
})
await vi.advanceTimersByTimeAsync(0)
await flushPromises()
expect(wrapper.find('[aria-busy="true"]').exists()).toBe(false)
expect(wrapper.text()).toContain('6')
})
})
describe('Default — the list loaded with a mix of online and draft articles', () => {
it('shows the subtitle, stat tiles and the first 5 articles in order', async () => {
const wrapper = await mountHome({
'GET /v1/article/': () => mockResponse(200, sixArticles),
})
expect(wrapper.text()).toContain("Here's where things stand on your site.")
const rows = wrapper.find('[data-testid="recent-list"]').findAll('li')
expect(rows).toHaveLength(5)
expect(rows[0].text()).toContain('How we price a bathroom renovation')
expect(rows[4].text()).toContain('When to reseal a stone worktop')
expect(wrapper.text()).not.toContain('Small bathroom lighting ideas')
expect(rows[0].find('a').attributes('href')).toBe('/article/1/edit')
expect(rows[0].text()).toContain('Online')
expect(rows[2].text()).toContain('Draft')
expect(wrapper.text()).toContain('6')
expect(wrapper.text()).toContain('articles')
expect(wrapper.text()).toContain('4')
expect(wrapper.text()).toContain('online')
expect(wrapper.text()).toContain('2')
expect(wrapper.text()).toContain('drafts')
const guideLink = wrapper.findAll('a').find((a) => a.text() === 'Open the guide')
expect(guideLink?.attributes('href')).toBe('/integration')
await findButton(wrapper, 'New article')?.trigger('click')
await flushPromises()
expect(document.body.querySelector('[role="dialog"]')).toBeTruthy()
})
})
describe('Empty, first run — zero articles', () => {
it('shows the empty state and opens NewArticleModal', async () => {
const wrapper = await mountHome({
'GET /v1/article/': () => mockResponse(200, []),
})
expect(wrapper.text()).toContain('Welcome to RenewCMS.')
expect(wrapper.text()).toContain('Write your first article')
expect(wrapper.text()).toContain(
'It starts as a draft, so nothing appears on your site until you publish it.',
)
expect(wrapper.find('[data-testid="stat-tile"]').exists()).toBe(false)
await findButton(wrapper, 'New article')?.trigger('click')
await flushPromises()
expect(document.body.querySelector('[role="dialog"]')).toBeTruthy()
})
})
describe('Error — a 500 or a network failure shows the same inline alert', () => {
it.each([
{ name: 'a 500 response', handler: () => mockResponse(500) },
{
name: 'a network failure',
handler: () => Promise.reject(new TypeError('Failed to fetch')),
},
])('shows the alert with identical copy for $name', async ({ handler }) => {
const wrapper = await mountHome({
'GET /v1/article/': handler,
})
expect(wrapper.text()).toContain("Here's where things stand on your site.")
expect(wrapper.text()).toContain('Good')
const alert = wrapper.find('[role="alert"]')
expect(alert.exists()).toBe(true)
expect(alert.text()).toContain("Couldn't load your articles")
expect(alert.text()).toContain('Check your connection and try again.')
expect(findButton(wrapper, 'Try again')).toBeTruthy()
})
})
describe('Retry re-issues the request and recovers into the Default state', () => {
it('replaces the alert with the stat tiles and recent list once the retry succeeds', async () => {
const listCall = vi
.fn()
.mockResolvedValueOnce(mockResponse(500))
.mockResolvedValueOnce(mockResponse(200, sixArticles))
const wrapper = await mountHome({
'GET /v1/article/': listCall,
})
expect(wrapper.find('[role="alert"]').exists()).toBe(true)
await findButton(wrapper, 'Try again')?.trigger('click')
await flushPromises()
expect(listCall).toHaveBeenCalledTimes(2)
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
expect(wrapper.text()).toContain('6')
expect(wrapper.text()).toContain('articles')
})
})
describe('The list is fetched exactly once per navigation', () => {
it('calls GET /v1/article/ exactly once and derives both stats and the list from it', async () => {
const listCall = vi.fn(() => mockResponse(200, sixArticles))
const wrapper = await mountHome({
'GET /v1/article/': listCall,
})
expect(listCall).toHaveBeenCalledTimes(1)
expect(wrapper.text()).toContain('6')
expect(wrapper.find('[data-testid="recent-list"]').findAll('li')).toHaveLength(5)
})
})
describe('The greeting matches the hour of day', () => {
it.each([
{ hour: 0, greeting: 'Good morning' },
{ hour: 11, greeting: 'Good morning' },
{ hour: 12, greeting: 'Good afternoon' },
{ hour: 17, greeting: 'Good afternoon' },
{ hour: 18, greeting: 'Good evening' },
{ hour: 23, greeting: 'Good evening' },
])('reads "$greeting, marta" at hour $hour', async ({ hour, greeting }) => {
vi.useFakeTimers()
vi.setSystemTime(new Date(2026, 0, 1, hour, 0, 0))
const wrapper = await mountHome({
'GET /v1/article/': () => mockResponse(200, sixArticles),
})
expect(wrapper.text()).toContain(`${greeting}, marta`)
})
})
describe('The greeting is identical across every load state at a fixed hour', () => {
it('reads "Good morning, marta" while loading, in Default, Empty and Error', async () => {
vi.useFakeTimers()
vi.setSystemTime(new Date(2026, 0, 1, 9, 0, 0))
const loadingWrapper = await mountHome({
'GET /v1/article/': () => new Promise(() => {}),
})
await vi.advanceTimersByTimeAsync(150)
expect(loadingWrapper.text()).toContain('Good morning, marta')
const defaultWrapper = await mountHome({
'GET /v1/article/': () => mockResponse(200, sixArticles),
})
expect(defaultWrapper.text()).toContain('Good morning, marta')
const emptyWrapper = await mountHome({
'GET /v1/article/': () => mockResponse(200, []),
})
expect(emptyWrapper.text()).toContain('Good morning, marta')
const errorWrapper = await mountHome({
'GET /v1/article/': () => mockResponse(500),
})
expect(errorWrapper.text()).toContain('Good morning, marta')
})
})
describe('The greeting handles a missing username', () => {
it('renders the plain greeting without a stray comma when the session has no username', async () => {
vi.useFakeTimers()
vi.setSystemTime(new Date(2026, 0, 1, 9, 0, 0))
setActivePinia(createPinia())
const session = useSessionStore()
session.session = { verified: true }
session.status = 'ready'
global.fetch = fetchRouter({
'GET /v1/article/': () => mockResponse(200, sixArticles),
}) as unknown as typeof fetch
await router.push('/home')
const wrapper = mount(HomeView, {
attachTo: document.body,
global: { plugins: [router, uiPlugin] },
})
currentWrapper = wrapper
await flushPromises()
const heading = wrapper.find('[data-testid="greeting"]')
expect(heading.text()).toBe('Good morning')
expect(heading.text()).not.toContain('undefined')
expect(heading.text()).not.toMatch(/,\s*$/)
})
})
describe('The "Connect your website" card renders in every state', () => {
it('renders the same card while loading, in Default, Empty and Error', async () => {
vi.useFakeTimers()
const wrapper = await mountHome({
'GET /v1/article/': () => new Promise(() => {}),
})
await vi.advanceTimersByTimeAsync(150)
expect(wrapper.text()).toContain('Connect your website')
expect(wrapper.text()).toContain(
'Your site reads published articles from RenewCMS. Share this guide with whoever builds it.',
)
vi.useRealTimers()
const defaultWrapper = await mountHome({
'GET /v1/article/': () => mockResponse(200, sixArticles),
})
expect(defaultWrapper.text()).toContain('Connect your website')
const emptyWrapper = await mountHome({
'GET /v1/article/': () => mockResponse(200, []),
})
expect(emptyWrapper.text()).toContain('Connect your website')
const errorWrapper = await mountHome({
'GET /v1/article/': () => mockResponse(500),
})
expect(errorWrapper.text()).toContain('Connect your website')
})
})