chore: update comments and documentation for clarity and consistency across various files

- Translated comments from Spanish to English in vite.config.ts, docker-compose.yml, attendance-risk.ts, analytics.ts, attendance.ts, attendees.ts, enums.ts, groups.ts, and onboarding.ts.
- Improved descriptions for better understanding of code functionality and purpose.
- Ensured uniformity in terminology and phrasing throughout the codebase.
This commit is contained in:
Jose Selesan
2026-10-01 16:06:54 -03:00
parent 01b35691df
commit 69275c37b4
100 changed files with 1121 additions and 1086 deletions

View File

@@ -20,8 +20,8 @@ export function BottomNav() {
isActive ? 'text-accent-fg' : 'text-foreground/80 hover:text-primary',
)}
>
{/* Pastilla suave detrás del ícono: el estado activo se lee por
color + fondo, no solo por el tono del texto. */}
{/* Soft pill behind the icon: the active state is read by
color + background, not only by the text tone. */}
<span
className={cn(
'flex size-8 items-center justify-center rounded-lg transition-colors duration-150',

View File

@@ -9,9 +9,9 @@ export function Header() {
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6">
<div className="flex min-w-0 items-center">
{/* `Link` y no `<a>`: en mobile el logo es la única forma de volver al
inicio y un anchor recargaría el documento entero, perdiendo el
estado en memoria (cache de React Query, evento de instalación). */}
{/* `Link` and not `<a>`: on mobile the logo is the only way back to the
home screen and an anchor would reload the whole document, losing
the in-memory state (React Query cache, install event). */}
<Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
<Logo className="h-8" />
</Link>

View File

@@ -4,32 +4,33 @@ 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 text. It's the same in the large title and in the bar's copy: the
* real `h1` is the large one, the bar's is a visual duplicate. */
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. */
/** Action to the left of the bar. On desktop it's the "Volver" link that
* used to live in the screen body; on mobile it's hidden. */
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. */
/** Context that can't disappear on scroll (e.g. the present counter). It
* travels to the bar and blends with the title. */
barTrailing?: ReactNode
/** Metadatos bajo el título grande: badges, descripción. Se van al colapsar. */
/** Metadata under the large title: badges, description. It goes away when
* the title collapses. */
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.
* Screen header with Large Title (the iOS pattern): the title starts large and
* slides under the bar as you scroll, while the bar goes opaque and takes the
* title in its small version.
*
* 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.
* The large title is a normal block in the flow; the bar lives in a sticky box
* that the layout mounts above `<main>` (see `ImmersiveBarHost`), so the content
* slides under it without negative margins or a `fixed` we'd have to compensate
* for on 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.
* The scroll state lives in here on purpose: `children` arrives as an already
* built prop, so React reuses the elements and the subtree below doesn't
* re-render on every scroll frame.
*/
export function LargeTitle({ title, leading, barTrailing, children }: LargeTitleProps) {
const { titleRef, progress } = useLargeTitleCollapse()
@@ -40,9 +41,9 @@ export function LargeTitle({ title, leading, barTrailing, children }: LargeTitle
{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. */}
{/* The background goes on its own layer: it goes opaque with the
scroll while the title slides in, and `leading` (the "Volver"
link) can't blend with it because it always exists. */}
<div
className="absolute inset-0 border-b border-border bg-background/80 backdrop-blur-md"
style={{ opacity: progress }}

View File

@@ -12,18 +12,18 @@ export function RootLayout({ children }: { children: ReactNode }) {
return (
<div className="min-h-dvh w-full overflow-x-clip">
{/* 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. */}
{/* On immersive routes the screen brings its own bar (LargeTitle) with
the logo and the group name: the global header with logo + theme +
avatar would be a second bar competing for the same pixels. */}
{immersive ? null : <Header />}
<div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6">
<Sidebar immersive={immersive} />
<ImmersiveBarProvider>
{/* pt-0 en immersive: el padding superior lo aporta la caja de la
barra, y si no el título grande arrancaría 16px más abajo de la
base de la barra y el colapso se mediría corrido. */}
{/* pt-0 on immersive: the bar's box provides the top padding,
otherwise the large title would start 16px below the bottom of the
bar and the collapse would be measured off. */}
<main
className={cn(
'min-w-0 flex-1 px-4 pb-[calc(6rem+env(safe-area-inset-bottom))] lg:px-0 lg:pb-8',

View File

@@ -7,17 +7,17 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
const location = useLocation()
return (
// 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.
// Without the global header there's nothing to clear above: the sidebar
// column takes over the whole window and lines up with the height of the
// LargeTitle bar.
<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
estado en memoria (cache de React Query, evento de instalación). */}
{/* `Link` and not `<a>`: an anchor would reload the document and lose the
in-memory state (React Query cache, install event). */}
<Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
<Logo className="h-10" />
</Link>

View File

@@ -13,10 +13,10 @@ export const NAV_ITEMS: NavItem[] = [
{ label: 'Ajustes', to: '/settings', icon: Settings },
]
/** Una sección sigue activa dentro de sus subrutas: en `/groups/abc` el ítem
* activo es "Grupos", no ninguno. El prefijo se corta en el separador para
* que `/groupsomething` no se considere "/groups". La raíz es exacta: no hay
* subrutas del home que deban marcarla. */
/** A section stays active within its subroutes: on `/groups/abc` the active
* item is "Grupos", not none. The prefix is cut at the separator so
* `/groupsomething` isn't taken for "/groups". The root is exact: the home has
* no subroutes that should mark it. */
export function isNavItemActive(pathname: string, to: string): boolean {
if (to === '/') return pathname === '/'
return pathname === to || pathname.startsWith(`${to}/`)

View File

@@ -12,10 +12,10 @@ const variants: Record<BadgeVariant, string> = {
warning: 'bg-warning-soft text-warning',
danger: 'bg-danger-soft text-danger',
neutral: 'bg-primary-soft text-primary',
/* Estado informativo que no es alerta: lista de espera, cupos libres. Usa la
tinta de acento legible (`accent-fg` es el azul claro en tema oscuro,
7.1:1 sobre la tarjeta) y no el `accent` directo, que en oscuro da 2.2:1
y no alcanza el mínimo de 3:1 para contenido no textual. */
/* Informational state, not an alert: waitlist, free spots. Uses the legible
accent ink (`accent-fg` is the light blue in the dark theme, 7.1:1 on the
card) and not the plain `accent`, which in dark scores 2.2:1 and misses the
3:1 minimum for non-text content. */
info: 'bg-accent-soft text-accent-fg',
}

View File

@@ -28,9 +28,9 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
ref={ref}
type={type}
className={cn(
// `transition-*` explícito en vez de `transition-all`: solo se animan
// color, fondo, borde y transform. El feedback de presión se anula
// con `motion-reduce` para respetar prefers-reduced-motion.
// Explicit `transition-*` instead of `transition-all`: only color,
// background, border and transform are animated. Press feedback is
// cancelled with `motion-reduce` to respect prefers-reduced-motion.
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl font-medium transition-[color,background-color,border-color,fill,stroke,transform] duration-150 ease-out active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50',
variants[variant],
sizes[size],

View File

@@ -11,8 +11,8 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(
<input
ref={ref}
className={cn(
// text-base (16px) en mobile: iOS auto-zoomea al enfocar controles con
// font-size < 16px y, al cerrar el teclado, no restaura el scale.
// text-base (16px) on mobile: iOS auto-zooms when focusing controls
// with font-size < 16px and doesn't restore the scale on keyboard close.
'h-10 w-full rounded-xl border border-border bg-surface px-3 text-base sm:text-sm text-primary placeholder:text-foreground/40 transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:cursor-not-allowed disabled:opacity-50',
invalid && 'border-danger focus:border-danger focus:ring-danger/30',
className,

View File

@@ -2,19 +2,20 @@ import { type ReactNode, useId, useState } from 'react'
import { cn } from '../../lib/utils'
export type TooltipProps = {
/** Texto explicativo que se muestra al hacer hover, foco de teclado o tap. */
/** Explanatory text shown on hover, keyboard focus or tap. */
content: ReactNode
/** Contenido del disparador. Queda dentro de un <button> para ser accesible. */
/** Trigger content. It sits inside a <button> to stay accessible. */
children: ReactNode
className?: string
/** Posicionamiento alternativo del globo (por defecto: abajo, anclado a la derecha en sm+). */
/** Alternate positioning for the bubble (default: below, anchored right on sm+). */
tooltipClassName?: string
}
/**
* Tooltip accesible sin dependencias: hover (ratón), foco (teclado) y tap
* (táctil, vía focus). Se cierra con Escape, al salir el puntero o al perder
* el foco. El globo se ancla abajo del disparador para no tapar el contenido.
* Accessible tooltip with no dependencies: hover (mouse), focus (keyboard) and
* tap (touch, via focus). It closes on Escape, when the pointer leaves or when
* it loses focus. The bubble is anchored below the trigger so it doesn't cover
* the content.
*/
export function Tooltip({ content, children, className, tooltipClassName }: TooltipProps) {
const [open, setOpen] = useState(false)
@@ -28,8 +29,8 @@ export function Tooltip({ content, children, className, tooltipClassName }: Tool
<button
type="button"
aria-describedby={open ? id : undefined}
// El hover solo aplica a punteros de ratón: en táctil no hay "hover
// persistente" y el tap se resuelve con focus + click.
// Hover only applies to mouse pointers: on touch there is no
// "persistent hover" and tap is handled with focus + click.
onPointerEnter={(e) => {
if (e.pointerType === 'mouse') show()
}}

View File

@@ -1,14 +1,14 @@
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.
/* "Immersive" screens (group detail and attendance) build their own title bar
instead of using the global header, but the bar has to be a direct child of
`<main>`: a `sticky` only sticks while its parent box is on screen, and the
bar's natural parent (the feature block) is short, so it would detach at
around ~200px of 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. */
This provider exposes a fixed 56px box pinned to the top of `<main>` where
the screen mounts its bar. The layout draws the box (so it holds its place
from the first render) and the screen supplies its content. */
type ImmersiveBarValue = {
host: HTMLElement | null
@@ -29,14 +29,14 @@ export function ImmersiveBarProvider({ children }: { children: ReactNode }) {
)
}
/** Caja de la barra: primer hijo de `<main>`, en las rutas immersive. */
/** The bar's box: first child of `<main>`, on immersive routes. */
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. */
/** Portal target for `LargeTitle`; `null` if the screen is not immersive. */
export function useImmersiveBarHost() {
return useContext(ImmersiveBarContext).host
}

View File

@@ -18,7 +18,7 @@ type ThemeContextValue = {
const STORAGE_KEY = 'theme'
/** Colores de la barra de estado en modo standalone. Debe matchear index.css. */
/** Status bar colors in standalone mode. Must match index.css. */
const THEME_COLOR = { light: '#ffffff', dark: '#020617' } as const
const THEME_COLOR_META_ID = 'theme-color'
@@ -50,8 +50,8 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
setIsDark(dark)
localStorage.setItem(STORAGE_KEY, theme)
// En standalone la barra de estado se pinta con theme-color; sin esto
// queda congelada en el valor que puso el script inline de index.html.
// In standalone the status bar is painted with theme-color; without this
// it stays frozen at the value the inline script in index.html set.
document
.getElementById(THEME_COLOR_META_ID)
?.setAttribute('content', dark ? THEME_COLOR.dark : THEME_COLOR.light)

View File

@@ -28,16 +28,16 @@ export function AbsenceLinkSection() {
title="Link de ausencias"
toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }}
>
{/* El panel queda en el DOM pero oculto: `aria-controls` siempre resuelve y
el texto de "Link copiado" no se pierde al plegar y desplegar. */}
{/* The panel stays in the DOM but hidden: `aria-controls` always resolves and
the "Link copied" text is not lost on collapse/expand. */}
<div id={panelId} hidden={!isOpen}>
<p className="px-3 text-sm text-foreground">
Mandales este link para que avisen cuando no puedan venir.
</p>
{/* Apiladas y a ancho completo: al 50% los rótulos ("Enviar por WhatsApp")
se partían en dos líneas y quedaban por debajo del mínimo táctil.
Copiar queda arriba, pegado a su confirmación, y la acción principal
se distingue por el relleno de acento. */}
{/* Stacked and full width: at 50% the labels ("Enviar por WhatsApp")
wrapped onto two lines and fell below the minimum touch target.
Copy stays on top, glued to its confirmation, and the primary action
is told apart by the accent fill. */}
<div className="mt-2.5 flex flex-col gap-2">
<button
type="button"

View File

@@ -6,21 +6,21 @@ import { useAttendeeDetail } from './AttendeeDetailProvider'
const ITEM_CLASS =
'flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-sm font-medium text-primary transition-colors hover:bg-danger-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Menú "⋯" de la ficha del miembro.
/** "⋯" menu on the attendee detail page.
*
* Por ahora solo guarda "Quitar del grupo": el backend no tiene forma de
* regenerar el token de ausencias, así que la opción no se muestra antes que
* exista el endpoint (ver `apps/backend/prisma/models/domain.prisma`, campo
* `notifyToken`). Cuando exista, es un `<button role="menuitem">` más en la
* lista de abajo.
* For now it only holds "Quitar del grupo": the backend has no way to
* regenerate the absence token, so the option is not shown before that
* endpoint exists (see `apps/backend/prisma/models/domain.prisma`, field
* `notifyToken`). Once it does, it is one more `<button role="menuitem">` in
* the list below.
*
* La etiqueta va en `text-primary` y el ícono lleva el `text-danger`: el rojo
* de `danger` sobre blanco queda en 3.7:1 y no llega a AA para texto normal. */
* The label goes in `text-primary` and the icon carries the `text-danger`: the
* `danger` red on white sits at 3.7:1 and does not reach AA for normal text. */
export function AttendeeActionsMenu({
triggerRef,
}: {
/** Se lo pasa la pantalla para que el diálogo de confirmación le devuelva el
* foco cuando se cierra. */
/** The screen passes it in so the confirmation dialog can give focus back
* when it closes. */
triggerRef: RefObject<HTMLButtonElement | null>
}) {
const { openRemoveDialog } = useAttendeeDetail()

View File

@@ -96,8 +96,8 @@ export function AttendeeAttendanceSection() {
})}
</ul>
{/* Las clases sin registro no son ausencias: se avisa aparte y en voz baja
para que el "1 de 1" de arriba no se lea como un fallo. */}
{/* Classes with no record are not absences: they are reported separately
and quietly so the "1 de 1" above does not read as a failure. */}
{summary.unmarkedLabel ? (
<p className="px-3 pt-2 text-right text-xs text-foreground">{summary.unmarkedLabel}</p>
) : null}

View File

@@ -10,15 +10,15 @@ export function AttendeeContactActions() {
const phone = attendee?.phone
if (!phone) return null
// Los links van con los dígitos crudos: wa.me y tel: no entienden formatos.
// The links use the raw digits: wa.me and tel: do not understand formats.
const digits = phone.replace(/\D/g, '')
const label = formatPhoneDisplay(phone) ?? phone
return (
<div className="flex gap-2.5">
{/* Los íconos van con `accent-fg` y no con `accent`: el azul de `accent` es
el mismo en los dos temas y sobre `primary-soft` oscuro queda en 2.2:1.
`accent-fg` da 6.2:1 en claro y 7.1:1 en oscuro. */}
{/* The icons go with `accent-fg` and not with `accent`: the `accent` blue is
the same in both themes and on dark `primary-soft` it sits at 2.2:1.
`accent-fg` gives 6.2:1 in light and 7.1:1 in dark. */}
<a
href={`https://wa.me/${digits}`}
target="_blank"

View File

@@ -2,19 +2,20 @@ import { Mail } from 'lucide-react'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { Section } from './Section'
/* `px-3` interno: la banda de hover sigue a sangre hasta el borde de la sección
(la separa del texto, no al revés) y las notas de abajo suman el mismo para
que el email y ellas caigan en la misma columna. */
/* Inner `px-3`: the hover band bleeds all the way to the section edge
(it separates from the text, not the other way around) and the notes below
add the same so the email and they land in the same column. */
const ROW_CLASS =
'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg px-3 py-2.5 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Email y notas del miembro. El teléfono no va acá: ya está en el subtítulo y
* detrás de los botones de WhatsApp y Llamar, y repetirlo llenaba la pantalla
* de un dato que ya estaba a la vista.
/** The attendee's email and notes. The phone does not go here: it is already in
* the subtitle, behind the WhatsApp and Llamar buttons, and repeating it filled
* the screen with a value that was already in view.
*
* Sin datos no se dibuja la sección: no hay filas con "Sin email"/"Sin notas".
* Aparece sola en cuanto el miembro tenga alguno (hoy el email puede llegar al
* aprobar una preinscripción; las notas, cuando exista la edición). */
* With no data the section is not drawn: there are no "Sin email"/"Sin notas"
* rows. It shows up on its own as soon as the attendee has one of them (today
* the email can arrive when approving a pre-registration; the notes, once
* editing exists). */
export function AttendeeContactSection() {
const { attendee } = useAttendeeDetail()

View File

@@ -51,16 +51,16 @@ export function AttendeeDetailProvider({
enabled: Boolean(groupId && attendeeId),
})
// Misma clave que usa la pantalla de estadísticas: las dos leen el mismo
// historial y no se pisan la caché.
// Same key the analytics screen uses: both read the same history and do not
// clobber each other's cache.
const historyQuery = useQuery({
queryKey: ['attendee-history', groupId, attendeeId],
queryFn: () => getAttendeeHistory(groupId, attendeeId),
enabled: Boolean(groupId && attendeeId),
})
// La lista de espera solo hace falta para el diálogo de quitar, así que no se
// pide hasta que el usuario lo abre.
// The waitlist is only needed for the remove dialog, so it is not fetched
// until the user opens it.
const waitlistQuery = useQuery({
queryKey: ['group-waitlist', groupId],
queryFn: () => getGroupWaitlist(groupId, 1, 100),

View File

@@ -28,9 +28,9 @@ export function AttendeeDetailView() {
if (attendeeFailed || !attendee) {
return (
<div className="animate-fade-in rounded-2xl bg-danger-soft p-6">
{/* El título lleva el rojo (a 18px ya cuenta como texto grande y llega a
los 3:1) y el cuerpo usa `text-primary`: en `danger-soft` el rojo no
pasa los 4.5:1 que necesita un `text-sm`. */}
{/* The title carries the red (at 18px it already counts as large text and
reaches 3:1) and the body uses `text-primary`: on `danger-soft` the red
does not pass the 4.5:1 a `text-sm` needs. */}
<h1 className="text-lg font-bold text-danger">Miembro no encontrado</h1>
<p className="mt-2 text-sm text-primary">
No se pudo cargar la información de este miembro.
@@ -75,9 +75,9 @@ export function AttendeeDetailView() {
<AttendeeContactActions />
</div>
{/* Orden por frecuencia de uso. Sumar Pagos es insertar un bloque más
arriba de Asistencia; cada sección lleva su propio aire, así que el
layout no se toca. */}
{/* Ordered by how often they are used. Adding Pagos means inserting one
more block above Asistencia; each section brings its own spacing, so
the layout does not need to change. */}
<div className="mt-5">
<AttendeeAttendanceSection />
<AttendeeContactSection />

View File

@@ -3,12 +3,12 @@ import { formatPhoneDisplay } from '../../lib/format'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useCopyToClipboard } from './useCopyToClipboard'
/** Teléfono como segunda línea del subtítulo.
/** The phone as the subtitle's second line.
*
* Vivía en una sección "Contacto" con una sola fila que repetía el número que
* ya está a la vista detrás de los botones de WhatsApp y Llamar. Acá acompaña
* al "Miembro desde…", se copia con un toque y tiene 44px de alto aunque el
* texto sea de 14px: es un control, no un dato decorativo. */
* It used to live in a "Contacto" section with a single row that repeated the
* number already visible behind the WhatsApp and Llamar buttons. Here it sits
* next to "Miembro desde…", copies on one tap and is 44px tall even though the
* text is 14px: it is a control, not decorative data. */
export function AttendeePhoneLine() {
const { attendee } = useAttendeeDetail()
const { copied, copy } = useCopyToClipboard()
@@ -25,8 +25,8 @@ export function AttendeePhoneLine() {
className="flex min-h-11 max-w-fit items-center gap-2 rounded-lg text-left transition-colors hover:bg-primary-soft active:scale-[0.98] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<span className="truncate text-sm text-foreground">{label}</span>
{/* `aria-hidden`: la confirmación se anuncia desde la región viva de
abajo, así no se cuela en el nombre del botón. */}
{/* `aria-hidden`: the confirmation is announced from the live region
below, so it does not sneak into the button's name. */}
{copied ? (
<span
aria-hidden="true"

View File

@@ -10,7 +10,7 @@ type Consequence = { key: string; icon: LucideIcon; text: string }
export function ConfirmRemoveAttendeeDialog({
returnFocusRef,
}: {
/** Elemento al que vuelve el foco al cerrarse (el botón "⋯"). */
/** The element focus returns to when it closes (the "⋯" button). */
returnFocusRef: RefObject<HTMLButtonElement | null>
}) {
const {
@@ -117,9 +117,9 @@ export function ConfirmRemoveAttendeeDialog({
<Button variant="ghost" onClick={closeRemoveDialog} autoFocus>
Cancelar
</Button>
{/* Etiqueta en negro sobre el relleno `danger`: es la única forma de
llegar a AA con el mismo rojo en los dos temas (4.9:1 claro,
6.7:1 oscuro); en blanco quedan 3.7:1 y 2.7:1. */}
{/* Label in black on the `danger` fill: it is the only way to reach AA
with the same red in both themes (4.9:1 light, 6.7:1 dark); in white
they are 3.7:1 and 2.7:1. */}
<Button
onClick={() => confirmRemoveAttendee(false)}
disabled={isSubmittingRemoval}
@@ -138,10 +138,10 @@ export function ConfirmRemoveAttendeeDialog({
)
}
/** El `Modal` de la app no atrapa el foco; este diálogo sí, para que el Tab no
* se vaya detrás del overlay. Solo cicla entre los controles del contenido: si
* el foco está en otro lado (la X del `Modal`, que se sigue cerrando con
* Escape) lo deja seguir su curso normal. */
/** The app's `Modal` does not trap focus; this dialog does, so Tab does not walk
* behind the overlay. It only cycles between the content's controls: if focus is
* somewhere else (the `Modal`'s X, which still closes on Escape) it lets it
* follow its normal course. */
function trapTabWithin(contentRef: RefObject<HTMLDivElement | null>) {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Tab') return

View File

@@ -3,18 +3,18 @@ import type { ReactNode } from 'react'
import { ChevronDown } from 'lucide-react'
import { cn } from '../../lib/utils'
/* El gris va sin opacidad: sobre el fondo oscuro `text-foreground/50` cae a
~2.7:1 y `/80` a ~4.2:1, los dos por debajo de AA. El token entero sí pasa. */
/* The grey has no opacity modifier: on the dark background `text-foreground/50`
drops to ~2.7:1 and `/80` to ~4.2:1, both below AA. The full token passes. */
export const SECTION_TITLE_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground'
/* La fila que despliega la sección es un botón, no un título: por eso lleva
superficie de hover y presión, se pinta en `primary` para que se lea
distinta de los títulos fijos, y el chevron cae al borde derecho de la fila
en vez de pegado al texto.
/* The row that expands the section is a button, not a heading: that is why it
gets hover and press surfaces, it is painted in `primary` so it reads
different from the fixed titles, and the chevron lands on the row's right edge
instead of hugging the text.
El `px-3` es interno: la banda de hover sigue a sangre hasta el borde de la
sección y lo que se separa del borde es el contenido (el `px-3` del `h2` y
del `trailing` de abajo alinea rótulo y resumen con esta fila). */
The `px-3` is internal: the hover band bleeds all the way to the section edge
and it is the content that is set off from the edge (the `px-3` on the `h2`
and on the `trailing` below align the label and the summary with this row). */
const TOGGLE_ROW_CLASS = cn(
SECTION_TITLE_CLASS,
'flex min-h-11 w-full items-center justify-between gap-2 rounded-lg px-3 text-left text-primary',
@@ -23,24 +23,24 @@ const TOGGLE_ROW_CLASS = cn(
)
type SectionProps = {
/** Título de la sección. Un string por lo general. */
/** The section title. Usually a string. */
title: ReactNode
/** A la derecha del título: el resumen de asistencia, por ejemplo. */
/** To the right of the title: the attendance summary, for example. */
trailing?: ReactNode
/** Cuando está, el título entero es el disparador del contenido y `title` es
* solo su rótulo: el `<h2>` sigue siendo el encabezado de la sección y el
* botón ocupa la fila completa. */
/** When present, the whole title is the content's trigger and `title` is just
* its label: the `<h2>` is still the section heading and the button takes the
* full row. */
toggle?: { isOpen: boolean; panelId: string; onToggle: () => void }
children: ReactNode
}
/** Bloque de sección: separador fino sobre el fondo, título chico en
* mayúsculas y contenido sin padding propio (el de la pantalla).
/** Section block: thin separator over the background, small uppercase title and
* content with no padding of its own (the screen's).
*
* El aire vive acá y no en la pantalla: cada sección cierra con su propio
* padding, así que el separador queda siempre a la misma distancia del
* contenido de arriba. Sumar otra sección (Pagos, por ejemplo) es insertar
* otro bloque y nada más. */
* The spacing lives here and not in the screen: every section closes with its
* own padding, so the separator always sits the same distance from the content
* above. Adding another section (Pagos, say) means inserting one more block and
* nothing else. */
export function Section({ title, trailing, toggle, children }: SectionProps) {
const headingId = useId()
@@ -48,9 +48,9 @@ export function Section({ title, trailing, toggle, children }: SectionProps) {
<section aria-labelledby={headingId} className="border-t border-border/70 py-4">
<div className="flex items-center justify-between gap-3">
{toggle ? (
// El botón vive dentro del `<h2>`: el encabezado no se pierde y el
// disparador sigue siendo un control de verdad (Enter, Espacio y foco
// visible por teclado).
// The button lives inside the `<h2>`: the heading is not lost and the
// trigger is still a real control (Enter, Space and keyboard-visible
// focus).
<h2 id={headingId} className="min-w-0 flex-1">
<button
type="button"

View File

@@ -1,15 +1,15 @@
/** Botón de acción de la pantalla (WhatsApp, Llamar, Copiar link).
/** The screen's action button (WhatsApp, Llamar, Copiar link).
*
* Relleno `primary-soft`, que es la misma superficie rellena que usa el detalle
* de grupo: un borde fino sobre `surface` en tema claro es invisible porque
* `surface` y `background` son el mismo blanco. 44px de alto para el dedo, y
* el mismo anillo de foco y feedback de presión que el `Button` de la app. */
* `primary-soft` fill, which is the same filled surface the group detail uses:
* a thin border over `surface` is invisible in the light theme because
* `surface` and `background` are both white. 44px tall for the finger, and the
* same focus ring and press feedback as the app's `Button`. */
export const ACTION_BUTTON_CLASS =
'inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary-soft px-3 text-sm font-medium text-primary transition-colors hover:bg-accent-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Acción principal de un panel (Enviar por WhatsApp). Misma superficie que el
* `Button` `primary` de la app —relleno `accent` con texto `on-accent`, que
* da 6.8:1 en los dos temas— pero a ancho completo porque sola en la columna:
* al lado de la secundaria al 50% los rótulos largos se parten en dos líneas. */
/** A panel's primary action (Enviar por WhatsApp). Same surface as the app's
* `primary` `Button` —`accent` fill with `on-accent` text, which gives 6.8:1 in
* both themes— but full width because it is alone in the column: next to the
* secondary one at 50% the long labels wrap onto two lines. */
export const PRIMARY_ACTION_CLASS =
'inline-flex h-11 w-full items-center justify-center gap-2 rounded-xl bg-accent px-4 text-sm font-medium text-on-accent transition-colors hover:bg-accent-strong active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'

View File

@@ -1,8 +1,8 @@
import type { AttendanceHistoryItem } from '@gruperly/shared'
/* El endpoint de historial corta en 20 sesiones (HISTORY_SESSIONS_LIMIT en el
backend). Es el techo real de lo que esta pantalla puede mostrar, así que
"Ver todas" no promete más de lo que hay. */
/* The history endpoint cuts off at 20 sessions (HISTORY_SESSIONS_LIMIT on the
backend). It is the real ceiling on what this screen can show, so "Ver todas"
does not promise more than there is. */
export const HISTORY_PREVIEW = 5
export const HISTORY_LIMIT = 20
@@ -29,9 +29,9 @@ export function attendanceStatusLabel(status: AttendanceSession['status']): stri
}
}
/* El estado se lee por texto e ícono, no solo por color: los tokens de estado
están pensados como texto sobre superficies oscuras y el verde sobre blanco
queda justo por debajo de AA, así que la fila lleva las tres señales. */
/* The status is read through text and icon, not color alone: the status tokens
are meant as text over dark surfaces and the green on white sits just below
AA, so the row carries all three signals. */
export function attendanceStatusClass(status: AttendanceSession['status']): string {
switch (status) {
case 'PRESENT':
@@ -45,7 +45,7 @@ export function attendanceStatusClass(status: AttendanceSession['status']): stri
}
}
/** "28 sep 2026". Es la fecha corta de siempre: entra en una línea en móvil. */
/** "28 sep 2026". It is the usual short date: it fits on one line on mobile. */
export function formatMemberSince(iso: string): string {
return new Date(iso).toLocaleDateString('es-MX', {
day: 'numeric',
@@ -59,9 +59,9 @@ export function classCountLabel(count: number): string {
return count === 1 ? '1 clase' : `${count} clases`
}
/** Lo que se muestra: de la más reciente a la más antigua, con las últimas
* `HISTORY_PREVIEW` como vista previa. El endpoint devuelve el orden
* contrario (más antigua → más reciente). */
/** What is displayed: from the most recent to the oldest, with the last
* `HISTORY_PREVIEW` as the preview. The endpoint returns the opposite order
* (oldest → most recent). */
export function visibleSessions(
sessions: AttendanceSession[],
showAll: boolean,
@@ -70,26 +70,27 @@ export function visibleSessions(
return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW)
}
/** Clases con asistencia registrada: asistió, faltó o faltó con aviso. Las
* "Sin registrar" no cuentan: sin dato no hay ni asistencia ni ausencia, y
* meterlas en el denominador hacía que "1 de 3" se leyera como dos ausencias. */
/** Classes with a recorded attendance: attended, was absent or was absent with
* notice. The "Sin registrar" ones do not count: without a record there is
* neither attendance nor absence, and putting them in the denominator made
* "1 de 3" read as two absences. */
function markedSessions(sessions: AttendanceSession[]): AttendanceSession[] {
return sessions.filter((session) => session.status != null)
}
export type AttendanceSummary = {
/** "1 de 1 clase", o "Sin clases registradas" si no hay ninguna con dato. */
/** "1 de 1 clase", or "Sin clases registradas" if there is none with a record. */
label: string
/** "2 sin registrar", o `null` si no hay clases sin registro. */
/** "2 sin registrar", or `null` if there are no classes without a record. */
unmarkedLabel: string | null
}
/** Resumen de las filas que se están mostrando: cuántas clases registró la
* persona sobre cuántas hay con dato, y cuántas quedaron sin registrar.
/** Summary of the rows being shown: how many classes the person recorded out of
* how many have a record, and how many were left unmarked.
*
* El texto de las "sin registrar" se apaga cuando no hay ninguna clase
* registrada: el resumen ya dice que no hay datos y los dos textos dirían lo
* mismo dos veces. */
* The "sin registrar" text is dimmed when there is no marked class: the summary
* already says there is no data and the two texts would say the same thing
* twice. */
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
const marked = markedSessions(sessions)
if (marked.length === 0) return { label: 'Sin clases registradas', unmarkedLabel: null }

View File

@@ -2,8 +2,9 @@ import { useEffect, useRef, useState } from 'react'
const FEEDBACK_MS = 1800
/** Copia al portapapeles y avisa en el mismo lugar donde se apretó, que es
* donde sigue la vista: un toast encima obliga a volver a buscar el control. */
/** Copies to the clipboard and confirms in the same spot where it was pressed,
* which is where the eye already is: a toast on top forces the view to hunt for
* the control again. */
export function useCopyToClipboard() {
const [copied, setCopied] = useState(false)
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -24,8 +25,8 @@ export function useCopyToClipboard() {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(() => setCopied(false), FEEDBACK_MS)
})
// Si el navegador rechaza la escritura no hay nada que confirmar: se
// deja el control como estaba en vez de dejar la promesa sin manejar.
// If the browser rejects the write there is nothing to confirm: the control
// is left as it was instead of leaving the promise unhandled.
.catch(() => setCopied(false))
}

View File

@@ -44,7 +44,8 @@ export function SignupPage() {
return
}
if (data?.token) {
// Con email verification activo, la sesión no se crea hasta verificar.
// With email verification on, the session is not created until it is
// verified.
navigate({ to: '/verify-email', search: { email } })
}
})

View File

@@ -21,9 +21,9 @@ export function ClassAttendanceView() {
return (
<section>
{/* El título grande va siempre, incluso mientras carga la sesión: es lo
que orienta y da altura de anclaje a la barra. El contador de
presentes, en cambio, solo aparece cuando ya hay alumnos en pantalla. */}
{/* The large title always renders, even while the session loads: it is what
orients and gives the bar its anchor height. The present counter, on the
other hand, only shows once there are students on screen. */}
<LargeTitle
title={sessionInfo?.groupName ?? 'Asistencia'}
leading={

View File

@@ -2,74 +2,73 @@ import type { CapacityCounts, RiskTone } from './card'
import { cn } from '../../lib/utils'
/**
* Indicador único de cupo y asistencia: una barra que junta "cuánta gente hay"
* con "cómo viene esa gente". Reemplaza al badge de baja asistencia y a la
* barrita de ocupación, que contaban dos cosas distintas y competían por el
* mismo lugar en la tarjeta.
* Single capacity and attendance indicator: one bar that joins "how many people
* there are" with "how those people are doing". It replaces the low attendance
* badge and the occupancy bar, which counted two different things and competed
* for the same spot on the card.
*
* ── Qué se está midiendo ───────────────────────────────────────────────────
* `capacity` es el total contra el que se reparten los bloques, y `places` dice
* si ese total son lugares del cupo o la matrícula. Sin cupo declarado el
* grupo no tiene lugares, pero sí tiene gente en riesgo, así que la barra
* mide a los miembros (`places: false`) en vez de desaparecer.
* ── What is being measured ──────────────────────────────────────────────────
* `capacity` is the total the blocks are split against, and `places` says whether
* that total is spots of the capacity or the roster. With no declared capacity the
* group has no spots, but it does have people at risk, so the bar measures the
* members (`places: false`) instead of disappearing.
*
* ── Dos modos ──────────────────────────────────────────────────────────────
* Con total chico (<= `SEGMENTED_CAPACITY_MAX`) hay un segmento por unidad y se
* ve exactamente qué posiciones están ocupadas y de qué color. Con total grande
* eso ya no se distingue, así que se pasa a bloques proporcionales. Ambos modos
* conservan la misma medida visual para que la lista se pueda escanear en
* vertical; importa la proporción, no que los grupos chicos queden diminutos.
* ── Two modes ───────────────────────────────────────────────────────────────
* With a small total (<= `SEGMENTED_CAPACITY_MAX`) there is one segment per unit
* and you see exactly which positions are occupied and in what color. With a large
* total that is no longer distinguishable, so it switches to proportional blocks.
* Both modes keep the same visual measure so the list can be scanned vertically;
* the proportion is what matters, not that small groups end up tiny.
*
* ── Ancho ──────────────────────────────────────────────────────────────────
* La barra se reparte el ancho disponible y nunca lo excede: es la regla que
* impide que la tarjeta desborde la pantalla en un teléfono. Por eso el
* segmento va `flex-1 max-w-[50px]` y no con un ancho fijo. Un `w-[50px]
* shrink-0` parece inocuo, pero a 10 segmentos son 554px (más los gaps) contra
* los ~288px que deja la tarjeta en un viewport de 402px: los hijos `shrink-0`
* se salen de la caja ya encogida y, sin nada que los recorte, empujan el
* documento a un scroll horizontal. Con `flex-1` cada segmento toma la parte
* que le toca del espacio real, y el `max-w` mantiene el ancho de escritorio
* (50px). El `overflow-hidden` del contenedor es la red de seguridad: recorta
* en vez de desbordar si algún día vuelve a pasar algo más grande que el
* espacio.
* ── Width ───────────────────────────────────────────────────────────────────
* The bar splits the available width and never exceeds it: that is the rule that
* stops the card from overflowing the screen on a phone. That is why the segment
* goes `flex-1 max-w-[50px]` and not with a fixed width. A `w-[50px] shrink-0`
* looks harmless, but at 10 segments it is 554px (plus the gaps) against the
* ~288px the card leaves on a 402px viewport: the `shrink-0` children spill out
* of the already-shrunk box and, with nothing clipping them, push the document
* into a horizontal scroll. With `flex-1` each segment takes its share of the real
* space, and the `max-w` keeps the desktop width (50px). The container's
* `overflow-hidden` is the safety net: it clips instead of overflowing if one day
* something bigger than the space shows up again.
*
* Ojo: repartirse el ancho no alcanza por sí solo. Un segmento muy angosto
* deja de distinguir su color del vecino y la barra se vuelve una línea de
* puntos. Por eso el ancho que se le cede a la barra importa tanto como el
* reparto: el label de la card dice "4/5" en móvil en vez de "4/5 miembros"
* justamente para que al cupo 10 le queden ~24px por píldora en vez de ~19px.
* Ver `SEGMENTED_CAPACITY_MAX` para el resto del reparto de cuentas.
* Note: splitting the width is not enough on its own. A very narrow segment
* stops telling its color apart from its neighbor and the bar becomes a line of
* dots. That is why the width ceded to the bar matters as much as the split: the
* card's label says "4/5" on mobile instead of "4/5 miembros" precisely so that
* capacity 10 is left with ~24px per pill instead of ~19px.
* See `SEGMENTED_CAPACITY_MAX` for the rest of the accounting.
*
* ── Lectura ────────────────────────────────────────────────────────────────
* El color solo no alcanza. El bloque va con `role="img"` y un `aria-label` que
* dice todo ("4 de 5 lugares ocupados: 2 en riesgo alto, 2 en atención"), que es
* lo que lee el lector de pantalla; y la tarjeta repite lo esencial en texto
* ("3 en riesgo alto · 4 en atención") abajo. Los tres niveles van siempre en el
* mismo orden, de peor a mejor, para que la barra se lea igual en todas las
* tarjetas y el ojo aprenda a escanearlas.
* ── Reading ─────────────────────────────────────────────────────────────────
* Color alone is not enough. The block carries `role="img"` and an `aria-label`
* that says everything ("4 de 5 lugares ocupados: 2 en riesgo alto, 2 en
* atención"), which is what the screen reader reads; and the card repeats the
* essentials in text ("3 en riesgo alto · 4 en atención") below. The three levels
* always go in the same order, worst to best, so the bar reads the same on every
* card and the eye learns to scan them.
*
* ── Contraste ──────────────────────────────────────────────────────────────
* Todo sale de tokens, nada hardcodeado. Los rellenos miden 5.74:1 (rojo),
* 4.58:1 (ámbar) y 6.20:1 (azul) contra la tarjeta en tema claro, y 5.44, 10.15
* y 7.10:1 en oscuro: los tres pasan el 3:1 que pide WCAG para contenido no
* textual y el 4.5:1 que necesita la línea de texto que los acompaña. El rojo
* usa `danger-fg` y no `danger` justamente por eso: `danger` en tema claro da
* 3.35:1 y no alcanzaría como texto.
* ── Contrast ────────────────────────────────────────────────────────────────
* Everything comes from tokens, nothing hardcoded. The fills measure 5.74:1 (red),
* 4.58:1 (amber) and 6.20:1 (blue) against the card in the light theme, and 5.44,
* 10.15 and 7.10:1 in dark: all three pass the 3:1 WCAG asks of non-text content
* and the 4.5:1 the accompanying text line needs. The red uses `danger-fg` and not
* `danger` precisely for that: `danger` in the light theme gives 3.35:1 and would
* not do as text.
*
* El contorno de los lugares libres NO puede usar `border`, que en tema oscuro
* vale lo mismo que la tarjeta (1.00:1 y no se ve); usa `foreground` al 70%,
* que da 3.42:1 en claro y 3.55:1 en oscuro.
* The outline of the free spots can NOT use `border`, which in the dark theme is
* the same as the card (1.00:1 and invisible); it uses `foreground` at 70%, which
* gives 3.42:1 in light and 3.55:1 in dark.
*/
type Level = keyof Pick<CapacityCounts, 'riesgoAlto' | 'atencion' | 'ok' | 'libres'>
/* De peor a mejor. Es el orden fijo de la barra: si mañana se agrega un nivel
entra en esta lista y no hay que tocar el componente. */
/* Worst to best. This is the bar's fixed order: if a level is ever added it goes
in this list and the component does not have to change. */
const LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok', 'libres']
const OCCUPIED_LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok']
/* El lugar libre no es un estado de la persona: es ausencia de gente. Por eso
es el único que no lleva relleno. */
/* The free spot is not a state of the person: it is the absence of people. That
is why it is the only one with no fill. */
const FILL: Record<Level, string> = {
riesgoAlto: 'bg-attendance-high',
atencion: 'bg-attendance-attention',
@@ -79,7 +78,7 @@ const FILL: Record<Level, string> = {
const OUTLINE = 'border-[1.5px] border-border dark:border-foreground/50'
/** Frase larga del `aria-label`: toda la información del bloque en una línea. */
/** The `aria-label`'s long phrase: all of the block's information in one line. */
export function capacityIndicatorLabel(
counts: CapacityCounts,
capacity: number,
@@ -99,9 +98,9 @@ export function capacityIndicatorLabel(
const detalle = niveles.length > 0 ? `: ${niveles.join(', ')}` : ''
/* Sin cupo declarado no hay lugares que ocupar ni libres que contar: la
barra es un reparto de la matrícula y decirlo con esas palabras sería
inventar un cupo que el grupo no tiene. */
/* With no declared capacity there are no spots to fill and no free ones to
count: the bar is a split of the roster, and saying it with those words
would invent a capacity the group does not have. */
if (!places) {
return `${ocupados} ${ocupados === 1 ? 'miembro' : 'miembros'}${detalle}`
}
@@ -119,12 +118,12 @@ export function AttendanceCapacityIndicator({
className,
}: {
counts: CapacityCounts
/** Total contra el que se reparte la barra: el cupo, o la matrícula si el
* grupo no tiene cupo declarado. */
/** The total the bar is split against: the capacity, or the roster if the
* group has no declared capacity. */
capacity: number
/** `true` cuando el total es chico y va un segmento por unidad. */
/** `true` when the total is small and goes one segment per unit. */
segmented: boolean
/** `false` cuando `capacity` son miembros y no lugares del cupo. */
/** `false` when `capacity` is members and not spots of the capacity. */
places?: boolean
className?: string
}) {
@@ -181,13 +180,13 @@ export function capacitySegmentWidth(count: number, capacity: number): string {
return `${((count / capacity) * 100).toFixed(4)}%`
}
/** Un segmento es una persona: el color es el del nivel de ese lugar. */
/** A segment is a person: the color is that of the level of this spot. */
function LevelSegment({ level, className }: { level: Level; className?: string }) {
if (level === 'libres') return <span className={cn(OUTLINE, 'rounded-full', className)} />
return <span className={cn('rounded-full', FILL[level], className)} />
}
/** El lugar `index` lo ocupa la persona de peor nivel que todavía entra. */
/** The person of the worst level that still fits occupies the `index` spot. */
function levelAt(counts: CapacityCounts, index: number): Level {
let restante = index
for (const level of LEVELS) {
@@ -197,10 +196,9 @@ function levelAt(counts: CapacityCounts, index: number): Level {
return 'libres'
}
/** Color del texto según el peor nivel: la línea de estado no puede quedar
* desalineada con la barra. `danger-fg` y no `danger` porque el primero es la
* versión legible (5.7:1 en claro, 5.4:1 en oscuro) y el segundo se queda en
* 3.35:1 como texto. */
/** Text color by worst level: the status line cannot end up misaligned with the
* bar. `danger-fg` and not `danger` because the first is the legible version
* (5.7:1 in light, 5.4:1 in dark) and the second stays at 3.35:1 as text. */
export const TONE_TEXT: Record<RiskTone, string> = {
riesgo_alto: 'text-danger-fg',
atencion: 'text-warning',

View File

@@ -74,10 +74,10 @@ export function GroupCardContent(props: GroupCardProps) {
places={true}
/>
{/* La palabra "miembros" se lleva ~60px que la barra necesita en un
teléfono. En móvil va solo el "4/5", que ya se entiende en una
tarjeta de cupos y no pierde nada: el `aria-label` del indicador
sigue contando todo ("4 de 5 lugares ocupados: 2 en riesgo alto..."). */}
{/* The word "miembros" takes ~60px that the bar needs on a phone. On
mobile only the "4/5" goes, which already reads on a capacity card
and loses nothing: the indicator's `aria-label` still counts
everything ("4 de 5 lugares ocupados: 2 en riesgo alto..."). */}
<span className="shrink-0 whitespace-nowrap text-base tabular-nums text-secondary">
{members.length}/{capacity}
<span className="hidden sm:inline">

View File

@@ -82,8 +82,8 @@ export function GroupsView() {
) : null}
{groupsQuery.isSuccess && groupsQuery.data.data.length === 0 && !showExamples ? (
/* Un ícono solo, con un punto focal, y el texto en secundario: la
pantalla vacía compite con la acción y no puede ganar. */
/* A single icon, one focal point, and the text in secondary: the empty
state competes with the action and must not win. */
<div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center">
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
<CalendarPlus className="size-7" aria-hidden="true" />

View File

@@ -83,8 +83,8 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
const [isParsingFile, setIsParsingFile] = useState(false)
const [isDragging, setIsDragging] = useState(false)
// Mismas query keys que el detalle del grupo: la data ya está en caché al navegar,
// así que la página se monta sin spinner ni fetch duplicado.
// Same query keys as the group detail: the data is already in cache on
// navigation, so the page mounts with no spinner and no duplicated fetch.
const groupQuery = useQuery({
queryKey: ['group', groupId],
queryFn: () => getGroup(groupId),

View File

@@ -73,13 +73,14 @@ export function AnalyticsView() {
await navigator.clipboard.writeText(message)
toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.')
} catch {
// Si clipboard falla, igual abrimos WhatsApp con el mensaje.
// If clipboard fails, we still open WhatsApp with the message.
}
window.open(waUrl, '_blank', 'noopener,noreferrer')
}
// 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.
// The group name is usually cached because the user comes from the group detail
// page: that way the large title shows right away and there is no jump when
// the queries load.
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
const groupName = riskQuery.data?.groupName ?? cachedGroupName
const analytics = analyticsQuery.data
@@ -87,14 +88,15 @@ export function AnalyticsView() {
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.
// The content needs both queries: without `riskQuery` there is neither the
// group name nor the list of attendees at risk.
const showContent = !isPending && !hasFailed && Boolean(analytics)
return (
<section className="mx-auto w-full max-w-md lg:max-w-6xl">
{/* El título grande va siempre, incluso cargando: es lo que da altura a
la barra y evita que el layout salte cuando llegan los datos. */}
{/* The large title always renders, even while loading: it is what gives
the bar its height and stops the layout from jumping when the data
arrives. */}
<LargeTitle
title={groupName ?? 'Grupo'}
leading={
@@ -108,9 +110,9 @@ export function AnalyticsView() {
</Link>
}
>
{/* "Estadísticas" es el subtítulo de la pantalla, no el título: el
título grande identifica el grupo y la barra colapsada lo muestra
para saber siempre sobre qué se está mirando. */}
{/* "Estadísticas" is the screen's subtitle, not its title: the large
title identifies the group and the collapsed bar keeps showing it so
you always know what you are looking at. */}
<div className="mt-2 flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
<p className="text-[14px] font-semibold uppercase tracking-wide text-foreground/70">

View File

@@ -1,34 +1,34 @@
import type { GroupListItem, GroupRiskSummary, UrgentMemberSummary } from '@gruperly/shared'
/* Derivaciones de la tarjeta del listado de grupos. La tarjeta no consulta
nada: decide acá qué se ve, con qué tono y con qué peso visual, para que el
JSX solo arme el layout y las reglas se puedan testear sueltas.
/* Derivations for the group listing card. The card queries nothing: it decides
here what is shown, with what tone and with what visual weight, so the JSX only
builds the layout and the rules can be tested on their own.
Los conteos por nivel y los miembros urgentes no se calculan en el cliente:
los trae `GET /groups-risk/overview`, que corre la misma función de dominio
(`getGroupAttendanceSummary` en packages/shared) que va a usar la sección de
seguimiento del Inicio. Acá solo se adapta esa respuesta a lo que la
tarjeta necesita pintar, y se decide cómo se lee. */
The per-level counts and the urgent attendees are not computed on the client:
they come from `GET /groups-risk/overview`, which runs the same domain function
(`getGroupAttendanceSummary` in packages/shared) that the follow-up section on
Home will use. Here we only adapt that response to what the card needs to paint,
and we decide how it reads. */
export type GroupLike = Pick<GroupListItem, 'attendeesCount' | 'capacity'>
/** A partir de este cupo el indicador deja de ser un segmento por lugar y pasa
* a bloques proporcionales.
/** From this capacity on, the indicator stops being one segment per spot and
* switches to proportional blocks.
*
* El umbral lo fija el ancho, no una ronda. La barra tiene que entrar en la
* tarjeta de un teléfono: ~291px en un viewport de 402px, ya descontando el
* padding de `<main>`, el de la card y el label de ocupación. Con el gap de
* 6px, diez segmentos salen de ~24px cada uno: angosto pero todavía una
* píldora con su color. Ese número depende de dos decisiones de la card que no
* son obvio: el label dice "4/5" en móvil y no "4/5 miembros" (la palabra se
* llevaba ~60px), y el segmento reparte el ancho en vez de medir 50px fijos.
* Con cualquiera de las dos al revés, el cupo 10 vuelve a ser ilegible.
* The threshold is set by the width, not by a round number. The bar has to fit
* in a phone's card: ~291px on a 402px viewport, after discounting `<main>`'s
* padding, the card's and the occupancy label. With the 6px gap, ten segments
* come out at ~24px each: narrow but still a pill with its own color. That number
* depends on two card decisions that are not obvious: the label says "4/5" on
* mobile and not "4/5 miembros" (the word took ~60px), and the segment splits
* the width instead of measuring a fixed 50px. With either of the two the other
* way, capacity 10 becomes unreadable again.
*
* A partir del séptimo la píldora se angosta de a poco, y en un viewport de
* 320px el cupo 10 cae a ~15px, que ya se lee más como punto que como color.
* Se prefiere igual: ver qué lugar está libre y de qué nivel es cada uno sigue
* informando más que una barra proporcional, y el reparto flexible más el
* `overflow-hidden` garantizan que nunca se desborde la pantalla. */
* From the seventh on the pill narrows gradually, and on a 320px viewport
* capacity 10 drops to ~15px, which already reads more like a dot than a color.
* We prefer it anyway: seeing which spot is free and what level each one is still
* says more than a proportional bar, and the flexible split plus `overflow-hidden`
* guarantee it never overflows the screen. */
export const SEGMENTED_CAPACITY_MAX = 10
export type MemberStatus = 'high_risk' | 'attention' | 'ok'
@@ -48,7 +48,7 @@ export type CapacityCounts = {
}
/**
* Conteos derivados directamente de una lista de miembros y el cupo.
* Counts derived directly from a member list and the capacity.
*/
export function capacityCountsFromMembers(
members: GroupMember[],
@@ -75,11 +75,11 @@ export function capacityCountsFromMembers(
}
/**
* Reglas de texto de alerta a partir de los miembros:
* - 1 en riesgo alto: "{Nombre}: {N} faltas" + (si hay atención > 0) " · {K} en atención"
* - 2 o más en riesgo alto: "{N} en riesgo alto" + (si hay atención > 0) " · {K} en atención"
* - 0 en riesgo alto pero atención > 0: "{K} en atención"
* - Ninguno: null
* Alert text rules derived from the members:
* - 1 at high risk: "{Nombre}: {N} faltas" + (if attention > 0) " · {K} en atención"
* - 2 or more at high risk: "{N} en riesgo alto" + (if attention > 0) " · {K} en atención"
* - 0 at high risk but attention > 0: "{K} en atención"
* - None: null
*/
export function alertTextFromMembers(members: GroupMember[]): string | null {
const highRisk = members.filter((m) => m.status === 'high_risk')
@@ -106,8 +106,8 @@ export function alertTextFromMembers(members: GroupMember[]): string | null {
}
/**
* Convierte un GroupListItem y GroupRiskSummary en una lista de GroupMember
* para unificar la representación interna.
* Turns a GroupListItem and GroupRiskSummary into a list of GroupMember to unify
* the internal representation.
*/
export function membersFromGroupAndRisk(
group: Pick<GroupListItem, 'attendeesCount' | 'capacity'>,
@@ -170,16 +170,16 @@ export function membersFromGroupAndRisk(
}
/**
* Conteos que consume el indicador de cupo y asistencia.
* Counts consumed by the capacity and attendance indicator.
*
* `ok` es la diferencia, no un número de la API: el resumen de riesgo solo
* nombra a los que hay que mirar, y el resto de la matrícula es lo que queda
* bien. Se acota a 0 porque el resumen cuenta los miembros activos y la tarjeta
* muestra todos.
* `ok` is the remainder, not a number from the API: the risk summary only names
* the ones worth watching, and the rest of the roster is what is doing fine. It
* is clamped to 0 because the summary counts active members while the card shows
* all of them.
*
* Sin resumen todavía (o si la consulta falla) todos los miembros caen en `ok`.
* Es el estado en calma: el resumen puede seguir cargando y la tarjeta tiene
* que poder pintar igual.
* With no summary yet (or if the query fails) every member falls into `ok`. It is
* the calm state: the summary can still be loading and the card has to be able
* to paint anyway.
*/
export function capacityCounts(group: GroupLike, risk: GroupRiskSummary | undefined): CapacityCounts {
const riesgoAlto = risk?.riesgoAlto ?? 0
@@ -194,7 +194,7 @@ export function capacityCounts(group: GroupLike, risk: GroupRiskSummary | undefi
}
}
/** Tono de la línea de estado y del indicador: el peor nivel presente. */
/** Tone of the status line and of the indicator: the worst level present. */
export type RiskTone = 'riesgo_alto' | 'atencion' | 'ok'
export function riskTone(counts: CapacityCounts): RiskTone {
@@ -209,11 +209,11 @@ export type StatusLine = {
}
/**
* La cuarta fila de la tarjeta: qué está pasando con la asistencia.
* The card's fourth row: what is going on with attendance.
*
* Con una sola persona en riesgo alto se muestra su nombre y cantidad de
* faltas. Con dos o más se resume por nivel. Cuando no hay nada que reportar,
* el componente omite esta línea por completo.
* With a single person at high risk it shows their name and absence count. With
* two or more it summarizes by level. When there is nothing to report, the
* component leaves this line out entirely.
*/
export function statusLine(group: GroupLike, risk: GroupRiskSummary | undefined): StatusLine {
const counts = capacityCounts(group, risk)
@@ -230,31 +230,31 @@ export function statusLine(group: GroupLike, risk: GroupRiskSummary | undefined)
}
/**
* El total con el que se mide el indicador.
* The total the indicator is measured against.
*
* Cuando el grupo no tiene cupo declarado la barra no desaparece: pasa a
* medir a la matrícula, un segmento (o bloque) por miembro, con los lugares
* libres en cero. Un grupo sin cupo no tiene "lugares libres" que mostrar, pero
* sí tiene gente en riesgo, y esa es justo la señal que la barra existe para
* comunicar. Lo que sí desaparece es la barra de un grupo vacío: sin miembros no
* hay nada que repartir.
* When the group has no declared capacity the bar does not disappear: it goes on
* measuring the roster, one segment (or block) per member, with the free spots
* at zero. A group with no capacity has no "free spots" to show, but it does have
* people at risk, and that is exactly the signal the bar exists to communicate.
* What does disappear is the bar of an empty group: with no members there is
* nothing to split.
*/
export function barCapacity(group: GroupLike): number {
return group.capacity ?? group.attendeesCount
}
/** ¿El indicador va con un segmento por lugar, o con bloques proporcionales? */
/** Does the indicator go with one segment per spot, or with proportional blocks? */
export function isSegmentedCapacity(capacity: number): boolean {
return capacity > 0 && capacity <= SEGMENTED_CAPACITY_MAX
}
/** "5/10 miembros", o "5 miembros" cuando el grupo no tiene cupo definido. */
/** "5/10 miembros", or "5 miembros" when the group has no defined capacity. */
export function occupancyLabel(group: GroupLike): string {
if (group.capacity === null) return membersLabel(group.attendeesCount)
return `${group.attendeesCount}/${group.capacity} ${group.capacity === 1 ? 'miembro' : 'miembros'}`
}
/** Nombra a la única persona en riesgo alto y agrega el total en atención. */
/** Names the single person at high risk and adds the attention total. */
function namedHighRiskMember(
urgentes: UrgentMemberSummary[],
counts: CapacityCounts,
@@ -269,7 +269,7 @@ function namedHighRiskMember(
return counts.atencion > 0 ? `${nombre} · ${counts.atencion} en atención` : nombre
}
/** Grupo grande: los conteos por nivel, y solo de los que hay algo que decir. */
/** Big group: the per-level counts, and only for the ones with something to say. */
function countedLevels(counts: CapacityCounts): string {
const partes: string[] = []
if (counts.riesgoAlto > 0) partes.push(`${counts.riesgoAlto} en riesgo alto`)
@@ -277,10 +277,11 @@ function countedLevels(counts: CapacityCounts): string {
return partes.join(' · ')
}
/* El motivo que mejor explica por qué alguien está en la línea de estado, en el
orden en que la regla los considera: primero la racha de faltas (algo que se
está yendo), después el tiempo sin aparecer, y por último la asistencia. Con
una sola falta y al día se devuelve null: no alcanza para nombrar a nadie. */
/* The reason that best explains why someone is on the status line, in the order
the rule considers them: first the streak of absences (something that is
going away), then the time since last showing up, and last the attendance
rate. With a single absence and ok it returns null: not enough to name
anyone. */
function absenceReason(miembro: UrgentMemberSummary): string | null {
const { consecutiveAbsences: faltas, daysSinceLastAttendance: dias, attendanceRate: asistencia } = miembro
@@ -290,8 +291,8 @@ function absenceReason(miembro: UrgentMemberSummary): string | null {
return null
}
/* Solo el primer nombre: en una línea de 360px "Sofía Ramírez: 4 faltas" no
entra, y entre dos personas con el mismo nombre la ficha las distingue. */
/* First name only: on a 360px line "Sofía Ramírez: 4 faltas" does not fit, and
between two people with the same name the detail page tells them apart. */
function firstName(fullName: string): string {
return fullName.trim().split(/\s+/)[0] || fullName
}
@@ -301,7 +302,7 @@ function membersLabel(count: number): string {
}
/**
* Casos de prueba solicitados para verificación contra la imagen de referencia.
* Test cases requested for verification against the reference image.
*/
export const MOCK_TEST_CASES = [
{

View File

@@ -5,11 +5,11 @@ export const RISK_LABELS: Record<Exclude<GroupRiskLevel, 'NONE'>, string> = {
MEDIUM: 'Riesgo moderado',
}
/* El badge solo dice "Riesgo moderado"; esta frase explica de qué habla
(abandono de un miembro, no fraude ni cobranza) y vive en el tooltip. */
/* The badge only says "Riesgo moderado"; this sentence explains what it is about
(an attendee dropping out, not fraud or collections) and lives in the tooltip. */
export const RISK_HINT =
'Riesgo de abandono: probabilidad estimada de que algún miembro abandone el grupo.'
/* El motivo concreto ("4 miembros con faltas seguidas") ya no se calcula acá:
vive en `card.ts`, que además decide el peso visual del badge. Esto quedó
con la copia estática de la ficha del grupo. */
/* The concrete reason ("4 members with consecutive absences") is not computed
here anymore: it lives in `card.ts`, which also decides the badge's visual
weight. What is left here is the static copy of the group detail. */

View File

@@ -30,7 +30,7 @@ export type ListSection = 'members' | 'pending'
type GroupDetailContextValue = {
groupId: string
group: GroupDto | undefined
/** Nombre para el título grande: dato real, caché o "Grupo" mientras carga. */
/** Name for the large title: real data, cache or "Grupo" while loading. */
groupTitle: string
groupQueryPending: boolean
riskLevel: GroupRiskLevel
@@ -50,7 +50,7 @@ type GroupDetailContextValue = {
whatsappMessage: string
searchFilter: string
setSearchFilter: (value: string) => void
/** La lista de miembros se reduce a quienes tienen el cobro vencido. */
/** The member list narrows down to those whose charge is overdue. */
overdueOnly: boolean
setOverdueOnly: (value: boolean) => void
listSection: ListSection
@@ -96,8 +96,8 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
const [searchFilter, setSearchFilter] = useState('')
const [overdueOnly, setOverdueOnly] = useState(false)
// Los controles de la lista pertenecen a la vista que los abrió: al cambiar de
// pestaña se limpian para no heredar un filtro sin coincidencias.
// The list's controls belong to the view that opened them: on a tab change
// they are cleared so as not to inherit a filter with no matches.
const setListSection = (value: ListSection) => {
setListSectionState(value)
setSearchFilter('')
@@ -286,14 +286,15 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.')
}
} catch {
// Si el portapapeles falla, igual abrimos WhatsApp con el mensaje.
// If the clipboard fails, we still open WhatsApp with the message.
}
window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer')
}
// El título grande va siempre, incluso cargando: es lo que da altura a la
// barra immersive y evita que el layout salte. Al llegar desde la ficha del
// grupo el nombre ya está en caché; en la primera carga cae a "Grupo".
// The large title always renders, even while loading: it is what gives the
// immersive bar its height and stops the layout from jumping. Arriving from
// the group detail page the name is already cached; on the first load it falls
// back to "Grupo".
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
const groupTitle = group?.name ?? cachedGroupName ?? 'Grupo'

View File

@@ -25,8 +25,9 @@ export function GroupDetailView() {
return (
<section className="animate-fade-in space-y-5 sm:space-y-6">
{/* El título grande va siempre, incluso cargando: es lo que da altura a
la barra immersive y evita que el layout salte cuando llegan los datos. */}
{/* The large title always renders, even while loading: it is what gives
the immersive bar its height and stops the layout from jumping when
the data arrives. */}
<GroupHeader />
{groupQueryPending ? (

View File

@@ -23,15 +23,16 @@ export function GroupHeader() {
const navigate = useNavigate()
const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM'
// Grupo recién creado (sin miembros ni pendientes): los empty states de cada
// pestaña ya ofrecen "Compartir" y "Agregar" con su primario explicado, así
// que el header no repite las mismas acciones una segunda vez.
// Brand new group (no members, nothing pending): each tab's empty state
// already offers "Compartir" and "Agregar" with its primary explained, so the
// header does not repeat the same actions a second time.
const listLoading = attendeesPending || preRegistrationsPending || waitlistPending
const isEmptyGroup =
!listLoading && attendeesTotal === 0 && preRegistrationsTotal === 0 && waitlistTotal === 0
// Sin grupo todavía solo se pinta el título: los badges, la descripción y las
// acciones necesitan datos, y mostrarlos a medias daría un header parpadeante.
// With no group yet only the title is painted: the badges, the description and
// the actions need data, and showing them halfway would give a flickering
// header.
const hasGroup = Boolean(group)
return (
@@ -48,8 +49,8 @@ export function GroupHeader() {
</Link>
}
>
{/* Los estados cuelgan del título y no de la barra: en la barra
colapsada solo va el nombre, que es lo que se usa para orientarse. */}
{/* The states hang off the title and not off the bar: in the collapsed
bar only the name goes, which is what you use to orient yourself. */}
{hasGroup ? (
<div className="mt-3 flex flex-wrap items-center gap-2">
<Badge variant="success" className="gap-1.5 text-[11px]">
@@ -57,8 +58,9 @@ export function GroupHeader() {
Activo
</Badge>
{hasRisk ? (
// El badge no puede llevar texto largo sin ensuciar el header: la
// explicación (riesgo de abandono, no de cobranza) vive en el tooltip.
// The badge cannot carry long text without cluttering the header:
// the explanation (dropout risk, not collections risk) lives in the
// tooltip.
<Tooltip content={RISK_HINT}>
<Badge
variant={riskLevel === 'HIGH' ? 'danger' : 'warning'}
@@ -86,13 +88,14 @@ export function GroupHeader() {
</LargeTitle>
{hasGroup ? (
// Una sola fila en mobile: el primario toma el ancho que sobra y las dos
// acciones de apoyo se pliegan a iconos de 44px. En sm+ recuperan el
// texto porque hay ancho de sobra y el rótulo hace más claro el destino.
// A single row on mobile: the primary takes the leftover width and the two
// supporting actions collapse into 44px icons. At sm+ they get their text
// back because there is plenty of width and the label makes the
// destination clearer.
<div className="mt-4 flex items-center gap-2.5 sm:mt-5 sm:justify-end">
{!isEmptyGroup ? (
// Un solo primario por pantalla: "Agregar" encabeza la jerarquía y
// las acciones de apoyo quedan al lado, en outline.
// One primary per screen: "Agregar" heads the hierarchy and the
// supporting actions sit beside it, in outline.
<Button
variant="primary"
onClick={() =>
@@ -110,7 +113,8 @@ export function GroupHeader() {
aria-label="Estadísticas"
className={cn(
'h-11 shrink-0 justify-center border-border',
// En grupo vacío es la única acción del header: ocupa la fila entera.
// On an empty group it is the header's only action: it takes the
// whole row.
isEmptyGroup && 'w-full sm:w-auto',
!isEmptyGroup && 'w-11 sm:w-auto sm:px-4',
)}

View File

@@ -7,10 +7,10 @@ import {
import { cn } from '../../../lib/utils'
import { useGroupDetail } from './GroupDetailProvider'
/* Escala de la tarjeta: label 11 (etiqueta) · valor 16 (dato) · hero 24
(cupo). El cupo es lo único que se escanea de un vistazo, por eso es el
único que sube de nivel; el resto se lee en línea. El ritmo vertical está
apretado a propósito (~24px menos que antes) sin bajar la legibilidad. */
/* The card's scale: label 11 (label) · value 16 (data) · hero 24 (capacity). The
capacity is the only thing you scan at a glance, which is why it is the only
one that goes up a level; the rest is read inline. The vertical rhythm is
deliberately tight (~24px less than before) without hurting legibility. */
const LABEL_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground/70'
const CELL_CLASS = 'flex items-start gap-3 py-2.5 first:pt-0 last:pb-0 md:py-0'

View File

@@ -11,9 +11,9 @@ import {
summarizeAttendance,
} from './member-row'
/* Solo lo excepcional se pinta. "Al día" queda en el tono base y con un check
para que el estado se lea sin depender del color; vencido es el único que
sube de peso. */
/* Only the exceptional is painted. "Ok" stays in the base tone and with a check
so the state reads without depending on color; overdue is the only one that
gains weight. */
const PAYMENT_TONE: Record<PaymentState['kind'], string> = {
settled: 'text-foreground',
dueSoon: 'font-medium text-warning',
@@ -40,8 +40,8 @@ function AttendanceStrip({ recent }: { recent: AttendanceStatus[] }) {
return (
<div className="mt-0.5 flex items-center gap-2">
{/* Cada punto lleva su propio nombre accesible: el color solo es el
refuerzo visual, no la única forma de saber qué pasó. */}
{/* Every dot carries its own accessible name: color is only the visual
reinforcement, not the only way to know what happened. */}
<span className="flex items-center gap-1">
{summary.dots.map((status, index) => (
<span
@@ -70,9 +70,10 @@ function MemberRow({
<Link
to="/groups/$groupId/attendees/$attendeeId"
params={{ groupId, attendeeId: attendee.id }}
// `min-h-14` (56px) es el piso táctil cómodo. La fila entera es el link, así
// que no hace falta chevron ni fila con tabIndex: hereda el rol y el
// teclado del <a>, y además sirve el href real al abrir en otra pestaña.
// `min-h-14` (56px) is the comfortable touch floor. The whole row is the
// link, so there is no need for a chevron or a row with tabIndex: it
// inherits the role and keyboard of the <a>, and it also serves the real
// href when opened in another tab.
className={cn(
'flex min-h-14 items-center border-b border-foreground/10 px-3 py-2.5',
'transition-colors duration-150 hover:bg-surface/60 active:bg-surface',
@@ -93,8 +94,8 @@ function MemberRow({
}
export function MembersList({ attendees }: { attendees: AttendeeListItem[] }) {
// El groupId se lee una vez y se pasa: suscribir cada fila al contexto entero
// hace que un cambio de estado del provider re-renderice N filas sin motivo.
// groupId is read once and passed down: subscribing every row to the whole
// context makes a provider state change re-render N rows for no reason.
const { groupId } = useGroupDetail()
return (

View File

@@ -16,7 +16,7 @@ function OverdueFilter({ count }: { count: number }) {
aria-pressed={overdueOnly}
onClick={() => setOverdueOnly(!overdueOnly)}
className={cn(
// min-h-11 (44px): objetivo táctil mínimo, igual que los chips de sección.
// min-h-11 (44px): minimum touch target, same as the section chips.
'inline-flex min-h-11 items-center gap-1.5 rounded-full border px-3.5 text-xs font-semibold',
'transition-[background-color,color,border-color,box-shadow] duration-150',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-primary-soft',
@@ -25,8 +25,8 @@ function OverdueFilter({ count }: { count: number }) {
: 'border-border bg-surface text-foreground hover:border-danger/40 hover:text-danger',
)}
>
{/* La ✕ solo aparece con el filtro puesto: es la señal de que tocarlo
lo saca, sin tener que decirlo. */}
{/* The ✕ only shows with the filter on: it is the signal that tapping it
takes the filter off, without having to say so. */}
{overdueOnly ? <X className="size-3.5 shrink-0" aria-hidden="true" /> : null}
<span className="whitespace-nowrap">{count} con pago vencido</span>
</button>
@@ -46,8 +46,8 @@ export function MembersView() {
const navigate = useNavigate()
const query = searchFilter.trim().toLowerCase()
// El teléfono no se muestra en la fila, pero sigue siendo una vía de búsqueda:
// es como la mayoría conoce a los alumnos del grupo.
// The phone is not shown on the row but is still a search path: it is how most
// people know the group's attendees.
const matchesQuery = (attendee: (typeof attendees)[number]) =>
!query ||
attendee.fullName.toLowerCase().includes(query) ||
@@ -61,9 +61,9 @@ export function MembersView() {
const visible = attendees
.filter((attendee) => !overdueOnly || isOverdue(resolvePaymentState(attendee.payment)))
.filter(matchesQuery)
// Orden alfabético fijo: si se ordenara por cobro o asistencia las filas
// saltarían de lugar cada vez que alguien paga o falta, y el nombre es la
// única columna estable de la lista.
// Fixed alphabetical order: if it were sorted by charge or attendance the
// rows would jump around every time someone pays or misses, and the name is
// the only stable column in the list.
.sort(byFullName)
if (attendeesPending) {
@@ -108,8 +108,8 @@ export function MembersView() {
const filterBar = overdueCount > 0 ? <OverdueFilter count={overdueCount} /> : null
if (visible.length === 0) {
// El filtro de vencidos nunca queda vacío por sí solo (el chip no se muestra
// si no hay vencidos), así que un vacío acá es siempre la búsqueda.
// The overdue filter never ends up empty on its own (the chip is not shown
// if there are none overdue), so an empty list here is always the search.
return (
<>
{filterBar}

View File

@@ -9,19 +9,19 @@ import { SectionChips } from './SectionChips'
export function MembersWaitlistSection() {
const { listSection, searchFilter, setSearchFilter, attendeesTotal } = useGroupDetail()
// Con pocos miembros el buscador es ruido: se alcanza con recorrer la lista.
// Se quita del árbol en vez de esconderse, para no dejar un hueco en la fila.
// En Pendientes no cambia nada: ahí el volumen es el que es.
// With few attendees the search is noise: scrolling the list is enough. It is
// removed from the tree instead of hidden, so as not to leave a gap in the
// row. In Pendientes nothing changes: there the volume is what it is.
const showSearch = listSection === 'pending' || attendeesTotal > MEMBER_SEARCH_MIN
return (
// Una sola superficie: la lista va directo sobre el lavado, como la info
// card de arriba, en vez de anidarse en una caja más clara. La separación
// entre controles y datos la dan los propios divisores de fila, el tono
// propio del input y el borde de los chips; una caja intermedia solo
// sumaba un nivel de contención y padding horizontal.
// `overflow-hidden` recorta el hover de las filas y el borde inferior
// contra el radio del panel: las filas son full-bleed.
// A single surface: the list sits directly on the wash, like the info card
// above, instead of nesting inside a lighter box. The separation between
// controls and data comes from the row dividers themselves, the input's own
// tone and the chips' border; an intermediate box only added a level of
// containment and horizontal padding.
// `overflow-hidden` clips the rows' hover and the bottom border against the
// panel's radius: the rows are full-bleed.
<div className="overflow-hidden rounded-2xl bg-primary-soft">
<div className="space-y-2 p-3">
<div className="flex flex-col gap-2.5 lg:flex-row lg:items-center lg:justify-between">
@@ -41,9 +41,9 @@ export function MembersWaitlistSection() {
) : null}
</div>
{/* Solo Pendientes lleva copia de apoyo: explica la diferencia entre
pre-inscripción y lista de espera, que no se deduce de los nombres.
En Miembros los rótulos de columna ya dicen todo. */}
{/* Only Pendientes has supporting copy: it explains the difference
between pre-registration and waitlist, which cannot be deduced from
the names. In Miembros the column labels already say everything. */}
{listSection === 'pending' ? (
<p className="max-w-2xl text-xs leading-snug text-foreground/80">
Pre-inscripciones que esperan tu aprobación y personas en lista de espera por un cupo

View File

@@ -37,9 +37,9 @@ export function PendingView() {
if (!hasAnyEntry && !query) {
return (
// Full-bleed y sin radio propio: el `overflow-hidden` del panel lo recorta
// contra la silueta redondeada. `surface` sobre `primary-soft` hunde el
// bloque; con el lavado anterior se camuflaba.
// Full-bleed and with no radius of its own: the panel's `overflow-hidden`
// clips it against the rounded silhouette. `surface` over `primary-soft`
// sinks the block; with the previous wash it camouflaged.
<div className="bg-surface px-4 py-10 text-center">
<Inbox className="mx-auto mb-2 size-10 text-foreground/40" />
<p className="text-sm font-semibold text-primary">No hay pendientes</p>
@@ -92,7 +92,7 @@ export function PendingView() {
const Icon = section.icon
const hasRows = section.count > 0
const titleId = `pending-${section.title.replace(/\s+/g, '-').toLowerCase()}`
// Con búsqueda activa, las secciones sin coincidencias se ocultan.
// With the search on, sections with no matches are hidden.
if (!hasRows && query) return null
return (

View File

@@ -9,12 +9,13 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
return (
<table className="w-full table-fixed text-left text-sm">
<thead>
{/* `border-foreground/10` y no `border`: en dark `--border` es igual a
`primary-soft`, el fondo de la fila, y el separador desaparecería. */}
{/* `border-foreground/10` and not `border`: in dark `--border` is the same
as `primary-soft`, the row's background, and the separator would
disappear. */}
<tr className="border-b border-foreground/10 text-xs font-semibold text-foreground/80">
<th scope="col" className="w-[47%] px-3 pb-1.5">Nombre</th>
<th scope="col" className="px-3 pb-1.5">Teléfono</th>
{/* En móvil el teléfono manda: la fecha vive en el detalle. */}
{/* On mobile the phone leads: the date lives in the detail. */}
<th scope="col" className="hidden px-3 pb-1.5 sm:table-cell">Solicitado</th>
<th scope="col" className="w-8 px-1 pb-1.5">
<span className="sr-only">Detalle</span>
@@ -26,7 +27,8 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
<tr
key={entry.id}
tabIndex={0}
// El hover va a `surface` porque la fila ya vive sobre `primary-soft`.
// The hover goes to `surface` because the row already lives on
// `primary-soft`.
className="group cursor-pointer border-b border-foreground/10 transition-colors last:border-b-0 hover:bg-surface/60 focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
onClick={() => setSelectedPreRegistration(entry)}
onKeyDown={(e) => {
@@ -36,8 +38,8 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
}
}}
>
{/* `px-3` alinea el texto con el chips y el search de arriba: es el
mismo eje izquierdo de 12px en toda la sección. */}
{/* `px-3` aligns the text with the chips and the search above: it is
the same 12px left axis across the whole section. */}
<td className="px-3 py-2">
<div className="flex min-w-0 items-center gap-2">
<div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">

View File

@@ -34,7 +34,8 @@ export function SectionChips() {
{SECTIONS.map((section) => {
const isActive = listSection === section.id
const count = counts[section.id]
// Ámbar solo cuando hay algo que decidir: pre-inscripciones por revisar.
// Amber only when there is something to decide: pre-registrations to
// review.
const isAttention = section.id === 'pending' && preRegistrationsTotal > 0
const Icon = section.icon
@@ -45,7 +46,7 @@ export function SectionChips() {
aria-pressed={isActive}
onClick={() => setListSection(section.id)}
className={cn(
// min-h-11 (44px): objetivo táctil mínimo de iOS/Android.
// min-h-11 (44px): minimum iOS/Android touch target.
'inline-flex min-h-11 items-center gap-1.5 rounded-full border px-3.5 text-xs font-semibold',
'transition-[background-color,color,border-color,box-shadow] duration-150',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-primary-soft',

View File

@@ -9,8 +9,9 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
return (
<table className="w-full table-fixed text-left text-sm">
<thead>
{/* `border-foreground/10` y no `border`: en dark `--border` es igual a
`primary-soft`, el fondo de la fila, y el separador desaparecería. */}
{/* `border-foreground/10` and not `border`: in dark `--border` is the same
as `primary-soft`, the row's background, and the separator would
disappear. */}
<tr className="border-b border-foreground/10 text-xs font-semibold text-foreground/80">
<th scope="col" className="w-[47%] px-3 pb-1.5">Nombre</th>
<th scope="col" className="px-3 pb-1.5">Teléfono</th>
@@ -24,7 +25,8 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
<tr
key={entry.id}
tabIndex={0}
// El hover va a `surface` porque la fila ya vive sobre `primary-soft`.
// The hover goes to `surface` because the row already lives on
// `primary-soft`.
className="group cursor-pointer border-b border-foreground/10 transition-colors last:border-b-0 hover:bg-surface/60 focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
onClick={() => setSelectedWaitlistEntry(entry)}
onKeyDown={(e) => {
@@ -34,8 +36,8 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
}
}}
>
{/* `px-3` alinea el texto con el chips y el search de arriba: es el
mismo eje izquierdo de 12px en toda la sección. */}
{/* `px-3` aligns the text with the chips and the search above: it is
the same 12px left axis across the whole section. */}
<td className="px-3 py-2">
<div className="flex min-w-0 items-center gap-2">
<div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">

View File

@@ -1,11 +1,12 @@
/* Ajustes de la lista de miembros de la ficha de grupo. Viven acá y no
incrustados en el componente porque son decisiones de producto, no de estilo:
cambiarlas no debería obligar a tocar la fila. */
/* Tuning of the group detail's member list. It lives here and not embedded in
the component because these are product decisions, not style: changing them
should not force a touch on the row. */
/* A partir de cuántos días para el vencimiento el cobro pasa a kuning y la fila
avisa. Más atrás ya no es "pronto": o se pagó o quedó en el pasado. */
/* From how many days to the due date does the charge turn yellow and the row
warn. Further back it is no longer "due soon": either it was paid or it is in
the past. */
export const PAYMENT_DUE_SOON_DAYS = 3
/* El buscador se muestra a partir de cierta cantidad de miembros. Con pocos, es
más ruido que ayuda: alcanza con mirar la lista. */
/* The search shows from a certain number of attendees. With few of them it is
more noise than help: looking at the list is enough. */
export const MEMBER_SEARCH_MIN = 8

View File

@@ -2,12 +2,13 @@ import type { AttendeeListItem, AttendanceStatus } from '@gruperly/shared'
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'
import { PAYMENT_DUE_SOON_DAYS } from './constants'
/* La fila del listado no pide al backend juicios de presentación: pide los
datos crudos (últimas clases, cobro vigente) y de acá sale el texto. Los
días que faltan cambian según cuándo se mira, así que no pueden venir
guardados desde el servidor. */
/* The listing's row does not ask the backend for presentation verdicts: it asks
for the raw data (recent classes, current charge) and the text comes from
here. The days remaining change depending on when you look, so they cannot
come stored from the server. */
/** Días calendario entre dos fechas, sin horas: "vence el día 10" no tiene hora. */
/** Calendar days between two dates, without times: "due on the 10th" has no
* time of day. */
function calendarDaysBetween(from: Date, to: Date): number {
const startOf = (date: Date) =>
new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
@@ -20,15 +21,15 @@ export type PaymentState =
| { kind: 'overdue'; days: number }
/**
* Qué hay que marcarle al cobro en la fila.
* What to mark on the charge in the row.
*
* Devuelve `null` cuando no hay nada que avisar: o el miembro no tiene ningún
* cobro registrado, o el que tiene vence más adelante que la ventana de aviso y
* todavía no venció. No es lo mismo que "al día", que es un pago cerrado.
* Returns `null` when there is nothing to warn about: either the attendee has no
* recorded charge, or the one they have is due later than the warning window and
* has not expired yet. That is not the same as "ok", which is a closed payment.
*
* Un `PENDING` con vencimiento ya pasado cuenta como vencido, igual que un
* `OVERDUE`: el estado guardado suele quedarse en PENDING hasta que alguien lo
* actualiza a mano y la fila no puede depender de esa disciplina.
* A `PENDING` whose due date has already passed counts as overdue, same as an
* `OVERDUE`: the stored state often stays at PENDING until someone updates it by
* hand, and the row cannot depend on that discipline.
*/
export function resolvePaymentState(
payment: AttendeeListItem['payment'],
@@ -57,7 +58,7 @@ export function paymentStateLabel(state: PaymentState): string {
case 'settled':
return 'Al día'
case 'dueSoon':
// "Vence en 0 d" no es español de persona: hoy y mañana tienen palabras.
// "Vence en 0 d" is not natural Spanish: today and tomorrow have words.
if (state.days === 0) return 'Vence hoy'
if (state.days === 1) return 'Vence mañana'
return `Vence en ${state.days} d`
@@ -67,20 +68,20 @@ export function paymentStateLabel(state: PaymentState): string {
}
export type AttendanceSummary = {
/** Estados a dibujar, del más antiguo al más reciente. */
/** States to draw, from the oldest to the most recent. */
dots: AttendanceStatus[]
attended: number
recorded: number
/** "Sin clases aún" cuando no hay nada registrado. */
/** "Sin clases aún" when nothing is recorded. */
label: string
}
/** Los últimos puntos de clase registrados, contados sobre esa misma ventana. */
/** The last recorded class points, counted over that same window. */
export function summarizeAttendance(
recentAttendance: AttendanceStatus[],
): AttendanceSummary {
// La ventana la fija el backend; el corte final evita que una fila se alargue
// si el contrato llegara con más clases de las previstas.
// The window is set by the backend; the final cut prevents a row from getting
// longer if the contract ever delivers more classes than expected.
const dots = recentAttendance.slice(-RECENT_ATTENDANCE_LIMIT)
const recorded = dots.length
@@ -97,7 +98,7 @@ export function summarizeAttendance(
}
}
/** Orden alfabético fijo del listado. */
/** The listing's fixed alphabetical order. */
export function byFullName(a: AttendeeListItem, b: AttendeeListItem): number {
return a.fullName.localeCompare(b.fullName, 'es', { sensitivity: 'base' })
}

View File

@@ -17,7 +17,7 @@ export function ConfirmationStep({ group, providerName }: ConfirmationStepProps)
const { refresh } = useAuth()
const goToDashboard = () => {
// Revalida la caché (estado del onboarding, sesión, grupos) antes de redirigir.
// Revalidates the cache (onboarding state, session, groups) before redirecting.
void queryClient.invalidateQueries()
void refresh()
void navigate({ to: '/' })

View File

@@ -35,7 +35,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
useEffect(() => {
const status = statusQuery.data
if (!status) return
// Si interrumpió después de conectar el cobro, retomamos en el paso del grupo.
// If they dropped out after connecting payments, we resume at the group step.
if (status.step === 'PAYMENT_CONNECTED') {
setStep((current) => (current === 0 ? 2 : current))
}

View File

@@ -3,8 +3,8 @@ import { InstallBanner } from './InstallBanner'
import { IosInstallHint } from './IosInstallHint'
/**
* Presenta el aviso de instalación. Cuándo mostrarse lo decide `PwaProvider`
* (sesión iniciada + dwell cumplido); acá solo se dibuja lo que corresponda.
* Renders the install prompt. `PwaProvider` decides when it should show (signed
* in + dwell satisfied); here we only draw whatever applies.
*/
export function InstallPrompt() {
const { canPrompt, canShowIosHint, promptInstall, dismiss } = usePwa()

View File

@@ -5,9 +5,9 @@ type IosInstallHintProps = {
}
/**
* Safari en iOS no expone `beforeinstallprompt`: no hay forma de disparar la
* instalación desde la web, hay que instruir al usuario. Solo informa, sin
* botón de acción.
* Safari on iOS does not expose `beforeinstallprompt`: there is no way to trigger
* the install from the web, the user has to be instructed. It only informs, with
* no action button.
*/
export function IosInstallHint({ onDismiss }: IosInstallHintProps) {
return (

View File

@@ -13,16 +13,16 @@ import { useAuth } from '../../context/AuthProvider'
import { useToast } from '../../components/ui'
import { InstallPrompt } from './InstallPrompt'
/** `beforeinstallprompt` todavía no está en lib.dom (Chromium >= 108). */
/** `beforeinstallprompt` is not in lib.dom yet (Chromium >= 108). */
type BeforeInstallPromptEvent = Event & {
prompt: () => Promise<void>
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>
}
type PwaContextValue = {
/** El navegador ofreció instalar y el usuario todavía no lo decidió. */
/** The browser offered to install and the user has not decided yet. */
canPrompt: boolean
/** Safari en iOS: no hay `prompt()`, hay que instruir al usuario. */
/** Safari on iOS: there is no `prompt()`, the user has to be instructed. */
canShowIosHint: boolean
promptInstall: () => Promise<void>
dismiss: () => void
@@ -31,19 +31,19 @@ type PwaContextValue = {
const PwaContext = createContext<PwaContextValue | null>(null)
/**
* El descarte es definitivo: una vez que el usuario dice "ahora no" no se vuelve
* a preguntar. Comparte clave con la pista de iOS porque el motivo es el mismo.
* The dismissal is final: once the user says "not now" we never ask again. It
* shares a key with the iOS hint because the reason is the same.
*/
const DISMISSED_KEY = 'pwa-install-dismissed'
/**
* Cuánto hay que quedarse en la misma ruta antes de ofrecer instalar. El evento
* `beforeinstallprompt` llega a los segundos, así que sin este margen el banner
* cae en medio de la primera tarea de la visita.
* How long you have to stay on the same route before we offer to install. The
* `beforeinstallprompt` event arrives within seconds, so without this margin the
* banner lands in the middle of the visit's first task.
*/
const DWELL_MS = 20_000
/** iOS Safari no dispara `beforeinstallprompt`: se chequea el modo standalone. */
/** iOS Safari does not fire `beforeinstallprompt`: we check the standalone mode instead. */
function isStandalone() {
return (
window.matchMedia('(display-mode: standalone)').matches ||
@@ -52,9 +52,9 @@ function isStandalone() {
}
/**
* iOS real, Safari real. Excluye Chrome/Firefox/Edge/Opera en iOS: usan WebKit
* pero también los instala desde Safari, así que la instrucción de compartir
* no aplica. El iPad de iPadOS 13+ se reporta como MacIntel con touch points.
* Real iOS, real Safari. Excludes Chrome/Firefox/Edge/Opera on iOS: they use
* WebKit but also install from Safari, so the share instruction does not apply.
* iPadOS 13+ iPads report as MacIntel with touch points.
*/
function detectIos() {
if (isStandalone()) return false
@@ -69,11 +69,12 @@ function detectIos() {
}
/**
* El registro se hace desde el provider y no con `injectRegister: 'auto'` para
* poder avisar cuando el shell quedó cacheado. El flag es de módulo porque
* StrictMode monta dos veces en dev y `onOfflineReady` dispararía dos toasts.
* No se limpia en el unmount: StrictMode lo resetea en el mismo ciclo de montaje
* y volvería a registrar. Con HMR el módulo se re-evalua y arranca en false.
* Registration is done from the provider and not with `injectRegister: 'auto'` so
* we can tell the user when the shell has been cached. The flag is a module
* variable because StrictMode mounts twice in dev and `onOfflineReady` would fire
* two toasts. It is not cleared on unmount: StrictMode resets it in the same
* mount cycle and we would register again. With HMR the module is re-evaluated
* and starts at false.
*/
let registered = false
@@ -103,7 +104,7 @@ export function PwaProvider({ children }: { children: ReactNode }) {
useEffect(() => {
const onBeforeInstallPrompt = (event: Event) => {
// Sin preventDefault el navegador muestra su propio mini-infobar.
// Without preventDefault the browser shows its own mini-infobar.
event.preventDefault()
setInstallEvent(event as BeforeInstallPromptEvent)
}
@@ -120,25 +121,25 @@ export function PwaProvider({ children }: { children: ReactNode }) {
}
}, [])
// `PwaProvider` monta fuera del `RouterProvider`, así que no puede usar
// `useRouterState`: se suscribe al singleton. Conviene tener la ruta acá y no
// en el componente que muestra el banner, porque `AppLayoutGuard` desmonta
// `RootLayout` cada vez que su query de onboarding vuelve a `pending` y un
// timer de dwell en el hijo se perdería en cada navegación.
// `PwaProvider` mounts outside the `RouterProvider`, so it cannot use
// `useRouterState`: it subscribes to the singleton. The route is kept here and
// not in the component that shows the banner, because `AppLayoutGuard`
// unmounts `RootLayout` every time its onboarding query goes back to `pending`,
// and a dwell timer in the child would be lost on every navigation.
useEffect(
() => router.subscribe('onResolved', ({ toLocation }) => setPathname(toLocation.pathname)),
[],
)
// Durante el alta inicial no se ofrece instalar: la persona todavía no
// conoce la app. El timer ni siquiera corre, así que al salir arranca de cero
// en la primera pantalla real.
// During the initial sign-up we do not offer to install: the person does not
// know the app yet. The timer does not even run, so leaving the flow starts it
// from scratch on the first real screen.
const inOnboarding = pathname.startsWith('/onboarding')
useEffect(() => {
// Navegar antes de que se cumpla el tiempo reinicia la cuenta: tampoco
// estamos pidiendo instalar a alguien que está peleando con la app. Una
// vez cumplido queda armed y no se oculta más al navegar.
// Navigating before the time is up restarts the count: we are not asking
// someone who is busy fighting the app to install it either. Once it is
// settled it stays armed and no longer hides on navigation.
if (settled || inOnboarding) return
const timer = setTimeout(() => setSettled(true), DWELL_MS)
return () => clearTimeout(timer)
@@ -163,12 +164,12 @@ export function PwaProvider({ children }: { children: ReactNode }) {
}, [info])
/**
* Sin sesión no hay nada que instalar todavía: la primera vez que alguien
* conoce la app es instalándola, no pidiéndole que la instale.
* Without a session there is nothing to install yet: the first time someone
* meets the app is by installing it, not by being asked to install it.
*
* OJO: `_authenticated` NO es un guard de sesión. `AppLayoutGuard` renderiza
* `RootLayout` aunque no haya usuario, así que el gate se chequea acá y no
* se puede inferir de dónde se monte el prompt.
* WATCH OUT: `_authenticated` is NOT a session guard. `AppLayoutGuard` renders
* `RootLayout` even when there is no user, so the gate is checked here and
* cannot be inferred from where the prompt is mounted.
*/
const eligible = !!user && settled && !dismissed && !isInstalled && !inOnboarding

View File

@@ -1,8 +1,8 @@
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. */
/* Height of the navigation bar where the small title slides in. It has to
match the `h-14` of `LargeTitle`: the bar is sticky to the top edge of the
window and the large title is measured against this value. */
const BAR_HEIGHT = 56
function clamp01(value: number) {
@@ -11,13 +11,13 @@ function clamp01(value: number) {
}
/**
* 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.
* Collapse progress of a Large Title: 0 with the large title fully shown,
* 1 once it's completely hidden behind the bar.
*
* 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.
* The progress comes from the title's position, not from time: it is
* recalculated on every frame while scrolling. That's why the gesture feels
* stuck to the finger instead of "animated", and why `requestAnimationFrame`
* is there to batch scroll events, not to interpolate the animation.
*/
export function useLargeTitleCollapse() {
const titleRef = useRef<HTMLHeadingElement>(null)
@@ -32,11 +32,11 @@ export function useLargeTitleCollapse() {
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).
// 0 when the title's top edge reaches the bottom of the bar, 1 when its
// bottom edge got there too (it ended up entirely underneath).
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.
// Group titles arrive asynchronously and can change height between
// renders: without this threshold it re-renders on every scroll frame.
setProgress((current) => (Math.abs(current - next) < 0.002 ? current : next))
}
@@ -48,8 +48,8 @@ export function useLargeTitleCollapse() {
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.
// The group name loads after the first render and the webfont can change
// the title's height: the collapse range depends on that measurement.
const observer = new ResizeObserver(schedule)
observer.observe(title)

View File

@@ -1,9 +1,10 @@
@import "tailwindcss";
/* Inter variable auto-hospedada. Declaramos solo latin y latin-ext a mano en
lugar de importar el wght.css de @fontsource: ese trae los 7 subsets y el
service worker precachea todo lo emitido, casi 1 MB que nunca se descarga.
El archivo .woff2 sí viene del paquete, con hash y cache immutable. */
/* Self-hosted Inter variable. We declare only latin and latin-ext by hand
instead of importing @fontsource's wght.css: that one brings all 7 subsets
and the service worker precaches everything emitted, almost 1 MB that never
gets downloaded. The .woff2 file does come from the package, hashed with an
immutable cache. */
@font-face {
font-family: "Inter Variable";
font-style: normal;
@@ -25,7 +26,7 @@
@custom-variant dark (&:where(.dark, .dark *));
@theme inline {
/* Escala de marca (identidad fija, igual a la landing) */
/* Brand scale (fixed identity, same as the landing) */
--color-brand-50: var(--brand-50);
--color-brand-100: var(--brand-100);
--color-brand-200: var(--brand-200);
@@ -38,12 +39,12 @@
--color-brand-900: var(--brand-900);
--color-brand-950: var(--brand-950);
/* Colores de la gráfica del isotipo/logotipo */
/* Colors sampled from the logo mark */
--color-brand-night: var(--brand-night);
--color-brand-celeste: var(--brand-celeste);
--color-brand-cloud: var(--brand-cloud);
/* Tokens semánticos (conmutan con tema claro/oscuro) */
/* Semantic tokens (switch with the light/dark theme) */
--color-background: var(--background);
--color-surface: var(--surface);
--color-primary: var(--primary);
@@ -70,14 +71,14 @@
--color-attendance-attention: var(--attendance-attention);
--color-attendance-ok: var(--attendance-ok);
/* Border radius por defecto */
/* Default border radius */
--radius-xl: 0.75rem;
/* Tipografía (igual que la landing) */
/* @fontsource-variable/inter registra la familia como "Inter Variable" */
/* Typography (same as the landing) */
/* @fontsource-variable/inter registers the family as "Inter Variable" */
--font-sans: "Inter Variable", ui-sans-serif, system-ui, sans-serif;
/* Animaciones */
/* Animations */
--animate-fade-in: fade-in 0.2s ease-out;
--animate-step-enter: step-enter 0.35s cubic-bezier(0.22, 1, 0.36, 1) both;
@@ -101,7 +102,7 @@
:root {
color-scheme: light;
/* Escala de marca */
/* Brand scale */
--brand-50: #eef4ff;
--brand-100: #dbe6fe;
--brand-200: #bfd3fe;
@@ -117,17 +118,17 @@
--brand-celeste: #93b4fd;
--brand-cloud: #eef4ff;
/* Tema claro */
/* Light theme */
--background: #ffffff;
--surface: #ffffff;
--primary: #0f172a;
--primary-soft: #f1f5f9;
--foreground: #475569;
/* Texto secundario sobre superficies suaves (tarjetas). En tema claro el
gris de `foreground` ya da 6.9:1 sobre `primary-soft` y 7.6:1 sobre
`background`, así que acá no hay que mover nada: mismo valor, mismo
contrato. El token existe igual para que "secundario" sea un nombre y no
una coincidencia de color. */
/* Secondary text on soft surfaces (cards). In the light theme the
`foreground` gray already scores 6.9:1 on `primary-soft` and 7.6:1 on
`background`, so there's nothing to move here: same value, same contract.
The token exists anyway so "secondary" is a name and not a color
coincidence. */
--secondary: #475569;
--accent: #2544ea;
--accent-strong: #1d33d8;
@@ -140,18 +141,18 @@
--success-soft: #ecfdf5;
--warning: #b45309;
--warning-soft: #fffbeb;
/* naranja: escalón de severidad para la misma familia de alertas (aviso por
asistencia, cupos). Sobre `warning-strong-soft` da 4.9:1 y sobre la
tarjeta 4.4:1, así que sirve para texto y para un borde tenue. */
/* Orange: severity step for the same alert family (attendance and capacity
warnings). It scores 4.9:1 on `warning-strong-soft` and 4.4:1 on the card,
so it works for text and for a subtle border. */
--warning-strong: #c2410c;
--warning-strong-soft: #fff7ed;
--danger: #f43f5e;
--danger-soft: #fff1f2;
/* Rojo legible como TEXTO. `--danger` da 3.35:1 sobre la tarjeta en tema
claro, así que como texto no llega al 4.5:1 de AA (sí sirve como relleno,
donde el mínimo es 3:1). Es el mismo patrón que `accent` / `accent-fg`: un
color para superficies grandes y su versión legible para rotular. Este
#be123c da 5.74:1 sobre la tarjeta y 5.72:1 sobre `danger-soft`. */
/* Red legible as TEXT. In the light theme `--danger` scores 3.35:1 on the
card, so as text it misses AA's 4.5:1 (it does work as a fill, where the
minimum is 3:1). Same pattern as `accent` / `accent-fg`: one color for
large surfaces and a legible version of it for labels. This #be123c scores
5.74:1 on the card and 5.72:1 on `danger-soft`. */
--danger-fg: #be123c;
--attendance-high: #d63b3b;
--attendance-attention: #f5a623;
@@ -161,16 +162,16 @@
.dark {
color-scheme: dark;
/* Tema oscuro (paleta slate/brand de la landing) */
/* Dark theme (slate/brand palette from the landing) */
--background: #020617;
--surface: #0f172a;
--primary: #f1f5f9;
--primary-soft: #1e293b;
--foreground: #94a3b8;
/* El secundario se sube un escalón sobre `foreground`: 7.1:1 sobre la
tarjeta (#1e293b) y 9.8:1 sobre el fondo, contra 5.7:1 del gris anterior.
El salto importa en las superficies suaves, que son las que dominan las
tarjetas de la lista: el texto de apoyo ahí es el que más se pierde. */
/* Secondary goes one step up from `foreground`: 7.1:1 on the card (#1e293b)
and 9.8:1 on the background, against 5.7:1 for the previous gray. The step
matters on soft surfaces, which are what dominates list cards: supporting
text there is what gets lost the most. */
--secondary: #a8b6c8;
--accent: #2544ea;
--accent-strong: #1d33d8;
@@ -183,15 +184,15 @@
--success-soft: color-mix(in srgb, var(--success) 15%, transparent);
--warning: #fcd34d;
--warning-soft: color-mix(in srgb, var(--warning) 15%, transparent);
/* En oscuro el "naranja" tiene que subir de luminosidad para alcanzar el
mismo contraste que su versión clara: #fb923c da 4.7:1 sobre el fondo
translúcido del badge, contra 4.1:1 del #f97316 de la paleta estándar. */
/* In dark the "orange" has to gain lightness to reach the same contrast as
its light version: #fb923c scores 4.7:1 on the badge's translucent
background, against 4.1:1 for the #f97316 of the standard palette. */
--warning-strong: #fb923c;
--warning-strong-soft: color-mix(in srgb, var(--warning-strong) 18%, transparent);
--danger: #fb7185;
--danger-soft: color-mix(in srgb, var(--danger) 15%, transparent);
/* En oscuro `#fb7185` ya da 5.44:1 sobre la tarjeta: legible como texto y de
sobra como relleno, así que acá no hay que mover nada. */
/* In dark `#fb7185` already scores 5.44:1 on the card: legible as text and
more than enough as a fill, so there's nothing to move here. */
--danger-fg: var(--danger);
}
@@ -205,14 +206,14 @@
min-height: 100dvh;
}
/* iOS (Safari y standalone) hace auto-zoom al enfocar un control de
formulario con font-size < 16px, y al cerrar el teclado no restaura el
scale: la app queda con zoom. El `Input` ya sube a 16px en mobile
(`text-base sm:text-sm`); esto es la red de seguridad para textareas,
selects o inputs crudos que se agreguen más adelante.
El 639px calza con el breakpoint `sm` de Tailwind. El `!important` es
a propósito: sin él, una clase `text-sm` en un input futuro ganaría por
especificidad y reintroduciría el bug sin avisar. */
/* iOS (Safari and standalone) auto-zooms when a form control with font-size
< 16px is focused, and on keyboard close it doesn't restore the scale:
the app is left zoomed in. `Input` already goes to 16px on mobile
(`text-base sm:text-sm`); this is the safety net for textareas, selects or
raw inputs added later.
The 639px matches Tailwind's `sm` breakpoint. The `!important` is on
purpose: without it a `text-sm` class on a future input would win on
specificity and reintroduce the bug without warning. */
@media (max-width: 639px) {
input,
textarea,

View File

@@ -80,7 +80,7 @@ async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
problem = body as ProblemDetails
}
} catch {
// Sin cuerpo JSON: usamos el error genérico.
// No JSON body: we use the generic error.
}
throw new ApiError(res.status, problem)
}
@@ -108,9 +108,9 @@ export const createGroup = (payload: CreateFirstGroup) =>
body: JSON.stringify(payload),
})
/* La pantalla de grupos no tiene paginación: se pide el máximo permitido para
que ningún grupo quede fuera de la lista, y la zona horaria del browser para
que el backend ordene por la próxima clase en la hora local de la persona. */
/* The groups screen has no pagination: we ask for the maximum allowed so no
group is left out of the listing, and for the browser time zone so the
backend sorts by the next class in the person's local time. */
const GROUPS_PAGE_SIZE = 100
export const getGroups = () => {
@@ -222,7 +222,7 @@ export const removeGroupAttendee = (
},
)
// — Día a Día: clases y asistencia —
// — Day to day: classes and attendance —
export const getClassesToday = () =>
apiFetch<ClassTodayList>(`/api/v1/classes/today${timeZoneParam()}`)
@@ -251,7 +251,7 @@ export const publicNotifyAbsence = (payload: PublicNotifyAbsence) =>
body: JSON.stringify(payload),
})
// — Analíticas y gestión de riesgo —
// — Analytics and risk management —
export const getGroupAnalytics = (groupId: string) =>
apiFetch<GroupAnalytics>(`/api/v1/groups/${groupId}/analytics`)

View File

@@ -18,11 +18,11 @@ export function normalizePhone(rawPhone: string): string {
}
/**
* Parsea texto CSV con soporte para:
* - Delimitadores automáticos (coma, punto y coma, tabulador)
* - Comillas y comillas escapadas ("")
* Parses CSV text with support for:
* - Automatic delimiters (comma, semicolon, tab)
* - Quotes and escaped quotes ("")
* - UTF-8 BOM
* - Saltos de línea CRLF o LF
* - CRLF or LF line breaks
*/
export function parseCsvContent(content: string): string[][] {
const cleanContent = content.replace(/^\uFEFF/, '');
@@ -30,7 +30,7 @@ export function parseCsvContent(content: string): string[][] {
if (lines.length === 0) return [];
// Detectar delimitador basado en la primera línea
// Detect the delimiter from the first line
const firstLine = lines[0];
const commaCount = (firstLine.match(/,/g) || []).length;
const semicolonCount = (firstLine.match(/;/g) || []).length;
@@ -56,7 +56,7 @@ export function parseCsvContent(content: string): string[][] {
if (char === '"') {
if (insideQuote && line[i + 1] === '"') {
currentCell += '"';
i++; // Saltear comilla escapada
i++; // Skip the escaped quote
} else {
insideQuote = !insideQuote;
}
@@ -75,8 +75,8 @@ export function parseCsvContent(content: string): string[][] {
}
/**
* Parsea un archivo XLSX de Excel extrayendo sharedStrings y sheet1.xml
* utilizando DecompressionStream nativo del navegador sin dependencias externas.
* Parses an Excel XLSX file by extracting sharedStrings and sheet1.xml with
* the browser's native DecompressionStream, without external dependencies.
*/
export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]> {
const view = new DataView(buffer);
@@ -112,7 +112,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]>
entries.set(fileName, new Uint8Array(decompressed));
}
} catch {
// Ignorar archivos que no se puedan descomprimir
// Ignore files that can't be decompressed
}
}
}
@@ -120,7 +120,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]>
offset = dataStart + compressedSize;
}
// Parsear strings compartidos
// Parse the shared strings
const sharedStringsData = entries.get('xl/sharedStrings.xml');
const sharedStrings: string[] = [];
if (sharedStringsData) {
@@ -138,7 +138,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]>
}
}
// Parsear sheet1.xml
// Parse sheet1.xml
const sheetData = entries.get('xl/worksheets/sheet1.xml');
if (!sheetData) {
throw new Error('No se pudo encontrar la hoja de cálculo principal en el archivo Excel.');
@@ -174,7 +174,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]>
}
/**
* Normaliza una matriz 2D en objetos de contactos con detección inteligente de columnas.
* Normalizes a 2D matrix into contact objects with smart column detection.
*/
export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[] {
if (rawRows.length === 0) return [];
@@ -219,7 +219,7 @@ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[]
}
}
// Fallbacks posicionales si no se detectaron encabezados explícitos
// Positional fallbacks when no explicit headers were detected
if (!hasHeader) {
firstNameCol = 0;
lastNameCol = 1;
@@ -230,7 +230,7 @@ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[]
}
if (phoneCol === -1) {
// Buscar la primera columna que parezca un número telefónico
// Look for the first column that looks like a phone number
for (let c = 0; c < (rawRows[1]?.length ?? 0); c++) {
const sample = rawRows[1][c];
if (/^[\d\s+\-()]{6,}$/.test(sample)) {
@@ -291,7 +291,7 @@ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[]
}
/**
* Descarga una plantilla de ejemplo en formato CSV para la carga masiva.
* Downloads a sample template in CSV format for the bulk upload.
*/
export function downloadAttendeeTemplateCsv() {
const csvContent =

View File

@@ -51,18 +51,18 @@ export function formatSchedule(days: readonly WeekDay[], time: string | null): s
return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ')
}
/* Un importe se escribe con el país de la persona: su moneda y su regional
(separadores, posición del símbolo), sin conversión — el importe lo fija
quien creó el grupo y no se toca. El país sale de la zona horaria del
sistema y, si no se conoce, del idioma del browser (ver countryOf). Sin
país conocido se pinta con el símbolo $ genérico, nunca con un código
inventado. La firma acepta moneda y locale para forzarlas (tests, print)
sin tocar los call sites. */
/* An amount is written with the person's country: its currency and its regional
format (separators, symbol position), with no conversion — the amount is set
by whoever created the group and is never touched. The country comes from the
system time zone and, when it's unknown, from the browser language (see
countryOf). With no known country we fall back to the generic $ symbol,
never to an invented code. The signature takes a currency and a locale to
force them (tests, print) without touching the call sites. */
/* La configuración regional del browser manda en cómo se pintan los datos.
Se lee en cada llamada (es un accessor barato) para que un cambio de idioma
del sistema se refleje sin recargar; lo caro es construir el formatter, así
que esos se memorizan por locale/moneda. */
/* The browser's regional settings decide how the data is rendered. It's read
on every call (it's a cheap accessor) so a system language change shows up
without a reload; building the formatter is the expensive part, so those are
memoized per locale/currency. */
type BrowserNavigator = { language?: string; languages?: readonly string[] }
function browserLocale(): string | undefined {
@@ -78,14 +78,14 @@ export function formatPrice(
locale?: string,
): string {
if (price == null) return '—'
// Importes enteros sin decimales ($50.000); con centavos se respetan.
// Whole amounts with no decimals ($50.000); cents are kept when present.
const hasCents = !Number.isInteger(price)
const browser = locale ?? browserLocale()
const country = countryOf(browser)
const resolvedCurrency = currency ?? currencyForRegion(country)
// Los separadores y la posición del símbolo siguen al país: un browser en
// inglés en Argentina tiene que ver $50.000, no ARS 50,000. Con la locale
// pasada explícita no se toca nada (tests, print).
// Separators and symbol position follow the country: an English browser in
// Argentina has to see $50.000, not ARS 50,000. When the locale is passed
// explicitly nothing is touched (tests, print).
const resolved = locale === undefined ? (localeForRegion(country) ?? browser) : browser
const key = `${resolved ?? ''}|${resolvedCurrency ?? '$'}|${hasCents ? 'c' : 'i'}`
@@ -103,27 +103,28 @@ export function formatPrice(
return tidyCurrencySpacing(formatter.format(price))
}
/* Intl separa el símbolo de la moneda con un espacio duro: "$ 50.000" se lee
como dos tokens sueltos. Lo quitamos solo cuando separa símbolo de número;
entre dígitos y código ("50.000 ARS") el no-break space evita el corte. */
/* Intl separates the currency symbol with a hard space: "$ 50.000" reads as two
loose tokens. We strip it only when it separates symbol from number; between
digits and the code ("50.000 ARS") the non-breaking space prevents the
break. */
const SYMBOL_GAP = /([^\p{L}\p{N}])\u00A0/gu
function tidyCurrencySpacing(value: string): string {
return value.replace(SYMBOL_GAP, '$1')
}
/* ── Teléfonos ──────────────────────────────────────────────────────────────
/* ── Phones ─────────────────────────────────────────────────────────────────
Presentación, nunca persistencia: los links wa.me siguen usando los dígitos
crudos. El formato sale de la región del propio número cuando su prefijo de
país es reconocible; si el número es nacional, manda la región del browser
(y si esa región no la conocemos, la de la app: AR). Si nada encaja se cae
a E.164 (+331234567890) o al valor original, siempre preferible a un número
inventado. */
Presentation, never persistence: the wa.me links still use the raw digits.
The format comes from the region of the number itself when its country
prefix is recognizable; if the number is national, the browser's region wins
(and if we don't know that region, the app's: AR). If nothing matches we fall
back to E.164 (+331234567890) or to the original value, always preferable to
an invented number. */
type PhoneRegion = 'AR' | 'US' | 'ES' | 'MX'
/** Prefijos de país que sabemos agrupar. */
/** Country prefixes we know how to group. */
const COUNTRY_CALLING_CODES: { region: PhoneRegion; code: string }[] = [
{ region: 'AR', code: '54' },
{ region: 'ES', code: '34' },
@@ -141,15 +142,15 @@ export function formatPhoneDisplay(
const hasPlus = raw.startsWith('+')
let digits = raw.replace(/\D/g, '')
// "0054…" es el mismo indicio internacional que "+54…".
// "0054…" is the same international hint as "+54…".
const hasDoubleZero = !hasPlus && raw.startsWith('00')
if (hasDoubleZero) digits = digits.slice(2)
if (digits.length < 6) return raw
const withCallingCode = formatWithCallingCode(digits)
if (withCallingCode) return withCallingCode
// Número de una región que no agrupamos: al menos se separa en bloques de a
// 3 para que no se lea como un muro de dígitos. El `+` se conserva si lo había.
// Number from a region we don't group: at least it's split into groups of 3
// so it doesn't read like a wall of digits. The `+` is kept if there was one.
if (hasPlus || hasDoubleZero) return `+${groupByThrees(digits)}`
return (
@@ -158,7 +159,7 @@ export function formatPhoneDisplay(
)
}
/** Bloques de a 3 desde la derecha: el sobrante de 1-2 dígitos queda a la izquierda. */
/** Groups of 3 from the right: the leftover 1-2 digits stay on the left. */
function groupByThrees(digits: string): string {
const groups: string[] = []
let rest = digits
@@ -170,7 +171,7 @@ function groupByThrees(digits: string): string {
return groups.join(' ')
}
/** Prueba el prefijo de país solo si lo que sigue encaja en sus reglas. */
/** Tries the country prefix only if what follows fits its rules. */
function formatWithCallingCode(digits: string): string | null {
for (const { region, code } of COUNTRY_CALLING_CODES) {
if (!digits.startsWith(code)) continue
@@ -180,12 +181,12 @@ function formatWithCallingCode(digits: string): string | null {
return null
}
/** Región ISO → región con reglas propias. CA comparte NANP con US. */
/** ISO region → region with its own rules. CA shares NANP with US. */
function appRegion(region: string | undefined): PhoneRegion {
if (region === 'US' || region === 'CA') return 'US'
if (region === 'ES') return 'ES'
if (region === 'MX') return 'MX'
// Sin región reconocible seguimos siendo una app de Argentina.
// With no recognizable region we are still an Argentine app.
return 'AR'
}
@@ -210,12 +211,12 @@ function formatArNational(digits: string, withCountry: boolean): string | null {
let national = digits
let isMobile = false
// Móvil argentino: 9 + 10 dígitos nacionales.
// Argentine mobile: 9 + 10 national digits.
if (national.length === 11 && national.startsWith('9')) {
national = national.slice(1)
isMobile = true
}
// 0 de trunk nacional: además implica que el número es argentino.
// National trunk 0: it also implies the number is Argentine.
if (national.startsWith('0') && national.length >= 9) {
national = national.slice(1)
withCountry = true
@@ -229,8 +230,8 @@ function formatArNational(digits: string, withCountry: boolean): string | null {
function groupArNational(digits: string): string {
if (digits.length === 10) {
// 11 es el único área de 2 dígitos (Gran Buenos Aires); el resto se
// agrupa 4-2-4, que es el patrón de las áreas de 4 dígitos.
// 11 is the only 2-digit area code (Gran Buenos Aires); the rest group
// 4-2-4, which is the pattern for 4-digit area codes.
return digits.startsWith('11')
? `${digits.slice(0, 2)} ${digits.slice(2, 6)}-${digits.slice(6)}`
: `${digits.slice(0, 4)} ${digits.slice(4, 6)}-${digits.slice(6)}`
@@ -240,31 +241,31 @@ function groupArNational(digits: string): string {
return digits
}
/** NANP (US/CA): 10 dígitos con área e intercambio que arrancan en 2–9. */
/** NANP (US/CA): 10 digits with area and exchange starting in 2–9. */
function formatUsNational(digits: string): string | null {
if (digits.length === 11 && digits.startsWith('1')) digits = digits.slice(1)
if (digits.length !== 10) return null
if (digits[0] === '0' || digits[0] === '1' || digits[3] === '0' || digits[3] === '1') return null
// Convención doméstica: el "1" del país no se escribe.
// Domestic convention: the country "1" is not written.
return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`
}
/** España: 9 dígitos (móvil 6/7, fijo 8/9) agrupados 3-2-2-2. */
/** Spain: 9 digits (mobile 6/7, landline 8/9) grouped 3-2-2-2. */
function formatEsNational(digits: string, withCountry: boolean): string | null {
if (digits.length !== 9 || !'6789'.includes(digits[0])) return null
const local = `${digits.slice(0, 3)} ${digits.slice(3, 5)} ${digits.slice(5, 7)} ${digits.slice(7)}`
return withCountry ? `+34 ${local}` : local
}
/** México: 10 dígitos agrupados 2-4-4. */
/** Mexico: 10 digits grouped 2-4-4. */
function formatMxNational(digits: string, withCountry: boolean): string | null {
if (digits.length !== 10 || digits[0] === '0' || digits[0] === '1') return null
const local = `${digits.slice(0, 2)} ${digits.slice(2, 6)} ${digits.slice(6)}`
return withCountry ? `+52 ${local}` : local
}
// El vencimiento se cuenta como frase ("Vence el día 10 de cada mes") en vez
// de "Vence día 10": se lee como una promesa, no como un dato suelto.
// The due date is worded as a phrase ("Vence el día 10 de cada mes") instead of
// "Vence día 10": it reads as a promise, not as a bare fact.
export function formatBillingMeta(
billingType: BillingType | null,
dueDay: number | null,

View File

@@ -1,11 +1,11 @@
/* 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.
/* "Immersive" routes: the ones that build their own navigation bar with
`LargeTitle` (a large title that collapses) and therefore don't show the
global header with logo + theme toggle + 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. */
The pattern is resolved by hand and not with `matchRoute` because the two
routes carry params (`matchRoute` requires them) and because child routes are
NOT immersive even when they share a prefix: `/groups/:id/attendees/new`
still uses the global header. */
const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
['groups', ':id'],
@@ -13,9 +13,9 @@ const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
['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. */
/* Static routes that sit where a param would go. Without this list
`/groups/new` (create group) would be taken for a group detail page and would
lose the global header. */
const STATIC_SEGMENTS: ReadonlySet<string> = new Set(['new'])
export function isImmersiveRoute(pathname: string) {

View File

@@ -1,24 +1,24 @@
/* De dónde es la persona y cómo se le escriben los números.
/* Where the person is from and how their numbers get written.
El idioma del browser dice en qué idioma se está, no en qué país se está:
con "en-US" a alguien en Argentina lo trata como estadounidense, y con
"es-419" no dice ningún país. La zona horaria —que sí expone el sistema—
es la señal del país real; el idioma solo define cuando la zona no se
conoce. Con el país resuelto salen la moneda (REGION_CURRENCY) y la
regional con la que se formatea (REGION_LOCALE), para que un browser en
inglés en Argentina vea $50.000 y no ARS 50,000.
The browser language says what language you're in, not what country you're
in: with "en-US" it treats someone in Argentina as American, and with
"es-419" it says no country at all. The time zone — which the system does
expose — is the signal for the real country; the language only decides when
the time zone is unknown. With the country resolved you get the currency
(REGION_CURRENCY) and the locale it's formatted with (REGION_LOCALE), so an
English browser in Argentina sees $50.000 and not ARS 50,000.
Estos mapas son dato a mano (Intl no expone región → moneda ni región →
locale). Solo definen cómo se PINTA un importe: el valor persistido no
cambia ni se convierte. Si el país no está en ninguno, formatPrice cae al
símbolo $ genérico. */
These maps are hand-written data (Intl exposes neither region → currency nor
region → locale). They only define how an amount is RENDERED: the persisted
value doesn't change and isn't converted. If the country is in neither map,
formatPrice falls back to the generic $ symbol. */
export const REGION_CURRENCY: Record<string, string> = {
// Norteamérica
// North America
CA: 'CAD',
US: 'USD',
// Latinoamérica y Caribe
// Latin America and the Caribbean
AR: 'ARS',
BO: 'BOB',
BR: 'BRL',
@@ -40,7 +40,7 @@ export const REGION_CURRENCY: Record<string, string> = {
UY: 'UYU',
VE: 'VES',
// Zona euro
// Eurozone
AT: 'EUR',
BE: 'EUR',
HR: 'EUR',
@@ -62,7 +62,7 @@ export const REGION_CURRENCY: Record<string, string> = {
SI: 'EUR',
ES: 'EUR',
// Fuera de la zona euro
// Outside the eurozone
CH: 'CHF',
GB: 'GBP',
CZ: 'CZK',
@@ -75,15 +75,15 @@ export const REGION_CURRENCY: Record<string, string> = {
UA: 'UAH',
}
/** Regional con la que se formatea para cada país. México y Argentina usan
separadores distintos (1,234.56 vs 1.234,56), así que el locale va con el
país y no solo con el idioma. */
/** Locale each country is formatted with. Mexico and Argentina use different
separators (1,234.56 vs 1.234,56), so the locale follows the country and not
just the language. */
export const REGION_LOCALE: Record<string, string> = {
// Norteamérica
// North America
CA: 'en-CA',
US: 'en-US',
// Latinoamérica y Caribe
// Latin America and the Caribbean
AR: 'es-AR',
BO: 'es-BO',
BR: 'pt-BR',
@@ -105,7 +105,7 @@ export const REGION_LOCALE: Record<string, string> = {
UY: 'es-UY',
VE: 'es-VE',
// Zona euro
// Eurozone
AT: 'de-AT',
BE: 'nl-BE',
HR: 'hr-HR',
@@ -127,7 +127,7 @@ export const REGION_LOCALE: Record<string, string> = {
SI: 'sl-SI',
ES: 'es-ES',
// Fuera de la zona euro
// Outside the eurozone
CH: 'de-CH',
GB: 'en-GB',
CZ: 'cs-CZ',
@@ -140,16 +140,16 @@ export const REGION_LOCALE: Record<string, string> = {
UA: 'uk-UA',
}
/* Zona horaria IANA → región ISO 3166-1 alpha-2.
/* IANA time zone → ISO 3166-1 alpha-2 region.
Cobertura: las zonas de los países de arriba, agrupadas por prefijo
(America/Argentina/*) o por la ciudad en la zona (Sao_Paulo). Cubre las
zonas principales; una zona desconocida cae al país del idioma. */
Coverage: the time zones of the countries above, grouped by prefix
(America/Argentina/*) or by the city in the zone (Sao_Paulo). It covers the
main zones; an unknown zone falls back to the country of the language. */
export const TIMEZONE_REGION: Record<string, string> = {
// ── Latinoamérica ─────────────────────────────────────────────────────────
// ── Latin America ─────────────────────────────────────────────────────────
'America/Argentina/': 'AR',
// Chromium/ICU reporta en la forma legacy (sin el prefijo "Argentina/") las
// zonas argentinas más comunes: America/Argentina/Buenos_Aires → America/Buenos_Aires.
// Chromium/ICU reports the most common Argentine zones in the legacy form
// (without the "Argentina/" prefix): America/Argentina/Buenos_Aires → America/Buenos_Aires.
'America/Buenos_Aires': 'AR',
'America/Catamarca': 'AR',
'America/Cordoba': 'AR',
@@ -182,7 +182,7 @@ export const TIMEZONE_REGION: Record<string, string> = {
'America/Santo_Domingo': 'DO',
'America/Puerto_Rico': 'PR',
// ── Norteamérica ─────────────────────────────────────────────────────────
// ── North America ─────────────────────────────────────────────────────────
'America/New_York': 'US',
'America/Detroit': 'US',
'America/Chicago': 'US',
@@ -199,7 +199,7 @@ export const TIMEZONE_REGION: Record<string, string> = {
'America/Regina': 'CA',
'America/St_Johns': 'CA',
// ── Europa ───────────────────────────────────────────────────────────────
// ── Europe ───────────────────────────────────────────────────────────────
'Europe/Madrid': 'ES',
'Atlantic/Canary': 'ES',
'Atlantic/Faeroe': 'ES',
@@ -244,8 +244,8 @@ export function regionForTimezone(timezone: string | undefined): string | undefi
return prefix ? TIMEZONE_REGION[prefix] : undefined
}
/** Región del locale (es-MX → MX). Un locale sin país se maximiza, pero solo
como último recurso: countryOf prefiere la zona horaria. */
/** Region of the locale (es-MX → MX). A locale without a country is
maximized, but only as a last resort: countryOf prefers the time zone. */
export function regionOf(locale: string | undefined): string | undefined {
if (!locale || typeof Intl.Locale === 'undefined') return undefined
try {
@@ -255,9 +255,9 @@ export function regionOf(locale: string | undefined): string | undefined {
}
}
/** País de la persona: el de la zona horaria, y si no se conoce, el del
idioma. `en` sin país no se maximiza a US a propósito: un usuario en
México con el browser en inglés caería en dólares. */
/** The person's country: the one from the time zone and, when unknown, the one
from the language. A bare `en` is deliberately not maximized to US: a user in
Mexico with an English browser would end up in dollars. */
export function countryOf(locale: string | undefined): string | undefined {
return regionForTimezone(browserTimezone()) ?? regionOf(locale)
}