feat/pre-registration #7
@@ -59,13 +59,42 @@ Preview visual de los dos estados (con miembros + vacío):
|
|||||||
neutro `bg-primary-soft text-foreground/60`; sobre chip activo `bg-on-accent/25 text-on-accent`.
|
neutro `bg-primary-soft text-foreground/60`; sobre chip activo `bg-on-accent/25 text-on-accent`.
|
||||||
- `aria-pressed` en cada chip. Envuelve en 1–3 filas según ancho: nunca recorta.
|
- `aria-pressed` en cada chip. Envuelve en 1–3 filas según ancho: nunca recorta.
|
||||||
|
|
||||||
|
### Encabezado de pantalla — `components/layout/LargeTitle.tsx`
|
||||||
|
- Patrón iOS: título grande que al scrollear se desliza debajo de una barra de
|
||||||
|
navegación que se opaca y recibe el título en versión chica.
|
||||||
|
- Caja de la barra: `h-14` (56px) `sticky top-0 z-40` + `bg-background/80 backdrop-blur-md`
|
||||||
|
y `border-b`, con opacidad ligada al progreso. `h-14` tiene que coincidir con
|
||||||
|
`BAR_HEIGHT` de `hooks/useLargeTitleCollapse.ts`.
|
||||||
|
- Título grande: `text-[2.125rem] leading-[1.1] tracking-tight`, `sm:text-[2.5rem]`,
|
||||||
|
con `text-balance` para nombres largos.
|
||||||
|
- Título de la barra: `text-base font-semibold`, `truncate`, `aria-hidden` (es
|
||||||
|
duplicado visual del `h1`).
|
||||||
|
- El progreso sale de la posición del título en cada frame (`rAF` agrupa los
|
||||||
|
eventos de scroll), no de una transición: por eso se siente pegado al dedo. El
|
||||||
|
estado vive dentro de `LargeTitle` para que `children` no se re-renderice en
|
||||||
|
cada frame.
|
||||||
|
- La barra se monta en una caja que el layout pone arriba de `<main>`
|
||||||
|
(`ImmersiveBarHost`): un `sticky` está limitado a la caja de su padre, y el
|
||||||
|
padre natural (el bloque del feature) es corto.
|
||||||
|
- Sólo en tres rutas: `isImmersiveRoute` (`lib/immersive-routes.ts`): ficha de
|
||||||
|
grupo, sus estadísticas y la asistencia. Ahí no se renderiza el header global
|
||||||
|
y el sidebar pasa a `top-0 h-dvh`.
|
||||||
|
- El link "volver" vive en la barra como `leading` y sigue `hidden lg:inline-flex`.
|
||||||
|
- En las pantallas de un grupo (ficha y estadísticas) el título grande es **el
|
||||||
|
nombre del grupo**, no el de la sección: la barra colapsada tiene que decir
|
||||||
|
sobre qué se está mirando. "Estadísticas" va como subtítulo (label 11px
|
||||||
|
uppercase + body), no como título.
|
||||||
|
|
||||||
### Acciones de cabecera — `detail/GroupHeader.tsx`
|
### Acciones de cabecera — `detail/GroupHeader.tsx`
|
||||||
|
- Título, badges y descripción los dibuja `LargeTitle`; las acciones quedan
|
||||||
|
debajo, en el flujo normal.
|
||||||
- Estadísticas y Compartir: `variant="outline"` con icono `text-accent`; **Agregar Miembros:
|
- Estadísticas y Compartir: `variant="outline"` con icono `text-accent`; **Agregar Miembros:
|
||||||
`variant="ghost"`** (disponible, no dominante). Todas `h-11` (44px).
|
`variant="ghost"`** (disponible, no dominante). Todas `h-11` (44px).
|
||||||
- **Grupo vacío** (0 miembros + 0 pendientes): el header muestra **solo Estadísticas** —
|
- **Grupo vacío** (0 miembros + 0 pendientes): el header muestra **solo Estadísticas** —
|
||||||
Compartir y Agregar los ofrecen los empty states, que ya llevan su primario explicado.
|
Compartir y Agregar los ofrecen los empty states, que ya llevan su primario explicado.
|
||||||
- Móvil: `grid grid-cols-2 gap-2.5` (tercera acción `col-span-2`); `sm+`: `flex justify-end`.
|
- Móvil: `grid grid-cols-2 gap-2.5` (tercera acción `col-span-2`); `sm+`: `flex justify-end`.
|
||||||
- Badges de estado: `rounded-full px-2.5 py-0.5 text-[11px]` + punto `size-1.5`.
|
- Badges de estado: `rounded-full px-2.5 py-0.5 text-[11px]` + punto `size-1.5`,
|
||||||
|
en su propia fila bajo el título grande (`mt-3`) y se van al colapsar la barra.
|
||||||
|
|
||||||
### Tarjeta de info — `detail/GroupInfoCard.tsx`
|
### Tarjeta de info — `detail/GroupInfoCard.tsx`
|
||||||
- Contenedor: `rounded-2xl bg-primary-soft p-4 sm:p-5` + `divide-y divide-border/70` en móvil,
|
- Contenedor: `rounded-2xl bg-primary-soft p-4 sm:p-5` + `divide-y divide-border/70` en móvil,
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
- **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con `<Outlet />`).
|
- **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con `<Outlet />`).
|
||||||
- **Vistas en `apps/web/src/features/<feature>/`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use<Feature>()` y las forms locales mantienen su propio estado.
|
- **Vistas en `apps/web/src/features/<feature>/`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use<Feature>()` y las forms locales mantienen su propio estado.
|
||||||
- Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista.
|
- Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista.
|
||||||
|
- **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `<Header />`, `<main>` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `<main>`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos.
|
||||||
- **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos.
|
- **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos.
|
||||||
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
|
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
|
||||||
- **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `<main>` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa.
|
- **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `<main>` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa.
|
||||||
|
|||||||
82
apps/web/src/components/layout/LargeTitle.tsx
Normal file
82
apps/web/src/components/layout/LargeTitle.tsx
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { createPortal } from 'react-dom'
|
||||||
|
import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider'
|
||||||
|
import { useLargeTitleCollapse } from '../../hooks/useLargeTitleCollapse'
|
||||||
|
|
||||||
|
type LargeTitleProps = {
|
||||||
|
/** Texto del título. Es el mismo en el grande y en el de la barra: el `h1`
|
||||||
|
* real es el grande, el de la barra es un duplicado visual. */
|
||||||
|
title: string
|
||||||
|
/** Acción a la izquierda de la barra. En desktop es el link "volver" que
|
||||||
|
* antes vivía en el cuerpo de la pantalla; en mobile se oculta. */
|
||||||
|
leading?: ReactNode
|
||||||
|
/** Contexto que no puede desaparecer al scrollear (ej. el contador de
|
||||||
|
* presentes). Viaja a la barra y se funde con el título. */
|
||||||
|
barTrailing?: ReactNode
|
||||||
|
/** Metadatos bajo el título grande: badges, descripción. Se van al colapsar. */
|
||||||
|
children?: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encabezado de pantalla con Large Title (patrón de iOS): el título arranca
|
||||||
|
* grande y al scrollear se desliza debajo de la barra, que se opaca y recibe
|
||||||
|
* el título en versión chica.
|
||||||
|
*
|
||||||
|
* El título grande es un bloque normal en el flujo; la barra vive en una caja
|
||||||
|
* sticky que el layout monta arriba de `<main>` (ver `ImmersiveBarHost`), así
|
||||||
|
* el contenido se desliza por debajo sin márgenes negativos ni `fixed` que
|
||||||
|
* haya que compensar en desktop.
|
||||||
|
*
|
||||||
|
* El estado del scroll vive acá adentro a propósito: `children` llega como prop
|
||||||
|
* ya construido, así React reutiliza los elementos y el subtree de abajo no se
|
||||||
|
* re-renderiza en cada frame de scroll.
|
||||||
|
*/
|
||||||
|
export function LargeTitle({ title, leading, barTrailing, children }: LargeTitleProps) {
|
||||||
|
const { titleRef, progress } = useLargeTitleCollapse()
|
||||||
|
const barHost = useImmersiveBarHost()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{barHost
|
||||||
|
? createPortal(
|
||||||
|
<div className="relative flex h-full items-center gap-3 px-4 lg:px-0">
|
||||||
|
{/* El fondo va en una capa propia: se opaca con el scroll mientras
|
||||||
|
el título entra, y `leading` (el link "volver") no puede
|
||||||
|
fundirse con él porque existe siempre. */}
|
||||||
|
<div
|
||||||
|
className="absolute inset-0 border-b border-border bg-background/80 backdrop-blur-md"
|
||||||
|
style={{ opacity: progress }}
|
||||||
|
/>
|
||||||
|
{leading}
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className="relative min-w-0 flex-1 truncate text-base font-semibold text-primary"
|
||||||
|
style={{ opacity: progress, transform: `translateY(${(1 - progress) * 12}px)` }}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</span>
|
||||||
|
{barTrailing ? (
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className="relative flex shrink-0 items-center"
|
||||||
|
style={{ opacity: progress }}
|
||||||
|
>
|
||||||
|
{barTrailing}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>,
|
||||||
|
barHost,
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
|
||||||
|
<h1
|
||||||
|
ref={titleRef}
|
||||||
|
className="text-balance text-[2.125rem] font-bold leading-[1.1] tracking-tight text-primary sm:text-[2.5rem]"
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
{children}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,21 +1,39 @@
|
|||||||
|
import { useLocation } from '@tanstack/react-router'
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
|
import { ImmersiveBarHost, ImmersiveBarProvider } from '../../context/ImmersiveBarProvider'
|
||||||
|
import { isImmersiveRoute } from '../../lib/immersive-routes'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
import { Header } from './Header'
|
import { Header } from './Header'
|
||||||
import { Sidebar } from './Sidebar'
|
import { Sidebar } from './Sidebar'
|
||||||
import { BottomNav } from './BottomNav'
|
import { BottomNav } from './BottomNav'
|
||||||
|
|
||||||
export function RootLayout({ children }: { children: ReactNode }) {
|
export function RootLayout({ children }: { children: ReactNode }) {
|
||||||
|
const immersive = useLocation({ select: (location) => isImmersiveRoute(location.pathname) })
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-dvh w-full">
|
<div className="min-h-dvh w-full">
|
||||||
<Header />
|
{/* En las rutas immersive la pantalla trae su propia barra (LargeTitle),
|
||||||
|
con el logo y el nombre del grupo: el header global con logo + tema +
|
||||||
|
avatar sería una segunda barra compitiendo por los mismos píxeles. */}
|
||||||
|
{immersive ? null : <Header />}
|
||||||
|
|
||||||
<div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6">
|
<div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6">
|
||||||
<Sidebar />
|
<Sidebar immersive={immersive} />
|
||||||
|
|
||||||
{/* pb-24 deja lugar para la BottomNav; en iOS standalone hay que sumar
|
<ImmersiveBarProvider>
|
||||||
el inset del home indicator o el contenido queda debajo. */}
|
{/* pt-0 en immersive: el padding superior lo aporta la caja de la
|
||||||
<main className="min-w-0 flex-1 px-4 pb-[calc(6rem+env(safe-area-inset-bottom))] pt-4 lg:px-0 lg:pb-8 lg:pt-8">
|
barra, y si no el título grande arrancaría 16px más abajo de la
|
||||||
{children}
|
base de la barra y el colapso se mediría corrido. */}
|
||||||
</main>
|
<main
|
||||||
|
className={cn(
|
||||||
|
'min-w-0 flex-1 px-4 pb-[calc(6rem+env(safe-area-inset-bottom))] lg:px-0 lg:pb-8',
|
||||||
|
immersive ? 'pt-0' : 'pt-4 lg:pt-8',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{immersive ? <ImmersiveBarHost /> : null}
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
</ImmersiveBarProvider>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<BottomNav />
|
<BottomNav />
|
||||||
|
|||||||
@@ -3,11 +3,19 @@ import { cn } from '../../lib/utils'
|
|||||||
import { Logo } from '../brand'
|
import { Logo } from '../brand'
|
||||||
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||||
|
|
||||||
export function Sidebar() {
|
export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside className="sticky top-16 hidden h-[calc(100dvh-4rem)] w-64 shrink-0 flex-col border-r border-border bg-surface px-4 py-6 lg:flex">
|
// Sin header global no hay nada que esquive arriba: la columna del sidebar
|
||||||
|
// pasa a ocupar la ventana completa y queda a la altura de la barra de
|
||||||
|
// LargeTitle.
|
||||||
|
<aside
|
||||||
|
className={cn(
|
||||||
|
'sticky hidden w-64 shrink-0 flex-col border-r border-border bg-surface px-4 py-6 lg:flex',
|
||||||
|
immersive ? 'top-0 h-dvh' : 'top-16 h-[calc(100dvh-4rem)]',
|
||||||
|
)}
|
||||||
|
>
|
||||||
{/* `Link` y no `<a>`: un anchor recargaría el documento y perdería el
|
{/* `Link` y no `<a>`: un anchor recargaría el documento y perdería el
|
||||||
estado en memoria (cache de React Query, evento de instalación). */}
|
estado en memoria (cache de React Query, evento de instalación). */}
|
||||||
<Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
|
<Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
export { RootLayout } from './RootLayout'
|
export { RootLayout } from './RootLayout'
|
||||||
export { Header } from './Header'
|
export { Header } from './Header'
|
||||||
|
export { LargeTitle } from './LargeTitle'
|
||||||
export { ThemeToggle } from './ThemeToggle'
|
export { ThemeToggle } from './ThemeToggle'
|
||||||
export { PublicHeader } from './PublicHeader'
|
export { PublicHeader } from './PublicHeader'
|
||||||
export { PublicFooter } from './PublicFooter'
|
export { PublicFooter } from './PublicFooter'
|
||||||
|
|||||||
42
apps/web/src/context/ImmersiveBarProvider.tsx
Normal file
42
apps/web/src/context/ImmersiveBarProvider.tsx
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { createContext, useCallback, useContext, useState, type ReactNode } from 'react'
|
||||||
|
|
||||||
|
/* Las pantallas "immersive" (ficha de grupo y asistencia) arman su propia barra
|
||||||
|
de título en vez de usar el header global, pero la barra tiene que ser hija
|
||||||
|
directa de `<main>`: un `sticky` solo se pega mientras su caja padre esté en
|
||||||
|
pantalla, y el padre natural de la barra (el bloque del feature) es corto, así
|
||||||
|
que se despegaría a los ~200px de scroll.
|
||||||
|
|
||||||
|
Este provider expone una caja fija de 56px clavada arriba de `<main>` donde la
|
||||||
|
pantalla monta su barra. La caja la dibuja el layout (para que ocupe su lugar
|
||||||
|
desde el primer render) y su contenido lo aporta la pantalla. */
|
||||||
|
|
||||||
|
type ImmersiveBarValue = {
|
||||||
|
host: HTMLElement | null
|
||||||
|
hostRef: (element: HTMLElement | null) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const ImmersiveBarContext = createContext<ImmersiveBarValue>({
|
||||||
|
host: null,
|
||||||
|
hostRef: () => undefined,
|
||||||
|
})
|
||||||
|
|
||||||
|
export function ImmersiveBarProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [host, setHost] = useState<HTMLElement | null>(null)
|
||||||
|
const hostRef = useCallback((element: HTMLElement | null) => setHost(element), [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ImmersiveBarContext.Provider value={{ host, hostRef }}>{children}</ImmersiveBarContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Caja de la barra: primer hijo de `<main>`, en las rutas immersive. */
|
||||||
|
export function ImmersiveBarHost() {
|
||||||
|
const { hostRef } = useContext(ImmersiveBarContext)
|
||||||
|
|
||||||
|
return <div ref={hostRef} className="sticky top-0 z-40 -mx-4 h-14 lg:mx-0" />
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Destino del portal de `LargeTitle`; `null` si la pantalla no es immersive. */
|
||||||
|
export function useImmersiveBarHost() {
|
||||||
|
return useContext(ImmersiveBarContext).host
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, Loader2 } from 'lucide-react'
|
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||||
|
import { LargeTitle } from '../../components/layout/LargeTitle'
|
||||||
import { Badge, Button } from '../../components/ui'
|
import { Badge, Button } from '../../components/ui'
|
||||||
import { useAttendance } from './AttendanceProvider'
|
import { useAttendance } from './AttendanceProvider'
|
||||||
import { StudentRow } from './StudentRow'
|
import { StudentRow } from './StudentRow'
|
||||||
@@ -16,15 +17,43 @@ export function ClassAttendanceView() {
|
|||||||
isSaving,
|
isSaving,
|
||||||
} = useAttendance()
|
} = useAttendance()
|
||||||
|
|
||||||
|
const total = sessionInfo?.students.length ?? 0
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
<Link
|
{/* El título grande va siempre, incluso mientras carga la sesión: es lo
|
||||||
to="/"
|
que orienta y da altura de anclaje a la barra. El contador de
|
||||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
presentes, en cambio, solo aparece cuando ya hay alumnos en pantalla. */}
|
||||||
|
<LargeTitle
|
||||||
|
title={sessionInfo?.groupName ?? 'Asistencia'}
|
||||||
|
leading={
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
<span>Volver al inicio</span>
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
|
barTrailing={
|
||||||
|
total > 0 ? (
|
||||||
|
<Badge variant="success" className="text-[11px] tabular-nums">
|
||||||
|
{presentCount}/{total}
|
||||||
|
</Badge>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-4" />
|
{sessionInfo ? (
|
||||||
<span>Volver al inicio</span>
|
<div className="mt-2 flex items-center justify-between gap-3">
|
||||||
</Link>
|
<p className="text-sm text-foreground/60">
|
||||||
|
{startTime ? `Hoy · ${startTime} hs` : 'Clase de hoy'}
|
||||||
|
</p>
|
||||||
|
<Badge variant="success" className="shrink-0 text-xs tabular-nums">
|
||||||
|
{presentCount}/{total} presentes
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</LargeTitle>
|
||||||
|
|
||||||
{studentsPending ? (
|
{studentsPending ? (
|
||||||
<div className="flex items-center justify-center py-16">
|
<div className="flex items-center justify-center py-16">
|
||||||
@@ -43,19 +72,7 @@ export function ClassAttendanceView() {
|
|||||||
|
|
||||||
{sessionInfo ? (
|
{sessionInfo ? (
|
||||||
<>
|
<>
|
||||||
<header className="sticky top-16 z-30 -mx-4 border-b border-border bg-background/95 px-4 py-3 backdrop-blur lg:mx-0 lg:rounded-xl lg:border lg:px-4">
|
{total === 0 ? (
|
||||||
<div className="flex items-center justify-between gap-3">
|
|
||||||
<div className="min-w-0">
|
|
||||||
<h1 className="truncate text-lg font-bold text-primary">{sessionInfo.groupName}</h1>
|
|
||||||
<p className="text-xs text-foreground/60">{startTime ? `Hoy · ${startTime} hs` : 'Clase de hoy'}</p>
|
|
||||||
</div>
|
|
||||||
<Badge variant="success" className="shrink-0 text-sm">
|
|
||||||
{presentCount}/{sessionInfo.students.length} presentes
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{sessionInfo.students.length === 0 ? (
|
|
||||||
<div className="mt-6 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
<div className="mt-6 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
||||||
<p className="text-sm font-medium text-primary">Este grupo no tiene alumnos</p>
|
<p className="text-sm font-medium text-primary">Este grupo no tiene alumnos</p>
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
@@ -70,7 +87,7 @@ export function ClassAttendanceView() {
|
|||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{sessionInfo.students.length > 0 ? (
|
{total > 0 ? (
|
||||||
<div className="sticky bottom-20 z-30 mt-6 lg:bottom-6">
|
<div className="sticky bottom-20 z-30 mt-6 lg:bottom-6">
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { Link, useParams } from '@tanstack/react-router'
|
import { Link, useParams } from '@tanstack/react-router'
|
||||||
import type { StudentAtRiskDto } from '@gruperly/shared'
|
import type { GroupDto, StudentAtRiskDto } from '@gruperly/shared'
|
||||||
import { ArrowLeft, CalendarCheck, DoorOpen, Loader2, Percent, Users } from 'lucide-react'
|
import { ArrowLeft, CalendarCheck, DoorOpen, Loader2, Percent, Users } from 'lucide-react'
|
||||||
|
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
||||||
import { Badge, Button, useToast } from '../../../components/ui'
|
import { Badge, Button, useToast } from '../../../components/ui'
|
||||||
import { getAttendeeHistory, getGroupAnalytics, getStudentsAtRisk, updateAttendeeStatus } from '../../../lib/api'
|
import { getAttendeeHistory, getGroupAnalytics, getStudentsAtRisk, updateAttendeeStatus } from '../../../lib/api'
|
||||||
import { KpiCard } from './KpiCard'
|
import { KpiCard } from './KpiCard'
|
||||||
@@ -77,124 +78,144 @@ export function AnalyticsView() {
|
|||||||
window.open(waUrl, '_blank', 'noopener,noreferrer')
|
window.open(waUrl, '_blank', 'noopener,noreferrer')
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupName = riskQuery.data?.groupName
|
// El nombre suele estar en caché porque se llega desde la ficha del grupo: así
|
||||||
|
// el título grande aparece de entrada y no hay salto cuando cargan las queries.
|
||||||
if (analyticsQuery.isPending || riskQuery.isPending) {
|
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
|
||||||
return (
|
const groupName = riskQuery.data?.groupName ?? cachedGroupName
|
||||||
<div className="flex items-center justify-center py-20">
|
|
||||||
<Loader2 className="size-8 animate-spin text-accent" />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (analyticsQuery.isError || riskQuery.isError || !analyticsQuery.data) {
|
|
||||||
return (
|
|
||||||
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
|
||||||
<h2 className="text-lg font-semibold">No pudimos cargar las estadísticas</h2>
|
|
||||||
<p className="mt-2 text-sm">Verificá tu conexión e intentá de nuevo.</p>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
className="mt-4"
|
|
||||||
onClick={() => {
|
|
||||||
void analyticsQuery.refetch()
|
|
||||||
void riskQuery.refetch()
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Reintentar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const analytics = analyticsQuery.data
|
const analytics = analyticsQuery.data
|
||||||
const atRisk = riskQuery.data?.data ?? []
|
const atRisk = riskQuery.data?.data ?? []
|
||||||
|
|
||||||
|
const isPending = analyticsQuery.isPending || riskQuery.isPending
|
||||||
|
const hasFailed = analyticsQuery.isError || riskQuery.isError
|
||||||
|
// El contenido necesita los dos queries: sin `riskQuery` no hay ni el nombre
|
||||||
|
// del grupo ni la lista de alumnos en riesgo.
|
||||||
|
const showContent = !isPending && !hasFailed && Boolean(analytics)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="mx-auto w-full max-w-md lg:max-w-6xl">
|
<section className="mx-auto w-full max-w-md lg:max-w-6xl">
|
||||||
<Link
|
{/* El título grande va siempre, incluso cargando: es lo que da altura a
|
||||||
to="/groups/$groupId"
|
la barra y evita que el layout salte cuando llegan los datos. */}
|
||||||
params={{ groupId }}
|
<LargeTitle
|
||||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
title={groupName ?? 'Grupo'}
|
||||||
|
leading={
|
||||||
|
<Link
|
||||||
|
to="/groups/$groupId"
|
||||||
|
params={{ groupId }}
|
||||||
|
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
Volver al grupo
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-4" />
|
{/* "Estadísticas" es el subtítulo de la pantalla, no el título: el
|
||||||
Volver a {groupName ?? 'el grupo'}
|
título grande identifica el grupo y la barra colapsada lo muestra
|
||||||
</Link>
|
para saber siempre sobre qué se está mirando. */}
|
||||||
|
<div className="mt-2 flex flex-wrap items-center justify-between gap-3">
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="min-w-0">
|
||||||
<div>
|
<p className="text-[14px] font-semibold uppercase tracking-wide text-foreground/70">
|
||||||
<h1 className="text-2xl font-bold text-primary">Estadísticas</h1>
|
Estadísticas
|
||||||
<p className="mt-2 text-sm text-foreground/60">
|
</p>
|
||||||
Asistencia y gestión de riesgo de {groupName ?? 'tu grupo'}.
|
<p className="mt-0.5 text-pretty text-sm text-foreground/80">
|
||||||
</p>
|
Asistencia y gestión de riesgo
|
||||||
</div>
|
|
||||||
<span className="shrink-0 rounded-xl bg-primary-soft px-3 py-1.5 text-xs font-semibold text-foreground/70">
|
|
||||||
Últimos 30 días
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
|
||||||
<KpiCard
|
|
||||||
icon={<Percent className="size-5" />}
|
|
||||||
label="Asistencia promedio"
|
|
||||||
value={`${analytics.attendanceRate}%`}
|
|
||||||
hint="últimos 30 días"
|
|
||||||
/>
|
|
||||||
<KpiCard
|
|
||||||
icon={<CalendarCheck className="size-5" />}
|
|
||||||
label="Asistencias del mes"
|
|
||||||
value={analytics.totalPresent.toLocaleString('es-MX')}
|
|
||||||
hint={`${analytics.totalClasses} clases dictadas`}
|
|
||||||
/>
|
|
||||||
<KpiCard
|
|
||||||
icon={<DoorOpen className="size-5" />}
|
|
||||||
label="Cupos recuperados"
|
|
||||||
value={analytics.recoveredSlots.toLocaleString('es-MX')}
|
|
||||||
hint="por ausencias avisadas"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-8">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Users className="size-5 text-accent" />
|
|
||||||
<h2 className="text-lg font-semibold text-primary">Alumnos en riesgo</h2>
|
|
||||||
{atRisk.length > 0 ? (
|
|
||||||
<Badge variant={atRisk.some((s) => s.riskLevel === 'HIGH') ? 'danger' : 'warning'}>
|
|
||||||
{atRisk.length} {atRisk.length === 1 ? 'alumno' : 'alumnos'}
|
|
||||||
</Badge>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
|
||||||
Alumnos con ausencias consecutivas o baja asistencia mensual.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{atRisk.length === 0 ? (
|
|
||||||
<div className="mt-4 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
|
||||||
<p className="font-medium text-primary">¡Sin alumnos en riesgo!</p>
|
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
|
||||||
No hay ausencias consecutivas ni asistencia por debajo del 50%.
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
<span className="shrink-0 rounded-xl bg-primary-soft px-3 py-1.5 text-xs font-semibold text-foreground/70">
|
||||||
<ul className="mt-4 space-y-3">
|
Últimos 30 días
|
||||||
{atRisk.map((student) => (
|
</span>
|
||||||
<AtRiskStudentCard
|
</div>
|
||||||
key={student.attendeeId}
|
</LargeTitle>
|
||||||
student={student}
|
|
||||||
menuOpen={menuOpenFor === student.attendeeId}
|
{isPending ? (
|
||||||
onToggleMenu={() =>
|
<div className="flex items-center justify-center py-20">
|
||||||
setMenuOpenFor(menuOpenFor === student.attendeeId ? null : student.attendeeId)
|
<Loader2 className="size-8 animate-spin text-accent" />
|
||||||
}
|
</div>
|
||||||
onViewHistory={() => setHistoryStudent(student)}
|
) : null}
|
||||||
onReengage={() => void handleReengage(student, groupName ?? 'tu clase')}
|
|
||||||
onRequestStatusAction={(action) => {
|
{hasFailed ? (
|
||||||
setStatusAction(action)
|
<div className="mt-6 rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
||||||
setMenuOpenFor(null)
|
<h2 className="text-lg font-semibold">No pudimos cargar las estadísticas</h2>
|
||||||
}}
|
<p className="mt-2 text-sm">Verificá tu conexión e intentá de nuevo.</p>
|
||||||
/>
|
<Button
|
||||||
))}
|
variant="outline"
|
||||||
</ul>
|
className="mt-4"
|
||||||
)}
|
onClick={() => {
|
||||||
</div>
|
void analyticsQuery.refetch()
|
||||||
|
void riskQuery.refetch()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Reintentar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{showContent && analytics ? (
|
||||||
|
<>
|
||||||
|
<div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||||
|
<KpiCard
|
||||||
|
icon={<Percent className="size-5" />}
|
||||||
|
label="Asistencia promedio"
|
||||||
|
value={`${analytics.attendanceRate}%`}
|
||||||
|
hint="últimos 30 días"
|
||||||
|
/>
|
||||||
|
<KpiCard
|
||||||
|
icon={<CalendarCheck className="size-5" />}
|
||||||
|
label="Asistencias del mes"
|
||||||
|
value={analytics.totalPresent.toLocaleString('es-MX')}
|
||||||
|
hint={`${analytics.totalClasses} clases dictadas`}
|
||||||
|
/>
|
||||||
|
<KpiCard
|
||||||
|
icon={<DoorOpen className="size-5" />}
|
||||||
|
label="Cupos recuperados"
|
||||||
|
value={analytics.recoveredSlots.toLocaleString('es-MX')}
|
||||||
|
hint="por ausencias avisadas"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-8">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Users className="size-5 text-accent" />
|
||||||
|
<h2 className="text-lg font-semibold text-primary">Alumnos en riesgo</h2>
|
||||||
|
{atRisk.length > 0 ? (
|
||||||
|
<Badge variant={atRisk.some((s) => s.riskLevel === 'HIGH') ? 'danger' : 'warning'}>
|
||||||
|
{atRisk.length} {atRisk.length === 1 ? 'alumno' : 'alumnos'}
|
||||||
|
</Badge>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
|
Alumnos con ausencias consecutivas o baja asistencia mensual.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{atRisk.length === 0 ? (
|
||||||
|
<div className="mt-4 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
||||||
|
<p className="font-medium text-primary">¡Sin alumnos en riesgo!</p>
|
||||||
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
|
No hay ausencias consecutivas ni asistencia por debajo del 50%.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="mt-4 space-y-3">
|
||||||
|
{atRisk.map((student) => (
|
||||||
|
<AtRiskStudentCard
|
||||||
|
key={student.attendeeId}
|
||||||
|
student={student}
|
||||||
|
menuOpen={menuOpenFor === student.attendeeId}
|
||||||
|
onToggleMenu={() =>
|
||||||
|
setMenuOpenFor(menuOpenFor === student.attendeeId ? null : student.attendeeId)
|
||||||
|
}
|
||||||
|
onViewHistory={() => setHistoryStudent(student)}
|
||||||
|
onReengage={() => void handleReengage(student, groupName ?? 'tu clase')}
|
||||||
|
onRequestStatusAction={(action) => {
|
||||||
|
setStatusAction(action)
|
||||||
|
setMenuOpenFor(null)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<AttendeeHistoryModal
|
<AttendeeHistoryModal
|
||||||
student={historyStudent}
|
student={historyStudent}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, BarChart3, Share2, UserPlus } from 'lucide-react'
|
import { ArrowLeft, BarChart3, Share2, UserPlus } from 'lucide-react'
|
||||||
import { Badge, Button, Tooltip } from '../../../components/ui'
|
import { Badge, Button, Tooltip } from '../../../components/ui'
|
||||||
|
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
||||||
import { cn } from '../../../lib/utils'
|
import { cn } from '../../../lib/utils'
|
||||||
import { RISK_HINT, RISK_LABELS } from '../constants'
|
import { RISK_HINT, RISK_LABELS } from '../constants'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
@@ -30,27 +31,21 @@ export function GroupHeader() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<Link
|
<LargeTitle
|
||||||
to="/groups"
|
title={group?.name ?? ''}
|
||||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
leading={
|
||||||
|
<Link
|
||||||
|
to="/groups"
|
||||||
|
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
<span>Volver a grupos</span>
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-4" />
|
{/* Los estados cuelgan del título y no de la barra: en la barra
|
||||||
<span>Volver a grupos</span>
|
colapsada solo va el nombre, que es lo que se usa para orientarse. */}
|
||||||
</Link>
|
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||||
|
|
||||||
{/* El título se queda con el ancho completo: los estados bajan a su propia
|
|
||||||
fila compacta en vez de competir con el nombre por el espacio. */}
|
|
||||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-6">
|
|
||||||
<div className="min-w-0 sm:max-w-2xl">
|
|
||||||
<h1 className="text-balance text-2xl font-bold leading-tight text-primary sm:text-[1.75rem]">
|
|
||||||
{group?.name}
|
|
||||||
</h1>
|
|
||||||
{group?.description ? (
|
|
||||||
<p className="mt-1.5 text-sm leading-relaxed text-foreground/80">{group.description}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-2 sm:shrink-0 sm:justify-end">
|
|
||||||
<Badge variant="success" className="gap-1.5 text-[11px]">
|
<Badge variant="success" className="gap-1.5 text-[11px]">
|
||||||
<span className="size-1.5 rounded-full bg-success" aria-hidden="true" />
|
<span className="size-1.5 rounded-full bg-success" aria-hidden="true" />
|
||||||
Activo
|
Activo
|
||||||
@@ -75,7 +70,13 @@ export function GroupHeader() {
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
{group?.description ? (
|
||||||
|
<p className="mt-2 text-pretty text-sm leading-relaxed text-foreground/80">
|
||||||
|
{group.description}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</LargeTitle>
|
||||||
|
|
||||||
<div className="mt-4 grid grid-cols-2 gap-2.5 sm:mt-5 sm:flex sm:flex-wrap sm:items-center sm:justify-end sm:gap-2.5">
|
<div className="mt-4 grid grid-cols-2 gap-2.5 sm:mt-5 sm:flex sm:flex-wrap sm:items-center sm:justify-end sm:gap-2.5">
|
||||||
{/* `h-11` (44px) para todos: objetivo táctil mínimo. */}
|
{/* `h-11` (44px) para todos: objetivo táctil mínimo. */}
|
||||||
|
|||||||
65
apps/web/src/hooks/useLargeTitleCollapse.ts
Normal file
65
apps/web/src/hooks/useLargeTitleCollapse.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
/* Alto de la barra de navegación donde entra el título chico. Tiene que
|
||||||
|
coincidir con el `h-14` de `LargeTitle`: la barra es sticky contra el borde
|
||||||
|
superior de la ventana y el título grande se mide contra este valor. */
|
||||||
|
const BAR_HEIGHT = 56
|
||||||
|
|
||||||
|
function clamp01(value: number) {
|
||||||
|
if (value < 0) return 0
|
||||||
|
return value > 1 ? 1 : value
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Progreso de colapso de un Large Title: 0 con el título grande desplegado,
|
||||||
|
* 1 cuando quedó por completo tapado detrás de la barra.
|
||||||
|
*
|
||||||
|
* El progreso sale de la posición del título, no del tiempo: se recalcula en
|
||||||
|
* cada frame mientras se scrollea. Por eso el gesto se siente pegado al dedo
|
||||||
|
* en vez de "animado", y por eso `requestAnimationFrame` sirve para agrupar
|
||||||
|
* eventos de scroll, no para interpolar la animación.
|
||||||
|
*/
|
||||||
|
export function useLargeTitleCollapse() {
|
||||||
|
const titleRef = useRef<HTMLHeadingElement>(null)
|
||||||
|
const [progress, setProgress] = useState(0)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const title = titleRef.current
|
||||||
|
if (!title) return
|
||||||
|
|
||||||
|
let frame = 0
|
||||||
|
|
||||||
|
const measure = () => {
|
||||||
|
frame = 0
|
||||||
|
const { top, height } = title.getBoundingClientRect()
|
||||||
|
// 0 cuando el borde superior del título llega a la base de la barra, 1
|
||||||
|
// cuando su borde inferior también llegó (quedó enteramente debajo).
|
||||||
|
const next = clamp01((BAR_HEIGHT - top) / (height || BAR_HEIGHT))
|
||||||
|
// Los títulos de grupo llegan asíncrono y pueden cambiar de alto entre
|
||||||
|
// renders: sin este umbral se re-renderiza en cada frame de scroll.
|
||||||
|
setProgress((current) => (Math.abs(current - next) < 0.002 ? current : next))
|
||||||
|
}
|
||||||
|
|
||||||
|
const schedule = () => {
|
||||||
|
if (frame === 0) frame = requestAnimationFrame(measure)
|
||||||
|
}
|
||||||
|
|
||||||
|
measure()
|
||||||
|
window.addEventListener('scroll', schedule, { passive: true })
|
||||||
|
window.addEventListener('resize', schedule)
|
||||||
|
|
||||||
|
// El nombre del grupo se carga después del primer render y la webfont puede
|
||||||
|
// cambiar el alto del título: el rango de colapso depende de esa medida.
|
||||||
|
const observer = new ResizeObserver(schedule)
|
||||||
|
observer.observe(title)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (frame !== 0) cancelAnimationFrame(frame)
|
||||||
|
window.removeEventListener('scroll', schedule)
|
||||||
|
window.removeEventListener('resize', schedule)
|
||||||
|
observer.disconnect()
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return { titleRef, progress }
|
||||||
|
}
|
||||||
33
apps/web/src/lib/immersive-routes.ts
Normal file
33
apps/web/src/lib/immersive-routes.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
/* Rutas "immersive": las que arman su propia barra de navegación con
|
||||||
|
`LargeTitle` (título grande que colapsa) y por eso no muestran el header
|
||||||
|
global con logo + toggle de tema + avatar.
|
||||||
|
|
||||||
|
El patrón se resuelve a mano y no con `matchRoute` porque las dos rutas
|
||||||
|
llevan parámetros (`matchRoute` los exige) y porque las rutas hijas NO son
|
||||||
|
immersive aunque compartan prefijo: `/groups/:id/attendees/new` sigue usando
|
||||||
|
el header global. */
|
||||||
|
|
||||||
|
const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
|
||||||
|
['groups', ':id'],
|
||||||
|
['groups', ':id', 'analytics'],
|
||||||
|
['class', ':id', 'attendance'],
|
||||||
|
]
|
||||||
|
|
||||||
|
/* Rutas estáticas que ocupan el lugar de un parámetro. Sin esta lista
|
||||||
|
`/groups/new` (crear grupo) se tomaría por una ficha de grupo y perdería el
|
||||||
|
header global. */
|
||||||
|
const STATIC_SEGMENTS: ReadonlySet<string> = new Set(['new'])
|
||||||
|
|
||||||
|
export function isImmersiveRoute(pathname: string) {
|
||||||
|
const segments = pathname.split('/').filter(Boolean)
|
||||||
|
|
||||||
|
return IMMERSIVE_SEGMENTS.some(
|
||||||
|
(pattern) =>
|
||||||
|
pattern.length === segments.length &&
|
||||||
|
pattern.every((part, index) => {
|
||||||
|
const segment = segments[index]
|
||||||
|
if (part.startsWith(':')) return !STATIC_SEGMENTS.has(segment)
|
||||||
|
return part === segment
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
35
apps/web/test/immersive-routes.test.ts
Normal file
35
apps/web/test/immersive-routes.test.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test'
|
||||||
|
import { isImmersiveRoute } from '../src/lib/immersive-routes'
|
||||||
|
|
||||||
|
/* Solo las pantallas con Large Title arman su propia barra. Todo lo demás
|
||||||
|
—incluidas las rutas hijas de un grupo— sigue con el header global. */
|
||||||
|
|
||||||
|
describe('isImmersiveRoute', () => {
|
||||||
|
test('la ficha de grupo, sus estadísticas y la asistencia son immersive', () => {
|
||||||
|
expect(isImmersiveRoute('/groups/cm1234')).toBe(true)
|
||||||
|
expect(isImmersiveRoute('/groups/cm1234/analytics')).toBe(true)
|
||||||
|
expect(isImmersiveRoute('/class/ses_987/attendance')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('las rutas hijas del grupo no lo son', () => {
|
||||||
|
expect(isImmersiveRoute('/groups')).toBe(false)
|
||||||
|
expect(isImmersiveRoute('/groups/')).toBe(false)
|
||||||
|
expect(isImmersiveRoute('/groups/new')).toBe(false)
|
||||||
|
expect(isImmersiveRoute('/groups/cm1234/attendees/new')).toBe(false)
|
||||||
|
expect(isImmersiveRoute('/groups/cm1234/attendees/at_55')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('el resto de la app mantiene el header global', () => {
|
||||||
|
expect(isImmersiveRoute('/')).toBe(false)
|
||||||
|
expect(isImmersiveRoute('/payments')).toBe(false)
|
||||||
|
expect(isImmersiveRoute('/settings')).toBe(false)
|
||||||
|
expect(isImmersiveRoute('/class/ses_987')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('el chequeo es por segmento exacto, no por prefijo', () => {
|
||||||
|
expect(isImmersiveRoute('/grupos/cm1234')).toBe(false)
|
||||||
|
expect(isImmersiveRoute('/clas/ses_987/attendance')).toBe(false)
|
||||||
|
expect(isImmersiveRoute('/grup')).toBe(false)
|
||||||
|
expect(isImmersiveRoute('/groups/cm1234/analytics/extra')).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user