🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(web): Migrate dashboard and widget tables to design-system (#17639)
Ben Bachemdd27fca8a020
diff --git a/web/src/components/design-system/DropdownMenu/DropdownMenu.tsx b/web/src/components/design-system/DropdownMenu/DropdownMenu.tsxindex 2b56dc6d07..ad168393e6 100644--- a/web/src/components/design-system/DropdownMenu/DropdownMenu.tsx+++ b/web/src/components/design-system/DropdownMenu/DropdownMenu.tsx@@ -50,6 +50,18 @@ const menuBodyVariants = cva(const menuItemVariants = cva("focus:bg-accent data-[active]:bg-accent data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 relative flex h-8 min-w-0 cursor-pointer items-center rounded-sm text-sm outline-hidden transition-colors",+ {+ variants: {+ variant: {+ default: "",+ destructive:+ "text-destructive focus:bg-destructive/10 data-[active]:bg-destructive/10",+ },+ },+ defaultVariants: {+ variant: "default",+ },+ },);const primaryActionVariants = cva(@@ -70,6 +82,7 @@ type DropdownMenuItem = {title: string;icon?: LucideIcon;type: "item";+ variant?: "default" | "destructive";secondaryAction?: MenuAction & {ariaLabel: string;icon: LucideIcon;@@ -138,6 +151,7 @@ function DropdownMenu({{children({getTriggerProps: () =>getReferenceProps({+ "aria-expanded": isOpen,ref: refs.setReference,}),})}@@ -267,7 +281,7 @@ function DropdownMenu({}}data-active={activeIndex === index ? "" : undefined}data-disabled={item.disabled ? "" : undefined}- className={menuItemVariants()}+ className={menuItemVariants({ variant: item.variant })}{...getItemProps({onClick: (event) => {if (item.disabled) return;diff --git a/web/src/components/design-system/IconButton/IconButton.tsx b/web/src/components/design-system/IconButton/IconButton.tsxindex f6030beef6..cac88612bb 100644--- a/web/src/components/design-system/IconButton/IconButton.tsx+++ b/web/src/components/design-system/IconButton/IconButton.tsx@@ -8,7 +8,9 @@ const buttonVariants = cva(variants: {variant: {ghost: "hover:bg-accent hover:text-accent-foreground",- subtle: "hover:bg-border",+ outline:+ "border border-input bg-background hover:bg-accent hover:text-accent-foreground",+ subtle: "hover:bg-border aria-expanded:bg-border",},size: {xs: "size-4 rounded-sm",@@ -44,7 +46,7 @@ type IconButtonProps = NativeButtonProps & {label: string;ref?: Ref<HTMLButtonElement>;size?: "xs" | "sm" | "md";- variant?: "ghost" | "subtle";+ variant?: "ghost" | "outline" | "subtle";};export function IconButton({diff --git a/web/src/components/design-system/PaginationBar/PaginationBar.stories.tsx b/web/src/components/design-system/PaginationBar/PaginationBar.stories.tsxnew file mode 100644index 0000000000..589dd5f131--- /dev/null+++ b/web/src/components/design-system/PaginationBar/PaginationBar.stories.tsx@@ -0,0 +1,36 @@+import { useState } from "react";+import { expect, userEvent, within } from "storybook/test";++import preview from "../../../../.storybook/preview";+import { PaginationBar } from "./PaginationBar";++function PaginationBarStory() {+ const [state, setState] = useState({ pageIndex: 0, pageSize: 20 });++ return <PaginationBar totalCount={45} state={state} onChange={setState} />;+}++const meta = preview.meta({+ component: PaginationBarStory,+ parameters: {+ layout: "fullscreen",+ },+});++export const Default = meta.story({+ name: "(Test) Navigates pages",+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(+ canvas.getByRole("spinbutton", { name: "Page number" }),+ ).toHaveValue(1);+ await expect(canvas.getByText("of 3")).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Go to next page" }),+ );+ await expect(+ canvas.getByRole("spinbutton", { name: "Page number" }),+ ).toHaveValue(2);+ },+});diff --git a/web/src/components/design-system/PaginationBar/PaginationBar.tsx b/web/src/components/design-system/PaginationBar/PaginationBar.tsxnew file mode 100644index 0000000000..1b254dc2bd--- /dev/null+++ b/web/src/components/design-system/PaginationBar/PaginationBar.tsx@@ -0,0 +1,175 @@+/* eslint-disable boundaries/dependencies */+import {+ ChevronLeft,+ ChevronRight,+ ChevronsLeft,+ ChevronsRight,+} from "lucide-react";+import { useState } from "react";++import { IconButton } from "@/src/components/design-system/IconButton/IconButton";+import { Input } from "@/src/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";++export type PaginationBarState = {+ pageIndex: number;+ pageSize: number;+};++export type PaginationBarProps = {+ totalCount: number | null;+ state: PaginationBarState;+ onChange: (state: PaginationBarState) => void;+ pageSizeOptions?: number[];+};++function PageNumberInput({+ currentPage,+ pageCount,+ onNavigate,+}: {+ currentPage: number;+ pageCount: number;+ onNavigate: (pageIndex: number) => void;+}) {+ const [value, setValue] = useState<number | string>(currentPage);++ const submit = (nextValue: string) => {+ const nextPage = Number(nextValue);+ if (!Number.isInteger(nextPage) || nextPage < 1 || nextPage > pageCount) {+ setValue(currentPage);+ return;+ }++ onNavigate(nextPage - 1);+ setValue(nextPage);+ };++ return (+ <Input+ aria-label="Page number"+ type="number"+ min={1}+ max={pageCount}+ value={value}+ onChange={(event) => setValue(event.target.value)}+ onKeyDown={(event) => {+ if (event.key !== "Enter") return;+ event.preventDefault();+ submit(event.currentTarget.value);+ }}+ onBlur={(event) => submit(event.target.value)}+ className="h-8 appearance-none"+ style={{+ width: `${3 + Math.max(1, pageCount.toString().length)}ch`,+ }}+ />+ );+}++export function PaginationBar({+ totalCount,+ state,+ onChange,+ pageSizeOptions = [10, 20, 30, 40, 50],+}: PaginationBarProps) {+ const pageCount = Math.max(1, Math.ceil((totalCount ?? 0) / state.pageSize));+ const currentPage = state.pageIndex + 1;+ const canGoBack = state.pageIndex > 0;+ const canGoForward = totalCount !== null && state.pageIndex < pageCount - 1;++ return (+ <div className="bg-background @container/pagination sticky bottom-0 z-10 flex w-full min-w-0 justify-end border-t py-2 pr-2 font-bold">+ <div className="flex min-w-0 flex-wrap items-center justify-end gap-x-4 gap-y-2 @min-[520px]/pagination:gap-x-6 @min-[720px]/pagination:gap-x-8">+ <div className="flex shrink-0 items-center gap-2">+ <span className="text-sm whitespace-nowrap @min-[440px]/pagination:hidden">+ Rows+ </span>+ <span className="hidden text-sm whitespace-nowrap @min-[440px]/pagination:block">+ Rows per page+ </span>+ <Select+ value={`${state.pageSize}`}+ onValueChange={(value) => {+ const pageSize = Number(value);+ const firstVisibleRow = state.pageIndex * state.pageSize;+ onChange({+ pageIndex: Math.floor(firstVisibleRow / pageSize),+ pageSize,+ });+ }}+ >+ <SelectTrigger className="h-8 w-[70px]">+ <SelectValue placeholder={state.pageSize} />+ </SelectTrigger>+ <SelectContent side="top">+ {pageSizeOptions.map((pageSize) => (+ <SelectItem key={pageSize} value={`${pageSize}`}>+ {pageSize}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ <div className="flex shrink-0 flex-nowrap items-center gap-x-4 @min-[520px]/pagination:gap-x-6">+ <div className="flex items-center justify-center gap-1 text-sm whitespace-nowrap">+ Page+ <PageNumberInput+ key={`${currentPage}-${pageCount}`}+ currentPage={currentPage}+ pageCount={pageCount}+ onNavigate={(pageIndex) => onChange({ ...state, pageIndex })}+ />+ <span>of {totalCount === null ? "…" : pageCount}</span>+ </div>++ <div className="flex items-center gap-2">+ <span className="hidden @min-[560px]/pagination:inline-flex">+ <IconButton+ icon={ChevronsLeft}+ onClick={() => onChange({ ...state, pageIndex: 0 })}+ disabled={!canGoBack}+ label="Go to first page"+ variant="outline"+ />+ </span>+ <IconButton+ icon={ChevronLeft}+ onClick={() =>+ onChange({ ...state, pageIndex: state.pageIndex - 1 })+ }+ disabled={!canGoBack}+ label="Go to previous page"+ variant="outline"+ />+ <IconButton+ icon={ChevronRight}+ onClick={() =>+ onChange({ ...state, pageIndex: state.pageIndex + 1 })+ }+ disabled={!canGoForward}+ label="Go to next page"+ variant="outline"+ />+ <span className="hidden @min-[560px]/pagination:inline-flex">+ <IconButton+ icon={ChevronsRight}+ onClick={() => onChange({ ...state, pageIndex: pageCount - 1 })}+ disabled={!canGoForward}+ label="Go to last page"+ variant="outline"+ />+ </span>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/web/src/components/design-system/table/Table.stories.tsx b/web/src/components/design-system/table/Table.stories.tsxnew file mode 100644index 0000000000..57a8762032--- /dev/null+++ b/web/src/components/design-system/table/Table.stories.tsx@@ -0,0 +1,220 @@+import { type OrderByState } from "@langfuse/shared";+import { useState } from "react";+import preview from "../../../../.storybook/preview";+import { expect, fn, userEvent, within } from "storybook/test";++import { Table } from "./Table";+import { createBadgeTableColumn } from "./columns/createBadgeTableColumn";+import { createDateTableColumn } from "./columns/createDateTableColumn";+import { createTextTableColumn } from "./columns/createTextTableColumn";++type Row = {+ createdAt: Date;+ description: string;+ name: string;+ status: "Active" | "Draft";+};++const columns = [+ createTextTableColumn<Row>({+ accessorKey: "name",+ header: "Name",+ }),+ createTextTableColumn<Row>({+ accessorKey: "description",+ header: "Description",+ }),+ createBadgeTableColumn<Row>({+ accessorKey: "status",+ header: "Status",+ }),+ createDateTableColumn<Row>({+ accessorKey: "createdAt",+ header: "Created at",+ }),+];+const onView = fn();++type TableStoryProps = Parameters<typeof Table<Row>>[0];++function TableStory(props: TableStoryProps) {+ return <Table<Row> {...props} />;+}++const sortableColumns = [+ createTextTableColumn<Row>({+ accessorKey: "name",+ header: "Name",+ enableSorting: true,+ }),+ createDateTableColumn<Row>({+ accessorKey: "createdAt",+ header: "Created at",+ enableSorting: true,+ }),+];++const sortableRows: Row[] = [+ {+ createdAt: new Date("2026-09-18"),+ description: "Team analytics overview",+ name: "Dashboard",+ status: "Active",+ },+ {+ createdAt: new Date("2026-09-17"),+ description: "Reusable chart configuration",+ name: "Widget",+ status: "Draft",+ },+];++function SortableTableStory() {+ const [orderBy, setOrderBy] = useState<OrderByState>(null);+ const rows = [...sortableRows];++ if (orderBy?.column === "name") {+ rows.sort((left, right) => left.name.localeCompare(right.name));+ }+ if (orderBy?.column === "createdAt") {+ rows.sort(+ (left, right) => left.createdAt.getTime() - right.createdAt.getTime(),+ );+ }+ if (orderBy?.order === "DESC") rows.reverse();++ return (+ <Table+ tableName="sortable-table-story"+ columns={sortableColumns}+ data={{ status: "success", data: rows }}+ orderBy={orderBy}+ setOrderBy={setOrderBy}+ />+ );+}++const meta = preview.meta({+ component: TableStory,+ parameters: {+ layout: "fullscreen",+ },+ args: {+ tableName: "design-system-table-story",+ columns,+ actions: () => [+ {+ id: "view",+ type: "item" as const,+ title: "View details",+ onClick: onView,+ },+ ],+ },+});++export const Default = meta.story({+ name: "(Test) Default",+ args: {+ data: {+ status: "success",+ data: [+ {+ createdAt: new Date("2026-09-18"),+ description: "Team analytics overview",+ name: "Dashboard",+ status: "Active",+ },+ {+ createdAt: new Date("2026-09-17"),+ description: "Reusable chart configuration",+ name: "Widget",+ status: "Draft",+ },+ ],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(+ canvas.getAllByRole("button", { name: "Open actions menu" })[0],+ );+ const menu = await within(canvasElement.ownerDocument.body).findByRole(+ "menu",+ );+ await userEvent.click(+ within(menu).getByRole("button", { name: "View details" }),+ );+ await expect(onView).toHaveBeenCalled();+ },+});++export const Loading = meta.story({+ args: {+ data: {+ status: "loading",+ },+ },+});++export const Sorting = meta.story({+ name: "(Test) Sorts columns",+ args: {+ data: { status: "success", data: sortableRows },+ },+ render: () => <SortableTableStory />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const nameHeader = canvas.getByRole("columnheader", { name: /Name/ });++ await expect(nameHeader).toHaveAttribute("aria-sort", "none");+ await userEvent.click(+ within(nameHeader).getByRole("button", { name: "Sort by Name" }),+ );+ await expect(nameHeader).toHaveAttribute("aria-sort", "descending");+ },+});++export const ResizeColumns = meta.story({+ name: "(Test) Resizes columns",+ args: {+ data: {+ status: "success",+ data: [+ {+ createdAt: new Date("2026-09-18"),+ description: "Team analytics overview",+ name: "Dashboard",+ status: "Active",+ },+ ],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const header = canvas.getByRole("columnheader", { name: /Name/ });+ const resizeHandle = canvas.getByRole("button", {+ name: "Resize Name column",+ });+ const initialWidth = header.getBoundingClientRect().width;++ await userEvent.pointer([+ { keys: "[MouseLeft>]", target: resizeHandle },+ { coords: { x: initialWidth + 80, y: 0 } },+ { keys: "[/MouseLeft]" },+ ]);++ await expect(header.getBoundingClientRect().width).toBeGreaterThan(+ initialWidth,+ );+ },+});++export const Error = meta.story({+ args: {+ data: {+ status: "error",+ error: "Unable to load rows",+ },+ },+});diff --git a/web/src/components/design-system/table/Table.tsx b/web/src/components/design-system/table/Table.tsxnew file mode 100644index 0000000000..03ccd85964--- /dev/null+++ b/web/src/components/design-system/table/Table.tsx@@ -0,0 +1,334 @@+/* eslint-disable boundaries/dependencies */+import { type OrderByState } from "@langfuse/shared";+import {+ type ColumnDef,+ flexRender,+ getCoreRowModel,+ useReactTable,+} from "@tanstack/react-table";+import { ArrowDown, ArrowUp, ArrowUpDown, MoreVertical } from "lucide-react";+import { type ComponentProps, useMemo } from "react";++import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";+import { Skeleton } from "@/src/components/ui/skeleton";+import { cn } from "@/src/utils/tailwind";++const INTERACTIVE_ROW_CLICK_SELECTOR =+ "a, button, input, select, textarea, summary, [role='button'], [role='link']";++function shouldIgnoreRowClickTarget(target: EventTarget | null) {+ if (!(target instanceof Element)) return false;+ return Boolean(target.closest(INTERACTIVE_ROW_CLICK_SELECTOR));+}++export type AsyncTableData<T> =+ | { status: "loading" }+ | { status: "error"; error: string }+ | { status: "success"; data: T };++export interface TableProps<TData> {+ tableName: string;+ columns: ColumnDef<TData>[];+ actions?: (row: TData) => ComponentProps<typeof DropdownMenu>["items"];+ data: AsyncTableData<TData[]>;+ orderBy?: OrderByState;+ setOrderBy?: (state: OrderByState) => void;+ loadingRowCount?: number;+ noResultsMessage?: React.ReactNode;+ onRowClick?: (row: TData, event?: React.MouseEvent) => void;+}++export function Table<TData extends object>({+ tableName,+ columns,+ actions,+ data,+ orderBy,+ setOrderBy,+ loadingRowCount = 8,+ noResultsMessage = "No results",+ onRowClick,+}: TableProps<TData>) {+ const tableColumns = useMemo<ColumnDef<TData>[]>(() => {+ if (!actions) return columns;++ return [+ ...columns,+ {+ id: "__actions",+ header: "",+ size: 48,+ enableResizing: false,+ headerClassName: "text-right",+ cellClassName: "text-right",+ cell: ({ row }) => (+ <div+ className="ml-auto flex size-6 items-center justify-end"+ onClick={(event) => event.stopPropagation()}+ >+ <DropdownMenu items={actions(row.original)} placement="bottom-end">+ {({ getTriggerProps }) => (+ <IconButton+ icon={MoreVertical}+ label="Open actions menu"+ size="sm"+ variant="subtle"+ {...getTriggerProps()}+ />+ )}+ </DropdownMenu>+ </div>+ ),+ loadingCell: (+ <div className="ml-auto flex h-4 w-6 items-center justify-center">+ <MoreVertical+ className="text-muted-foreground/30 size-4 animate-pulse"+ aria-hidden="true"+ />+ </div>+ ),+ },+ ];+ }, [actions, columns]);+ const table = useReactTable({+ data: data.status === "success" ? data.data : [],+ columns: tableColumns,+ getCoreRowModel: getCoreRowModel(),+ columnResizeMode: "onChange",+ });++ const visibleColumns = table.getVisibleLeafColumns();++ return (+ <div className="flex w-full max-w-full flex-1 flex-col overflow-auto">+ <div className="relative min-h-full w-full overflow-auto border-t [scrollbar-gutter:stable]">+ <table+ aria-label={tableName}+ className="w-full table-fixed border-separate border-spacing-0 space-y-4 overflow-auto text-sm"+ >+ <thead className="sticky top-0 z-20 [&_tr]:border-b">+ {table.getHeaderGroups().map((headerGroup) => (+ <tr key={headerGroup.id} className="border-b transition-colors">+ {headerGroup.headers.map((header) => {+ const column = header.column.columnDef;+ const isSortable = Boolean(+ column.enableSorting && setOrderBy,+ );+ const isSorted = orderBy?.column === header.column.id;+ const headerTitle =+ typeof column.header === "string"+ ? column.header+ : undefined;+ let ariaSort: React.AriaAttributes["aria-sort"];+ if (isSortable) ariaSort = "none";+ if (isSorted && orderBy.order === "ASC") {+ ariaSort = "ascending";+ }+ if (isSorted && orderBy.order === "DESC") {+ ariaSort = "descending";+ }++ return (+ <th+ key={header.id}+ aria-sort={ariaSort}+ className={cn(+ "group bg-background text-muted-foreground relative h-10 border-b p-1 text-left align-middle font-bold first:pl-2",+ column.headerClassName,+ column.hideBelowMd && "hidden md:table-cell",+ )}+ style={{ width: header.getSize() }}+ >+ <div className="flex min-w-0 items-center select-none">+ {!header.isPlaceholder && !isSortable && (+ <span+ className="truncate leading-normal"+ title={headerTitle}+ >+ {flexRender(column.header, header.getContext())}+ </span>+ )}+ {!header.isPlaceholder && isSortable && setOrderBy && (+ <button+ type="button"+ aria-label={`Sort by ${headerTitle ?? header.column.id}`}+ className="hover:text-foreground focus-visible:ring-ring group/sort flex min-w-0 cursor-pointer items-center rounded-sm outline-none focus-visible:ring-2"+ onClick={() => {+ if (!isSorted) {+ setOrderBy({+ column: header.column.id,+ order: "DESC",+ });+ return;+ }+ if (orderBy.order === "DESC") {+ setOrderBy({+ column: header.column.id,+ order: "ASC",+ });+ return;+ }+ setOrderBy(null);+ }}+ >+ <span+ className="truncate leading-normal"+ title={headerTitle}+ >+ {flexRender(column.header, header.getContext())}+ </span>+ {!isSorted && (+ <ArrowUpDown+ className="ml-1.5 size-3 shrink-0 opacity-40 transition-opacity group-hover/sort:opacity-70"+ aria-hidden="true"+ />+ )}+ {isSorted && orderBy.order === "ASC" && (+ <ArrowUp+ className="ml-1.5 size-3 shrink-0"+ aria-hidden="true"+ />+ )}+ {isSorted && orderBy.order === "DESC" && (+ <ArrowDown+ className="ml-1.5 size-3 shrink-0"+ aria-hidden="true"+ />+ )}+ </button>+ )}+ </div>+ {header.column.getCanResize() && (+ <button+ type="button"+ aria-label={`Resize ${headerTitle ?? header.column.id} column`}+ tabIndex={-1}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onDoubleClick={(event) => {+ event.stopPropagation();+ header.column.resetSize();+ }}+ onMouseDown={header.getResizeHandler()}+ onTouchStart={header.getResizeHandler()}+ className={cn(+ "bg-secondary absolute top-0 right-0 h-full w-1.5 cursor-col-resize touch-none opacity-0 select-none group-hover:opacity-100",+ header.column.getIsResizing() &&+ "bg-primary-accent opacity-100",+ )}+ />+ )}+ </th>+ );+ })}+ </tr>+ ))}+ </thead>+ <tbody className="text-xs [&_tr:last-child_td]:border-b-0">+ {data.status === "loading" &&+ Array.from({ length: loadingRowCount }).map((_, rowIndex) => (+ <tr+ key={`loading-row-${rowIndex}`}+ className="h-12"+ aria-hidden="true"+ >+ {visibleColumns.map((column, columnIndex) => {+ const loadingCell = column.columnDef.loadingCell;+ return (+ <td+ key={column.id}+ className={cn(+ "h-full overflow-hidden border-b p-2 align-middle text-xs whitespace-nowrap first:pl-2",+ column.columnDef.cellClassName,+ column.columnDef.hideBelowMd &&+ "hidden md:table-cell",+ )}+ >+ <div className="flex min-w-0 items-center overflow-hidden">+ {typeof loadingCell === "function" && loadingCell()}+ {typeof loadingCell !== "function" && loadingCell}+ {loadingCell === undefined && (+ <Skeleton+ className={cn(+ "h-4 min-w-12",+ (rowIndex + columnIndex) % 4 === 0 && "w-3/4",+ (rowIndex + columnIndex) % 4 === 1 && "w-1/2",+ (rowIndex + columnIndex) % 4 === 2 && "w-2/3",+ (rowIndex + columnIndex) % 4 === 3 && "w-5/6",+ )}+ />+ )}+ </div>+ </td>+ );+ })}+ </tr>+ ))}+ {data.status === "error" && (+ <tr className="hover:bg-transparent">+ <td+ colSpan={visibleColumns.length}+ className="text-destructive h-24 border-b p-2 text-center align-middle"+ >+ {data.error}+ </td>+ </tr>+ )}+ {data.status === "success" &&+ table.getRowModel().rows.map((row) => (+ <tr+ key={row.id}+ className={cn(+ "hover:bg-accent h-12 transition-colors",+ onRowClick ? "cursor-pointer" : "cursor-default",+ )}+ tabIndex={onRowClick ? 0 : undefined}+ onClick={(event) => {+ if (shouldIgnoreRowClickTarget(event.target)) return;+ onRowClick?.(row.original, event);+ }}+ onKeyDown={(event) => {+ if (event.key !== "Enter") return;+ if (shouldIgnoreRowClickTarget(event.target)) return;+ onRowClick?.(row.original);+ }}+ >+ {row.getVisibleCells().map((cell) => {+ const column = cell.column.columnDef;+ return (+ <td+ key={cell.id}+ className={cn(+ "h-full overflow-hidden border-b p-2 align-middle text-xs whitespace-nowrap first:pl-2",+ column.cellClassName,+ column.hideBelowMd && "hidden md:table-cell",+ )}+ >+ <div className="flex min-w-0 items-center overflow-hidden">+ {flexRender(column.cell, cell.getContext())}+ </div>+ </td>+ );+ })}+ </tr>+ ))}+ {data.status === "success" &&+ table.getRowModel().rows.length === 0 && (+ <tr className="hover:bg-transparent">+ <td+ colSpan={visibleColumns.length}+ className="text-muted-foreground h-24 border-b p-2 text-center align-middle"+ >+ {noResultsMessage}+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ </div>+ );+}diff --git a/web/src/components/design-system/table/columns/createBadgeTableColumn.tsx b/web/src/components/design-system/table/columns/createBadgeTableColumn.tsxindex bc105099ae..f758e380b7 100644--- a/web/src/components/design-system/table/columns/createBadgeTableColumn.tsx+++ b/web/src/components/design-system/table/columns/createBadgeTableColumn.tsx@@ -1,28 +1,48 @@/* eslint-disable boundaries/dependencies */-import { type RowData } from "@tanstack/react-table";+import { type CellContext, type RowData } from "@tanstack/react-table";+import { type LucideIcon } from "lucide-react";-import { Badge } from "@/src/components/ui/badge";+import { Badge, type BadgeProps } from "@/src/components/ui/badge";import { Skeleton } from "@/src/components/ui/skeleton";import {createTableColumn,type TableColumnOptions,} from "./utils/createTableColumn";-export function createBadgeTableColumn<TData extends RowData>(- options: TableColumnOptions<TData, string>,-) {+export function createBadgeTableColumn<TData extends RowData>({+ getIcon,+ getVariant,+ ...options+}: TableColumnOptions<TData, string> & {+ getIcon?: (+ value: string,+ context: CellContext<TData, string | null | undefined>,+ ) => LucideIcon | undefined;+ getVariant?: (+ value: string,+ context: CellContext<TData, string | null | undefined>,+ ) => BadgeProps["variant"];+}) {return createTableColumn<TData, string>({...options,loadingCell: <Skeleton className="h-5 w-16 shrink-0 rounded-sm" />,- renderCell: (value) =>- value ? (+ renderCell: (value, context) => {+ if (!value) return null;++ const Icon = getIcon?.(value, context);++ return (<Badge- variant="secondary"- className="max-w-fit truncate rounded-sm px-1 font-normal"+ variant={getVariant?.(value, context) ?? "secondary"}+ className="max-w-fit gap-1 truncate rounded-sm px-1 font-normal"title={value}>- {value}+ {Icon && <Icon className="size-3 shrink-0" aria-hidden />}+ <span className="truncate" title={value}>+ {value}+ </span></Badge>- ) : null,+ );+ },});}diff --git a/web/src/components/design-system/table/columns/createDateTableColumn.tsx b/web/src/components/design-system/table/columns/createDateTableColumn.tsxindex 169ec57d5e..e87bf24281 100644--- a/web/src/components/design-system/table/columns/createDateTableColumn.tsx+++ b/web/src/components/design-system/table/columns/createDateTableColumn.tsx@@ -1,5 +1,6 @@/* eslint-disable boundaries/dependencies */import { type CellContext, type RowData } from "@tanstack/react-table";+import { formatDistanceToNow } from "date-fns";import { buildLocalIsoDatePresentation } from "@/src/utils/dates";import { Skeleton } from "@/src/components/ui/skeleton";@@ -8,37 +9,26 @@ import {type TableColumnOptions,} from "./utils/createTableColumn";-export function createDateTableColumn<TData extends RowData>(- options: TableColumnOptions<TData, Date> & {- getValue?: (- value: Date | null | undefined,- context: CellContext<TData, Date | null | undefined>,- ) => Date | { type: "loading" } | undefined;- },-) {- const { getValue } = options;-+export function createDateTableColumn<TData extends RowData>({+ getValue,+ mode = "absolute",+ ...options+}: TableColumnOptions<TData, Date> & {+ getValue?: (+ value: Date | null | undefined,+ context: CellContext<TData, Date | null | undefined>,+ ) => Date | { type: "loading" } | undefined;+ mode?: "absolute" | "relative";+}) {return createTableColumn<TData, Date>({...options,loadingCell: <Skeleton className="h-4 w-1/2" />,renderCell: (value, context) => {- if (!getValue) {- if (value === null || value === undefined) return null;-- const preparedDate = buildLocalIsoDatePresentation({ date: value });-- return (- preparedDate && (- <span title={preparedDate.title}>{preparedDate.display}</span>- )- );- }-- const resolvedValue = getValue(value, context);+ const resolvedValue = getValue ? getValue(value, context) : value;if (resolvedValue === null || resolvedValue === undefined) return null;- if ("type" in resolvedValue && resolvedValue.type === "loading") {+ if (!(resolvedValue instanceof Date)) {return <Skeleton className="h-4 w-1/2" />;}@@ -47,7 +37,11 @@ export function createDateTableColumn<TData extends RowData>(});return preparedDate ? (- <span title={preparedDate.title}>{preparedDate.display}</span>+ <span className="block w-full truncate" title={preparedDate.title}>+ {mode === "relative"+ ? formatDistanceToNow(resolvedValue, { addSuffix: true })+ : preparedDate.display}+ </span>) : null;},});diff --git a/web/src/components/design-system/table/columns/createTextTableColumn.tsx b/web/src/components/design-system/table/columns/createTextTableColumn.tsxindex c8fd250630..aab1ae799f 100644--- a/web/src/components/design-system/table/columns/createTextTableColumn.tsx+++ b/web/src/components/design-system/table/columns/createTextTableColumn.tsx@@ -35,7 +35,11 @@ export function createTextTableColumn<TData extends RowData, TValue = string>({if (text === null || text === undefined) return null;if (typeof text !== "string") return loadingCell;- return <span title={text}>{text}</span>;+ return (+ <span className="block w-full truncate" title={text}>+ {text}+ </span>+ );},});}diff --git a/web/src/components/ui/badge.tsx b/web/src/components/ui/badge.tsxindex 0c1091e4bf..e590eb005d 100644--- a/web/src/components/ui/badge.tsx+++ b/web/src/components/ui/badge.tsx@@ -20,6 +20,9 @@ const badgeVariants = cva(success: "bg-light-green text-dark-green",error: "bg-light-red text-dark-red",warning: "bg-light-yellow text-dark-yellow",+ blue: "bg-light-blue text-dark-blue",+ violet: "bg-light-violet text-dark-violet",+ teal: "bg-light-teal text-dark-teal",},size: {default: "px-2.5 py-0.5 text-xs",diff --git a/web/src/features/dashboard/components/DashboardTable.tsx b/web/src/features/dashboard/components/DashboardTable.tsxdeleted file mode 100644index cc4d25fda0..0000000000--- a/web/src/features/dashboard/components/DashboardTable.tsx+++ /dev/null@@ -1,324 +0,0 @@-/* eslint-disable no-nested-ternary */-import { showErrorToast, showSuccessToast } from "@/src/features/notifications";-import { useHasProjectAccess } from "@/src/features/rbac";-import { useEffect, useState } from "react";-import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";-import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";-import { NumberParam, useQueryParams, withDefault } from "use-query-params";-import { api } from "@/src/utils/api";-import { safeExtract } from "@/src/utils/map-utils";-import { DataTable } from "@/src/components/table/data-table";-import { type LangfuseColumnDef } from "@/src/components/table/types";-import { createColumnHelper } from "@tanstack/react-table";-import { createDateTableColumn } from "@/src/components/design-system/table/columns/createDateTableColumn";-import { createDropdownTableColumn } from "@/src/components/design-system/table/columns/createDropdownTableColumn";-import { createLinkTableColumn } from "@/src/components/design-system/table/columns/createLinkTableColumn";-import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";-import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";-import { Copy, Edit, Trash2, User as UserIcon } from "lucide-react";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics";-import { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";-import { EditDialogDashboardContent } from "@/src/features/dashboard/components/EditDialogDashboardContent";-import { CloneFirstDialogController } from "@/src/features/dashboard/components/CloneFirstDialogController";-import { useRouter } from "next/router";-import { DialogController } from "@/src/components/ui/dialog";-import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";--type DashboardTableRow = {- id: string;- name: string;- description: string;- createdAt: Date;- updatedAt: Date;- owner: "PROJECT" | "LANGFUSE";-};--export function DashboardTable() {- const projectId = useProjectIdFromURL() as string;- const { setDetailPageList } = useDetailPageLists();- const router = useRouter();- const utils = api.useUtils();- const capture = usePostHogClientCapture();- const hasAccess = useHasProjectAccess({ projectId, scope: "dashboards:CUD" });- const [selectedDashboard, setSelectedDashboard] =- useState<DashboardTableRow | null>(null);- const cloneDashboard = api.dashboard.cloneDashboard.useMutation({- onSuccess: () => {- utils.dashboard.invalidate();- showSuccessToast({- title: "Dashboard cloned",- description: "The dashboard has been cloned successfully",- });- },- onError: (error) => {- showErrorToast("Failed to clone dashboard", error.message);- },- });- const deleteDashboard = api.dashboard.delete.useMutation({- onSuccess: () => {- capture("dashboard:delete_dashboard_button_click");- showSuccessToast({- title: "Dashboard deleted",- description: "The dashboard has been deleted successfully",- });- utils.dashboard.invalidate();- },- onError: (error) => {- showErrorToast("Failed to delete dashboard", error.message);- },- });-- const [orderByState, setOrderByState] = useOrderByState({- column: "updatedAt",- order: "DESC",- });- const [paginationState, setPaginationState] = useQueryParams({- pageIndex: withDefault(NumberParam, 0),- pageSize: withDefault(NumberParam, 50),- });-- const dashboards = api.dashboard.allDashboards.useQuery(- {- page: paginationState.pageIndex,- limit: paginationState.pageSize,- projectId: projectId as string, // Typecast as query is enabled only when projectId is present- orderBy: orderByState,- },- {- enabled: Boolean(projectId),- trpc: {- context: {- skipBatch: true,- },- },- },- );-- useEffect(() => {- if (dashboards.isSuccess) {- setDetailPageList(- "dashboards",- dashboards.data?.dashboards.map((d) => ({ id: d.id })),- );- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [dashboards.isSuccess, dashboards.data]);-- const columnHelper = createColumnHelper<DashboardTableRow>();- const dashboardColumns = [- createLinkTableColumn<DashboardTableRow>({- accessorKey: "name",- header: "Name",- enableSorting: true,- size: 200,- getCell: (name, { row }) => {- if (name) {- return {- type: "link",- props: {- path: `/project/${projectId}/dashboards/${encodeURIComponent(row.original.id)}`,- value: name,- },- };- }-- return undefined;- },- }),- createTextTableColumn<DashboardTableRow>({- accessorKey: "description",- header: "Description",- size: 300,- }),- columnHelper.display({- id: "ownerTag",- header: "Owner",- size: 80,- cell: (row) => {- return row.row.original.owner === "LANGFUSE" ? (- <span className="flex gap-1 px-2 py-0.5 text-xs">- <span role="img" aria-label="Langfuse">- 🪢- </span>- Langfuse- </span>- ) : (- <span className="flex gap-1 px-2 py-0.5 text-xs">- <UserIcon className="h-3 w-3" /> Project- </span>- );- },- }),- createDateTableColumn<DashboardTableRow>({- accessorKey: "createdAt",- header: "Created At",- enableSorting: true,- size: 150,- }),- createDateTableColumn<DashboardTableRow>({- accessorKey: "updatedAt",- header: "Updated At",- enableSorting: true,- size: 150,- }),- ] as LangfuseColumnDef<DashboardTableRow>[];-- return (- <CloneFirstDialogController- projectId={projectId}- dashboardId={selectedDashboard?.id ?? ""}- dashboardName={selectedDashboard?.name ?? "Dashboard"}- >- {({ openDialog: openCloneFirstDialog }) => (- <DialogController- closeOnInteractionOutside={false}- size="default"- renderContent={({ closeDialog }) =>- selectedDashboard ? (- <EditDialogDashboardContent- closeDialog={closeDialog}- projectId={projectId}- dashboardId={selectedDashboard.id}- initialName={selectedDashboard.name}- initialDescription={selectedDashboard.description}- />- ) : null- }- >- {({ openDialog: openEditDialog }) => (- <ConfirmationDialogController- title="Delete dashboard"- text="This action cannot be undone. It permanently deletes this dashboard."- confirmLabel="Delete dashboard"- variant="destructive"- loading={deleteDashboard.isPending}- onConfirm={async () => {- if (!selectedDashboard) return;-- await deleteDashboard.mutateAsync({- projectId,- dashboardId: selectedDashboard.id,- });- }}- >- {({ openDialog: openDeleteDialog }) => (- <DataTable- tableName="dashboards"- columns={[- ...dashboardColumns,- createDropdownTableColumn<DashboardTableRow, string>({- id: "actions",- accessorFn: (row) => row.id,- header: "Actions",- size: 70,- renderMenu: (id, { row }) => {- if (!id) return null;- const dashboard = row.original;-- return (- <>- <DropdownMenuItem- disabled={!hasAccess}- onSelect={() => {- setSelectedDashboard(dashboard);- if (dashboard.owner === "PROJECT") {- openEditDialog();- return;- }-- capture("dashboard:locked_edit_attempt", {- dashboard_id: dashboard.id,- attempt: "list_edit",- surface: "list",- });- openCloneFirstDialog();- }}- >- <Edit className="mr-2 h-4 w-4" />- Edit- </DropdownMenuItem>- <DropdownMenuItem- disabled={!hasAccess}- onSelect={() => {- cloneDashboard.mutate(- {- projectId,- dashboardId: dashboard.id,- },- {- onSuccess: () => {- capture("dashboard:clone_dashboard", {- source: "list_clone_button",- dashboardId: dashboard.id,- owner: dashboard.owner,- });- },- },- );- }}- >- <Copy className="mr-2 h-4 w-4" />- Clone- </DropdownMenuItem>- {dashboard.owner === "PROJECT" ? (- <DropdownMenuItem- className="text-destructive"- disabled={!hasAccess}- onSelect={() => {- setSelectedDashboard(dashboard);- capture(- "dashboard:delete_dashboard_form_open",- );- openDeleteDialog();- }}- >- <Trash2 className="mr-2 h-4 w-4" />- Delete- </DropdownMenuItem>- ) : null}- </>- );- },- }),- ]}- data={- dashboards.isPending- ? { isLoading: true, isError: false }- : dashboards.isError- ? {- isLoading: false,- isError: true,- error: dashboards.error.message,- }- : {- isLoading: false,- isError: false,- data: safeExtract(- dashboards.data,- "dashboards",- [],- ),- }- }- orderBy={orderByState}- setOrderBy={setOrderByState}- pagination={{- totalCount: dashboards.data?.totalCount ?? null,- onChange: setPaginationState,- state: paginationState,- }}- onRowClick={(row) => {- router.push(- `/project/${projectId}/dashboards/${encodeURIComponent(row.id)}`,- );- }}- cellPadding="comfortable"- />- )}- </ConfirmationDialogController>- )}- </DialogController>- )}- </CloneFirstDialogController>- );-}diff --git a/web/src/features/dashboard/components/DashboardTable/ConnectedDashboardTable.tsx b/web/src/features/dashboard/components/DashboardTable/ConnectedDashboardTable.tsxnew file mode 100644index 0000000000..0dfb770693--- /dev/null+++ b/web/src/features/dashboard/components/DashboardTable/ConnectedDashboardTable.tsx@@ -0,0 +1,226 @@+import { showErrorToast, showSuccessToast } from "@/src/features/notifications";+import { useHasProjectAccess } from "@/src/features/rbac";+import { useEffect, useMemo, useState } from "react";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";+import { NumberParam, useQueryParams, withDefault } from "use-query-params";+import { api } from "@/src/utils/api";+import { safeExtract } from "@/src/utils/map-utils";+import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics";+import { EditDialogDashboardContent } from "@/src/features/dashboard/components/EditDialogDashboardContent";+import { CloneFirstDialogController } from "@/src/features/dashboard/components/CloneFirstDialogController";+import { useRouter } from "next/router";+import { DialogController } from "@/src/components/ui/dialog";+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";+import { PaginationBar } from "@/src/components/design-system/PaginationBar/PaginationBar";+import { type AsyncTableData } from "@/src/components/design-system/table/Table";+import { assertUnreachable } from "@/src/utils/types";+import { DashboardTable, type DashboardTableRow } from "./DashboardTable";++export function ConnectedDashboardTable() {+ const projectId = useProjectIdFromURL() as string;+ const { setDetailPageList } = useDetailPageLists();+ const router = useRouter();+ const utils = api.useUtils();+ const capture = usePostHogClientCapture();+ const hasAccess = useHasProjectAccess({ projectId, scope: "dashboards:CUD" });+ const [selectedDashboard, setSelectedDashboard] =+ useState<DashboardTableRow | null>(null);+ const cloneDashboard = api.dashboard.cloneDashboard.useMutation({+ onSuccess: () => {+ utils.dashboard.invalidate();+ showSuccessToast({+ title: "Dashboard cloned",+ description: "The dashboard has been cloned successfully",+ });+ },+ onError: (error) => {+ showErrorToast("Failed to clone dashboard", error.message);+ },+ });+ const deleteDashboard = api.dashboard.delete.useMutation({+ onSuccess: () => {+ capture("dashboard:delete_dashboard_button_click");+ showSuccessToast({+ title: "Dashboard deleted",+ description: "The dashboard has been deleted successfully",+ });+ utils.dashboard.invalidate();+ },+ onError: (error) => {+ showErrorToast("Failed to delete dashboard", error.message);+ },+ });++ const [orderByState, setOrderByState] = useOrderByState({+ column: "updatedAt",+ order: "DESC",+ });+ const [paginationState, setPaginationState] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 50),+ });++ const dashboards = api.dashboard.allDashboards.useQuery(+ {+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ projectId: projectId as string, // Typecast as query is enabled only when projectId is present+ orderBy: orderByState,+ },+ {+ enabled: Boolean(projectId),+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ );++ useEffect(() => {+ if (!dashboards.data) return;++ const pageCount = Math.max(+ 1,+ Math.ceil(dashboards.data.totalCount / paginationState.pageSize),+ );+ if (paginationState.pageIndex < pageCount) return;++ setPaginationState({ ...paginationState, pageIndex: 0 });+ }, [dashboards.data, paginationState, setPaginationState]);++ useEffect(() => {+ if (dashboards.isSuccess) {+ setDetailPageList(+ "dashboards",+ dashboards.data?.dashboards.map((d) => ({ id: d.id })),+ );+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dashboards.isSuccess, dashboards.data]);++ const {+ status: dashboardStatus,+ data: dashboardData,+ error: dashboardError,+ } = dashboards;+ const tableData = useMemo<AsyncTableData<DashboardTableRow[]>>(() => {+ if (dashboardStatus === "pending") return { status: "loading" };+ if (dashboardStatus === "error") {+ return { status: "error", error: dashboardError.message };+ }+ if (dashboardStatus === "success") {+ return {+ status: "success",+ data: safeExtract(dashboardData, "dashboards", []),+ };+ }++ return assertUnreachable(dashboardStatus);+ }, [dashboardData, dashboardError, dashboardStatus]);++ return (+ <CloneFirstDialogController+ projectId={projectId}+ dashboardId={selectedDashboard?.id ?? ""}+ dashboardName={selectedDashboard?.name ?? "Dashboard"}+ >+ {({ openDialog: openCloneFirstDialog }) => (+ <DialogController+ closeOnInteractionOutside={false}+ size="default"+ renderContent={({ closeDialog }) =>+ selectedDashboard ? (+ <EditDialogDashboardContent+ closeDialog={closeDialog}+ projectId={projectId}+ dashboardId={selectedDashboard.id}+ initialName={selectedDashboard.name}+ initialDescription={selectedDashboard.description}+ />+ ) : null+ }+ >+ {({ openDialog: openEditDialog }) => (+ <ConfirmationDialogController+ title="Delete dashboard"+ text="This action cannot be undone. It permanently deletes this dashboard."+ confirmLabel="Delete dashboard"+ variant="destructive"+ loading={deleteDashboard.isPending}+ onConfirm={async () => {+ if (!selectedDashboard) return;++ await deleteDashboard.mutateAsync({+ projectId,+ dashboardId: selectedDashboard.id,+ });+ }}+ >+ {({ openDialog: openDeleteDialog }) => (+ <div className="flex min-h-0 flex-1 flex-col">+ <DashboardTable+ projectId={projectId}+ hasAccess={hasAccess}+ loadingRowCount={Math.min(paginationState.pageSize, 8)}+ onEdit={(dashboard) => {+ setSelectedDashboard(dashboard);+ if (dashboard.owner === "PROJECT") {+ openEditDialog();+ return;+ }++ capture("dashboard:locked_edit_attempt", {+ dashboard_id: dashboard.id,+ attempt: "list_edit",+ surface: "list",+ });+ openCloneFirstDialog();+ }}+ onClone={(dashboard) => {+ cloneDashboard.mutate(+ {+ projectId,+ dashboardId: dashboard.id,+ },+ {+ onSuccess: () => {+ capture("dashboard:clone_dashboard", {+ source: "list_clone_button",+ dashboardId: dashboard.id,+ owner: dashboard.owner,+ });+ },+ },+ );+ }}+ onDelete={(dashboard) => {+ setSelectedDashboard(dashboard);+ capture("dashboard:delete_dashboard_form_open");+ openDeleteDialog();+ }}+ data={tableData}+ orderBy={orderByState}+ setOrderBy={setOrderByState}+ onRowClick={(row) => {+ router.push(+ `/project/${projectId}/dashboards/${encodeURIComponent(row.id)}`,+ );+ }}+ />+ <PaginationBar+ totalCount={dashboards.data?.totalCount ?? null}+ onChange={setPaginationState}+ state={paginationState}+ />+ </div>+ )}+ </ConfirmationDialogController>+ )}+ </DialogController>+ )}+ </CloneFirstDialogController>+ );+}diff --git a/web/src/features/dashboard/components/DashboardTable/DashboardTable.stories.tsx b/web/src/features/dashboard/components/DashboardTable/DashboardTable.stories.tsxnew file mode 100644index 0000000000..9dd3b217db--- /dev/null+++ b/web/src/features/dashboard/components/DashboardTable/DashboardTable.stories.tsx@@ -0,0 +1,33 @@+import { fn } from "storybook/test";++import preview from "../../../../../.storybook/preview";+import { DashboardTable } from "./DashboardTable";++const onEdit = fn();++const meta = preview.meta({+ component: DashboardTable,+});++export const Default = meta.story({+ args: {+ projectId: "project-1",+ hasAccess: true,+ onClone: fn(),+ onDelete: fn(),+ onEdit,+ data: {+ status: "success",+ data: [+ {+ id: "dashboard-1",+ name: "Product analytics",+ description: "Key product metrics",+ owner: "PROJECT",+ createdAt: new Date("2026-09-01"),+ updatedAt: new Date("2026-09-18"),+ },+ ],+ },+ },+});diff --git a/web/src/features/dashboard/components/DashboardTable/DashboardTable.tsx b/web/src/features/dashboard/components/DashboardTable/DashboardTable.tsxnew file mode 100644index 0000000000..eb59bfa7ad--- /dev/null+++ b/web/src/features/dashboard/components/DashboardTable/DashboardTable.tsx@@ -0,0 +1,148 @@+import { useCallback, useMemo } from "react";+import { Copy, Edit, Trash2 } from "lucide-react";++import {+ Table,+ type TableProps,+} from "@/src/components/design-system/table/Table";+import { createBadgeTableColumn } from "@/src/components/design-system/table/columns/createBadgeTableColumn";+import { createDateTableColumn } from "@/src/components/design-system/table/columns/createDateTableColumn";+import { createLinkTableColumn } from "@/src/components/design-system/table/columns/createLinkTableColumn";+import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";+import { type LangfuseColumnDef } from "@/src/components/table/types";++export type DashboardTableRow = {+ id: string;+ name: string;+ description: string;+ createdAt: Date;+ updatedAt: Date;+ owner: "PROJECT" | "LANGFUSE";+};++export function DashboardTable({+ hasAccess,+ onClone,+ onDelete,+ onEdit,+ projectId,+ ...tableProps+}: Pick<+ TableProps<DashboardTableRow>,+ | "data"+ | "loadingRowCount"+ | "noResultsMessage"+ | "onRowClick"+ | "orderBy"+ | "setOrderBy"+> & {+ hasAccess: boolean;+ onClone: (dashboard: DashboardTableRow) => void;+ onDelete: (dashboard: DashboardTableRow) => void;+ onEdit: (dashboard: DashboardTableRow) => void;+ projectId: string;+}) {+ const columns = useMemo<LangfuseColumnDef<DashboardTableRow>[]>(+ () => [+ createLinkTableColumn<DashboardTableRow>({+ accessorKey: "name",+ header: "Name",+ enableSorting: true,+ size: 200,+ getCell: (name, { row }) => {+ if (!name) return undefined;++ return {+ type: "link",+ props: {+ path: `/project/${projectId}/dashboards/${encodeURIComponent(row.original.id)}`,+ value: name,+ },+ };+ },+ }),+ createTextTableColumn<DashboardTableRow>({+ accessorKey: "description",+ header: "Description",+ size: 300,+ }),+ createBadgeTableColumn<DashboardTableRow>({+ id: "ownerTag",+ accessorFn: (row) =>+ row.owner === "LANGFUSE" ? "Langfuse" : "Project",+ header: "Owner",+ size: 80,+ getVariant: (owner) => (owner === "Langfuse" ? "teal" : "blue"),+ }),+ createDateTableColumn<DashboardTableRow>({+ accessorKey: "createdAt",+ header: "Created At",+ enableSorting: true,+ mode: "relative",+ size: 80,+ }),+ createDateTableColumn<DashboardTableRow>({+ accessorKey: "updatedAt",+ header: "Updated At",+ enableSorting: true,+ mode: "relative",+ size: 80,+ }),+ ],+ [projectId],+ );+ const actions = useCallback<+ NonNullable<TableProps<DashboardTableRow>["actions"]>+ >(+ (dashboard) => [+ {+ id: "edit",+ type: "item",+ title: "Edit",+ icon: Edit,+ disabled: hasAccess+ ? undefined+ : { reason: "You do not have permission to edit dashboards" },+ onClick: () => onEdit(dashboard),+ },+ {+ id: "clone",+ type: "item",+ title: "Clone",+ icon: Copy,+ disabled: hasAccess+ ? undefined+ : { reason: "You do not have permission to clone dashboards" },+ onClick: () => onClone(dashboard),+ },+ ...(dashboard.owner === "PROJECT"+ ? [+ { id: "delete-separator", type: "separator" as const },+ {+ id: "delete",+ type: "item" as const,+ title: "Delete",+ icon: Trash2,+ variant: "destructive" as const,+ disabled: hasAccess+ ? undefined+ : {+ reason: "You do not have permission to delete dashboards",+ },+ onClick: () => onDelete(dashboard),+ },+ ]+ : []),+ ],+ [hasAccess, onClone, onDelete, onEdit],+ );++ return (+ <Table+ tableName="dashboards"+ columns={columns}+ actions={actions}+ {...tableProps}+ />+ );+}diff --git a/web/src/features/widgets/chart-library/chartTypeIcons.ts b/web/src/features/widgets/chart-library/chartTypeIcons.tsnew file mode 100644index 0000000000..d11345068c--- /dev/null+++ b/web/src/features/widgets/chart-library/chartTypeIcons.ts@@ -0,0 +1,27 @@+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import {+ AreaChart,+ BarChart,+ BarChart3,+ BarChartHorizontal,+ Hash,+ LineChart,+ PieChart,+ Table,+ type LucideIcon,+} from "lucide-react";++export const dashboardWidgetChartTypeIcons: Record<+ DashboardWidgetChartType,+ LucideIcon+> = {+ LINE_TIME_SERIES: LineChart,+ AREA_TIME_SERIES: AreaChart,+ BAR_TIME_SERIES: BarChart,+ HORIZONTAL_BAR: BarChartHorizontal,+ VERTICAL_BAR: BarChart,+ PIE: PieChart,+ NUMBER: Hash,+ HISTOGRAM: BarChart3,+ PIVOT_TABLE: Table,+};diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsxindex a5f22d099e..f88c248ba9 100644--- a/web/src/features/widgets/components/WidgetForm.tsx+++ b/web/src/features/widgets/components/WidgetForm.tsx@@ -68,19 +68,8 @@ import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";import { showErrorToast } from "@/src/features/notifications";import { type FilterState } from "@langfuse/shared";import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";-import {- BarChart,- PieChart,- LineChart,- BarChartHorizontal,- Hash,- BarChart3,- Table,- Plus,- X,- AlertCircle,- Sparkles,-} from "lucide-react";+import { Plus, X, AlertCircle, Sparkles } from "lucide-react";+import { dashboardWidgetChartTypeIcons } from "@/src/features/widgets/chart-library/chartTypeIcons";import {Popover,PopoverContent,@@ -142,49 +131,49 @@ const chartTypes: ChartType[] = [group: "total-value",name: "Big Number",value: "NUMBER",- icon: Hash,+ icon: dashboardWidgetChartTypeIcons.NUMBER,},{group: "time-series",name: "Line Chart",value: "LINE_TIME_SERIES",- icon: LineChart,+ icon: dashboardWidgetChartTypeIcons.LINE_TIME_SERIES,},{group: "time-series",name: "Vertical Bar Chart",value: "BAR_TIME_SERIES",- icon: BarChart,+ icon: dashboardWidgetChartTypeIcons.BAR_TIME_SERIES,},{group: "total-value",name: "Horizontal Bar Chart",value: "HORIZONTAL_BAR",- icon: BarChartHorizontal,+ icon: dashboardWidgetChartTypeIcons.HORIZONTAL_BAR,},{group: "total-value",name: "Vertical Bar Chart",value: "VERTICAL_BAR",- icon: BarChart,+ icon: dashboardWidgetChartTypeIcons.VERTICAL_BAR,},{group: "total-value",name: "Histogram",value: "HISTOGRAM",- icon: BarChart3,+ icon: dashboardWidgetChartTypeIcons.HISTOGRAM,},{group: "total-value",name: "Pie Chart",value: "PIE",- icon: PieChart,+ icon: dashboardWidgetChartTypeIcons.PIE,},{group: "total-value",name: "Pivot Table",value: "PIVOT_TABLE",- icon: Table,+ icon: dashboardWidgetChartTypeIcons.PIVOT_TABLE,},];diff --git a/web/src/features/widgets/components/WidgetTable.tsx b/web/src/features/widgets/components/WidgetTable.tsxdeleted file mode 100644index a1c2ddf55b..0000000000--- a/web/src/features/widgets/components/WidgetTable.tsx+++ /dev/null@@ -1,416 +0,0 @@-/* eslint-disable no-nested-ternary */-import { showErrorToast, showSuccessToast } from "@/src/features/notifications";-import { useEffect, type ReactNode } from "react";-import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";-import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";-import { NumberParam, useQueryParams, withDefault } from "use-query-params";-import { api } from "@/src/utils/api";-import { DataTable } from "@/src/components/table/data-table";-import { type LangfuseColumnDef } from "@/src/components/table/types";-import { createColumnHelper } from "@tanstack/react-table";-import { createDateTableColumn } from "@/src/components/design-system/table/columns/createDateTableColumn";-import { createLinkTableColumn } from "@/src/components/design-system/table/columns/createLinkTableColumn";-import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";-import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";-import startCase from "lodash/startCase";-import { Button } from "@/src/components/ui/button";-import { useHasProjectAccess } from "@/src/features/rbac";-import { Copy, CopyPlus, FileJson, MoreVertical, Trash } from "lucide-react";-import {- buildWidgetExport,- downloadWidgetJson,- toWidgetCreateFields,- type WidgetExportSource,-} from "@/src/features/widgets/utils/import-export-utils";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/src/components/ui/dropdown-menu";-import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";-import { copyTextToClipboard } from "@/src/utils/clipboard";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics";-import { useRouter } from "next/router";-import { getChartTypeDisplayName } from "@/src/features/widgets/chart-library/utils";-import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";-import { type metricAggregations } from "@langfuse/shared/query";-import { type z } from "zod";--type WidgetTableRow = {- id: string;- name: string;- description: string;- view: string;- chartType: string;- createdAt: Date;- updatedAt: Date;- owner: "PROJECT" | "LANGFUSE";-};--function DeleteWidgetDialogController({- children,- hasDeleteAccess,- projectId,- widgetId,-}: {- children: (control: {- disabled: boolean;- openDialog: () => void;- }) => ReactNode;- hasDeleteAccess: boolean;- projectId: string | undefined;- widgetId: string;-}) {- const utils = api.useUtils();- const capture = usePostHogClientCapture();- const deleteWidget = api.dashboardWidgets.delete.useMutation({- onSuccess: () => {- utils.dashboardWidgets.invalidate();- capture("dashboard:delete_widget_form_open");- },- onError: (error) => {- if (error.data?.code === "CONFLICT") {- showErrorToast(- "Widget in use",- "Widget is still in use. Please remove it from all dashboards before deleting it.",- );- return;- }-- showErrorToast("Failed to delete widget", error.message);- },- });-- return (- <ConfirmationDialogController- title="Delete widget"- text="This action permanently deletes this widget. If the widget is currently used in any dashboard, you will need to remove it from those dashboards first."- confirmLabel="Delete Widget"- variant="destructive"- disabled={!hasDeleteAccess}- loading={deleteWidget.isPending}- onConfirm={async () => {- if (!projectId) {- console.error("Project ID is missing");- return;- }- await deleteWidget.mutateAsync({ projectId, widgetId });- }}- >- {({ openDialog }) => children({ disabled: !hasDeleteAccess, openDialog })}- </ConfirmationDialogController>- );-}--function WidgetActionsCell({- widgetId,- owner,-}: {- widgetId: string;- owner: "PROJECT" | "LANGFUSE";-}) {- const projectId = useProjectIdFromURL();- const utils = api.useUtils();- const capture = usePostHogClientCapture();- const hasCUDAccess = useHasProjectAccess({- projectId,- scope: "dashboards:CUD",- });- const hasDeleteAccess = hasCUDAccess && owner !== "LANGFUSE";- const { mutateAsync: createWidgetAsync } =- api.dashboardWidgets.create.useMutation();-- const fetchExportSource = async (): Promise<WidgetExportSource> => {- if (!projectId) {- throw new Error("Project ID is missing");- }- const widget = await utils.dashboardWidgets.get.fetch(- {- projectId,- widgetId,- },- // Serve rapid repeat actions (double-click, copy-then-download) from- // the cache instead of firing a request per menu click.- { staleTime: 30_000 },- );-- return {- name: widget.name,- description: widget.description,- view: widget.view,- dimensions: widget.dimensions,- metrics: widget.metrics.map((metric) => ({- measure: metric.measure,- agg: metric.agg as z.infer<typeof metricAggregations>,- })),- filters: widget.filters,- chartType: widget.chartType,- chartConfig: widget.chartConfig,- minVersion: widget.minVersion,- };- };-- const handleDownloadJson = async () => {- try {- downloadWidgetJson(await fetchExportSource());- capture("dashboard:widget_json_downloaded", {- surface: "widget_table",- widget_id: widgetId,- });- } catch (error) {- showErrorToast(- "Failed to download widget",- error instanceof Error ? error.message : "Unknown error",- );- }- };-- const handleCopyToClipboard = async () => {- try {- const exportSource = await fetchExportSource();- await copyTextToClipboard(- JSON.stringify(buildWidgetExport(exportSource), null, 2),- );- capture("dashboard:widget_copied_to_clipboard", {- surface: "widget_table",- kind: "widget",- widget_id: widgetId,- });- showSuccessToast({- title: "Widget copied",- description: "Paste it on any dashboard with Cmd/Ctrl+V.",- });- } catch (error) {- showErrorToast(- "Failed to copy widget",- error instanceof Error ? error.message : "Unknown error",- );- }- };-- const handleDuplicate = async () => {- try {- if (!projectId) {- throw new Error("Project ID is missing");- }- const exportSource = await fetchExportSource();- await createWidgetAsync({- projectId,- ...toWidgetCreateFields(exportSource),- name: `${exportSource.name} (Copy)`,- });- capture("dashboard:widget_duplicated", {- surface: "widget_table",- kind: "widget",- chart_type: exportSource.chartType,- view: exportSource.view,- });- utils.dashboardWidgets.invalidate();- showSuccessToast({- title: "Widget cloned",- description: `Created "${exportSource.name} (Copy)".`,- });- } catch (error) {- showErrorToast(- "Failed to duplicate widget",- error instanceof Error ? error.message : "Unknown error",- );- }- };-- return (- <DeleteWidgetDialogController- hasDeleteAccess={hasDeleteAccess}- projectId={projectId}- widgetId={widgetId}- >- {({ disabled, openDialog }) => (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="xs" aria-label="Widget actions">- <MoreVertical className="h-4 w-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={handleCopyToClipboard}>- <Copy className="mr-2 h-4 w-4" />- Copy widget- </DropdownMenuItem>- <DropdownMenuItem- disabled={!hasCUDAccess}- onClick={handleDuplicate}- >- <CopyPlus className="mr-2 h-4 w-4" />- Clone- </DropdownMenuItem>- <DropdownMenuItem onClick={handleDownloadJson}>- <FileJson className="mr-2 h-4 w-4" />- Download as JSON- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- disabled={disabled}- onClick={openDialog}- className="text-destructive focus:text-destructive"- >- <Trash className="mr-2 h-4 w-4" />- Delete- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- </DeleteWidgetDialogController>- );-}--export function DashboardWidgetTable() {- const projectId = useProjectIdFromURL();- const { setDetailPageList } = useDetailPageLists();- const router = useRouter();-- const [orderByState, setOrderByState] = useOrderByState({- column: "updatedAt",- order: "DESC",- });- const [paginationState, setPaginationState] = useQueryParams({- pageIndex: withDefault(NumberParam, 0),- pageSize: withDefault(NumberParam, 50),- });-- const widgets = api.dashboardWidgets.all.useQuery(- {- page: paginationState.pageIndex,- limit: paginationState.pageSize,- projectId: projectId as string, // Typecast as query is enabled only when projectId is present- orderBy: orderByState,- },- {- enabled: Boolean(projectId),- trpc: {- context: {- skipBatch: true,- },- },- },- );-- useEffect(() => {- if (widgets.isSuccess) {- setDetailPageList(- "widgets",- widgets.data?.widgets.map((w) => ({ id: w.id })),- );- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [widgets.isSuccess, widgets.data]);-- const columnHelper = createColumnHelper<WidgetTableRow>();- const widgetColumns = [- createLinkTableColumn<WidgetTableRow>({- accessorKey: "name",- header: "Name",- enableSorting: true,- size: 200,- getCell: (name, { row }) => {- if (name) {- return {- type: "link",- props: {- path: `/project/${projectId}/widgets/${encodeURIComponent(row.original.id)}`,- value: name,- },- };- }-- return undefined;- },- }),- createTextTableColumn<WidgetTableRow>({- accessorKey: "description",- header: "Description",- size: 300,- }),- createTextTableColumn<WidgetTableRow>({- accessorKey: "view",- header: "View Type",- enableSorting: true,- size: 100,- mapValue: (value) => startCase(value?.toLowerCase()),- }),- createTextTableColumn<WidgetTableRow>({- accessorKey: "chartType",- header: "Chart Type",- enableSorting: true,- size: 100,- mapValue: (value) =>- value- ? getChartTypeDisplayName(value as DashboardWidgetChartType)- : undefined,- }),- createDateTableColumn<WidgetTableRow>({- accessorKey: "createdAt",- header: "Created At",- enableSorting: true,- size: 150,- }),- createDateTableColumn<WidgetTableRow>({- accessorKey: "updatedAt",- header: "Updated At",- enableSorting: true,- size: 150,- }),- columnHelper.display({- id: "actions",- header: "Actions",- size: 70,- cell: (row) => {- const id = row.row.original.id;- return (- <div- className="flex items-center gap-1"- onClick={(e) => e.stopPropagation()}- >- <WidgetActionsCell widgetId={id} owner={row.row.original.owner} />- </div>- );- },- }),- ] as LangfuseColumnDef<WidgetTableRow>[];-- return (- <DataTable- tableName="widgets"- columns={widgetColumns}- data={- widgets.isLoading- ? { isLoading: true, isError: false }- : widgets.isError- ? {- isLoading: false,- isError: true,- error: widgets.error.message,- }- : {- isLoading: false,- isError: false,- data: widgets.data?.widgets ?? [],- }- }- orderBy={orderByState}- setOrderBy={setOrderByState}- cellPadding="comfortable"- pagination={{- totalCount: widgets.data?.totalCount ?? null,- onChange: setPaginationState,- state: paginationState,- }}- onRowClick={(row) => {- router.push(- `/project/${projectId}/widgets/${encodeURIComponent(row.id)}`,- );- }}- />- );-}diff --git a/web/src/features/widgets/components/WidgetTable/ConnectedWidgetTable.tsx b/web/src/features/widgets/components/WidgetTable/ConnectedWidgetTable.tsxnew file mode 100644index 0000000000..c9213ba84a--- /dev/null+++ b/web/src/features/widgets/components/WidgetTable/ConnectedWidgetTable.tsx@@ -0,0 +1,289 @@+import { showErrorToast, showSuccessToast } from "@/src/features/notifications";+import { useCallback, useEffect, useMemo, useState } from "react";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";+import { NumberParam, useQueryParams, withDefault } from "use-query-params";+import { api } from "@/src/utils/api";+import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";+import { useHasProjectAccess } from "@/src/features/rbac";+import {+ buildWidgetExport,+ downloadWidgetJson,+ toWidgetCreateFields,+ type WidgetExportSource,+} from "@/src/features/widgets/utils/import-export-utils";+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";+import { copyTextToClipboard } from "@/src/utils/clipboard";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics";+import { useRouter } from "next/router";+import { type metricAggregations } from "@langfuse/shared/query";+import { type z } from "zod";+import { PaginationBar } from "@/src/components/design-system/PaginationBar/PaginationBar";+import { type AsyncTableData } from "@/src/components/design-system/table/Table";+import { assertUnreachable } from "@/src/utils/types";+import { DashboardWidgetTable, type WidgetTableRow } from "./WidgetTable";++export function ConnectedDashboardWidgetTable() {+ const projectId = useProjectIdFromURL();+ const utils = api.useUtils();+ const capture = usePostHogClientCapture();+ const [selectedWidget, setSelectedWidget] = useState<WidgetTableRow | null>(+ null,+ );+ const deleteWidget = api.dashboardWidgets.delete.useMutation({+ onSuccess: () => {+ utils.dashboardWidgets.invalidate();+ capture("dashboard:delete_widget_form_open");+ },+ onError: (error) => {+ if (error.data?.code === "CONFLICT") {+ showErrorToast(+ "Widget in use",+ "Widget is still in use. Please remove it from all dashboards before deleting it.",+ );+ return;+ }++ showErrorToast("Failed to delete widget", error.message);+ },+ });++ return (+ <ConfirmationDialogController+ title="Delete widget"+ text="This action permanently deletes this widget. If the widget is currently used in any dashboard, you will need to remove it from those dashboards first."+ confirmLabel="Delete Widget"+ variant="destructive"+ loading={deleteWidget.isPending}+ onConfirm={async () => {+ if (!projectId || !selectedWidget) return;+ await deleteWidget.mutateAsync({+ projectId,+ widgetId: selectedWidget.id,+ });+ }}+ >+ {({ openDialog }) => (+ <ConnectedDashboardWidgetTableContent+ openDeleteDialog={(widget) => {+ setSelectedWidget(widget);+ openDialog();+ }}+ />+ )}+ </ConfirmationDialogController>+ );+}++function ConnectedDashboardWidgetTableContent({+ openDeleteDialog,+}: {+ openDeleteDialog: (widget: WidgetTableRow) => void;+}) {+ const projectId = useProjectIdFromURL();+ const { setDetailPageList } = useDetailPageLists();+ const router = useRouter();+ const utils = api.useUtils();+ const capture = usePostHogClientCapture();+ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });+ const { mutateAsync: createWidgetAsync } =+ api.dashboardWidgets.create.useMutation();++ const fetchExportSource = useCallback(+ async (widgetId: string): Promise<WidgetExportSource> => {+ if (!projectId) throw new Error("Project ID is missing");++ const widget = await utils.dashboardWidgets.get.fetch(+ { projectId, widgetId },+ { staleTime: 30_000 },+ );++ return {+ name: widget.name,+ description: widget.description,+ view: widget.view,+ dimensions: widget.dimensions,+ metrics: widget.metrics.map((metric) => ({+ measure: metric.measure,+ agg: metric.agg as z.infer<typeof metricAggregations>,+ })),+ filters: widget.filters,+ chartType: widget.chartType,+ chartConfig: widget.chartConfig,+ minVersion: widget.minVersion,+ };+ },+ [projectId, utils.dashboardWidgets.get],+ );++ const handleDownloadJson = useCallback(+ async (widgetId: string) => {+ try {+ downloadWidgetJson(await fetchExportSource(widgetId));+ capture("dashboard:widget_json_downloaded", {+ surface: "widget_table",+ widget_id: widgetId,+ });+ } catch (error) {+ showErrorToast(+ "Failed to download widget",+ error instanceof Error ? error.message : "Unknown error",+ );+ }+ },+ [capture, fetchExportSource],+ );++ const handleCopyToClipboard = useCallback(+ async (widgetId: string) => {+ try {+ const exportSource = await fetchExportSource(widgetId);+ await copyTextToClipboard(+ JSON.stringify(buildWidgetExport(exportSource), null, 2),+ );+ capture("dashboard:widget_copied_to_clipboard", {+ surface: "widget_table",+ kind: "widget",+ widget_id: widgetId,+ });+ showSuccessToast({+ title: "Widget copied",+ description: "Paste it on any dashboard with Cmd/Ctrl+V.",+ });+ } catch (error) {+ showErrorToast(+ "Failed to copy widget",+ error instanceof Error ? error.message : "Unknown error",+ );+ }+ },+ [capture, fetchExportSource],+ );++ const handleDuplicate = useCallback(+ async (widgetId: string) => {+ try {+ if (!projectId) throw new Error("Project ID is missing");++ const exportSource = await fetchExportSource(widgetId);+ await createWidgetAsync({+ projectId,+ ...toWidgetCreateFields(exportSource),+ name: `${exportSource.name} (Copy)`,+ });+ capture("dashboard:widget_duplicated", {+ surface: "widget_table",+ kind: "widget",+ chart_type: exportSource.chartType,+ view: exportSource.view,+ });+ utils.dashboardWidgets.invalidate();+ showSuccessToast({+ title: "Widget cloned",+ description: `Created "${exportSource.name} (Copy)".`,+ });+ } catch (error) {+ showErrorToast(+ "Failed to duplicate widget",+ error instanceof Error ? error.message : "Unknown error",+ );+ }+ },+ [capture, createWidgetAsync, fetchExportSource, projectId, utils],+ );++ const [orderByState, setOrderByState] = useOrderByState({+ column: "updatedAt",+ order: "DESC",+ });+ const [paginationState, setPaginationState] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 50),+ });++ const widgets = api.dashboardWidgets.all.useQuery(+ {+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ projectId: projectId as string, // Typecast as query is enabled only when projectId is present+ orderBy: orderByState,+ },+ {+ enabled: Boolean(projectId),+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ );++ useEffect(() => {+ if (!widgets.data) return;++ const pageCount = Math.max(+ 1,+ Math.ceil(widgets.data.totalCount / paginationState.pageSize),+ );+ if (paginationState.pageIndex < pageCount) return;++ setPaginationState({ ...paginationState, pageIndex: 0 });+ }, [paginationState, setPaginationState, widgets.data]);++ useEffect(() => {+ if (widgets.isSuccess) {+ setDetailPageList(+ "widgets",+ widgets.data?.widgets.map((w) => ({ id: w.id })),+ );+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [widgets.isSuccess, widgets.data]);++ const {+ status: widgetStatus,+ data: widgetData,+ error: widgetError,+ } = widgets;+ const tableData = useMemo<AsyncTableData<WidgetTableRow[]>>(() => {+ if (widgetStatus === "pending") return { status: "loading" };+ if (widgetStatus === "error") {+ return { status: "error", error: widgetError.message };+ }+ if (widgetStatus === "success") {+ return { status: "success", data: widgetData.widgets };+ }++ return assertUnreachable(widgetStatus);+ }, [widgetData, widgetError, widgetStatus]);++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <DashboardWidgetTable+ projectId={projectId}+ hasCUDAccess={hasCUDAccess}+ loadingRowCount={Math.min(paginationState.pageSize, 8)}+ onCopy={(widget) => handleCopyToClipboard(widget.id)}+ onDelete={openDeleteDialog}+ onDownload={(widget) => handleDownloadJson(widget.id)}+ onDuplicate={(widget) => handleDuplicate(widget.id)}+ data={tableData}+ orderBy={orderByState}+ setOrderBy={setOrderByState}+ onRowClick={(row) => {+ router.push(+ `/project/${projectId}/widgets/${encodeURIComponent(row.id)}`,+ );+ }}+ />+ <PaginationBar+ totalCount={widgets.data?.totalCount ?? null}+ onChange={setPaginationState}+ state={paginationState}+ />+ </div>+ );+}diff --git a/web/src/features/widgets/components/WidgetTable/WidgetTable.stories.tsx b/web/src/features/widgets/components/WidgetTable/WidgetTable.stories.tsxnew file mode 100644index 0000000000..bdcd5447bb--- /dev/null+++ b/web/src/features/widgets/components/WidgetTable/WidgetTable.stories.tsx@@ -0,0 +1,36 @@+import { fn } from "storybook/test";++import preview from "../../../../../.storybook/preview";+import { DashboardWidgetTable } from "./WidgetTable";++const onCopy = fn();++const meta = preview.meta({+ component: DashboardWidgetTable,+});++export const Default = meta.story({+ args: {+ projectId: "project-1",+ hasCUDAccess: true,+ onCopy,+ onDelete: fn(),+ onDownload: fn(),+ onDuplicate: fn(),+ data: {+ status: "success",+ data: [+ {+ id: "widget-1",+ name: "Trace count",+ description: "Daily trace volume",+ view: "TRACES",+ chartType: "LINE_TIME_SERIES",+ owner: "PROJECT",+ createdAt: new Date("2026-09-01"),+ updatedAt: new Date("2026-09-18"),+ },+ ],+ },+ },+});diff --git a/web/src/features/widgets/components/WidgetTable/WidgetTable.tsx b/web/src/features/widgets/components/WidgetTable/WidgetTable.tsxnew file mode 100644index 0000000000..6f28c1ae04--- /dev/null+++ b/web/src/features/widgets/components/WidgetTable/WidgetTable.tsx@@ -0,0 +1,234 @@+import { useCallback, useMemo } from "react";+import { Copy, CopyPlus, FileJson, Trash } from "lucide-react";+import startCase from "lodash/startCase";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";++import {+ Table,+ type TableProps,+} from "@/src/components/design-system/table/Table";+import { createDateTableColumn } from "@/src/components/design-system/table/columns/createDateTableColumn";+import { createBadgeTableColumn } from "@/src/components/design-system/table/columns/createBadgeTableColumn";+import { createLinkTableColumn } from "@/src/components/design-system/table/columns/createLinkTableColumn";+import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import { dashboardWidgetChartTypeIcons } from "@/src/features/widgets/chart-library/chartTypeIcons";++const TYPE_COLUMN_SIZE = 140;++const chartTypeLabels: Record<DashboardWidgetChartType, string> = {+ LINE_TIME_SERIES: "Line Chart",+ AREA_TIME_SERIES: "Area Chart",+ BAR_TIME_SERIES: "Bar Chart",+ HORIZONTAL_BAR: "Horizontal Bar Chart",+ VERTICAL_BAR: "Vertical Bar Chart",+ PIE: "Pie Chart",+ NUMBER: "Big Number",+ HISTOGRAM: "Histogram",+ PIVOT_TABLE: "Pivot Table",+};++const chartDisplayModes: Record<DashboardWidgetChartType, string> = {+ LINE_TIME_SERIES: "Time Series",+ AREA_TIME_SERIES: "Time Series",+ BAR_TIME_SERIES: "Time Series",+ HORIZONTAL_BAR: "Total Value",+ VERTICAL_BAR: "Total Value",+ PIE: "Total Value",+ NUMBER: "Total Value",+ HISTOGRAM: "Total Value",+ PIVOT_TABLE: "Total Value",+};++const viewBadgeVariants = {+ TRACES: "blue",+ OBSERVATIONS: "success",+ SCORES_NUMERIC: "warning",+ SCORES_BOOLEAN: "violet",+ SCORES_CATEGORICAL: "destructive",+} as const;++const chartTypeBadgeVariants = {+ LINE_TIME_SERIES: "blue",+ AREA_TIME_SERIES: "blue",+ BAR_TIME_SERIES: "violet",+ HORIZONTAL_BAR: "teal",+ VERTICAL_BAR: "destructive",+ PIE: "warning",+ NUMBER: "success",+ HISTOGRAM: "violet",+ PIVOT_TABLE: "teal",+} as const;++export type WidgetTableRow = {+ id: string;+ name: string;+ description: string;+ view: string;+ chartType: string;+ createdAt: Date;+ updatedAt: Date;+ owner: "PROJECT" | "LANGFUSE";+};++export function DashboardWidgetTable({+ projectId,+ hasCUDAccess,+ onCopy,+ onDelete,+ onDownload,+ onDuplicate,+ ...tableProps+}: Pick<+ TableProps<WidgetTableRow>,+ | "data"+ | "loadingRowCount"+ | "noResultsMessage"+ | "onRowClick"+ | "orderBy"+ | "setOrderBy"+> & {+ projectId: string | undefined;+ hasCUDAccess: boolean;+ onCopy: (widget: WidgetTableRow) => void;+ onDelete: (widget: WidgetTableRow) => void;+ onDownload: (widget: WidgetTableRow) => void;+ onDuplicate: (widget: WidgetTableRow) => void;+}) {+ const columns = useMemo<LangfuseColumnDef<WidgetTableRow>[]>(+ () => [+ createLinkTableColumn<WidgetTableRow>({+ accessorKey: "name",+ header: "Name",+ enableSorting: true,+ size: 200,+ getCell: (name, { row }) =>+ name+ ? {+ type: "link",+ props: {+ path: `/project/${projectId}/widgets/${encodeURIComponent(row.original.id)}`,+ value: name,+ },+ }+ : undefined,+ }),+ createTextTableColumn<WidgetTableRow>({+ accessorKey: "description",+ header: "Description",+ size: 300,+ }),+ createBadgeTableColumn<WidgetTableRow>({+ accessorFn: (row) => startCase(row.view.toLowerCase()),+ id: "view",+ header: "View Type",+ enableSorting: true,+ size: TYPE_COLUMN_SIZE,+ getVariant: (_view, { row }) =>+ viewBadgeVariants[+ row.original.view as keyof typeof viewBadgeVariants+ ] ?? "blue",+ }),+ createBadgeTableColumn<WidgetTableRow>({+ accessorFn: (row) =>+ chartTypeLabels[row.chartType as DashboardWidgetChartType],+ id: "chartType",+ header: "Chart Type",+ enableSorting: true,+ size: TYPE_COLUMN_SIZE,+ getVariant: (_chartType, { row }) =>+ chartTypeBadgeVariants[+ row.original.chartType as DashboardWidgetChartType+ ],+ getIcon: (_chartType, { row }) =>+ dashboardWidgetChartTypeIcons[+ row.original.chartType as DashboardWidgetChartType+ ],+ }),+ createBadgeTableColumn<WidgetTableRow>({+ accessorFn: (row) =>+ chartDisplayModes[row.chartType as DashboardWidgetChartType],+ id: "displayMode",+ header: "Display Mode",+ enableSorting: true,+ size: TYPE_COLUMN_SIZE,+ getVariant: (displayMode) =>+ displayMode === "Time Series" ? "blue" : "teal",+ getIcon: (displayMode) =>+ displayMode === "Time Series"+ ? dashboardWidgetChartTypeIcons.LINE_TIME_SERIES+ : dashboardWidgetChartTypeIcons.NUMBER,+ }),+ createDateTableColumn<WidgetTableRow>({+ accessorKey: "createdAt",+ header: "Created At",+ enableSorting: true,+ mode: "relative",+ size: 100,+ }),+ createDateTableColumn<WidgetTableRow>({+ accessorKey: "updatedAt",+ header: "Updated At",+ enableSorting: true,+ mode: "relative",+ size: 100,+ }),+ ],+ [projectId],+ );+ const actions = useCallback<+ NonNullable<TableProps<WidgetTableRow>["actions"]>+ >(+ (row) => [+ {+ id: "copy",+ type: "item",+ title: "Copy widget",+ icon: Copy,+ onClick: () => onCopy(row),+ },+ {+ id: "clone",+ type: "item",+ title: "Clone",+ icon: CopyPlus,+ disabled: hasCUDAccess+ ? undefined+ : { reason: "You do not have permission to clone widgets" },+ onClick: () => onDuplicate(row),+ },+ {+ id: "download",+ type: "item",+ title: "Download as JSON",+ icon: FileJson,+ onClick: () => onDownload(row),+ },+ { id: "delete-separator", type: "separator" },+ {+ id: "delete",+ type: "item",+ title: "Delete",+ icon: Trash,+ variant: "destructive",+ disabled:+ hasCUDAccess && row.owner !== "LANGFUSE"+ ? undefined+ : {+ reason: "You do not have permission to delete this widget",+ },+ onClick: () => onDelete(row),+ },+ ],+ [hasCUDAccess, onCopy, onDelete, onDownload, onDuplicate],+ );++ return (+ <Table+ tableName="widgets"+ columns={columns}+ actions={actions}+ {...tableProps}+ />+ );+}diff --git a/web/src/features/widgets/index.ts b/web/src/features/widgets/index.tsindex 2ceaa1073c..479cecc884 100644--- a/web/src/features/widgets/index.ts+++ b/web/src/features/widgets/index.ts@@ -34,4 +34,4 @@ export type {} from "@/src/features/widgets/utils/import-export-utils";export { DashboardWidget } from "@/src/features/widgets/components/DashboardWidget";export { WidgetForm } from "@/src/features/widgets/components/WidgetForm";-export { DashboardWidgetTable } from "@/src/features/widgets/components/WidgetTable";+export { ConnectedDashboardWidgetTable } from "@/src/features/widgets/components/WidgetTable/ConnectedWidgetTable";diff --git a/web/src/pages/project/[projectId]/dashboards/index.tsx b/web/src/pages/project/[projectId]/dashboards/index.tsxindex 0fb277d87f..039b89c393 100644--- a/web/src/pages/project/[projectId]/dashboards/index.tsx+++ b/web/src/pages/project/[projectId]/dashboards/index.tsx@@ -1,6 +1,6 @@import { useRouter } from "next/router";import Page from "@/src/components/layouts/page";-import { DashboardTable } from "@/src/features/dashboard/components/DashboardTable";+import { ConnectedDashboardTable } from "@/src/features/dashboard/components/DashboardTable/ConnectedDashboardTable";import { ActionButton } from "@/src/components/ActionButton";import { PlusIcon } from "lucide-react";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";@@ -42,7 +42,7 @@ export default function Dashboards() {),}}>- <DashboardTable />+ <ConnectedDashboardTable /></Page>);}diff --git a/web/src/pages/project/[projectId]/widgets/index.tsx b/web/src/pages/project/[projectId]/widgets/index.tsxindex a7c222d954..51b3f1e791 100644--- a/web/src/pages/project/[projectId]/widgets/index.tsx+++ b/web/src/pages/project/[projectId]/widgets/index.tsx@@ -3,7 +3,7 @@ import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccesimport Page from "@/src/components/layouts/page";import { ActionButton } from "@/src/components/ActionButton";import { PlusIcon } from "lucide-react";-import { DashboardWidgetTable } from "@/src/features/widgets";+import { ConnectedDashboardWidgetTable } from "@/src/features/widgets";import {getDashboardTabs,DASHBOARD_TABS,@@ -42,7 +42,7 @@ export default function Widgets() {),}}>- <DashboardWidgetTable />+ <ConnectedDashboardWidgetTable /></Page>);}diff --git a/web/src/utils/dates.ts b/web/src/utils/dates.tsindex 017e6e3efe..972c221f8a 100644--- a/web/src/utils/dates.ts+++ b/web/src/utils/dates.ts@@ -85,7 +85,7 @@ export const buildLocalIsoDatePresentation = ({return {display: formatLocalIsoDate(date, false, accuracy),- title: `UTC: ${formatLocalIsoDate(date, true, "millisecond")}`,+ title: `Local: ${formatLocalIsoDate(date, false, "millisecond")}\nUTC: ${formatLocalIsoDate(date, true, "millisecond")}`,};};