### Implementation Guides Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/COMPLETION-REPORT.txt Guides on implementing common patterns and features with Flop Phoenix. ```APIDOC ## Implementation Guides ### Description Provides step-by-step instructions and examples for implementing various features using Flop Phoenix. ### Guides Available - Pagination how-to - Tables how-to - Filters how-to ### Content - Quick start examples - Step-by-step instructions - Multiple implementation approaches - Common patterns and recipes - Integration examples - Accessibility notes - Performance considerations - Troubleshooting tips ``` -------------------------------- ### Configuration Guide Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/COMPLETION-REPORT.txt Information on configuring Flop Phoenix at application and component levels. ```APIDOC ## Configuration Guide ### Description Details how to configure Flop Phoenix, including application-level options, component-level overrides, and integration with CSS frameworks. ### Configuration Options - Application-level options - Component-level options - Global configuration patterns - CSS framework integration (Tailwind, Bulma) - Customization examples ``` -------------------------------- ### Example Usage of filter_fields with Flop.Meta Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/errors.md Provides a complete example of how to correctly use the filter_fields component within a form, ensuring the form is initialized from Flop.Meta. ```heex ~H""" <.form for={@form}> <.filter_fields :let={i} form={@form} fields={[:email, :name]}> <.input field={i.field} label={i.label} type={i.type} {i.rest} /> """ ``` -------------------------------- ### Option Merging Strategy Example Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/configuration.md Demonstrates how default, global, and component-level options are merged. Later values override earlier ones. ```elixir # Default [symbol_asc: "▴", symbol_desc: "▾"] # + Global config config :flop_phoenix, :table, opts: [symbol_asc: "↑", custom: "value"] # Result: [symbol_asc: "↑", symbol_desc: "▾", custom: "value"] # + Component opts opts={[symbol_desc: "↓"]} # Final: [symbol_asc: "↑", symbol_desc: "↓", custom: "value"] ``` -------------------------------- ### Filter Field Configuration Example Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/form-data-protocol.md This example demonstrates how to configure individual filter fields within the `Phoenix.HTML.FormData` protocol implementation. It shows how to specify labels, operators, input types, and other HTML attributes for each filter. ```elixir fields: [ name: [ label: "Name", op: :ilike, type: "text", maxlength: 50 ], age: [ label: "Minimum Age", op: :>=, type: "number" ], email: [ label: "Email", type: "email", op: :== ] ] ``` -------------------------------- ### Build Path with Query Parameters Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-main.md Constructs a URL path with query parameters derived from a Flop struct or keyword list. Can append to existing paths or start from scratch. ```elixir iex> flop = %Flop{page: 2, page_size: 10} iex> path = Flop.Phoenix.build_path("/pets", flop) iex> %URI{path: p, query: q} = URI.parse(path) {p, URI.decode_query(q)} {"/pets", %{"page" => "2", "page_size" => "10"}} ``` ```elixir iex> # With existing query parameters iex> path = Flop.Phoenix.build_path("/pets?species=dogs", flop) iex> %URI{path: p, query: q} = URI.parse(path) {p, URI.decode_query(q)} {"/pets", %{"page" => "2", "page_size" => "10", "species" => "dogs"}} ``` -------------------------------- ### Localizing Pagination with Gettext Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/configuration.md Integrate Flop Phoenix pagination with Gettext for localized text. This example shows how to define custom previous, next, and page number labels. ```elixir # lib/my_app_web/components/flop_components.ex defmodule MyAppWeb.Components.FlopComponents do use Phoenix.Component import MyAppWeb.Gettext def localized_pagination(assigns) do ~H""" <:previous>{gettext("Previous")} <:next>{gettext("Next")} """ end defp page_label(n) do gettext("Page %{page_number}", page_number: n) end end ``` -------------------------------- ### Basic Filter Form Example Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-filters.md Sets up a basic filter form with input fields for name and email, and a submit button. The form uses `phx-change` to trigger an event when filter values change. ```heex <.form for={to_form(@meta)} phx-change="filter-changed"> <.filter_fields :let={i} form={to_form(@meta)} fields={[:name, :email]}> <.input field={i.field} label={i.label} type={i.type} phx-debounce={120} /> ``` -------------------------------- ### Static Filter Fields Example Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/form-data-protocol.md Illustrates the default behavior of `filter_fields` where only filters specified in the `:fields` list are shown. ```heex <.filter_fields form={form} fields={[:name, :email]} /> ``` -------------------------------- ### Valid Filter Field Configuration: With Field Options Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/errors.md This example demonstrates a valid configuration for the `fields` attribute, including options for specific fields like labels, operators, and types. ```heex <.filter_fields form={@form} fields=[ name: [label: "Full Name"], email: [ label: "Email Address", op: :ilike, type: "email" ], age: [ label: "Minimum Age", type: "number", op: :>=" ] ] /> ``` -------------------------------- ### Valid Filter Field Configuration: Simple Atom List Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/errors.md This example shows a valid configuration for the `fields` attribute using a simple list of atoms. ```heex <.filter_fields form={@form} fields={[:name, :email, :age]} /> ``` -------------------------------- ### Rendering a Filter Form Source: https://github.com/woylie/flop_phoenix/blob/main/README.md Example of how to render the filter_form component in a LiveView template, passing the fields to filter and the meta data. ```heex <.filter_form fields={[:name, :email]} meta={@meta} id="user-filter-form" /> ``` -------------------------------- ### Dynamic Filter Fields Example Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/form-data-protocol.md Demonstrates how to use `dynamic: true` with `filter_fields`. This setting ignores the `:fields` list and only renders filters present in `@meta.flop.filters`, allowing for dynamic filter management. ```heex <.filter_fields form={form} fields={[:name, :email]} dynamic={true} /> ``` -------------------------------- ### Get Default Table Options Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-utilities.md Returns a keyword list containing all default options for the table component. Use this to understand available options or as a base for custom configurations. ```elixir [ container: false, container_attrs: [class: "table-container"], no_results_content: Phoenix.HTML.raw("

No results.

"), symbol_asc: "▴", symbol_attrs: [class: "order-direction"], symbol_desc: "▾", symbol_unsorted: nil, table_attrs: [], tbody_attrs: [], tbody_td_attrs: [], tbody_tr_attrs: [], thead_attrs: [], thead_th_attrs: [], thead_tr_attrs: [] ] ``` -------------------------------- ### Styling Tables with Bulma CSS Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/configuration.md Configure Flop Phoenix tables and pagination to use Bulma CSS framework classes. This example enables the table container and applies Bulma-specific classes. ```elixir # config/config.exs config :flop_phoenix, :table, opts: [ container: true, container_attrs: [class: "table-container"], table_attrs: [class: "table is-striped is-hoverable is-fullwidth"], no_results_content: ~H"

No results found

", symbol_asc: "↑", symbol_desc: "↓" ] config :flop_phoenix, :pagination, opts: [ page_list_attrs: [class: "pagination-list"], page_link_attrs: [class: "pagination-link"], current_page_link_attrs: [class: "pagination-link is-current"], disabled_link_attrs: [class: "pagination-link is-disabled"] ] ``` -------------------------------- ### Custom Path Builder Function Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-pagination.md Provides an example of a custom path builder function for complex path generation. The function receives parameters and returns the constructed path string. ```elixir defp build_product_path(params) do {page, params} = Keyword.pop(params, :page) query = Plug.Conn.Query.encode(params) if page do "/products/page/#{page}?#{query}" else "/products?#{query}" end end ``` -------------------------------- ### Styling Tables with Tailwind CSS Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/configuration.md Configure Flop Phoenix tables and pagination to use Tailwind CSS classes. This example sets attributes for various table elements and pagination links. ```elixir # config/config.exs config :flop_phoenix, :table, opts: [ table_attrs: [class: "min-w-full divide-y divide-gray-300"], thead_attrs: [class: "bg-gray-50"], thead_th_attrs: [class: "px-6 py-3 text-left text-sm font-semibold text-gray-900"], tbody_attrs: [class: "divide-y divide-gray-200 bg-white"], tbody_td_attrs: [class: "whitespace-nowrap px-6 py-4 text-sm text-gray-900"], tbody_tr_attrs: [class: "hover:bg-gray-50"], symbol_asc: "↑", symbol_desc: "↓" ] config :flop_phoenix, :pagination, opts: [ page_list_attrs: [class: "inline-flex space-x-2"], page_link_attrs: [class: "px-3 py-2 text-sm font-medium text-gray-500 hover:bg-gray-100"], current_page_link_attrs: [class: "px-3 py-2 text-sm font-medium bg-blue-500 text-white"] ] ``` -------------------------------- ### Valid Filter Field Configuration: Mixed Simple and Configured Fields Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/errors.md This example shows a valid configuration for the `fields` attribute that mixes simple atom fields with fields that have custom options. ```heex <.filter_fields form={@form} fields=[ :name, email: [label: "Email Address"] ] /> ``` -------------------------------- ### Table with Inline Editing Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-tables.md This HEEx example demonstrates inline editing for a Flop Phoenix table. It conditionally renders an input field when editing a product's name, otherwise displaying the name as plain text. ```heex <:col :let={product} label="Name"> {product.name} ``` -------------------------------- ### Basic Table Implementation Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-tables.md Renders a basic table with products and pagination controls. Requires product data and meta information to be assigned to the socket. ```heex <:col :let={product} label="Name" field={:name}>{product.name} <:col :let={product} label="Price" field={:price}>${product.price} <:col :let={product} label="Stock" field={:stock}>{product.stock} ``` ```elixir def handle_params(params, _uri, socket) do {products, meta} = MyApp.Products.list_products(params) {:noreply, assign(socket, products: products, meta: meta)} end ``` -------------------------------- ### Pagination with Verified Routes Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-pagination.md Demonstrates using verified routes with `~p` sigil for defining the pagination path. This is the recommended approach for type safety and clarity. ```heex ``` ```heex ``` -------------------------------- ### Usage of Custom Wrapper Components Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/configuration.md Illustrates how to use the custom `my_table` and `my_pagination` wrapper components, which encapsulate default configurations. ```heex <:col :let={item} label="Name">{item.name} <:col :let={item} label="Email">{item.email} ``` -------------------------------- ### Correct Approach for filter_fields Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/errors.md Demonstrates the correct way to initialize a form from Flop.Meta and pass it to the filter_fields component. ```heex <% form = to_form(@meta) %> <.filter_fields form={form} fields={[:name, :email]}> <% ... %> ``` -------------------------------- ### JavaScript Scroll Event Listener Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-pagination.md Example JavaScript code to handle a custom scroll event for scrolling to a specific element. ```javascript // app.js window.addEventListener("app:scroll_to", (e) => { e.target.scrollIntoView({ behavior: 'smooth', block: 'start' }); }); ``` -------------------------------- ### Localized Page Label Function Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-pagination.md Define a function to generate localized page labels. This example shows how to use `gettext` for internationalization. ```elixir defp page_label(n) do case :erlang.system_info(:otp_release) do _ -> "Go to page #{n}" # Fallback end |> gettext(page: n) end ``` ```elixir # Or with Gettext defp page_label(n) do gettext("Go to page %{page}", page: n) end ``` -------------------------------- ### Custom Pagination UI with Flop.Phoenix.pagination_for Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/README.md Create a custom pagination UI using the `pagination_for` component. This allows for full control over the pagination's appearance and behavior, including custom navigation links and page information. ```heex <.pagination_for :let={p} meta={@meta} path={~p"/items"} page_links={5}> ``` -------------------------------- ### Basic Paginated List Template Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/README.md Render a table of items and pagination controls using Flop Phoenix components. Assumes 'items' and 'meta' are assigned to the socket. ```heex <:col :let={item} label="Name" field={:name}>{item.name} ``` -------------------------------- ### Handle Params for LiveView Streams Source: https://github.com/woylie/flop_phoenix/blob/main/README.md Modify your `handle_params/3` function to include LiveView streams. This setup is required to pass stream data to the table component. ```elixir def handle_params(params, _, socket) do {pets, meta} = Pets.list_pets(params) {:noreply, socket |> assign(:meta, meta) |> stream(:pets, pets, reset: true)} end ``` -------------------------------- ### page_link_range/3 Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-main.md Calculates the start and end page numbers for rendering pagination links based on a specified strategy, current page, and total number of pages. ```APIDOC ## page_link_range/3 ### Description Returns the range of page links to be rendered based on page linking strategy. ### Signature ```elixir @spec page_link_range(page_link_option(), pos_integer(), pos_integer()) :: {pos_integer() | nil, pos_integer() | nil} def page_link_range(:all, _, total_pages), do: {1, total_pages} def page_link_range(:none, _, _), do: {nil, nil} def page_link_range(max_pages, current_page, total_pages) ``` ### Parameters #### Path Parameters - **page_links** (':all' | ':none' | integer) - Required - Strategy for page link rendering - **current_page** (pos_integer) - Required - Current active page - **total_pages** (pos_integer) - Required - Total number of pages ### Returns Tuple `{start, end}` or `{nil, nil}` if no links ### Example ```elixir iex> Flop.Phoenix.page_link_range(:all, 4, 20) {1, 20} iex> Flop.Phoenix.page_link_range(5, 4, 20) {2, 6} iex> Flop.Phoenix.page_link_range(:none, 4, 20) {nil, nil} ``` ``` -------------------------------- ### Show All Page Links Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-pagination.md Renders all available page links for pagination. ```heex ``` -------------------------------- ### Catching NoMetaFormError in LiveView Render Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/errors.md This example demonstrates how to catch `Flop.Phoenix.NoMetaFormError` when rendering a LiveView component. Use this when the `meta` assign might not be correctly initialized for form generation. ```elixir def render(assigns) do try do form = to_form(assigns.meta) ~H""" <.filter_fields form={form} fields={[:name]}> """ rescue Flop.Phoenix.NoMetaFormError -> ~H"

Form initialization failed

" end end ``` -------------------------------- ### Invalid Filter Field Config: Strings instead of Atoms Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/errors.md This example shows an invalid configuration where strings are used for field names instead of atoms, triggering `Flop.Phoenix.InvalidFilterFieldConfigError`. ```heex <.filter_fields form={@form} fields={"name", "email"} /> ``` -------------------------------- ### Handle Apply Preset Event Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-filters.md Handles the 'apply-preset' event by fetching preset filters, applying them using Flop, listing items, and updating the socket state with the new items, meta, and active preset. ```elixir def handle_event("apply-preset", %{"preset" => preset_id}, socket) do preset = MyApp.get_preset(preset_id) flop = Flop.from_filters(preset.filters) {items, meta} = MyApp.list_items(flop) {:noreply, assign(socket, items: items, meta: meta, active_preset: preset_id)} end ``` -------------------------------- ### Pagination Links Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-main.md Renders pagination links for a given Flop.Meta struct. Supports page-based and cursor-based pagination. Ensure `path` or `on_paginate` is provided. ```heex ``` ```heex <:previous>« Back <:next>Forward » ``` -------------------------------- ### Pagination with Route Helper Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-pagination.md Shows how to use Phoenix route helpers (module, function, args) to define the pagination path. This is useful when you need to pass arguments to your route helper. ```heex ``` ```heex ``` -------------------------------- ### Main API Components Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/README.md Reference for core Flop Phoenix components and utility functions used for pagination, tables, and filters. ```APIDOC ## `pagination/1` ### Description Render pagination links for the current page. ### Function Signature `pagination(assigns)` ### Parameters #### Assigns - **assigns** (keyword list) - Assigns passed to the component, expected to contain pagination data. ### Response - Renders pagination links. ``` ```APIDOC ## `pagination_for/1` ### Description Pagination builder component used to construct pagination data. ### Function Signature `pagination_for(assigns)` ### Parameters #### Assigns - **assigns** (keyword list) - Assigns passed to the component, typically containing data for pagination. ### Response - Builds and returns pagination data. ``` ```APIDOC ## `table/1` ### Description Sortable table component for displaying data with sorting capabilities. ### Function Signature `table(assigns)` ### Parameters #### Assigns - **assigns** (keyword list) - Assigns passed to the component, expected to contain table data and configuration. ### Response - Renders a sortable table. ``` ```APIDOC ## `filter_fields/1` ### Description Filter form inputs component for creating filter forms. ### Function Signature `filter_fields(assigns)` ### Parameters #### Assigns - **assigns** (keyword list) - Assigns passed to the component, typically containing filter field configurations. ### Response - Renders filter input fields. ``` ```APIDOC ## `to_query/2` ### Description Convert Flop data structure to URL query parameters. ### Function Signature `to_query(flop_data, options)` ### Parameters #### `flop_data` - **flop_data** (any) - The Flop data structure to convert. #### `options` - **options** (keyword list) - Optional configuration for conversion. ### Response - Returns a string representing URL query parameters. ``` ```APIDOC ## `build_path/3` ### Description Builds URL paths with appended query parameters. ### Function Signature `build_path(path, params, options)` ### Parameters #### `path` - **path** (string) - The base path. #### `params` - **params** (keyword list) - Query parameters to append. #### `options` - **options** (keyword list) - Optional configuration for path building. ### Response - Returns the constructed URL path string. ``` -------------------------------- ### Adding Visible Filter Inputs Source: https://github.com/woylie/flop_phoenix/blob/main/README.md This example shows how to add visible input fields, such as 'page_size', directly within the Phoenix form component, overriding the default hidden inputs. ```heex <.form for={@form} id={@id} phx-target={@target} phx-change={@on_change} phx-submit={@on_change} > <%!-- ... --%> ``` -------------------------------- ### Render Table with LiveView Streams Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-tables.md This HEEx template renders a Flop Phoenix table using streamed products and pagination. It defines columns for product name and price, and an action to view product details. ```heex <:col :let={{_id, product}} label="Name" field={:name}>{product.name} <:col :let={{_id, product}} label="Price" field={:price}>${product.price} <:action :let={{_id, product}}> <.link navigate={~p"/products/#{product.id}"}>View ``` -------------------------------- ### Pagination Module Utilities Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-utilities.md Utilities for creating and managing pagination structures based on Flop.Meta. ```APIDOC ## new/2 ### Description Creates a `Flop.Phoenix.Pagination` struct from a `Flop.Meta`. ### Signature ```elixir @spec new(Meta.t(), keyword) :: Flop.Phoenix.Pagination.t() def new(meta, opts \ []) ``` ### Parameters #### Path Parameters - **meta** (`Flop.Meta`) - Required - Meta struct from Flop query - **opts** (`keyword`) - Optional - Configuration options ### Options #### Query Parameters - **:page_links** (`integer` | `:all` | `:none`) - Optional - Number of page links to render. Default: 5 - **:path** (`string` | `tuple` | `function`) - Optional - Path builder for pagination links. Default: nil - **:reverse** (`boolean`) - Optional - Reverse next/previous for cursor pagination. Default: false ### Returns `Flop.Phoenix.Pagination` struct with all data needed to render pagination. ### Behavior - For page-based pagination (`:page`, `:offset`): returns page links info - For cursor-based pagination (`:first`, `:last`): returns cursor info - Returns struct with `pagination_type: nil` if no pagination needed - Calculates ellipsis placement based on `page_links` option ``` -------------------------------- ### Invalid Filter Field Config: Invalid Tuple Structure Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/errors.md This example demonstrates an invalid tuple structure in the `fields` attribute, where the key is a string instead of an atom, leading to `Flop.Phoenix.InvalidFilterFieldConfigError`. ```heex <.filter_fields form={@form} fields={[{"name", []}]} /> ``` -------------------------------- ### List Products with Cursor-Based Pagination Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-pagination.md Handles incoming parameters to list products using cursor-based pagination. Assigns products and meta to the socket. ```elixir def handle_params(params, _uri, socket) do {products, meta} = MyApp.Products.list_products( params, pagination: :cursor_based ) {:noreply, assign(socket, products: products, meta: meta)} end ``` -------------------------------- ### Invalid Filter Field Config: Non-List Tuple Value Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/errors.md This example illustrates an invalid configuration where the value in a tuple within the `fields` attribute is a string instead of a list, causing `Flop.Phoenix.InvalidFilterFieldConfigError`. ```heex <.filter_fields form={@form} fields={[name: "invalid"]} /> ``` -------------------------------- ### Build Form from Flop.Meta, Not Changeset Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/README.md To fix a NoMetaFormError, construct the form using 'to_form(@meta)' instead of 'to_form(@changeset)'. This ensures the form is built from the correct Flop.Meta structure. ```heex <.filter_fields form={to_form(@changeset)} /> <.filter_fields form={to_form(@meta)} /> ``` -------------------------------- ### Pagination with Captured Function Reference Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-pagination.md Illustrates using a captured function reference (e.g., `&Routes.product_path/3`) to define the pagination path. This provides a concise way to reference route helpers. ```heex ``` -------------------------------- ### Retrieve Global Component Options Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-utilities.md Fetches global component options from the application environment for `:pagination` or `:table`. Reads from the `:flop_phoenix` application config, looking for a `component` key and its `:opts` value. ```elixir config :flop_phoenix, :table, opts: [container: true, table_attrs: [class: "my-table"]] ``` ```elixir config :flop_phoenix, :table, opts: {MyApp.Flop, :get_table_opts} ``` ```elixir Flop.Phoenix.Misc.get_global_opts(:table) # => [container: true, table_attrs: [class: "my-table"]] ``` -------------------------------- ### Accessible Filter Form with Aria Label Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-filters.md This example shows how to create an accessible filter form by including an `aria-label` attribute for screen readers. It also manually defines labels and inputs for demonstration. ```heex
<.filter_fields :let={i} form={form} fields={[:name, :price]}>
``` -------------------------------- ### LiveView Handler for Product Listing Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-pagination.md This Elixir snippet shows how to fetch paginated products in your LiveView handler. It takes parameters, fetches data using `MyApp.Products.list_products/1`, and assigns the results and metadata to the socket. ```elixir def handle_params(params, _uri, socket) do {products, meta} = MyApp.Products.list_products(params) {:noreply, assign(socket, products: products, meta: meta)} end ``` -------------------------------- ### Flop.Phoenix.Pagination.new/2 Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-pagination.md Creates a `Pagination` struct from a `Flop.Meta` struct and optional configuration. This function is essential for generating pagination links and information. ```APIDOC ## `Flop.Phoenix.Pagination.new/2` ### Description Creates a `Pagination` struct from a `Flop.Meta` struct. This struct contains information necessary for rendering pagination controls, such as current page, total pages, and navigation links. ### Function Signature ```elixir @spec new(Meta.t(), keyword) :: t def new(meta, opts \ []) ``` ### Parameters #### Parameters - **meta** (`Flop.Meta`) - Required - Meta struct from Flop query. - **opts** (`keyword`) - Optional - Options for configuring pagination. #### Options - **`:page_links`** (`integer` | `:all` | `:none`) - Optional - Default: `5` - Number of page links to render. - **`:path`** (`string` | `tuple` | `function`) - Optional - Default: `nil` - Path builder for links. - **`:reverse`** (`boolean`) - Optional - Default: `false` - Reverse next/previous for cursor pagination. ### Returns - `Pagination` struct ### Example ```elixir meta = %Flop.Meta{ flop: %Flop{page: 2, page_size: 10}, current_page: 2, total_pages: 5, has_previous_page?: true, has_next_page?: true, errors: [] } pagination = Flop.Phoenix.Pagination.new(meta, page_links: 5, path: ~p"/pets") # Access the pagination info: pagination.current_page # => 2 pagination.total_pages # => 5 pagination.previous_page # => 1 pagination.next_page # => 3 path = pagination.path_fun.(2) # => "/pets?page=2&page_size=10" ``` ``` -------------------------------- ### Generate HTML Input Validations Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-utilities.md The `input_validations/3` function generates HTML validation attributes for form inputs. Example validations include minimum and maximum values for numeric fields and maximum length for text fields. ```elixir :page -> [min: 1] :offset -> [min: 0] :after, :before -> [maxlength: 100] :page_size, :limit, :first, :last -> [min: 1, max: max_limit] :value (text type) -> [maxlength: 100] ``` -------------------------------- ### Combining Filters with Table and Pagination Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-filters.md This snippet demonstrates how to use Flop filters in a form, display data in a table, and include pagination controls. Ensure the form's `phx-change` event matches the backend handler. ```heex <.form for={form} phx-change="filter"> <.filter_fields :let={i} form={form} fields={[:category, :status]}> <.input field={i.field} label={i.label} type={i.type} /> <:col :let={p} label="Name" field={:name}>{p.name} <:col :let={p} label="Category" field={:category}>{p.category} <:col :let={p} label="Status" field={:status}>{p.status} ``` -------------------------------- ### Determine Page Link Rendering Range Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-main.md Calculates the start and end page numbers for rendering pagination links based on the chosen strategy. Handles 'all' pages, 'none', or a maximum number of visible links. ```elixir iex> Flop.Phoenix.page_link_range(:all, 4, 20) {1, 20} ``` ```elixir iex> Flop.Phoenix.page_link_range(5, 4, 20) {2, 6} ``` ```elixir iex> Flop.Phoenix.page_link_range(:none, 4, 20) {nil, nil} ``` -------------------------------- ### Create Form from Meta Data Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-filters.md Demonstrates two ways to create a form object from meta data using `Phoenix.Component.to_form/1` and `Phoenix.Component.to_form/2` with an `as` option. ```elixir form = Phoenix.Component.to_form(@meta) form = Phoenix.Component.to_form(@meta, as: :search) ``` -------------------------------- ### Table with Bulk Action Checkboxes Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-tables.md This HEEx code renders a Flop Phoenix table with checkboxes in a dedicated action column for selecting multiple items. It includes example buttons for common bulk actions like delete and publish. ```heex <:col :let={product} label="Name" field={:name}>{product.name} <:action :let={product}>
``` -------------------------------- ### build_path/3 Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-main.md Constructs a URL path, appending query parameters derived from a Flop or Flop.Meta struct, compatible with Phoenix routing. ```APIDOC ## build_path/3 ### Description Builds a path including query parameters from a `Flop` or `Flop.Meta` struct. ### Signature ```elixir @spec build_path( String.t() | {module, atom, [any]} | {function, [any]} | (keyword -> String.t()), Meta.t() | Flop.t() | keyword, keyword ) :: String.t() def build_path(path, meta_or_flop_or_params, opts \ []) ``` ### Parameters #### Path Parameters - **path** (string | tuple | function) - Required - Verified route string, MFA tuple, FA tuple, or 1-ary function - **meta_or_flop_or_params** (`Flop.Meta` | `Flop.t()` | keyword) - Required - Pagination/filtering state - **opts** (keyword) - Required - Options: `:for` (schema), `:backend` ### Returns String containing the built path with query parameters ### Example ```elixir iex> flop = %Flop{page: 2, page_size: 10} iex> path = Flop.Phoenix.build_path("/pets", flop) iex> %URI{path: p, query: q} = URI.parse(path) iex> {p, URI.decode_query(q)} {"/pets", %{"page" => "2", "page_size" => "10"}} iex> # With existing query parameters iex> path = Flop.Phoenix.build_path("/pets?species=dogs", flop) iex> %URI{path: p, query: q} = URI.parse(path) iex> {p, URI.decode_query(q)} {"/pets", %{"page" => "2", "page_size" => "10", "species" => "dogs"}} ``` ``` -------------------------------- ### Table with Row Click Handler Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-tables.md Configures the table to navigate to a product's detail page when a row is clicked. ```heex ``` -------------------------------- ### Filtered and Sorted List Table and Pagination Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/README.md Render a sortable table with multiple columns and pagination controls, suitable for filtered and sorted lists. Assumes 'items' and 'meta' are assigned to the socket. ```heex <:col :let={item} label="Name" field={:name}>{item.name} <:col :let={item} label="Status" field={:status}>{item.status} ``` -------------------------------- ### Pagination Components Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/COMPLETION-REPORT.txt Documentation for pagination components, including their signatures, parameters, and usage. ```APIDOC ## Pagination Components ### Description Provides functions for handling page-based, offset-based, and cursor-based pagination. ### Components - `pagination/1` - `pagination_for/1` ### Functions - `Pagination.new/2` ### Features - Page-based pagination (page + page_size) - Offset-based pagination (offset + limit) - Cursor-based pagination (first/last with after/before) - Custom path builders - Event-based pagination - Customizable UI via slots - Sort indicators - Accessibility features ``` -------------------------------- ### Protocol Implementation for Flop.Meta Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/form-data-protocol.md This snippet shows the basic implementation of the Phoenix.HTML.FormData protocol for the Flop.Meta struct. It serves as the foundation for using Flop.Meta with Phoenix form functions. ```elixir defimpl Phoenix.HTML.FormData, for: Flop.Meta do # Implementation details end ``` -------------------------------- ### Combining Flop Phoenix Table with Pagination Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-tables.md This HEEx snippet renders a table with product data and includes pagination controls. The Elixir snippet demonstrates how to handle incoming parameters for pagination and filtering, fetch the corresponding data, and update the socket. ```heex <:col :let={product} label="Name" field={:name}>{product.name} <:col :let={product} label="Price" field={:price}>${product.price} ``` ```elixir def handle_params(params, _uri, socket) do {products, meta} = MyApp.Products.list_products(params) {:noreply, assign(socket, products: products, meta: meta)} end ``` -------------------------------- ### Wrapper Component for Table Configuration Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/configuration.md Create a custom wrapper component to set default options for the `Flop.Phoenix.table` component, simplifying usage. ```elixir defmodule MyAppWeb.Components.FlopComponents do use Phoenix.Component import Flop.Phoenix attr :items, :list, required: true attr :meta, Flop.Meta, required: true attr :path, :any, default: nil attr :on_sort, :any, default: nil attr :target, :string, default: nil attr :opts, :list, default: [] slot :col, required: true slot :action def my_table(assigns) do opts = [ container: true, container_attrs: [class: "table-wrapper"], table_attrs: [class: "table is-striped is-hoverable"], symbol_asc: "↑", symbol_desc: "↓" ] |> Keyword.merge(assigns.opts) assigns = assign(assigns, :opts, opts) ~H"" {render_slot(@col)} {render_slot(@action)} """ end attr :meta, Flop.Meta, required: true attr :path, :any, default: nil attr :on_paginate, :any, default: nil attr :target, :string, default: nil def my_pagination(assigns) do ~H"" <:previous>← Previous <:next>Next → <:ellipsis>… """ end end ``` -------------------------------- ### Create Pagination Struct Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-pagination.md Creates a Pagination struct from a Flop.Meta struct and optional configuration. Use this to manually build pagination information when not using the `pagination_for/1` component directly. ```elixir meta = %Flop.Meta{ flop: %Flop{page: 2, page_size: 10}, current_page: 2, total_pages: 5, has_previous_page?: true, has_next_page?: true, errors: [] } pagination = Flop.Phoenix.Pagination.new(meta, page_links: 5, path: ~p"/pets") # Access the pagination info: pagination.current_page # => 2 pagination.total_pages # => 5 pagination.previous_page # => 1 pagination.next_page # => 3 path = pagination.path_fun.(2) # => "/pets?page=2&page_size=10" ``` -------------------------------- ### to_query/2 Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/api-reference-main.md Transforms a Flop struct into a keyword list, which can be directly used with Phoenix verified routes or route helpers for constructing URLs. ```APIDOC ## to_query/2 ### Description Converts a `Flop` struct into a keyword list suitable for use with Phoenix verified routes or route helpers. ### Signature ```elixir @spec to_query(Flop.t(), keyword) :: keyword def to_query(%Flop{filters: filters} = flop, opts \ []) ``` ### Parameters #### Path Parameters - **flop** (`Flop.t()`) - Required - Flop struct to convert - **opts** (keyword) - Optional - Options: `:for` (schema), `:backend`, `:default_limit`, `:default_order` ### Returns Keyword list with query parameters ### Example ```elixir iex> f = %Flop{page: 2, page_size: 10} iex> Flop.Phoenix.to_query(f) [page_size: 10, page: 2] iex> f = %Flop{ ...> filters: [ ...> %Flop.Filter{field: :name, op: :=~, value: "Mag"} ...> ] ...> } iex> Flop.Phoenix.to_query(f) [filters: %{0 => %{field: :name, op: :=~, value: "Mag"}}] ``` ``` -------------------------------- ### LiveView Template for Pagination Source: https://github.com/woylie/flop_phoenix/blob/main/_autodocs/guide-pagination.md Use this HEEx snippet in your LiveView template to render the pagination component. It requires the `meta` data and the `path` to the resource. ```heex ```