Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/diagramas/whiteboard-c4.html
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ <h1>Pizarra: componentes y funciones</h1>

<svg viewBox="0 0 960 660" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="wb-title wb-desc">
<title id="wb-title">Código de la feature de pizarra</title>
<desc id="wb-desc">Whiteboard carga la escena con useWhiteboard y recién entonces renderiza WhiteboardCanvas (Excalidraw); cada onChange pasa por toStoredScene y vuelve al hook, que guarda con debounce de 1 s y flush al salir, validando con isValidScene. El hook usa whiteboardRepositoryFactory: con sesión, la server action saveWhiteboard revalida y hace upsert en prisma.whiteboard; como invitado, localStorage capo-whiteboard. El botón de fondo de WhiteboardCanvas setea la preferencia compartida usePageSurface, que aplica PageContainer con allowSurface.</desc>
<desc id="wb-desc">Whiteboard carga la escena con useWhiteboard y recién entonces renderiza WhiteboardCanvas (Excalidraw); cada onChange pasa por toStoredScene y vuelve al hook, que guarda con debounce de 1 s y flush al salir, validando con isValidScene. WhiteboardToolbarSlot mete botones propios en la barra de Excalidraw por portal; el de actor inserta stickmanSkeleton. El hook usa whiteboardRepositoryFactory: con sesión, la server action saveWhiteboard revalida y hace upsert en prisma.whiteboard; como invitado, localStorage capo-whiteboard. El botón de fondo de WhiteboardCanvas setea la preferencia compartida usePageSurface, que aplica PageContainer con allowSurface.</desc>

<defs>
<style>@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&amp;family=Geist:wght@400;500;600&amp;family=Geist+Mono:wght@400;500;600&amp;display=swap');</style>
Expand Down Expand Up @@ -137,7 +137,7 @@ <h1>Pizarra: componentes y funciones</h1>
<text x="494" y="126" fill="#2d3142" font-size="11" font-weight="600" font-family="'Geist', sans-serif" text-anchor="middle">WhiteboardCanvas</text>
<line x1="398" y1="134" x2="590" y2="134" stroke="rgba(45,49,66,0.15)" stroke-width="0.8"/>
<text x="400" y="148" fill="#4f5d75" font-size="9" font-family="'Geist Mono', monospace">Excalidraw · tema · idioma</text>
<text x="400" y="160" fill="#4f5d75" font-size="9" font-family="'Geist Mono', monospace">sin imágenes · botón exportar</text>
<text x="400" y="160" fill="#4f5d75" font-size="9" font-family="'Geist Mono', monospace">slot barra: + actor (stickman)</text>

<!-- toStoredScene -->
<rect x="684" y="92" width="232" height="76" rx="6" fill="#f5f5f5"/>
Expand Down
4 changes: 2 additions & 2 deletions docs/diagramas/whiteboard-c4.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions docs/features/crear-tablero.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,4 @@ Namespace `dashboard.*` en `es.json` / `en.json`:
- 2026-09-28 — Bug: el paso tema desbordaba el modal (~29 temas + `ThemePreview`). Fix: `ThemeSwatches` tiene la prop `paginated`, que cambia la grilla completa por el subcomponente `ThemeSwatchesPager` (12 temas por página, botones Atrás/Siguiente, arranca en la página del tema elegido). El modal crece a `md:max-w-2xl` y el `DialogContent` tiene `max-h-[90dvh] overflow-y-auto` de respaldo. Settings sigue con la grilla completa.
- 2026-09-28 — Tope global de columnas: `MAX_COLUMNS = 5` en `taskColumn.ts`, aplicado al crear (`createBoard`, botón "Agregar columna" del wizard), al agregar desde el tablero (`addNewTaskColumn`, `AddNewColumnForm`) y en el server (`saveTaskBoard`). En `saveTaskBoard` solo se rechaza que el tablero crezca por encima del tope: los tableros previos con más columnas se siguen guardando.
- 2026-09-28 — `MAX_BOARDS` pasa de constante local en `createBoard` a `dashboard/model/board.ts`; `board_limit_error` interpola `{{max}}`.
- 2026-10-01 — El botón "Nuevo tablero" se muda al header del dashboard (`Header` lo monta si `whereUserIs === DASHBOARD`) como un "+" icon-only (`aria-label`/`title` = `create_board`). El estado vacío conserva su botón con texto "Crear primer tablero".
1 change: 1 addition & 0 deletions docs/features/limbo.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,4 @@ y `task_notes.save_toast`.
y: 0 })}` (mobile no tiene lienzo ni pan para calcular un punto), pero esa
posición es la que usa `LimboCanvas` en desktop. Fix: `getSpawnPoint` en
mobile ahora devuelve el centro del canvas (`CANVAS_WIDTH/2, CANVAS_HEIGHT/2`).
- **Bug — la task recién creada parpadeaba con sesión (2026-10-01).** Desaparecía y volvía. Causa raíz: cada `LimboTask` usa `useLimboQuery`; al montarse la card nueva, el query (stale) se re-fetcheaba mientras el save (server action) seguía en vuelo y traía el limbo previo, pisando el update optimista. En invitado no pasaba porque el save a localStorage es instantáneo. Fix: la mutación lleva `mutationKey` y el query no refetchea al montar con un guardado en curso; `onSettled` solo invalida si es el último guardado pendiente (misma carrera con creaciones seguidas). Test en `useLimboQuery.test.tsx`.
14 changes: 12 additions & 2 deletions docs/features/whiteboard.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ UI de Excalidraw (`ui/WhiteboardCanvas.tsx`):
- "Exportar imagen": botón abajo a la derecha, junto al "?" (md+). Abre el diálogo nativo con
`updateScene({ appState: { openDialog: { name: 'imageExport' } } })`. En mobile la barra
inferior de Excalidraw lo taparía, así que ahí queda el menú (que solo tiene esa opción).
- Items propios en la barra de herramientas: `ui/WhiteboardToolbarSlot.tsx` agrega un
`div.wb-toolbar-slot` al final de la fila `.App-toolbar .Stack_horizontal` y renderiza sus
`children` ahí con `createPortal`: quedan dentro de la isla (mismo fondo, centrado y subida al
header). Un `MutationObserver` lo re-engancha cuando Excalidraw vuelve a montar la barra
(modo vista, diálogo de links). Los botones usan las clases `ToolIcon ToolIcon_type_button`
de Excalidraw para verse nativos. Solo md+: en mobile la barra es otra (`MobileMenu`).
- Los ajustes a la UI de Excalidraw que no tienen prop viven en `ui/WhiteboardCanvas.module.css`
(selectores `:global` sobre sus clases internas):
- Ocultos: botón de librería, "Más herramientas" y, en md+, el menú.
Expand Down Expand Up @@ -111,7 +117,7 @@ UI de Excalidraw (`ui/WhiteboardCanvas.tsx`):
## i18next

- `menu.whiteboard`: "Pizarra" / "Whiteboard".
- `whiteboard.export_image`, `whiteboard.toggle_background`, `whiteboard.too_large_toast`, `whiteboard.save_error_toast`.
- `whiteboard.add_stickman`, `whiteboard.export_image`, `whiteboard.toggle_background`, `whiteboard.too_large_toast`, `whiteboard.save_error_toast`.
- Archivos: `src/shared/i18n/es.json` y `en.json`.
- Los textos de Excalidraw usan su propio i18n: `langCode` `es-ES` o `en` según
`i18n.language`.
Expand All @@ -131,8 +137,12 @@ UI de Excalidraw (`ui/WhiteboardCanvas.tsx`):
- 2026-09-28 — El export se sacó del menú hamburguesa a un botón propio: Excalidraw no deja
agregar botones a su barra de herramientas. Se renderiza como `children` de `<Excalidraw>`
(queda dentro de su capa de UI) y reusa la clase `help-icon` para verse igual que el "?".
- 2026-10-01 — Items propios dentro de la barra de herramientas (primero: stick-man para casos
de uso). Excalidraw 0.18 no tiene slot ahí; se descartó una isla aparte pegada a la barra
(difícil de alinear: la barra está centrada y con `translateY`) a favor de un portal dentro
de su fila.
- Límite conocido: el recorte de la UI de Excalidraw (librería, "Más herramientas", menú,
barra en el header, margen del panel) depende de sus clases CSS internas. Al actualizar
barra en el header, margen del panel, slot de la barra) depende de sus clases CSS internas. Al actualizar
`@excalidraw/excalidraw`, revisar que sigan existiendo.
- Límite conocido: el flush de `beforeunload` con sesión es best-effort (la server action
puede no terminar si la pestaña se cierra). En invitado es síncrono.
Expand Down
2 changes: 2 additions & 0 deletions web-app/app/_components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { USER_IS_IN } from '@/shared/ui/organisms/userIsIn'
import { Notes } from '@/features/notes'
import { CreateBoardDialog } from '@/features/dashboard'
import { useTypeOfView } from '@/shared/preferences/view-mode'
import { cn } from '@/shared/lib/utils'
import { HeaderNav } from './HeaderNav'
Expand All @@ -25,6 +26,7 @@ export function Header({ title, whereUserIs, showBoardNavigation = true, textCol
<header className='w-full h-20 px-6 md:px-11 flex justify-between items-center'>
<h1 className={cn('text-xl font-medium', whereUserIs === USER_IS_IN.BOARD && 'opacity-60')}>{title}</h1>
<div className='flex gap-2 items-center'>
{whereUserIs === USER_IS_IN.DASHBOARD && <CreateBoardDialog textColor={textColor} />}
{showNotes && <Notes textColor={textColor} />}
<HeaderNav whereUserIs={whereUserIs} showBoardLinks={showBoardLinks} textColor={textColor} />
</div>
Expand Down
1 change: 1 addition & 0 deletions web-app/src/features/dashboard/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export type { Board } from './model/board'
export { default as Dashboard } from './ui/Dashboard'
export { default as CreateBoardDialog } from './ui/CreateBoardDialog'
export { CanvasSelection } from './ui/CanvasSelection'
export { useDashboardQuery } from './hooks/useDashboardQuery'
23 changes: 18 additions & 5 deletions web-app/src/features/dashboard/ui/CreateBoardDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ import { LazyMotion, domMax, m, AnimatePresence, useReducedMotion } from 'motion

interface CreateBoardDialogProps {
hasNoBoards?: boolean
/** Color del "+" del header (cambia con page-surface) */
textColor?: string
}

const SETUP_STEPS = ['name', 'columns', 'theme', 'canvas'] as const
Expand All @@ -48,7 +50,7 @@ const initialState = (themeId: string) => ({
cardCanvas: Math.floor(Math.random() * HERO_COUNT),
})

function CreateBoardDialog({ hasNoBoards = false }: CreateBoardDialogProps) {
function CreateBoardDialog({ hasNoBoards = false, textColor }: CreateBoardDialogProps) {
const { t } = useTranslation()
const colors = useTheme()
const { createAnEmptyBoard } = useDashboardQuery()
Expand Down Expand Up @@ -89,10 +91,21 @@ function CreateBoardDialog({ hasNoBoards = false }: CreateBoardDialogProps) {
return (
<Dialog open={state.isOpen} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant='secondary' className='flex items-center'>
<PlusIcon className='mr-2' />{' '}
{hasNoBoards ? t('dashboard.create_first_board') : t('dashboard.create_board')}
</Button>
{hasNoBoards ? (
<Button variant='secondary' className='flex items-center'>
<PlusIcon className='mr-2' /> {t('dashboard.create_first_board')}
</Button>
) : (
<Button
variant='ghost'
size='icon'
className={textColor}
aria-label={t('dashboard.create_board')}
title={t('dashboard.create_board')}
>
<PlusIcon />
</Button>
)}
</DialogTrigger>
<DialogContent
className={cn(
Expand Down
6 changes: 0 additions & 6 deletions web-app/src/features/dashboard/ui/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,6 @@ function Dashboard() {
{boards.map((board) => (
<BoardCard board={board} key={board.id} />
))}

{!hasNoBoards && (
<li className='self-end '>
<CreateBoardDialog />
</li>
)}
</ul>

<SharedWithMe />
Expand Down
35 changes: 35 additions & 0 deletions web-app/src/features/limbo/hooks/useLimboQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,38 @@ describe('useLimboQuery — carrera contra la carga inicial', () => {
})
})
})

describe('useLimboQuery — refetch durante un guardado', () => {
it('montar otro observer mientras se guarda no trae el limbo viejo del server (parpadeo)', async () => {
const oldLimbo: Limbo = []
vi.mocked(fetchLimbo).mockClear().mockResolvedValue(oldLimbo)
let resolveSave: () => void = () => {}
vi.mocked(saveLimboTasks).mockReturnValue(new Promise((r) => (resolveSave = r)))
useBoardId.setState({ board_id: 'b1' })

const queryClient = new QueryClient()
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const { result } = renderHook(() => useLimboQuery(), { wrapper })
await vi.waitFor(() => expect(fetchLimbo).toHaveBeenCalledTimes(1))
await vi.waitFor(() => expect(result.current.isLoading).toBe(false))

const task = { id: 'new-1', descriptionText: 'nueva' } as taskModel
act(() => {
result.current.updateLimbo(addTaskToLimbo({ limbo: [], task, x: 0, y: 0 }))
})
await vi.waitFor(() => expect(result.current.limbo).toHaveLength(1))

// La card nueva se monta y usa el mismo hook (como LimboTask).
renderHook(() => useLimboQuery(), { wrapper })
await act(async () => {
await new Promise((r) => setTimeout(r, 10))
})

expect(fetchLimbo).toHaveBeenCalledTimes(1)
expect(result.current.limbo).toHaveLength(1)

await act(async () => resolveSave())
})
})
6 changes: 6 additions & 0 deletions web-app/src/features/limbo/hooks/useLimboQuery.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Limbo, emptyLimbo } from '../model/limbo'
import { fetchLimbo, saveLimboTasks } from '../api/repository'

const limboQueryKey = ['limbo']
const saveLimboKey = ['save-limbo']

export const useLimboQuery = () => {
const { session } = useSession()
Expand All @@ -17,11 +18,14 @@ export const useLimboQuery = () => {
queryKey: fullQueryKey,
queryFn: () => fetchLimbo(session, boardId),
enabled: !!boardId,
// Como cada LimboTask usa este hook, al montarse la card recién creada, el refetch traería del server el limbo previo al guardado en curso y la card parpadearía.
refetchOnMount: () => queryClient.isMutating({ mutationKey: saveLimboKey }) === 0,
})

const limbo = data ?? emptyLimbo

const { mutate: rawUpdateLimbo, isPending: isSaving } = useMutation({
mutationKey: saveLimboKey,
mutationFn: (newLimbo: Limbo) => saveLimboTasks({ session, tasks: newLimbo, boardId }),
onMutate: async (newLimbo: Limbo) => {
await queryClient.cancelQueries({ queryKey: fullQueryKey })
Expand All @@ -35,6 +39,8 @@ export const useLimboQuery = () => {
}
},
onSettled: () => {
// Con otro guardado en vuelo, el refetch pisaría su update optimista: invalida el último.
if (queryClient.isMutating({ mutationKey: saveLimboKey }) > 1) return
queryClient.invalidateQueries({ queryKey: fullQueryKey })
},
})
Expand Down
36 changes: 36 additions & 0 deletions web-app/src/features/whiteboard/model/stickman.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { ExcalidrawElementSkeleton } from '@excalidraw/excalidraw/data/transform'

const HEAD = 30
const BODY = 40
const ARM = 25
const LEG = 30

const line = (x: number, y: number, dx: number, dy: number) => ({
type: 'line' as const,
x,
y,
points: [
[0, 0],
[dx, dy],
],
})

/** Actor UML ("stick-man") de ~50×100 centrado en (cx, cy), agrupado bajo `groupId`. */
export function stickmanSkeleton(
cx: number,
cy: number,
groupId: string
): ExcalidrawElementSkeleton[] {
const top = cy - (HEAD + BODY + LEG) / 2
const neck = top + HEAD
const hip = neck + BODY

// `points` es LocalPoint (tupla con brand) en Excalidraw: el cast evita importar @excalidraw/math.
return [
{ type: 'ellipse', x: cx - HEAD / 2, y: top, width: HEAD, height: HEAD },
line(cx, neck, 0, BODY),
line(cx - ARM, neck + BODY / 3, ARM * 2, 0),
line(cx, hip, -LEG / 1.5, LEG),
line(cx, hip, LEG / 1.5, LEG),
].map((el) => ({ ...el, groupIds: [groupId] })) as ExcalidrawElementSkeleton[]
}
Loading
Loading