Skip to content
WebJs
Menu

Powerful tables and datagrids built from the table helpers.

Status
Amount
Actions
success
$316.00
success
$242.00
processing
$837.00
success
$874.00
failed
$721.00
0 of 5 row(s) selected.

Introduction

Every data table or datagrid I've created has been unique. They all behave differently, have specific sorting and filtering requirements, and work with different data sources.

It doesn't make sense to combine all of these variations into a single component. If we do that, we'll lose the flexibility that composing the table yourself provides.

So instead of a data-table component, I thought it would be more helpful to provide a guide on how to build your own.

We'll start with the kit's table helpers and build a complex data table from scratch.

Tip: If you find yourself using the same table in multiple places in your app, you can always extract it into a reusable fragment.

Table of Contents

This guide will show you how to use the Table helpers to build your own custom data table, rendered by the server, with its state in the URL. We'll cover the following topics:

Installation

  1. Add the table helpers to your project:

pnpm dlx @webjsdev/ui add table
  1. A WebJs page runs on the server, so it filters, sorts and paginates plain arrays before it renders, and the browser receives finished HTML. The few behaviours that need the browser are a small custom element each.

Prerequisites

We are going to build a table to show recent payments. Here's what our data looks like:

type Payment = {
  id: string;
  amount: number;
  status: 'pending' | 'processing' | 'success' | 'failed';
  email: string;
};

export const payments: Payment[] = [
  {
    id: '728ed52f',
    amount: 100,
    status: 'pending',
    email: '[email protected]',
  },
  {
    id: '489e1d42',
    amount: 125,
    status: 'processing',
    email: '[email protected]',
  },
  // ...
];

Project Structure

Start by creating the following file structure:

app
└── payments
    └── page.ts
modules
└── payments
    ├── components
    │   ├── columns.ts
    │   └── data-table.ts
    ├── queries
    │   └── get-payments.server.ts
    └── utils
        └── data-table-state.ts
  • columns.ts will contain our column definitions.
  • data-table-state.ts will contain the table's state, read from the query string, and the functions that filter, sort and paginate the rows.
  • data-table.ts will contain our dataTable() fragment, which renders the table.
  • get-payments.server.ts is a 'use server' query that reads the data.
  • page.ts is where we'll fetch data and render our table.

Set up Table Features

Every feature in this guide (sorting, filtering, pagination, visibility) is state the reader changes. Put that state in the query string and each feature becomes a link or a GET form: the server reads the state, applies it to the rows, and renders the result. It works with JavaScript off, the back button undoes a change, and a filtered, sorted page is a URL you can share. Declare the state and the row functions in one module that every part of the table reads.

modules/payments/utils/data-table-state.ts
import type { Payment } from './columns.ts';

// The table's state, read from the query string, so a link or a GET form is
// all it takes to change it, and the server renders every state.
export interface TableState {
  q: string;                      // the email filter
  sortBy: keyof Payment;          // the sorted column
  sort: 'asc' | 'desc' | null;    // its direction
  page: number;                   // zero-based
  pageSize: number;
  hidden: string[];               // hidden column ids
}

export function readTableState(params: URLSearchParams): TableState {
  const sort = params.get('sort');
  return {
    q: params.get('q') ?? '',
    sortBy: (['status', 'email', 'amount'] as const).find((k) => k === params.get('sortBy')) ?? 'email',
    sort: sort === 'asc' || sort === 'desc' ? sort : null,
    page: Math.max(0, Number(params.get('page') ?? 0) || 0),
    pageSize: [10, 20, 30, 40, 50].includes(Number(params.get('size'))) ? Number(params.get('size')) : 10,
    hidden: params.getAll('hide'),
  };
}

/** A link to the same table with some of its state changed. */
export function tableHref(state: TableState, change: Partial<TableState>): string {
  const next = { ...state, ...change };
  const p = new URLSearchParams();
  if (next.q) p.set('q', next.q);
  if (next.sort) p.set('sort', next.sort);
  if (next.sort && next.sortBy !== 'email') p.set('sortBy', next.sortBy);
  if (next.page) p.set('page', String(next.page));
  if (next.pageSize !== 10) p.set('size', String(next.pageSize));
  for (const id of next.hidden) p.append('hide', id);
  const qs = p.toString();
  return qs ? '?' + qs : '?';
}

/** Filter, sort and paginate: the row models, in the order TanStack runs them. */
export function applyTableState(rows: Payment[], state: TableState) {
  const q = state.q.toLowerCase();
  const filtered = q ? rows.filter((r) => r.email.toLowerCase().includes(q)) : rows;
  const sorted = state.sort
    ? [...filtered].sort((a, b) => (state.sort === 'asc' ? 1 : -1) * String(a[state.sortBy]).localeCompare(String(b[state.sortBy]), 'en', { sensitivity: 'base', numeric: true }))
    : filtered;
  const pageCount = Math.max(1, Math.ceil(sorted.length / state.pageSize));
  const page = Math.min(state.page, pageCount - 1);
  return {
    rows: sorted.slice(page * state.pageSize, (page + 1) * state.pageSize),
    filteredCount: sorted.length,
    page,
    pageCount,
  };
}

Note: The functions run in the order TanStack Table runs its row models: filter, then sort, then paginate, so the page count and the "row(s) selected" total count the filtered rows.

Basic Table

Let's start by building a basic table.

Column Definitions

First, we'll define our columns.

modules/payments/components/columns.ts
import type { TemplateResult } from '@webjsdev/core';

// This type is used to define the shape of our data.
// A schema validated in your query can derive it instead.
export type Payment = {
  id: string;
  amount: number;
  status: 'pending' | 'processing' | 'success' | 'failed';
  email: string;
};

export interface Column {
  id: string;
  header: string;
  cell: (row: Payment) => TemplateResult | string;
}

export const columns: Column[] = [
  { id: 'status', header: 'Status', cell: (row) => row.status },
  { id: 'email', header: 'Email', cell: (row) => row.email },
  { id: 'amount', header: 'Amount', cell: (row) => String(row.amount) },
];

Note: Columns are where you define the core of what your table will look like. They define the data that will be displayed, how it will be formatted, sorted and filtered.

dataTable() fragment

Next, we'll create a dataTable() fragment to render our table. It is a function returning an html template, so it renders on the server and ships no JavaScript.

modules/payments/components/data-table.ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  tableContainerClass,
  tableClass,
  tableHeaderClass,
  tableBodyClass,
  tableRowClass,
  tableHeadClass,
  tableCellClass,
} from '#components/ui/table.ts';
import type { Column, Payment } from './columns.ts';

interface DataTableProps {
  columns: Column[];
  data: Payment[];
}

export function dataTable({ columns, data }: DataTableProps) {
  return html`
    <div class="overflow-hidden rounded-md border">
      <div class=${tableContainerClass()}>
        <table class=${tableClass()}>
          <thead class=${tableHeaderClass()}>
            <tr class=${tableRowClass()}>
              ${columns.map((column) => html`<th scope="col" class=${tableHeadClass()}>${column.header}</th>`)}
            </tr>
          </thead>
          <tbody class=${tableBodyClass()}>
            ${data.length
              ? data.map((row) => html`
                  <tr class=${tableRowClass()}>
                    ${columns.map((column) => html`<td class=${tableCellClass()}>${column.cell(row)}</td>`)}
                  </tr>`)
              : html`
                  <tr class=${tableRowClass()}>
                    <td colspan=${columns.length} class=${cn(tableCellClass(), 'h-24 text-center')}>No results.</td>
                  </tr>`}
          </tbody>
        </table>
      </div>
    </div>
  `;
}

Tip: If you find yourself using dataTable() in multiple places, this is the fragment you could make reusable by giving it generic columns and moving it to components/data-table.ts.

Render the table

Finally, we'll render our table in our page.

app/payments/page.ts
import { html } from '@webjsdev/core';
import { columns } from '#modules/payments/components/columns.ts';
import { dataTable } from '#modules/payments/components/data-table.ts';
import { getPayments } from '#modules/payments/queries/get-payments.server.ts';

export default async function PaymentsPage() {
  // A 'use server' query: the real function on the server.
  const data = await getPayments();

  return html`
    <div class="container mx-auto py-10">
      ${dataTable({ columns, data })}
    </div>
  `;
}

Cell Formatting

Let's format the amount cell to display the dollar amount. We'll also align the cell to the right.

Update columns definition

Update the header and cell definitions for amount as follows:

modules/payments/components/columns.ts
const usd = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

export const columns: Column[] = [
  // ...
  {
    id: 'amount',
    header: html`<div class="text-right">Amount</div>`,
    cell: (row) => html`<div class="text-right font-medium">${usd.format(row.amount)}</div>`,
  },
];

You can use the same approach to format other cells and headers. The formatter runs on the server, so it ships nothing to the browser.

Row Actions

Let's add row actions to our table. We'll use a <ui-dropdown-menu> for this.

Update columns definition

Update our columns definition to add a new actions column. The actions cell returns a <ui-dropdown-menu>.

modules/payments/components/columns.ts
import { html } from '@webjsdev/core';
import { buttonClass } from '#components/ui/button.ts';
import '#components/ui/dropdown-menu.ts';
import { MoreHorizontalIcon } from '#lib/utils/icons.ts';

export const columns: Column[] = [
  // ...
  {
    id: 'actions',
    header: '',
    cell: (payment) => html`
      <ui-dropdown-menu>
        <ui-dropdown-menu-trigger>
          <button type="button" class=${buttonClass({ variant: 'ghost', size: 'icon-xs' })}>
            <span class="sr-only">Open menu</span>
            ${MoreHorizontalIcon()}
          </button>
        </ui-dropdown-menu-trigger>
        <ui-dropdown-menu-content align="end">
          <ui-dropdown-menu-label>Actions</ui-dropdown-menu-label>
          <ui-dropdown-menu-item value=${payment.id}>Copy payment ID</ui-dropdown-menu-item>
          <ui-dropdown-menu-separator></ui-dropdown-menu-separator>
          <ui-dropdown-menu-item>
            <a href=${'/customers/' + payment.id}>View customer</a>
          </ui-dropdown-menu-item>
          <ui-dropdown-menu-item>
            <a href=${'/payments/' + payment.id}>View payment details</a>
          </ui-dropdown-menu-item>
        </ui-dropdown-menu-content>
      </ui-dropdown-menu>
    `,
  },
];

You can access the row data as the cell function's argument. Use it to build the action, for example a <form action=${deletePayment}> with the row's id in a hidden field, which posts to a server action with or without JavaScript.

Pagination

Next, we'll add pagination to our table.

Pagination is already enabled

Because applyTableState() slices the sorted rows into pages, the table paginates into pages of 10 as soon as the page reads its state. Pass ?size= to change the page size.

app/payments/page.ts
import { readTableState, applyTableState } from '#modules/payments/utils/data-table-state.ts';

export default async function PaymentsPage({ searchParams }: PageProps<'/payments'>) {
  const state = readTableState(new URLSearchParams(await searchParams));
  const table = applyTableState(await getPayments(), state);

  return html`
    <div class="container mx-auto py-10">
      ${dataTable({ columns, table, state })}
    </div>
  `;
}

Add pagination controls

We can add pagination controls to our table with the buttonClass() helper on two links, each pointing at the same page with another page in the query string.

modules/payments/components/data-table.ts
import { buttonClass } from '#components/ui/button.ts';
import { tableHref, type TableState } from '../utils/data-table-state.ts';

export function dataTable({ columns, table, state }: DataTableProps) {
  const prev = table.page > 0;
  const next = table.page < table.pageCount - 1;
  return html`
    <div>
      <div class="overflow-hidden rounded-md border">
        <!-- the table, as before, over table.rows -->
      </div>
      <div class="flex items-center justify-end space-x-2 py-4">
        <a
          class=${buttonClass({ variant: 'outline', size: 'sm' })}
          href=${prev ? tableHref(state, { page: table.page - 1 }) : null}
          aria-disabled=${prev ? null : 'true'}
        >Previous</a>
        <a
          class=${buttonClass({ variant: 'outline', size: 'sm' })}
          href=${next ? tableHref(state, { page: table.page + 1 }) : null}
          aria-disabled=${next ? null : 'true'}
        >Next</a>
      </div>
    </div>
  `;
}

See Reusable Components section for a more advanced pagination component.

Sorting

Let's make the email column sortable.

The sort is already part of TableState and applyTableState(), so all that's left is a header that links to the other direction.

Update dataTable()

modules/payments/components/data-table.ts
export function dataTable({ columns, table, state }: DataTableProps) {
  return html`
    <thead class=${tableHeaderClass()}>
      <tr class=${tableRowClass()}>
        ${columns.map((column) => html`
          <th
            scope="col"
            class=${tableHeadClass()}
            aria-sort=${column.id === 'email' && state.sort ? (state.sort === 'asc' ? 'ascending' : 'descending') : null}
          >${typeof column.header === 'function' ? column.header(state) : column.header}</th>`)}
      </tr>
    </thead>
  `;
}

Make header cell sortable

We can now update the email header cell to add sorting controls.

modules/payments/components/columns.ts
import { ArrowUpDownIcon } from '#lib/utils/icons.ts';
import { tableHref } from '../utils/data-table-state.ts';

export const columns: Column[] = [
  // ...
  {
    id: 'email',
    header: (state) => html`
      <a
        class=${buttonClass({ variant: 'ghost' })}
        href=${tableHref(state, { sort: state.sort === 'asc' ? 'desc' : 'asc', page: 0 })}
      >
        Email
        ${ArrowUpDownIcon()}
      </a>
    `,
    cell: (row) => html`<div class="lowercase">${row.email}</div>`,
  },
];

This will automatically sort the table (asc and desc) when the user follows the header link. The aria-sort on the header tells a screen reader which way the column is sorted.

Filtering

Let's add a search input to filter emails in our table.

The filter is already part of the table's state, so we only need to render an input. A GET form with a field named q is the whole wiring: submitting it loads the page with the new filter.

Update dataTable()

modules/payments/components/data-table.ts
import { inputClass } from '#components/ui/input.ts';

export function dataTable({ columns, table, state }: DataTableProps) {
  return html`
    <div>
      <form method="get" class="flex items-center py-4">
        <input
          type="search"
          name="q"
          value=${state.q}
          placeholder="Filter emails..."
          aria-label="Filter emails"
          class=${cn(inputClass(), 'max-w-sm')}
        >
        ${state.sort ? html`<input type="hidden" name="sort" value=${state.sort}>` : ''}
        ${state.hidden.map((id) => html`<input type="hidden" name="hide" value=${id}>`)}
      </form>
      <div class="overflow-hidden rounded-md border">
        <!-- the table, as before -->
      </div>
    </div>
  `;
}

Filtering is now enabled for the email column. You can add filters to other columns as well: give each its own field and read it in readTableState(). To filter as the reader types, add a small element that submits the form on input, after a short delay.

Visibility

Adding column visibility is fairly simple: the hidden columns are a list in the query string, and the table renders the other ones.

Update dataTable()

modules/payments/components/data-table.ts
import '#components/ui/dropdown-menu.ts';
import { ChevronDownIcon } from '#lib/utils/icons.ts';

export function dataTable({ columns, table, state }: DataTableProps) {
  const shown = columns.filter((column) => !state.hidden.includes(column.id));
  const hideable = columns.filter((column) => column.hideable !== false);

  return html`
    <div>
      <div class="flex items-center py-4">
        <!-- the filter form, as before -->
        <ui-dropdown-menu>
          <ui-dropdown-menu-trigger class="ms-auto">
            <button type="button" class=${buttonClass({ variant: 'outline' })}>
              Columns ${ChevronDownIcon()}
            </button>
          </ui-dropdown-menu-trigger>
          <ui-dropdown-menu-content align="end">
            ${hideable.map((column) => {
              const hidden = state.hidden.includes(column.id);
              const href = tableHref(state, {
                hidden: hidden ? state.hidden.filter((id) => id !== column.id) : [...state.hidden, column.id],
              });
              return html`
                <ui-dropdown-menu-item type="checkbox" ?checked=${!hidden} class="capitalize">
                  <a href=${href}>${column.id}</a>
                </ui-dropdown-menu-item>`;
            })}
          </ui-dropdown-menu-content>
        </ui-dropdown-menu>
      </div>
      <div class="overflow-hidden rounded-md border">
        <!-- the table, rendering only the shown columns -->
      </div>
    </div>
  `;
}

This adds a dropdown menu that you can use to toggle column visibility.

Row Selection

Next, we're going to add row selection to our table.

Selection is the one piece of state that belongs to the reader alone, so it is not in the URL. Each row's checkbox is a named form field, so a form around the table posts the selected ids to a server action with JavaScript off, and a small element adds the select-all checkbox and the count.

Update column definitions

modules/payments/components/columns.ts
import { checkboxClass } from '#components/ui/checkbox.ts';

export const columns: Column[] = [
  {
    id: 'select',
    hideable: false,
    header: () => html`
      <input type="checkbox" data-slot="checkbox" data-select-all aria-label="Select all" class=${checkboxClass()}>
    `,
    cell: (row) => html`
      <input type="checkbox" data-slot="checkbox" name="selected" value=${row.id} aria-label="Select row" class=${checkboxClass()}>
    `,
  },
  // ...
];

Update dataTable()

modules/payments/components/data-table.ts
import { deletePayments } from '../actions/delete-payments.server.ts';
import './row-selection.ts';

export function dataTable({ columns, table, state }: DataTableProps) {
  return html`
    <form action=${deletePayments}>
      <row-selection>
        <div class="overflow-hidden rounded-md border">
          <!-- the table, as before, with the select column first -->
        </div>
      </row-selection>
      <button class=${buttonClass({ variant: 'outline', size: 'sm' })}>Delete selected</button>
    </form>
  `;
}
modules/payments/components/row-selection.ts
import { WebComponent, html } from '@webjsdev/core';

// The header checkbox and the live count. The checkboxes themselves are the
// state, so the form posts the selection with or without this element.
export class RowSelection extends WebComponent {
  connectedCallback() {
    super.connectedCallback();
    this.addEventListener('change', this._onChange);
    this._sync();
  }

  _boxes() {
    return Array.from(this.querySelectorAll<HTMLInputElement>('input[name="selected"]'));
  }

  _onChange = (e: Event) => {
    const box = e.target as HTMLInputElement;
    if (box.hasAttribute('data-select-all')) {
      for (const row of this._boxes()) row.checked = box.checked;
    }
    this._sync();
  };

  _sync() {
    const boxes = this._boxes();
    const picked = boxes.filter((b) => b.checked).length;
    const all = this.querySelector<HTMLInputElement>('input[data-select-all]');
    if (all) {
      all.checked = boxes.length > 0 && picked === boxes.length;
      all.indeterminate = picked > 0 && picked < boxes.length;
    }
    for (const b of boxes) b.closest('tr')?.toggleAttribute('data-state', b.checked);
    const count = this.querySelector('[data-selected-count]');
    if (count) count.textContent = String(picked);
  }

  render() {
    return html`<slot></slot>`;
  }
}
RowSelection.register('row-selection');

This adds a checkbox to each row and a checkbox in the header to select all rows.

Show selected rows

You can show the number of selected rows with an element the <row-selection> element updates.

<div class="flex-1 text-sm text-muted-foreground" aria-live="polite">
  <span data-selected-count>0</span> of ${table.filteredCount} row(s) selected.
</div>

Reusable Components

Here are some fragments you can use to build your data tables. Each reads the same TableState from Set up Table Features, so every control is a link that keeps the rest of the table's state.

Column header

Make any column header sortable and hideable.

components/data-table-column-header.ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import '#components/ui/dropdown-menu.ts';
import { ArrowDownIcon, ArrowUpIcon, ChevronsUpDownIcon, EyeOffIcon } from '#lib/utils/icons.ts';
import { tableHref, type TableState } from '../utils/data-table-state.ts';

interface ColumnHeaderProps {
  id: string;
  title: string;
  state: TableState;
  sortable?: boolean;
  class?: string;
}

export function dataTableColumnHeader({ id, title, state, sortable = true, class: cls }: ColumnHeaderProps) {
  if (!sortable) return html`<div class=${cls ?? ''}>${title}</div>`;
  const sorted = state.sortBy === id ? state.sort : null;
  return html`
    <div class=${cn('flex items-center gap-2', cls)}>
      <ui-dropdown-menu>
        <ui-dropdown-menu-trigger>
          <button type="button" class=${cn(buttonClass({ variant: 'ghost', size: 'sm' }), '-ml-3 h-8')}>
            <span>${title}</span>
            ${sorted === 'desc' ? ArrowDownIcon() : sorted === 'asc' ? ArrowUpIcon() : ChevronsUpDownIcon()}
          </button>
        </ui-dropdown-menu-trigger>
        <ui-dropdown-menu-content align="start">
          <ui-dropdown-menu-item><a href=${tableHref(state, { sortBy: id, sort: 'asc', page: 0 })}>${ArrowUpIcon()} Asc</a></ui-dropdown-menu-item>
          <ui-dropdown-menu-item><a href=${tableHref(state, { sortBy: id, sort: 'desc', page: 0 })}>${ArrowDownIcon()} Desc</a></ui-dropdown-menu-item>
          <ui-dropdown-menu-separator></ui-dropdown-menu-separator>
          <ui-dropdown-menu-item><a href=${tableHref(state, { hidden: [...state.hidden, id] })}>${EyeOffIcon()} Hide</a></ui-dropdown-menu-item>
        </ui-dropdown-menu-content>
      </ui-dropdown-menu>
    </div>
  `;
}
export const columns: Column[] = [
  {
    id: 'email',
    header: (state) => dataTableColumnHeader({ id: 'email', title: 'Email', state }),
    cell: (row) => html`<div class="lowercase">${row.email}</div>`,
  },
];

Pagination

Add pagination controls to your table including page size and selection count.

components/data-table-pagination.ts
import { html } from '@webjsdev/core';
import { buttonClass } from '#components/ui/button.ts';
import { nativeSelectClass } from '#components/ui/native-select.ts';
import { ChevronLeftIcon, ChevronRightIcon, ChevronsLeftIcon, ChevronsRightIcon } from '#lib/utils/icons.ts';
import { tableHref, type TableState } from '../utils/data-table-state.ts';

interface PaginationProps {
  state: TableState;
  page: number;
  pageCount: number;
  filteredCount: number;
}

export function dataTablePagination({ state, page, pageCount, filteredCount }: PaginationProps) {
  const link = (to: number, label: string, icon: unknown, cls = '') => html`
    <a
      class=${buttonClass({ variant: 'outline', size: 'icon-sm' }) + ' ' + cls}
      href=${to >= 0 && to < pageCount && to !== page ? tableHref(state, { page: to }) : null}
      aria-disabled=${to >= 0 && to < pageCount && to !== page ? null : 'true'}
    ><span class="sr-only">${label}</span>${icon}</a>`;

  return html`
    <div class="flex items-center justify-between px-2">
      <div class="flex-1 text-sm text-muted-foreground" aria-live="polite">
        <span data-selected-count>0</span> of ${filteredCount} row(s) selected.
      </div>
      <div class="flex items-center space-x-6 lg:space-x-8">
        <form method="get" class="flex items-center space-x-2">
          <label for="page-size" class="text-sm font-medium">Rows per page</label>
          <select id="page-size" name="size" class=${nativeSelectClass()}>
            ${[10, 20, 30, 40, 50].map((n) => html`<option value=${n} ?selected=${n === state.pageSize}>${n}</option>`)}
          </select>
          <button class=${buttonClass({ variant: 'outline', size: 'sm' })}>Apply</button>
        </form>
        <div class="flex w-[100px] items-center justify-center text-sm font-medium">
          Page ${page + 1} of ${pageCount}
        </div>
        <div class="flex items-center space-x-2">
          ${link(0, 'Go to first page', ChevronsLeftIcon(), 'hidden lg:flex')}
          ${link(page - 1, 'Go to previous page', ChevronLeftIcon())}
          ${link(page + 1, 'Go to next page', ChevronRightIcon())}
          ${link(pageCount - 1, 'Go to last page', ChevronsRightIcon(), 'hidden lg:flex')}
        </div>
      </div>
    </div>
  `;
}
${dataTablePagination({ state, page: table.page, pageCount: table.pageCount, filteredCount: table.filteredCount })}

Column toggle

A fragment to toggle column visibility.

components/data-table-view-options.ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import '#components/ui/dropdown-menu.ts';
import { Settings2Icon } from '#lib/utils/icons.ts';
import { tableHref, type TableState } from '../utils/data-table-state.ts';
import type { Column } from './columns.ts';

export function dataTableViewOptions({ columns, state }: { columns: Column[]; state: TableState }) {
  return html`
    <ui-dropdown-menu>
      <ui-dropdown-menu-trigger class="ms-auto hidden lg:block">
        <button type="button" class=${cn(buttonClass({ variant: 'outline', size: 'sm' }), 'h-8')}>
          ${Settings2Icon()}
          View
        </button>
      </ui-dropdown-menu-trigger>
      <ui-dropdown-menu-content align="end" class="w-[150px]">
        <ui-dropdown-menu-label>Toggle columns</ui-dropdown-menu-label>
        <ui-dropdown-menu-separator></ui-dropdown-menu-separator>
        ${columns
          .filter((column) => column.hideable !== false)
          .map((column) => {
            const hidden = state.hidden.includes(column.id);
            const hiddenNext = hidden ? state.hidden.filter((id) => id !== column.id) : [...state.hidden, column.id];
            return html`
              <ui-dropdown-menu-item type="checkbox" ?checked=${!hidden} class="capitalize">
                <a href=${tableHref(state, { hidden: hiddenNext })}>${column.id}</a>
              </ui-dropdown-menu-item>`;
          })}
      </ui-dropdown-menu-content>
    </ui-dropdown-menu>
  `;
}
${dataTableViewOptions({ columns, state })}

RTL

To enable RTL support, see the RTL configuration guide.

الحالة
المبلغ
الإجراءات
ناجح
‏٣١٦٫٠٠ US$
ناجح
‏٢٤٢٫٠٠ US$
قيد المعالجة
‏٨٣٧٫٠٠ US$
ناجح
‏٨٧٤٫٠٠ US$
فشل
‏٧٢١٫٠٠ US$
0 من 5 صف(وف) محدد.