AvenUI.DataTable (AvenUI v1.0.0)

Copy Markdown View Source

State helper for the data_table/1 component.

Manages filter, sort, and pagination state in a single struct that lives in your LiveView assigns. All filtering and sorting happens server-side — you control the query.

Setup

alias AvenUI.DataTable

def mount(_params, _session, socket) do
  {:ok,
   socket
   |> assign(:table, DataTable.new(per_page: 20))
   |> load_rows()}
end

# Reload rows whenever table state changes
defp load_rows(socket) do
  %{filter: filter, sort_field: field, sort_dir: dir,
    page: page, per_page: per} = socket.assigns.table

  {rows, total} = Accounts.list_users(
    search: filter["search"],
    status: filter["status"],
    sort_field: field,
    sort_dir: dir,
    page: page,
    per_page: per
  )

  socket
  |> assign(:rows, rows)
  |> assign(:table, DataTable.put_total(socket.assigns.table, total))
end

Handle events

def handle_event("dt_filter", params, socket) do
  table = socket.assigns.table
          |> DataTable.set_filter(params)
          |> DataTable.reset_page()
  {:noreply, socket |> assign(:table, table) |> load_rows()}
end

def handle_event("dt_sort", %{"field" => field}, socket) do
  table = DataTable.toggle_sort(socket.assigns.table, field)
  {:noreply, socket |> assign(:table, table) |> load_rows()}
end

def handle_event("dt_paginate", %{"page" => page}, socket) do
  table = DataTable.set_page(socket.assigns.table, String.to_integer(page))
  {:noreply, socket |> assign(:table, table) |> load_rows()}
end

Summary

Functions

Returns the filter value for a given key.

True if any filter is active.

Create a new DataTable state struct.

Compute the SQL/Ecto offset for the current page.

Set total row count (used to compute total_pages).

Reset to page 1 (call after filter changes).

Update filter params. Strips blank values.

Set the current page.

Toggle sort on a field. Flips direction if already sorted by that field.

Compute total pages from total rows and per_page.

Types

t()

@type t() :: %AvenUI.DataTable{
  filter: map(),
  page: pos_integer(),
  per_page: pos_integer(),
  sort_dir: String.t(),
  sort_field: String.t() | nil,
  total: non_neg_integer()
}

Functions

filter_value(data_table, key)

Returns the filter value for a given key.

filtered?(data_table)

True if any filter is active.

new(opts \\ [])

Create a new DataTable state struct.

offset(data_table)

Compute the SQL/Ecto offset for the current page.

put_total(dt, total)

Set total row count (used to compute total_pages).

reset_page(dt)

Reset to page 1 (call after filter changes).

set_filter(dt, params)

Update filter params. Strips blank values.

set_page(dt, page)

Set the current page.

toggle_sort(dt, new_field)

Toggle sort on a field. Flips direction if already sorted by that field.

total_pages(data_table)

Compute total pages from total rows and per_page.