feat: make the web app installable and rework the app shell

Add a Vite PWA (`vite-plugin-pwa`): manifest, icons and an `autoUpdate`
service worker, plus an install prompt so the app can be added to the
home screen.

Rework the shell for mobile: mount the bottom navigation bar and the
install prompt in the authenticated layout, hide the sidebar trigger
below `md`, and add a sign-out card to Settings. Drop the placeholder
Tasks page together with its unused shadcn table and the
`@tanstack/react-table` dependency, and remove the in-app router/query
dev tools.
This commit is contained in:
Jose Selesan
2026-10-16 15:44:20 -03:00
parent 4035a4bf20
commit 370e3022c8
19 changed files with 777 additions and 272 deletions

View File

@@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, viewport-fit=cover"

View File

@@ -19,7 +19,6 @@
"@tanstack/react-query": "^5.104.2",
"@tanstack/react-query-devtools": "^5.104.2",
"@tanstack/react-router": "^1.170.42",
"@tanstack/react-table": "^9.3.1",
"better-auth": "^1.7.7",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -48,6 +47,7 @@
"tw-animate-css": "^1.4.0",
"typescript": "~6.0.2",
"vite": "^8.3.0",
"vite-plugin-pwa": "^2.0.0",
"vitest": "^5.0.4"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32" role="img" aria-label="Superlist">
<rect width="32" height="32" rx="7" fill="#0a0a0a" />
<text
x="16"
y="17"
text-anchor="middle"
dominant-baseline="middle"
font-family="'Geist Variable', Helvetica, Arial, sans-serif"
font-size="15"
font-weight="600"
letter-spacing="-0.6"
fill="#fafafa"
>SL</text>
</svg>

After

Width:  |  Height:  |  Size: 431 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

View File

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="Superlist">
<rect width="512" height="512" fill="#0a0a0a" />
<text
x="256"
y="270"
text-anchor="middle"
dominant-baseline="middle"
font-family="'Geist Variable', Helvetica, Arial, sans-serif"
font-size="216"
font-weight="600"
letter-spacing="-9"
fill="#fafafa"
>SL</text>
</svg>

After

Width:  |  Height:  |  Size: 431 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@@ -0,0 +1,42 @@
import { DownloadIcon, SmartphoneIcon, XIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useInstallPrompt } from '@/hooks/use-install-prompt'
export function InstallPrompt() {
const { visible, canInstall, needsManualInstructions, install, dismiss } = useInstallPrompt()
if (!visible) return null
return (
<div className="fixed inset-x-0 bottom-0 z-40 px-3 pb-[calc(4.75rem+env(safe-area-inset-bottom))] md:left-auto md:right-4 md:max-w-md md:px-4 md:pb-4">
<div className="bg-card shadow-lg border rounded-xl p-3 flex items-center gap-3 w-full">
<div className="bg-primary/10 text-primary rounded-lg p-2">
{needsManualInstructions ? (
<SmartphoneIcon className="size-4" />
) : (
<DownloadIcon className="size-4" />
)}
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">Instalar Superlist</p>
<p className="text-xs text-muted-foreground">
{needsManualInstructions
? 'Toca Compartir y luego «Añadir a pantalla de inicio».'
: 'Añádela a tu pantalla de inicio para usarla como una app.'}
</p>
</div>
<div className="flex items-center gap-1">
{canInstall && (
<Button size="sm" onClick={install}>
Instalar
</Button>
)}
<Button size="icon-sm" variant="ghost" aria-label="Cerrar" onClick={dismiss}>
<XIcon className="size-3.5" />
</Button>
</div>
</div>
</div>
)
}

View File

@@ -8,7 +8,6 @@ import { SidebarTrigger } from '@/components/ui/sidebar'
function titleFor(pathname: string) {
if (pathname === '/') return 'Panel'
if (pathname.startsWith('/lists')) return 'Listas'
if (pathname.startsWith('/tasks')) return 'Tareas'
if (pathname.startsWith('/settings')) return 'Ajustes'
return 'Superlist'
}
@@ -20,7 +19,7 @@ export function AppHeader() {
return (
<header className="bg-background/95 supports-[backdrop-filter]:bg-background/60 sticky top-0 z-10 flex h-16 shrink-0 items-center gap-2 border-b backdrop-blur">
<div className="flex w-full items-center gap-2 px-4">
<SidebarTrigger className="-ml-1" />
<SidebarTrigger className="-ml-1 hidden md:inline-flex" />
<Separator orientation="vertical" className="mr-2 h-4" />
<h1 className="truncate text-sm font-medium">{title}</h1>
<div className="ml-auto flex items-center gap-1">

View File

@@ -1,6 +1,6 @@
import { Link, useRouterState } from '@tanstack/react-router'
import type { LucideIcon } from 'lucide-react'
import { HomeIcon, ListTodoIcon, SettingsIcon, ShoppingCartIcon } from 'lucide-react'
import { HomeIcon, SettingsIcon, ShoppingCartIcon } from 'lucide-react'
import { focusNewItemInput } from '@/components/items/create-item-form'
import { NavUser } from '@/components/layout/nav-user'
@@ -26,7 +26,6 @@ type NavItem = {
const NAV_ITEMS: NavItem[] = [
{ title: 'Principal', to: '/', icon: HomeIcon },
{ title: 'Listas', to: '/lists', icon: ShoppingCartIcon },
{ title: 'Tareas', to: '/tasks', icon: ListTodoIcon },
{ title: 'Ajustes', to: '/settings', icon: SettingsIcon },
]

View File

@@ -1,88 +0,0 @@
'use client'
import { cn } from 'cn'
import * as React from 'react'
function Table({ className, ...props }: React.ComponentProps<'table'>) {
return (
<div data-slot="table-container" className="relative w-full overflow-x-auto">
<table
data-slot="table"
className={cn('w-full caption-bottom text-sm', className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {
return <thead data-slot="table-header" className={cn('[&_tr]:border-b', className)} {...props} />
}
function TableBody({ className, ...props }: React.ComponentProps<'tbody'>) {
return (
<tbody
data-slot="table-body"
className={cn('[&_tr:last-child]:border-0', className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {
return (
<tfoot
data-slot="table-footer"
className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<'tr'>) {
return (
<tr
data-slot="table-row"
className={cn(
'border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted',
className,
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<'th'>) {
return (
<th
data-slot="table-head"
className={cn(
'h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0',
className,
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<'td'>) {
return (
<td
data-slot="table-cell"
className={cn('p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0', className)}
{...props}
/>
)
}
function TableCaption({ className, ...props }: React.ComponentProps<'caption'>) {
return (
<caption
data-slot="table-caption"
className={cn('mt-4 text-sm text-muted-foreground', className)}
{...props}
/>
)
}
export { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow }

View File

@@ -0,0 +1,111 @@
import * as React from 'react'
/**
* `beforeinstallprompt` is still non-standard, so TypeScript has no DOM type
* for it. This is the subset of the event we use.
*/
interface BeforeInstallPromptEvent extends Event {
readonly platforms: string[]
readonly userChoice: Promise<{ outcome: 'accepted' | 'dismissed'; platform: string }>
prompt(): Promise<void>
}
const DISMISSED_KEY = 'superlist-install-dismissed'
function readDismissed() {
try {
return localStorage.getItem(DISMISSED_KEY) === '1'
} catch {
return false
}
}
function isStandalone() {
if (typeof window === 'undefined') return false
const navigatorWithStandalone = navigator as Navigator & { standalone?: boolean }
return (
window.matchMedia('(display-mode: standalone)').matches ||
navigatorWithStandalone.standalone === true
)
}
function isIosSafari() {
if (typeof navigator === 'undefined') return false
const ua = navigator.userAgent
const isIos = /iphone|ipad|ipod/i.test(ua)
// On iOS only Safari can add apps to the home screen, and it never fires
// `beforeinstallprompt`, so we detect it to show manual instructions.
const isSafari = /safari/i.test(ua) && !/crios|fxios|edgios/i.test(ua)
return isIos && isSafari
}
export type InstallPromptState = {
/** We can trigger the native install dialog. */
canInstall: boolean
/** iOS Safari: no native prompt, show "Compartir → Añadir a pantalla de inicio". */
needsManualInstructions: boolean
/** The app is already running as an installed PWA. */
isInstalled: boolean
/** The user dismissed the banner before (persisted). */
isDismissed: boolean
install: () => Promise<void>
dismiss: () => void
/** Show the banner: installable or needing instructions, and not dismissed/installed. */
visible: boolean
}
export function useInstallPrompt(): InstallPromptState {
const [deferredPrompt, setDeferredPrompt] = React.useState<BeforeInstallPromptEvent | null>(null)
const [isInstalled, setIsInstalled] = React.useState(isStandalone)
const [isDismissed, setIsDismissed] = React.useState(readDismissed)
const [isIos] = React.useState(isIosSafari)
React.useEffect(() => {
const onBeforeInstallPrompt = (event: Event) => {
// Stop Chrome from showing its own mini-infobar so we control the banner.
event.preventDefault()
setDeferredPrompt(event as BeforeInstallPromptEvent)
}
const onInstalled = () => {
setDeferredPrompt(null)
setIsInstalled(true)
}
window.addEventListener('beforeinstallprompt', onBeforeInstallPrompt)
window.addEventListener('appinstalled', onInstalled)
return () => {
window.removeEventListener('beforeinstallprompt', onBeforeInstallPrompt)
window.removeEventListener('appinstalled', onInstalled)
}
}, [])
const install = React.useCallback(async () => {
if (!deferredPrompt) return
await deferredPrompt.prompt()
const { outcome } = await deferredPrompt.userChoice
if (outcome === 'accepted') setDeferredPrompt(null)
}, [deferredPrompt])
const dismiss = React.useCallback(() => {
setIsDismissed(true)
try {
localStorage.setItem(DISMISSED_KEY, '1')
} catch {
// Storage can be unavailable (private mode); the banner just comes back.
}
}, [])
const canInstall = deferredPrompt !== null
const needsManualInstructions = isIos && !deferredPrompt && !isInstalled
return {
canInstall,
needsManualInstructions,
isInstalled,
isDismissed,
install,
dismiss,
visible: !isInstalled && !isDismissed && (canInstall || needsManualInstructions),
}
}

View File

@@ -1,5 +1,4 @@
import { createRootRouteWithContext, Link, Outlet } from '@tanstack/react-router'
import { lazy } from 'react'
import { ThemeProvider } from '@/components/theme-provider'
import { Button } from '@/components/ui/button'
@@ -7,22 +6,6 @@ import { Toaster } from '@/components/ui/sonner'
import { TooltipProvider } from '@/components/ui/tooltip'
import type { RouterContext } from '@/lib/query-client'
const RouterDevtools = import.meta.env.DEV
? lazy(() =>
import('@tanstack/react-router-devtools').then((mod) => ({
default: mod.TanStackRouterDevtools,
})),
)
: () => null
const QueryDevtools = import.meta.env.DEV
? lazy(() =>
import('@tanstack/react-query-devtools').then((mod) => ({
default: mod.ReactQueryDevtools,
})),
)
: () => null
export const Route = createRootRouteWithContext<RouterContext>()({
component: RootLayout,
notFoundComponent: NotFound,
@@ -34,8 +17,6 @@ function RootLayout() {
<TooltipProvider delayDuration={200}>
<Outlet />
<Toaster richColors position="top-right" />
<QueryDevtools />
<RouterDevtools />
</TooltipProvider>
</ThemeProvider>
)

View File

@@ -1,7 +1,8 @@
import { createFileRoute, Navigate, Outlet, useRouterState } from '@tanstack/react-router'
import { InstallPrompt } from '@/components/install-prompt'
import { AppHeader } from '@/components/layout/app-header'
import { AppSidebar } from '@/components/layout/app-sidebar'
import { BottomNav } from '@/components/layout/bottom-nav'
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'
import { Skeleton } from '@/components/ui/skeleton'
import { useSession } from '@/lib/auth-client'
@@ -32,9 +33,11 @@ function AuthenticatedLayout() {
<AppSidebar />
<SidebarInset>
<AppHeader />
<div className="flex flex-1 flex-col gap-4 p-4 md:gap-6 md:p-6">
<div className="flex flex-1 flex-col gap-4 p-4 pb-20 md:gap-6 md:p-6 md:pb-6">
<Outlet />
</div>
<BottomNav />
<InstallPrompt />
</SidebarInset>
</SidebarProvider>
)

View File

@@ -1,15 +1,14 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { createFileRoute } from '@tanstack/react-router'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { useSession } from '@/lib/auth-client'
import { signOut, useSession } from '@/lib/auth-client'
export const Route = createFileRoute('/_authenticated/settings')({
component: SettingsPage,
@@ -24,6 +23,7 @@ type ProfileValues = z.infer<typeof profileSchema>
function SettingsPage() {
const { data: session } = useSession()
const navigate = useNavigate()
const [saved, setSaved] = useState(false)
const form = useForm<ProfileValues>({
@@ -108,6 +108,24 @@ function SettingsPage() {
))}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Sesión</CardTitle>
<CardDescription>Cierra sesión en este dispositivo.</CardDescription>
</CardHeader>
<CardContent>
<Button
variant="outline"
onClick={async () => {
await signOut()
await navigate({ to: '/sign-in' })
}}
>
Cerrar sesión
</Button>
</CardContent>
</Card>
</div>
)
}

View File

@@ -1,150 +0,0 @@
import { createFileRoute } from '@tanstack/react-router'
import { createColumnHelper, tableFeatures, useTable } from '@tanstack/react-table'
import { SearchIcon } from 'lucide-react'
import { useMemo, useState } from 'react'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
export const Route = createFileRoute('/_authenticated/tasks')({
component: TasksPage,
})
type Task = {
title: string
list: string
status: 'pendiente' | 'en curso' | 'hecha'
priority: 'baja' | 'media' | 'alta'
}
const TASKS: Task[] = [
{
title: 'Diseñar el flujo de registro',
list: 'Hoja de ruta Q4',
status: 'en curso',
priority: 'alta',
},
{
title: 'Escribir la documentación de la API',
list: 'Docs',
status: 'pendiente',
priority: 'media',
},
{
title: 'Revisar migraciones de Prisma',
list: 'Backend',
status: 'pendiente',
priority: 'alta',
},
{
title: 'Publicar el modo oscuro',
list: 'Sistema de diseño',
status: 'hecha',
priority: 'baja',
},
{ title: 'Migrar a Turborepo', list: 'Infra', status: 'hecha', priority: 'media' },
{ title: 'Añadir prueba e2e', list: 'Calidad', status: 'en curso', priority: 'baja' },
]
// `tableFeatures` and the columns live at module scope so row models stay stable.
const features = tableFeatures({})
const columnHelper = createColumnHelper<typeof features, Task>()
const columns = columnHelper.columns([
columnHelper.accessor('title', { header: 'Tarea' }),
columnHelper.accessor('list', { header: 'Lista' }),
columnHelper.accessor('status', { header: 'Estado' }),
columnHelper.accessor('priority', { header: 'Prioridad' }),
])
const STATUS_VARIANT = {
pendiente: 'outline',
'en curso': 'secondary',
hecha: 'default',
} as const
function TasksPage() {
const [query, setQuery] = useState('')
const data = useMemo(
() =>
TASKS.filter((task) =>
`${task.title} ${task.list} ${task.status}`.toLowerCase().includes(query.toLowerCase()),
),
[query],
)
const table = useTable({ features, columns, data })
return (
<Card>
<CardHeader>
<CardTitle>Tareas</CardTitle>
<CardDescription>Todas las tareas de tus listas.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="relative w-full sm:max-w-sm">
<SearchIcon className="text-muted-foreground absolute top-2.5 left-2.5 size-4" />
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Filtrar tareas…"
className="pl-8"
/>
</div>
<div className="overflow-x-auto rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder ? null : <table.FlexRender header={header} />}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.length === 0 && (
<TableRow>
<TableCell
colSpan={columns.length}
className="text-muted-foreground h-24 text-center"
>
Ninguna tarea coincide con el filtro.
</TableCell>
</TableRow>
)}
{table.getRowModel().rows.map((row) => (
<TableRow key={row.id}>
{row.getAllCells().map((cell) => (
<TableCell key={cell.id}>
{cell.column.id === 'status' ? (
<Badge variant={STATUS_VARIANT[cell.getValue<Task['status']>()]}>
{cell.getValue<Task['status']>()}
</Badge>
) : (
<table.FlexRender cell={cell} />
)}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
)
}

View File

@@ -4,6 +4,7 @@ import tailwindcss from '@tailwindcss/vite'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
import { VitePWA } from 'vite-plugin-pwa'
const srcDir = path.resolve(import.meta.dirname, './src')
@@ -13,6 +14,46 @@ export default defineConfig({
tanstackRouter({ target: 'react', autoCodeSplitting: true }),
react(),
tailwindcss(),
VitePWA({
// `autoUpdate` pre-caches the app shell and swaps in new releases on the
// next navigation. Registration is injected into `index.html` at build
// time, so no `virtual:pwa-register` import is needed in the app.
registerType: 'autoUpdate',
includeAssets: ['favicon.svg', 'apple-touch-icon.png'],
manifest: {
name: 'Superlist — Listas de compras compartidas',
short_name: 'Superlist',
description: 'Listas de compras compartidas con las personas de tu hogar.',
lang: 'es',
start_url: '/',
scope: '/',
display: 'standalone',
orientation: 'portrait',
theme_color: '#ffffff',
background_color: '#ffffff',
icons: [
{ src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' },
{
src: 'maskable-512x512.png',
sizes: '512x512',
type: 'image/png',
purpose: 'maskable',
},
],
},
workbox: {
// Pre-cache the app shell (JS/CSS/HTML + self-hosted Geist fonts).
globPatterns: ['**/*.{js,css,html,svg,png,ico,woff2}'],
// SPA fallback so deep links work offline, but never swallow API calls.
navigateFallback: 'index.html',
navigateFallbackDenylist: [/^\/api\//],
},
devOptions: {
// The service worker is only built for `vite build`; verify with `preview`.
enabled: false,
},
}),
],
resolve: {
alias: {

530
bun.lock

File diff suppressed because it is too large Load Diff