From 63b95fb834d42c37289931de95256d6bce27d6e6 Mon Sep 17 00:00:00 2001 From: Alexis Date: Tue, 28 Apr 2026 12:02:11 +0200 Subject: [PATCH] feat: enhance ExportDropdown and PublicationsTable components for improved export functionality - Update ExportDropdown to support selected item count and use new icons for formats - Refactor PublicationsTable to include tri-state checkbox for selection management and year filtering - Modify DashboardPage to handle selected publication IDs for export - Adjust API service to support selective export based on publication IDs --- .../components/dashboard/ExportDropdown.jsx | 23 +- .../dashboard/PublicationsTable.jsx | 530 +++++++++++++++--- frontend/src/components/ui/Icons.jsx | 18 + frontend/src/pages/DashboardPage.jsx | 23 +- frontend/src/services/api.js | 35 +- frontend/vite.config.js | 2 +- 6 files changed, 535 insertions(+), 96 deletions(-) diff --git a/frontend/src/components/dashboard/ExportDropdown.jsx b/frontend/src/components/dashboard/ExportDropdown.jsx index cccf24b..3cbe68e 100644 --- a/frontend/src/components/dashboard/ExportDropdown.jsx +++ b/frontend/src/components/dashboard/ExportDropdown.jsx @@ -1,20 +1,22 @@ import { useEffect, useRef, useState } from "react"; import { ChevronDownIcon, + DocumentIcon, DownloadIcon, + PackageIcon, } from "../ui/Icons"; import { Spinner } from "../ui/Spinner"; const FORMATS = [ { format: "xml", - icon: "📄", + icon: , label: "SWORD XML", desc: "Metadatos en formato Atom", }, { format: "zip", - icon: "📦", + icon: , label: "Paquete ZIP", desc: "XML + ficheros adjuntos", }, @@ -28,7 +30,11 @@ const FORMATS = [ * `exportingFormat` (optional) lets the parent keep the button in a loading * state between clicks (e.g. while waiting for the backend blob). */ -export function ExportDropdown({ onExport, exportingFormat = null }) { +export function ExportDropdown({ + onExport, + exportingFormat = null, + selectedCount = 0, +}) { const [open, setOpen] = useState(false); const rootRef = useRef(null); @@ -43,12 +49,17 @@ export function ExportDropdown({ onExport, exportingFormat = null }) { }, []); const isBusy = Boolean(exportingFormat); + const hasSelection = selectedCount > 0; function handlePick(format) { setOpen(false); onExport(format); } + const idleLabel = hasSelection + ? `Exportar seleccionadas (${selectedCount})` + : "Exportar todas"; + return (
@@ -77,9 +88,7 @@ export function ExportDropdown({ onExport, exportingFormat = null }) { : "" }`} > - - {icon} - + {icon}
{label} diff --git a/frontend/src/components/dashboard/PublicationsTable.jsx b/frontend/src/components/dashboard/PublicationsTable.jsx index 2a56fb2..89e4ac7 100644 --- a/frontend/src/components/dashboard/PublicationsTable.jsx +++ b/frontend/src/components/dashboard/PublicationsTable.jsx @@ -1,5 +1,5 @@ -import { useMemo, useState } from "react"; -import { AlertIcon, SearchIcon } from "../ui/Icons"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { AlertIcon, ChevronDownIcon, FilterIcon, SearchIcon } from "../ui/Icons"; import { Spinner } from "../ui/Spinner"; import { Badge } from "../ui/Badge"; @@ -11,6 +11,9 @@ const COLUMNS = [ { key: "type", label: "Tipo" }, ]; +const PAGE_SIZE = 15; +const EMPTY_SELECTION = new Set(); + function SortIcon({ active, direction }) { const path = direction === "asc" || !active ? "M6 8L3 5h6z" : "M6 4l3 3H3z"; @@ -40,67 +43,329 @@ function sortPublications(rows, key, direction) { } /** - * Publications table. Owns only UI-state (filter + sort). Data, loading and - * error states are driven by the parent page so retries and toasts can be - * handled in one place. + * Tri-state checkbox. We can't express `indeterminate` via React props, so + * we set it imperatively on the DOM node whenever the flag changes. + */ +function TriStateCheckbox({ checked, indeterminate = false, onChange, ariaLabel }) { + const ref = useRef(null); + useEffect(() => { + if (ref.current) ref.current.indeterminate = indeterminate && !checked; + }, [indeterminate, checked]); + return ( + + ); +} + +/** + * Publications table. UI-state (filter, sort, pagination) lives here; the + * *selection* set is lifted to the parent so export / bulk actions can see + * it. Data, loading and error states are also driven by the parent so + * retries and toasts can be handled in one place. + * + * Selection semantics: + * - The master checkbox toggles the WHOLE currently-filtered set (not + * just the visible page). This matches the user mental model of + * "filtrar por 2024 → marcar todas de 2024". + * - Selection survives filter changes: the stored IDs remain even if + * those rows are no longer visible. */ export function PublicationsTable({ publications, loading = false, error = null, onRetry, + selectedIds = EMPTY_SELECTION, + onSelectedIdsChange, }) { const [filter, setFilter] = useState(""); const [sortKey, setSortKey] = useState("publication_year"); const [sortDir, setSortDir] = useState("desc"); + const [page, setPage] = useState(1); + + const [filtersOpen, setFiltersOpen] = useState(false); + const [yearFrom, setYearFrom] = useState(""); + const [yearTo, setYearTo] = useState(""); + + const availableYears = useMemo(() => { + const years = publications + .map((p) => p.publication_year) + .filter((y) => typeof y === "number" && Number.isFinite(y)); + if (years.length === 0) return []; + const min = Math.min(...years); + const max = Math.max(...years, new Date().getFullYear()); + const list = []; + for (let y = max; y >= min; y -= 1) list.push(y); + return list; + }, [publications]); + + const hasYearFilter = yearFrom !== "" || yearTo !== ""; + + useEffect(() => { + if (availableYears.length === 0) return; + if (yearFrom && !availableYears.includes(Number(yearFrom))) setYearFrom(""); + if (yearTo && !availableYears.includes(Number(yearTo))) setYearTo(""); + }, [availableYears, yearFrom, yearTo]); const filtered = useMemo(() => { const needle = filter.trim().toLowerCase(); - const rows = needle - ? publications.filter( - (p) => - (p.title ?? "").toLowerCase().includes(needle) || - (p.journal ?? "").toLowerCase().includes(needle) || - String(p.publication_year ?? "").includes(needle) || - (p.doi ?? "").toLowerCase().includes(needle), - ) - : publications; + let rows = publications; + + if (needle) { + rows = rows.filter( + (p) => + (p.title ?? "").toLowerCase().includes(needle) || + (p.journal ?? "").toLowerCase().includes(needle) || + String(p.publication_year ?? "").includes(needle) || + (p.doi ?? "").toLowerCase().includes(needle), + ); + } + + if (hasYearFilter) { + const from = yearFrom ? Number(yearFrom) : null; + const to = yearTo ? Number(yearTo) : null; + rows = rows.filter((p) => { + const year = p.publication_year; + if (typeof year !== "number" || !Number.isFinite(year)) return false; + if (from !== null && year < from) return false; + if (to !== null && year > to) return false; + return true; + }); + } + return sortPublications(rows, sortKey, sortDir); - }, [publications, filter, sortKey, sortDir]); + }, [publications, filter, yearFrom, yearTo, hasYearFilter, sortKey, sortDir]); + + const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE)); + const currentPage = Math.min(page, totalPages); + + const pageRows = useMemo(() => { + const start = (currentPage - 1) * PAGE_SIZE; + return filtered.slice(start, start + PAGE_SIZE); + }, [filtered, currentPage]); + + const selectionStats = useMemo(() => { + if (filtered.length === 0) { + return { allChecked: false, anyChecked: false, selectedInFiltered: 0 }; + } + let count = 0; + for (const pub of filtered) { + if (selectedIds.has(pub.id)) count += 1; + } + return { + allChecked: count === filtered.length, + anyChecked: count > 0, + selectedInFiltered: count, + }; + }, [filtered, selectedIds]); function toggleSort(key) { if (sortKey === key) { setSortDir((d) => (d === "asc" ? "desc" : "asc")); + setPage(1); } else { setSortKey(key); setSortDir("desc"); + setPage(1); } } + function emit(nextSet) { + onSelectedIdsChange?.(nextSet); + } + + function toggleRow(id) { + const next = new Set(selectedIds); + if (next.has(id)) next.delete(id); + else next.add(id); + emit(next); + } + + function toggleAllFiltered() { + const next = new Set(selectedIds); + if (selectionStats.allChecked) { + for (const pub of filtered) next.delete(pub.id); + } else { + for (const pub of filtered) next.add(pub.id); + } + emit(next); + } + + function handleYearFromChange(value) { + setYearFrom(value); + // Si el usuario elige un "Desde" mayor que el "Hasta" actual, + // auto-corregimos el "Hasta" para preservar un rango coherente. + if (value && yearTo && Number(value) > Number(yearTo)) { + setYearTo(value); + } + setPage(1); + } + + function handleYearToChange(value) { + setYearTo(value); + if (value && yearFrom && Number(value) < Number(yearFrom)) { + setYearFrom(value); + } + setPage(1); + } + + function clearYearFilter() { + setYearFrom(""); + setYearTo(""); + setPage(1); + } + + const pageStart = + filtered.length === 0 ? 0 : (currentPage - 1) * PAGE_SIZE + 1; + const pageEnd = Math.min(currentPage * PAGE_SIZE, filtered.length); + + const yearFilterSummary = hasYearFilter + ? yearFrom && yearTo && yearFrom === yearTo + ? `Año: ${yearFrom}` + : `Años: ${yearFrom || "…"} – ${yearTo || "…"}` + : null; + return (
{/* Toolbar */} -
-
-

- Publicaciones -

-

- {filtered.length} de {publications.length} resultados -

-
-
- setFilter(e.target.value)} - className="w-[220px] rounded-lg border border-surface-border-strong bg-surface-secondary py-2 pl-9 pr-3.5 text-[13px] text-ink-primary outline-none focus:border-brand-accent" - /> - - - +
+
+
+

+ Publicaciones +

+

+ {filtered.length} de {publications.length} resultados + {yearFilterSummary && ( + <> + {" · "} + {yearFilterSummary} + + )} + {selectedIds.size > 0 && ( + <> + {" · "} + + {selectedIds.size} seleccionada + {selectedIds.size === 1 ? "" : "s"} + + + )} +

+
+
+ +
+ { + setFilter(e.target.value); + setPage(1); + }} + className="w-[220px] rounded-lg border border-surface-border-strong bg-surface-secondary py-2 pl-9 pr-3.5 text-[13px] text-ink-primary outline-none focus:border-brand-accent" + /> + + + +
+
+ + {filtersOpen && ( +
+
+ + +
+
+ + +
+ {hasYearFilter && ( + + )} + {availableYears.length === 0 && ( +

+ Aún no hay años disponibles. +

+ )} +
+ )}
{/* Body */} @@ -110,9 +375,21 @@ export function PublicationsTable({ ) : loading ? ( ) : ( - +
+ {COLUMNS.map((col) => ( ) : ( - filtered.map((pub, i) => ( - - - - - - - - )) + pageRows.map((pub, i) => { + const isSelected = selectedIds.has(pub.id); + return ( + + + + + + + + + ); + }) )}
e.stopPropagation()} + > + + - No se encontraron publicaciones con ese filtro. + No se encontraron publicaciones con los filtros aplicados.
- {pub.title} - - {pub.journal || "—"} - - {pub.publication_year ?? "—"} - - {pub.doi ? ( - - {pub.doi} - - ) : ( - - — - - )} - - -
{ + e.stopPropagation(); + toggleRow(pub.id); + }} + > + toggleRow(pub.id)} + ariaLabel={`Seleccionar publicación ${pub.title}`} + /> + + {pub.title} + + {pub.journal || "—"} + + {pub.publication_year ?? "—"} + + {pub.doi ? ( + e.stopPropagation()} + className="whitespace-nowrap font-mono text-xs text-brand-accent hover:underline" + > + {pub.doi} + + ) : ( + + — + + )} + + +
)}
+ + {/* Pagination */} + {!loading && !error && filtered.length > 0 && ( + setPage((p) => Math.max(1, Math.min(p, totalPages) - 1))} + onNext={() => setPage((p) => Math.min(totalPages, Math.min(p, totalPages) + 1))} + /> + )}
); } +function PaginationBar({ + page, + totalPages, + pageStart, + pageEnd, + total, + onPrev, + onNext, +}) { + const hasPrev = page > 1; + const hasNext = page < totalPages; + const isSinglePage = totalPages <= 1; + const noun = total === 1 ? "publicación" : "publicaciones"; + const visibleCount = pageEnd - pageStart + 1; + + return ( +
+ {isSinglePage ? ( + // Caso "todo entra en una página": evitamos el "del X al Y" + // porque coincide con el total y resulta ruidoso. Un simple + // "Mostrando N de N publicaciones" comunica lo mismo con menos + // palabras. +

+ Mostrando{" "} + {visibleCount}{" "} + de {total}{" "} + {noun} +

+ ) : ( +

+ Mostrando del{" "} + {pageStart}{" "} + al {pageEnd}{" "} + de un total de{" "} + {total} {noun} +

+ )} + {!isSinglePage && ( +
+ + + Página {page}{" "} + de {totalPages} + + +
+ )} +
+ ); +} + function LoadingState() { return (
diff --git a/frontend/src/components/ui/Icons.jsx b/frontend/src/components/ui/Icons.jsx index 67ec57b..ac50b72 100644 --- a/frontend/src/components/ui/Icons.jsx +++ b/frontend/src/components/ui/Icons.jsx @@ -94,6 +94,14 @@ export function SearchIcon({ size = 14, className = "" }) { ); } +export function FilterIcon({ size = 14, className = "" }) { + return ( + + + + ); +} + export function AlertIcon({ size = 16, className = "" }) { return ( @@ -102,3 +110,13 @@ export function AlertIcon({ size = 16, className = "" }) { ); } + +export function PackageIcon({ size = 18, className = "" }) { + return ( + + + + + + ); +} diff --git a/frontend/src/pages/DashboardPage.jsx b/frontend/src/pages/DashboardPage.jsx index 43f4bb9..5d99ceb 100644 --- a/frontend/src/pages/DashboardPage.jsx +++ b/frontend/src/pages/DashboardPage.jsx @@ -36,6 +36,8 @@ export function DashboardPage() { const [syncStatus, setSyncStatus] = useState("idle"); // idle | loading | success const [exportingFormat, setExportingFormat] = useState(null); + const [selectedIds, setSelectedIds] = useState(() => new Set()); + const loadResearcher = useCallback( async (signal) => { try { @@ -57,7 +59,16 @@ export function DashboardPage() { setPubsError(null); try { const data = await getPublications(orcid, { signal }); - if (!signal?.aborted) setPublications(data); + if (!signal?.aborted) { + setPublications(data); + setSelectedIds((prev) => { + if (prev.size === 0) return prev; + const alive = new Set(data.map((p) => p.id)); + const next = new Set(); + for (const id of prev) if (alive.has(id)) next.add(id); + return next.size === prev.size ? prev : next; + }); + } } catch (err) { if (signal?.aborted) return; setPubsError(err); @@ -89,8 +100,6 @@ export function DashboardPage() { throw new Error(summary.message || "El backend rechazó la sincronización."); } - // El backend devuelve un resumen del SyncJob, no el researcher. - // Refrescamos ambos recursos en paralelo. await Promise.all([loadResearcher(), loadPublications()]); setSyncStatus("success"); @@ -115,7 +124,10 @@ export function DashboardPage() { async function handleExport(format) { setExportingFormat(format); try { - const { blob, url } = await downloadExport(orcid, format); + const ids = Array.from(selectedIds); + const { blob, url } = await downloadExport(orcid, format, { + publicationIds: ids.length > 0 ? ids : undefined, + }); if (blob) { const objectUrl = URL.createObjectURL(blob); const anchor = document.createElement("a"); @@ -152,6 +164,7 @@ export function DashboardPage() { } @@ -167,6 +180,8 @@ export function DashboardPage() { loading={pubsLoading} error={pubsError} onRetry={() => loadPublications()} + selectedIds={selectedIds} + onSelectedIdsChange={setSelectedIds} />