### Install Trunk and WASM Target Source: https://github.com/synphonyte/leptos-struct-table/blob/master/examples/getter/README.md Install Trunk for serving Rust WASM applications and add the wasm32-unknown-unknown target. These are necessary to build and run the example. ```bash cargo install trunk rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Serve the Leptos Struct Table Example Source: https://github.com/synphonyte/leptos-struct-table/blob/master/examples/getter/README.md Run the Leptos struct table example using Trunk. This command serves the application and automatically opens it in your default web browser. ```bash trunk serve --open ``` -------------------------------- ### Install Dependencies and Build Tools Source: https://github.com/synphonyte/leptos-struct-table/blob/master/examples/selectable/README.md Install Trunk for serving, Tailwind CSS for styling, and the wasm32-unknown-unknown target for WebAssembly compilation. ```bash cargo install trunk npm install -D tailwindcss rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Install cargo-leptos Source: https://github.com/synphonyte/leptos-struct-table/blob/master/examples/serverfn_sqlx/README.md Install the cargo-leptos toolchain if you don't have it already. This is required to build and run Leptos applications. ```bash cargo install cargo-leptos ``` -------------------------------- ### Run Leptos Development Server Source: https://github.com/synphonyte/leptos-struct-table/blob/master/examples/serverfn_sqlx/README.md Execute this command to start the Leptos development server. It will watch for file changes and automatically reload the application. ```bash cargo leptos watch ``` -------------------------------- ### Implement Image Cell Renderer - Rust Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Example of a custom cell renderer that displays an image from a URL. It takes class, value (Signal), row (RwSignal), and index as parameters. ```rust #[derive(TableRow)] pub struct Book { title: String, #[table(renderer = "ImageTableCellRenderer")] img: String, } // Easy cell renderer that just displays an image from an URL. #[component] fn ImageTableCellRenderer( class: String, value: Signal, row: RwSignal, index: usize, ) -> impl IntoView { view! { Book image } } ``` -------------------------------- ### SSR Setup with SQLx and Leptos Struct Table Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Configure Cargo.toml for SSR and Leptos Struct Table. Define a struct with `TableRow` and `sqlx::FromRow` for database integration. Implement server functions to fetch data and a `TableDataProvider` to bridge data to the table component. ```rust // Cargo.toml (relevant parts): // [dependencies] // leptos-struct-table = { version = "0.18" } // leptos-use = { version = "0.18", default-features = false, features = [...] } // // [features] // hydrate = ["leptos/hydrate", "leptos-use/hydrate"] // ssr = ["leptos/ssr", "leptos-use/ssr"] use leptos::prelude::*; use leptos_struct_table::*; use std::collections::VecDeque; use std::ops::Range; #[derive(TableRow, Clone, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))] #[table(sortable)] pub struct Customer { pub customer_id: String, pub first_name: String, pub last_name: String, pub email: String, } // Server function — only compiled and called on the server #[server] pub async fn fetch_customers( range: Range, sort: VecDeque<(usize, ColumnSort)>, ) -> Result, ServerFnError> { use sqlx::QueryBuilder; // build dynamic SQL with sort + LIMIT/OFFSET … // Customer::sorting_to_sql(&sort) returns an ORDER BY clause string Ok(vec![]) // replace with actual DB query } #[derive(Default)] pub struct CustomerProvider { sort: VecDeque<(usize, ColumnSort)>, } impl TableDataProvider for CustomerProvider { async fn get_rows(&self, range: Range) -> Result<(Vec, Range), String> { fetch_customers(range.clone(), self.sort.clone()) .await .map(|rows| { let len = rows.len(); (rows, range.start..range.start + len) }) .map_err(|e| format!("{e:?}")) } fn set_sorting(&mut self, sorting: &VecDeque<(usize, ColumnSort)>) { self.sort = sorting.clone(); } } ``` -------------------------------- ### Table Content with Change Event Listener - Rust Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Example of using the TableContent component with an `on_change` event handler to log changes to the row data. Requires `ChangeEvent` and `TableContent` imports. ```rust // Then in the table component you can listen to the `on_change` event: #[component] pub fn App() -> impl IntoView { let rows = vec![Book::default(), Book::default()]; let on_change = move |evt: ChangeEvent| { logging::log!("Changed row at index {}:\n{:#?}", evt.row_index, evt.changed_row.get_untracked()); }; view! {
} } ``` -------------------------------- ### Custom CSS Class Provider with BemClassesPreset Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Implement the `TableClassesProvider` trait to customize all CSS classes applied to table elements. This example uses BEM-style class names. ```rust use leptos_struct_table::{ColumnSort, TableClassesProvider, TableRow}; /// Minimal custom class provider using BEM-style class names #[derive(Clone, Copy)] pub struct BemClassesPreset; impl TableClassesProvider for BemClassesPreset { fn new() -> Self { Self } fn thead_row(&self, extra: &str) -> String { format!("table__head-row {extra}") } fn thead_cell(&self, sort: ColumnSort, extra: &str) -> String { let sort_class = match sort { ColumnSort::Ascending => "table__head-cell--asc", ColumnSort::Descending => "table__head-cell--desc", ColumnSort::None => "", }; format!("table__head-cell {sort_class} {extra}") } fn row(&self, row_index: usize, selected: bool, extra: &str) -> String { let modifier = if selected { "table__row--selected" } else if row_index % 2 == 0 { "table__row--even" } else { "table__row--odd" }; format!("table__row {modifier} {extra}") } fn cell(&self, extra: &str) -> String { format!("table__cell {extra}") } fn loading_cell_inner(&self, _row: usize, _col: usize, extra: &str) -> String { format!("table__loading-skeleton {extra}") } } // Usage: #[derive(TableRow, Clone)] #[table(impl_vec_data_provider, classes_provider = "BemClassesPreset")] pub struct Item { pub id: u32, pub label: String, } ``` -------------------------------- ### Custom Cell Renderer with InputCellRenderer Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Use a custom Leptos component to render table cells. The component receives `class`, `value`, `row`, and `index` props. This example shows an editable text input that updates the row's title. ```rust use leptos::prelude::*; use leptos_struct_table::*; #[derive(TableRow, Clone, Debug)] #[table(impl_vec_data_provider)] pub struct Book { pub id: u32, #[table(renderer = "InputCellRenderer")] pub title: String, pub author: String, } /// Editable text input that writes back to the row signal on change #[component] fn InputCellRenderer( class: String, value: Signal, row: RwSignal, index: usize, ) -> impl IntoView { let on_change = move |evt: web_sys::Event| { use leptos::ev::Event; row.write().title = event_target_value(&evt); }; view! { } } #[component] fn EditableBooks() -> impl IntoView { let rows = RwSignal::new(vec![ Book { id: 1, title: "Rust Programming".to_string(), author: "Steve Klabnik".to_string() }, ]); // `on_change` fires after any cell edit let on_change = move |evt: ChangeEvent| { rows.write()[evt.row_index] = evt.changed_row.get_untracked(); leptos::logging::log!("Row {} updated", evt.row_index); }; view! {
{move || format!("{:#?}", rows.get())}
} } ``` -------------------------------- ### Set usize column index type Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Explicitly set the column index type to usize. Fields marked with `#[table(skip)]` are not indexed. Indexes start at 0 for the first relevant struct field. ```rust #[derive(TableRow, Clone, Default, Debug)] #[table(impl_vec_data_provider, column_index_type = "usize")] pub struct Book { id: u32, // index = 0 #[table(skip)] content: String, // no index (skipped) title: String, // index = 1 } ``` -------------------------------- ### Basic Table Usage with Struct Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Demonstrates how to create a Leptos table component from a struct using the `leptos-struct-table` crate. Requires deriving `TableRow` and implementing `impl_vec_data_provider` for the struct. ```rust use leptos::prelude::*; use leptos_struct_table::*; #[derive(TableRow, Clone)] #[table(impl_vec_data_provider)] pub struct Person { id: u32, name: String, age: u32, } #[component] fn Demo() -> impl IntoView { let rows = vec![ Person { id: 1, name: "John".to_string(), age: 32 }, Person { id: 2, name: "Jane".to_string(), age: 28 }, Person { id: 3, name: "Bob".to_string(), age: 45 }, ]; view! {
} } ``` -------------------------------- ### Implement Multi-Column Sorting with ColumnSort and SortingMode Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Demonstrates how to enable multi-column sorting for table data. The `build_order_by` function generates SQL ORDER BY clauses from the current sorting state. Requires `SortingMode::MultiColumn` to be set. ```rust use leptos::prelude::*; use leptos_struct_table::*; use std::collections::VecDeque; #[derive(TableRow, Clone)] #[table(sortable, impl_vec_data_provider)] pub struct Product { pub name: String, pub price: f64, pub stock: u32, } // Generate SQL ORDER BY from current sorting state fn build_order_by(sorting: &VecDeque<(usize, ColumnSort)>) -> String { let col_name = |i: usize| match i { 0 => "name", 1 => "price", _ => "stock" }; let parts: Vec = sorting .iter() .filter_map(|(col, sort)| { sort.as_sql().map(|dir| format!("{} {}", col_name(*col), dir)) // e.g., "price DESC", "name ASC" }) .collect(); if parts.is_empty() { String::new() } else { format!("ORDER BY {}", parts.join(", ")) } } #[component] fn SortableProducts() -> impl IntoView { let rows = vec![ Product { name: "Widget".to_string(), price: 9.99, stock: 100 }, Product { name: "Gadget".to_string(), price: 24.99, stock: 50 }, ]; let sorting: RwSignal> = RwSignal::new(VecDeque::new()); view! {

"SQL: " {move || build_order_by(&sorting.read())}

} } ``` -------------------------------- ### Configure Table DisplayStrategy for Pagination Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Use `DisplayStrategy::Pagination` to configure the table for row-based pagination. Custom pagination controls can be implemented using `PaginationController`. ```rust use leptos::prelude::*; use leptos_struct_table::*; #[derive(TableRow, Clone)] #[table(impl_vec_data_provider)] pub struct Row { pub id: u32, pub label: String } #[component] fn PaginatedTable() -> impl IntoView { let rows = (0..100u32) .map(|i| Row { id: i, label: format!("Item {i}") }) .collect::>(); let controller = PaginationController::default(); view! {
// Custom pagination controls { move || format!( "Page {} / {}", controller.current_page.get() + 1, controller.page_count().get().unwrap_or(0) )}
} } ``` -------------------------------- ### Implement Custom Async Data Source with TableDataProvider Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Implement `TableDataProvider` for custom asynchronous data fetching, suitable for sources like databases with offset/limit queries. Ensure the data struct derives `TableRow`, `Clone`, `Serialize`, and `Deserialize`. ```rust use leptos::prelude::*; use leptos_struct_table::*; use std::collections::VecDeque; use std::ops::Range; #[derive(TableRow, Clone, serde::Serialize, serde::Deserialize)] #[table(sortable, classes_provider = "TailwindClassesPreset")] pub struct Customer { pub id: u32, pub name: String, pub email: String, } pub struct CustomerProvider { sort: VecDeque<(usize, ColumnSort)>, pub search: RwSignal, } impl Default for CustomerProvider { fn default() -> Self { Self { sort: VecDeque::new(), search: RwSignal::new(String::new()) } } } impl TableDataProvider for CustomerProvider { async fn get_rows(&self, range: Range) -> Result<(Vec, Range), String> { // Simulate async DB fetch; replace with real sqlx/reqwest call let all = vec![ Customer { id: 1, name: "Alice".to_string(), email: "alice@example.com".to_string() }, Customer { id: 2, name: "Bob".to_string(), email: "bob@example.com".to_string() }, ]; let (rows, actual_range) = get_vec_range_clamped(&all, range); Ok((rows, actual_range)) } async fn row_count(&self) -> Option { Some(2) // known total; return None if unknown } fn set_sorting(&mut self, sorting: &VecDeque<(usize, ColumnSort)>) { self.sort = sorting.clone(); // re-sort your backing data here } fn track(&self) { // track reactive signals that affect data loading self.search.track(); } } #[component] fn CustomerTable() -> impl IntoView { let provider = CustomerProvider::default(); view! {
} } ``` -------------------------------- ### Leptos Struct Table SSR Configuration Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Configuration for using Leptos Struct Table with Leptos' server-side rendering (SSR). Requires adding `leptos-use` as a dependency and enabling the `ssr` feature. ```toml [dependencies] leptos-use = "" # ... [features] hydrate = [ "leptos/hydrate", # ... ] ssr = [ "leptos/ssr", # ... "leptos-use/ssr", ] ``` -------------------------------- ### Customize Table Classes with TailwindPreset Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Use the `classes_provider` attribute to specify a custom class provider like `TailwindClassesPreset` for table styling. ```rust #[derive(TableRow, Clone)] #[table(classes_provider = "TailwindClassesPreset")] pub struct Book { id: u32, title: String, } ``` -------------------------------- ### Control Column Visibility and Reordering in Leptos Struct Table Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Use `RwSignal>` with the `columns` prop to manage which columns are displayed and their order. Combine with `HeadDragHandler` for drag-and-drop reordering. Ensure `sort()` is called on the column vector after modifications to maintain order. ```rust use leptos::prelude::*; use leptos_struct_table::*; use std::sync::Arc; #[derive(TableRow, Clone)] #[table(impl_vec_data_provider, column_index_type = "enum", sortable, classes_provider = "TailwindClassesPreset")] pub struct Book { pub title: String, pub author: String, pub year: u32, } struct MyDragHandler; impl DragHandler for MyDragHandler { fn grabbed_class(&self) -> &'static str { "opacity-50 bg-blue-100" } fn hover_left_class(&self) -> &'static str { "border-l-2 border-blue-500" } fn hover_right_class(&self) -> &'static str { "border-r-2 border-blue-500" } } #[component] fn ConfigurableTable() -> impl IntoView { let rows = vec![ Book { title: "Dune".to_string(), author: "Frank Herbert".to_string(), year: 1965 }, ]; // Start with all columns visible let columns = RwSignal::new(Vec::from(Book::columns())); view! {
// Toggle visibility checkboxes {Book::columns().iter().map(|col| { let col = *col; view! { } }).collect_view()}
} } ``` -------------------------------- ### Render Table with TableContent Component Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Use `TableContent` to render the table body and head. Configure sorting, selection, and other behaviors via props. Ensure necessary structs derive `TableRow` and implement `Clone`. ```rust use leptos::prelude::*; use leptos_struct_table::*; #[derive(TableRow, Clone)] #[table(sortable, impl_vec_data_provider, classes_provider = "TailwindClassesPreset")] pub struct Person { pub id: u32, pub name: String, pub age: u32, } #[component] fn App() -> impl IntoView { let rows = vec![ Person { id: 1, name: "Alice".to_string(), age: 30 }, Person { id: 2, name: "Bob".to_string(), age: 25 }, ]; // RwSignal to hold sort state across renders let sorting = RwSignal::new(std::collections::VecDeque::new()); // Track which row is selected let selected = RwSignal::new(None::); // Manually trigger data reload (e.g., after a filter change) let reload_controller = ReloadController::default(); view! { | { leptos::logging::log!("Row {} selected={}", evt.row_index, evt.selected); } // limit loading skeleton rows shown at once loading_row_display_limit=Some(5) // optional reload trigger reload_controller=reload_controller // optional extra CSS classes row_class="cursor-pointer" thead_class="sticky top-0" />
} } ``` -------------------------------- ### Implement PaginatedTableDataProvider for Async Data Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Implement this trait when your data source is page-oriented, like REST APIs with pagination parameters. `TableDataProvider` is automatically implemented. The `get_page` function should return data for the requested page or an empty vector to signal the end of data. ```rust use leptos::prelude::*; use leptos_struct_table::*; use std::collections::VecDeque; #[derive(TableRow, Clone, serde::Deserialize)] #[table(sortable, impl_vec_data_provider)] pub struct Brewery { pub name: String, pub city: String, pub country: String, } pub struct BreweryProvider { sort: VecDeque<(usize, ColumnSort)>, pub search: RwSignal, } impl Default for BreweryProvider { fn default() -> Self { Self { sort: VecDeque::new(), search: RwSignal::new(String::new()) } } } impl PaginatedTableDataProvider for BreweryProvider { const PAGE_ROW_COUNT: usize = 50; async fn get_page(&self, page_index: usize) -> Result, String> { // Build URL with sort/search/page params and fetch JSON let url = format!( "https://api.openbrewerydb.org/v1/breweries?page={}&per_page={}", page_index + 1, Self::PAGE_ROW_COUNT, ); // gloo_net or reqwest fetch here … // Returning empty vec signals end of data Ok(vec![]) } async fn page_count(&self) -> Option { None // unknown; the table will load until an empty page is returned } fn set_sorting(&mut self, sorting: &VecDeque<(usize, ColumnSort)>) { self.sort = sorting.clone(); } fn track(&self) { self.search.track(); } } ``` -------------------------------- ### Apply Built-in Value Formatting with `#[table(format(...))]` Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Allows direct application of formatting options to struct fields without custom renderers. Supports numeric precision and, with feature flags, `chrono` dates and `rust_decimal` values. The `precision` argument controls the number of decimal places displayed. ```rust use leptos::prelude::*; use leptos_struct_table::*; // With features = ["chrono", "rust_decimal"] in Cargo.toml: // [dependencies] // leptos-struct-table = { version = "0.18", features = ["chrono", "rust_decimal"] } #[derive(TableRow, Clone)] #[table(impl_vec_data_provider)] pub struct Measurement { pub sensor_id: u32, // Display with 2 decimal places #[table(title = "Temperature (°C)", format(precision = 2usize))] pub temperature: f64, // Display with 3 decimal places #[table(format(precision = 3usize))] pub voltage: f32, // chrono date formatted with strftime pattern (requires "chrono" feature) // #[table(format(string = "%d.%m.%Y"))] // pub recorded_at: chrono::NaiveDate, } #[component] fn MeasurementTable() -> impl IntoView { let rows = vec![ Measurement { sensor_id: 1, temperature: 23.456789, voltage: 3.14159 }, Measurement { sensor_id: 2, temperature: -1.2, voltage: 5.0 }, // Displayed as: 23.46 | 3.142 (respecting precision) ]; view! {
} } ``` -------------------------------- ### Implement Single and Multi-Row Selection in Leptos Table Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Use the `Selection` enum with `Selection::Single` or `Selection::Multiple` to manage row selection. React to selection changes using the `on_selection_change` prop. For multi-select, standard keyboard modifiers like Ctrl+click and Shift+click are supported. ```rust use leptos::prelude::*; use leptos_struct_table::*; use std::collections::HashSet; #[derive(TableRow, Clone, Debug)] #[table(impl_vec_data_provider, classes_provider = "TailwindClassesPreset")] pub struct Product { pub id: u32, pub name: String, pub price: f64, } #[component] fn ProductPicker() -> impl IntoView { let rows = vec![ Product { id: 1, name: "Widget".to_string(), price: 9.99 }, Product { id: 2, name: "Gadget".to_string(), price: 24.99 }, Product { id: 3, name: "Doohickey".to_string(), price: 4.99 }, ]; // --- Single selection --- let single_selected = RwSignal::new(None::); // --- Multiple selection --- let multi_selected: RwSignal> = RwSignal::new(HashSet::new()); view! {

"Single select"

| { leptos::logging::log!("Selected product at index {}", evt.row_index); } row_class="cursor-pointer select-none" />

"Selected index: " {move || single_selected.get().map(|i| i.to_string()).unwrap_or_default()}

"Multi select (Ctrl+click / Shift+click)"

"Selected count: " {move || multi_selected.read().len()}

} } ``` -------------------------------- ### Watch Tailwind CSS for Changes Source: https://github.com/synphonyte/leptos-struct-table/blob/master/examples/selectable/README.md Run this command in a terminal to continuously compile Tailwind CSS whenever changes are detected in your input CSS file. ```bash npx tailwindcss -i ./input.css -o ./style/output.css --watch ``` -------------------------------- ### Implement Editable Input Cell Renderer - Rust Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Custom cell renderer for editable input fields. It uses a Signal for the value and an RwSignal for the row to update the data directly. The `on_change` event handler updates the row's title. ```rust #[derive(TableRow, Clone, Default, Debug)] #[table(impl_vec_data_provider)] pub struct Book { id: u32, #[table(renderer = "InputCellRenderer")] title: String, } #[component] fn InputCellRenderer( class: String, value: Signal, row: RwSignal, index: usize, ) -> impl IntoView { let on_change = move |evt| { row.write().title = event_target_value(&evt); }; view! { } } ``` -------------------------------- ### Manual Data Reload Trigger with ReloadController Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Use `ReloadController` to manually trigger a data reload for the table. This is useful after external data changes, such as search input updates. ```rust use leptos::prelude::*; use leptos_struct_table::*; use std::ops::Range; #[derive(TableRow, Clone)] #[table(sortable)] pub struct LogEntry { pub timestamp: String, pub level: String, pub message: String, } pub struct LogProvider { pub filter: RwSignal, } impl TableDataProvider for LogProvider { async fn get_rows(&self, range: Range) -> Result<(Vec, Range), String> { // fetch logs filtered by `self.filter.get_untracked()` Ok((vec![], 0..0)) } fn track(&self) { self.filter.track(); } } #[component] fn LogViewer() -> impl IntoView { let filter = RwSignal::new(String::new()); let reload_controller = ReloadController::default(); let provider = LogProvider { filter }; view! {
} } ``` -------------------------------- ### Define Computed/Virtual Columns with FieldGetter or #[table(getter)] in Leptos Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Use `FieldGetter` for virtual columns that derive values from other fields without runtime memory cost. Alternatively, use the `#[table(getter = "...")]` attribute on an existing field to intercept and customize its displayed value using a custom getter method. ```rust use leptos::prelude::*; use leptos_struct_table::*; #[derive(TableRow, Clone)] #[table(impl_vec_data_provider)] pub struct Employee { pub id: u32, pub first_name: String, pub last_name: String, pub salary_cents: u64, // Virtual column — no memory allocated at runtime (PhantomData internally) pub full_name: FieldGetter, // Existing field displayed via custom getter method #[table(getter = "display_salary")] pub salary_display: String, } impl Employee { /// Called by the table macro to render the `full_name` column pub fn full_name(&self) -> String { format!("{} {}", self.first_name, self.last_name) } /// Called by the table macro to render the `salary_display` column pub fn display_salary(&self) -> String { format!("${:.2}", self.salary_cents as f64 / 100.0) } } #[component] fn EmployeeTable() -> impl IntoView { let rows = vec![ Employee { id: 1, first_name: "Jane".to_string(), last_name: "Smith".to_string(), salary_cents: 9500000, full_name: FieldGetter::default(), salary_display: String::new(), // filled by getter at render time }, ]; view! {
} } ``` -------------------------------- ### Derive TableRow for Structs Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Use `#[derive(TableRow)]` on a struct to generate a Leptos table component. The `#[table(...)]` attribute configures field-level behavior like skipping fields, setting display values for None, or applying custom CSS classes. ```rust use leptos::prelude::*; use leptos_struct_table::*; use chrono::NaiveDate; use uuid::Uuid; // Generates the BookTable component. // `sortable` makes header cells clickable for sorting. // `impl_vec_data_provider` lets Vec be passed directly as `rows`. #[derive(TableRow, Clone)] #[table(sortable, impl_vec_data_provider, classes_provider = "TailwindClassesPreset")] pub struct Book { pub id: Uuid, pub title: String, pub author: String, // `none_value` sets the display string when the Option is None #[table(none_value = "-")] pub publish_date: Option, // `skip` hides the field entirely from the table #[table(skip)] pub internal_key: String, // `head_class` / `cell_class` apply extra CSS classes to the header / body cells #[table( title = "Category", cell_class = "text-blue-600", head_class = "text-blue-800" )] pub genre: String, } #[component] fn BookList() -> impl IntoView { let rows = vec![ Book { id: Uuid::new_v4(), title: "The Great Gatsby".to_string(), author: "F. Scott Fitzgerald".to_string(), publish_date: Some(NaiveDate::from_ymd_opt(1925, 4, 10).unwrap()), internal_key: "gatsby".to_string(), genre: "Fiction".to_string(), }, Book { id: Uuid::new_v4(), title: "Nineteen Eighty-Four".to_string(), author: "George Orwell".to_string(), publish_date: None, internal_key: "1984".to_string(), genre: "Dystopia".to_string(), }, ]; view! { // `scroll_container` is required; use "" for no-scroll or pass an element ref
} } ``` -------------------------------- ### Use Enum Column Indexes for Type-Safe References Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Enables the generation of a type-safe enum for column references, replacing raw `usize` indexes. The macro `#[table(column_index_type = "enum")]` generates `{StructName}Column` with variants for each field. Skipped fields do not generate variants. ```rust use leptos::prelude::*; use leptos_struct_table::*; use std::collections::VecDeque; #[derive(TableRow, Clone)] #[table(impl_vec_data_provider, column_index_type = "enum", sortable)] pub struct Sensor { pub id: u32, #[table(skip)] pub raw_data: Vec, // no variant generated (skipped) pub temperature: f64, // SensorColumn::Temperature pub humidity: f64, // SensorColumn::Humidity } // Custom cell renderer referencing columns by enum variant #[component] fn TempCellRenderer( class: String, value: Signal, row: RwSignal, index: SensorColumn, // typed enum, not usize ) -> impl IntoView { let color = if index == SensorColumn::Temperature { "text-red-500" } else { "text-blue-500" }; view! { { move || format!("{:.1}", value.get()) } } } ``` -------------------------------- ### Define Derived Field with FieldGetter Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Use `FieldGetter` for virtual fields that are derived from other struct fields. The associated method provides the value at runtime. ```rust #[derive(TableRow, Clone)] #[table(classes_provider = "TailwindClassesPreset")] pub struct Book { id: u32, title: String, author: String, // this tells the macro that you're going to provide a method called `title_and_author` that returns a `String` title_and_author: FieldGetter } impl Book { // Returns the value that is displayed in the column pub fn title_and_author(&self) -> String { format!("{} by {}", self.title, self.author) } } ``` -------------------------------- ### Read Cached Row State with RowReader in Leptos Struct Table Source: https://context7.com/synphonyte/leptos-struct-table/llms.txt Use `RowReader` to programmatically access the table's internal row cache and read row states (loaded, loading, error) from outside the table component. Initialize with `RowReader::default()` and use `cached_row(index)` to retrieve the state. ```rust use leptos::prelude::*; use leptos_struct_table::*; #[derive(TableRow, Clone, Debug)] #[table(impl_vec_data_provider)] pub struct Item { pub id: u32, pub name: String, } #[component] fn ItemTable() -> impl IntoView { let rows = vec![ Item { id: 1, name: "Alpha".to_string() }, Item { id: 2, name: "Beta".to_string() }, ]; let row_reader = RowReader::::default(); let reader_copy = row_reader.clone(); view! {
} } ``` -------------------------------- ### Set enum column index type Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Set the column index type to an enum. The `#[table]` proc-macro generates an enum (e.g., `BookColumn`) where struct fields are converted to UpperCamelCase variants for indexing. Fields marked `#[table(skip)]` are not indexed. ```rust #[derive(TableRow, Clone, Default, Debug)] #[table(impl_vec_data_provider, column_index_type = "enum")] // Proc-macro `table` generates enum "{struct_name}Column", in this case: BookColumn pub struct Book { id: u32, // index = BookColumn::Id #[table(skip)] content: String, // no index (skipped) title: String, // index = BookColumn::Title } ``` -------------------------------- ### Configure Column Index Type - Rust Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Attribute to configure the column index type for a TableRow struct. Supported values are 'usize' or 'enum'. ```rust #[table(columne_index_type = value)] ``` -------------------------------- ### Modify Field Value with Getter Attribute Source: https://github.com/synphonyte/leptos-struct-table/blob/master/README.md Use the `getter` attribute on a struct field to specify a method that modifies the field's value before rendering. This is useful for existing fields. ```rust #[derive(TableRow, Clone)] #[table(classes_provider = "TailwindClassesPreset")] pub struct Book { // this tells the macro that you're going to provide a method called `get_title` that returns a `String` #[table(getter = "get_title")] title: String, } impl Book { pub fn get_title(&self) -> String { format!("Title: {}", self.title) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.