Skip to content
Open
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
62 changes: 51 additions & 11 deletions app/components/ExecucaoCicloviaria/CityContent.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
import React, { useState, useEffect, useRef, useMemo } from "react";
import type { ColumnDef } from "@tanstack/react-table";
import { filterById, filterByName, IntlNumberMax1Digit, IntlPercentil } from "~/services/utils";
import { CyclingInfrastructureByCity } from "./CyclingInfrastructureByCity";
import { StatisticsBox } from "./StatisticsBox";
import Table from "../Commom/Table/Table";
import { DataTable } from "~/components/ui/data-table";

interface PdcRelation {
name: string;
pdc_typology: string;
typologies_str: string;
length: number;
has_cycleway_length: number;
}

const pdcColumns: ColumnDef<PdcRelation>[] = [
{ header: "Nome", accessorKey: "name" },
{ header: "Tipologia Prevista", accessorKey: "pdc_typology" },
{ header: "Tipologia Executada", accessorKey: "typologies_str" },
{ header: "Extensão Prevista (km)", accessorKey: "length" },
{ header: "Extensão Executada (km)", accessorKey: "has_cycleway_length" },
];

interface CityContentProps {
citiesStats: any;
Expand Down Expand Up @@ -197,17 +214,40 @@ export function CityContent({

{localSelectedCity?.relations && localSelectedCity.relations.length > 0 && (
<div data-table-section className="container mx-auto my-12">
<Table
title={`Estruturas do PDC para ${localSelectedCity?.name || ""}`}
<h3 className="text-gray-600 text-3xl mb-4">
Estruturas do PDC para {localSelectedCity?.name || ""}
</h3>
<DataTable
columns={pdcColumns}
data={localSelectedCity.relations}
columns={[
{ header: "Nome", accessorKey: "name" },
{ header: "Tipologia Prevista", accessorKey: "pdc_typology" },
{ header: "Tipologia Executada", accessorKey: "typologies_str" },
{ header: "Extensão Prevista (km)", accessorKey: "length" },
{ header: "Extensão Executada (km)", accessorKey: "has_cycleway_length" },
]}
showFilters={true}
toolbar={(table) => {
const column = table.getColumn("pdc_typology");
const rawFilterValue = column?.getFilterValue();
const filterValue = typeof rawFilterValue === "string" ? rawFilterValue : "";
const options = Array.from(column?.getFacetedUniqueValues().keys() ?? [])
.filter((v): v is string => typeof v === "string" && v.length > 0)
.sort();
return (
<div className="flex items-center gap-2">
<label htmlFor="pdc-typology-filter" className="text-sm text-gray-600">
Tipologia Prevista:
</label>
<select
id="pdc-typology-filter"
value={filterValue}
onChange={(e) => column?.setFilterValue(e.target.value || undefined)}
className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#008080] focus:border-transparent"
>
<option value="">Todas</option>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</div>
);
}}
/>
</div>
)}
Expand Down
29 changes: 18 additions & 11 deletions app/components/Samu/SamuClientSide.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
import { useState, useEffect, useMemo } from "react";
import Table from "../Commom/Table/Table";
import type { ColumnDef } from "@tanstack/react-table";
import { DataTable } from "~/components/ui/data-table";
import { VerticalBarChart } from "../Charts/VerticalBarChart";
import { NumberCards } from "../Commom/NumberCards";
import { SamuChoroplethMap } from "./SamuChoroplethMap";
import { SAMU_CALLS_OUTCOMES, SAMU_CALLS_PROFILES } from "~/servers";

interface CityRow {
ranking: number;
municipio: string;
total_chamadas: string;
percentual: string;
}

const citiesTableColumns: ColumnDef<CityRow>[] = [
{ header: "Ranking", accessorKey: "ranking" },
{ header: "Município", accessorKey: "municipio" },
{ header: "Total de Chamadas", accessorKey: "total_chamadas" },
{ header: "Percentual (%)", accessorKey: "percentual" },
];

interface CityData {
id?: string | number;
name?: string;
Expand Down Expand Up @@ -598,16 +613,8 @@ export default function SamuClientSide({ citiesData }: SamuClientSideProps) {

<div className="mx-auto container my-2">
<div className="bg-white rounded-lg shadow-lg p-6">
<Table
title="Lista completa das cidades"
data={allCitiesTableData}
columns={[
{ header: "Ranking", accessorKey: "ranking", enableColumnFilter: false },
{ header: "Município", accessorKey: "municipio", enableColumnFilter: false },
{ header: "Total de Chamadas", accessorKey: "total_chamadas", enableColumnFilter: false },
{ header: "Percentual (%)", accessorKey: "percentual", enableColumnFilter: false },
]}
/>
<h3 className="text-lg font-bold mb-4 text-gray-700">Lista completa das cidades</h3>
<DataTable columns={citiesTableColumns} data={allCitiesTableData} />
</div>
</div>
</section>
Expand Down
183 changes: 183 additions & 0 deletions app/components/ui/data-table.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import { useState } from "react";
import {
ColumnDef,
ColumnFiltersState,
SortingState,
Table as TanstackTable,
flexRender,
getCoreRowModel,
getFacetedRowModel,
getFacetedUniqueValues,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import { ChevronUp, ChevronDown, ChevronsUpDown } from "lucide-react";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "~/components/ui/table";

export interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
/** Initial page size (defaults to 10) */
pageSize?: number;
/** Enables the pagination controls (defaults to true) */
pagination?: boolean;
/** Copy shown when data is empty */
emptyMessage?: string;
/** Optional className overrides */
className?: string;
/** Optional per-row className — useful for type-based coloring */
rowClassName?: (row: TData) => string | undefined;
/**
* Optional render-prop for a toolbar above the table. Receives the TanStack
* table instance so the consumer can wire up filter inputs, selects, etc.
* Example:
* toolbar={(table) => (
* <MyFilters onChange={v => table.getColumn("x")?.setFilterValue(v)} />
* )}
*/
toolbar?: (table: TanstackTable<TData>) => React.ReactNode;
}

export function DataTable<TData, TValue>({
columns,
data,
pageSize = 10,
pagination = true,
emptyMessage = "Nenhum resultado encontrado.",
className,
rowClassName,
toolbar,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = useState<SortingState>([]);
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);

const table = useReactTable({
data,
columns,
state: { sorting, columnFilters },
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
initialState: { pagination: { pageSize } },
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: pagination ? getPaginationRowModel() : undefined,
getFacetedRowModel: getFacetedRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
});

const pageIndex = table.getState().pagination.pageIndex;
const pageCount = table.getPageCount();

return (
<div className={className}>
{toolbar && <div className="mb-4">{toolbar(table)}</div>}
<div className="overflow-hidden rounded-lg border border-gray-200 bg-white shadow">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="bg-gray-100 hover:bg-gray-100">
{headerGroup.headers.map((header) => {
const column = header.column;
const canSort = column.getCanSort();
const isSorted = column.getIsSorted();
const headerText =
typeof column.columnDef.header === "string" ? column.columnDef.header : "coluna";
return (
<TableHead key={header.id}>
{canSort ? (
<button
onClick={column.getToggleSortingHandler()}
className="inline-flex items-center gap-1 rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#008080]"
aria-label={`Ordenar por ${headerText}${
isSorted === "desc"
? " em ordem decrescente"
: isSorted === "asc"
? " em ordem crescente"
: ""
}`}
aria-sort={
isSorted === "desc" ? "descending" : isSorted === "asc" ? "ascending" : "none"
}
>
<span className="inline-flex w-4 h-4 items-center justify-center shrink-0">
{isSorted === "desc" ? (
<ChevronDown size={16} className="text-gray-600" aria-hidden="true" />
) : isSorted === "asc" ? (
<ChevronUp size={16} className="text-gray-600" aria-hidden="true" />
) : (
<ChevronsUpDown size={16} className="text-gray-400" aria-hidden="true" />
)}
</span>
{flexRender(column.columnDef.header, header.getContext())}
</button>
) : (
flexRender(column.columnDef.header, header.getContext())
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.length > 0 ? (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id} className={rowClassName?.(row.original)}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="text-center text-gray-500">
{emptyMessage}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>

{pagination && pageCount > 1 && (
<div className="flex items-center justify-between border-t border-gray-200 bg-white px-6 py-3">
<div className="text-xs text-gray-500">
{table.getFilteredRowModel().rows.length} resultados • Página {pageIndex + 1} de {Math.max(pageCount, 1)}
</div>
<div className="flex items-center space-x-1">
<button
className={`px-2 py-1 text-xs rounded transition-colors ${
table.getCanPreviousPage() ? "text-gray-600 hover:bg-gray-100" : "text-gray-300 cursor-not-allowed"
}`}
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
← Anterior
</button>
<button
className={`px-2 py-1 text-xs rounded transition-colors ${
table.getCanNextPage() ? "text-gray-600 hover:bg-gray-100" : "text-gray-300 cursor-not-allowed"
}`}
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
Próxima →
</button>
</div>
</div>
)}
</div>
</div>
);
}
89 changes: 89 additions & 0 deletions app/components/ui/table.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import * as React from "react";
import { cn } from "~/lib/utils";

const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm divide-y divide-gray-200", className)}
{...props}
/>
</div>
)
);
Table.displayName = "Table";

const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<thead ref={ref} className={cn("bg-gray-100", className)} {...props} />
)
);
TableHeader.displayName = "TableHeader";

const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("divide-y divide-gray-200 bg-white text-gray-700", className)}
{...props}
/>
)
);
TableBody.displayName = "TableBody";

const TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn("border-t border-gray-200 bg-gray-50 font-medium", className)}
{...props}
/>
)
);
TableFooter.displayName = "TableFooter";

const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn("border-b border-gray-200 transition-colors hover:bg-gray-100", className)}
{...props}
/>
)
);
TableRow.displayName = "TableRow";

const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-700",
className
)}
{...props}
/>
)
);
TableHead.displayName = "TableHead";

const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<td
ref={ref}
className={cn("px-6 py-4 text-sm leading-5 break-words", className)}
{...props}
/>
)
);
TableCell.displayName = "TableCell";

const TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>(
({ className, ...props }, ref) => (
<caption ref={ref} className={cn("mt-4 text-sm text-gray-500", className)} {...props} />
)
);
TableCaption.displayName = "TableCaption";

export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
Loading