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

@@ -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>
)
}