defmodule ToweropsWeb.CoreComponents do @moduledoc """ Provides core UI components. At first glance, this module may seem daunting, but its goal is to provide core building blocks for your application, such as tables, forms, and inputs. The components consist mostly of markup and are well-documented with doc strings and declarative assigns. You may customize and style them in any way you want, based on your application growth and needs. The foundation for styling is Tailwind CSS, a utility-first CSS framework. Here are useful references: * [Tailwind CSS](https://tailwindcss.com) - the foundational framework we build on. You will use it for layout, sizing, flexbox, grid, and spacing. * [Heroicons](https://heroicons.com) - see `icon/1` for usage. * [Phoenix.Component](https://hexdocs.pm/phoenix_live_view/Phoenix.Component.html) - the component system used by Phoenix. Some components, such as `<.link>` and `<.form>`, are defined there. """ use Phoenix.Component use Gettext, backend: ToweropsWeb.Gettext alias Phoenix.HTML.Form alias Phoenix.HTML.FormField alias Phoenix.LiveView.JS @doc """ Renders flash notices. ## Examples <.flash kind={:info} flash={@flash} /> <.flash kind={:info} phx-mounted={show("#flash")}>Welcome Back! """ attr :id, :string, doc: "the optional id of flash container" attr :flash, :map, default: %{}, doc: "the map of flash messages to display" attr :title, :string, default: nil attr :kind, :atom, values: [:info, :error], doc: "used for styling and flash lookup" attr :rest, :global, doc: "the arbitrary HTML attributes to add to the flash container" slot :inner_block, doc: "the optional inner block that renders the flash message" def flash(assigns) do assigns = assign_new(assigns, :id, fn -> "flash-#{assigns.kind}" end) ~H"""
hide("##{@id}")} phx-hook="AutoDismissFlash" data-dismiss-after="30000" role="alert" aria-live="assertive" class="pointer-events-none fixed inset-0 flex items-end px-4 py-6 sm:items-start sm:p-6 z-50" {@rest} >
<.icon :if={@kind == :info} name="hero-check-circle" class="size-6 text-green-400" /> <.icon :if={@kind == :error} name="hero-x-circle" class="size-6 text-red-400" />

{@title}

{render_flash_message(msg)}

""" end # Renders flash message content, supporting both plain strings and maps with links # Map format: %{text: "Message", link_text: "Link", link_url: "/path"} defp render_flash_message(%{text: text, link_text: link_text, link_url: link_url}) do assigns = %{text: text, link_text: link_text, link_url: link_url} ~H""" {@text} <.link navigate={@link_url} class="font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300" > {@link_text} """ end defp render_flash_message(msg), do: msg @doc """ Renders a button with navigation support. ## Examples <.button>Send! <.button phx-click="go" variant="primary">Send! <.button navigate={~p"/"}>Home """ attr :rest, :global, include: ~w(href navigate patch method download name value disabled) attr :class, :any attr :variant, :string, values: ~w(primary secondary danger ghost) attr :size, :string, default: "md", values: ~w(sm md lg) attr :loading, :boolean, default: false slot :inner_block, required: true def button(%{rest: rest} = assigns) do variants = %{ "primary" => "bg-blue-600 text-white hover:bg-blue-500 active:bg-blue-700 focus:ring-blue-500 shadow-md hover:shadow-lg dark:bg-blue-500 dark:hover:bg-blue-400 dark:active:bg-blue-600", "secondary" => "bg-white text-gray-700 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:ring-blue-500 dark:bg-gray-800 dark:text-gray-200 dark:ring-gray-600 dark:hover:bg-gray-700", "danger" => "bg-red-600 text-white hover:bg-red-500 active:bg-red-700 focus:ring-red-500 dark:bg-red-500 dark:hover:bg-red-400", "ghost" => "bg-transparent text-gray-700 hover:bg-gray-100 focus:ring-blue-500 shadow-none dark:text-gray-300 dark:hover:bg-gray-800", nil => "bg-white text-gray-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:ring-blue-500 dark:bg-gray-800 dark:text-white dark:ring-gray-700 dark:hover:bg-gray-700" } sizes = %{ "sm" => "px-2.5 py-1.5 text-xs", "md" => "px-3.5 py-2.5 text-sm", "lg" => "px-5 py-3 text-base" } assigns = assign_new(assigns, :class, fn -> [ "inline-flex items-center justify-center gap-2 rounded-lg font-semibold shadow-sm transition-all duration-150 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed dark:focus:ring-offset-gray-900", Map.fetch!(sizes, assigns.size), Map.fetch!(variants, assigns[:variant]) ] end) if rest[:href] || rest[:navigate] || rest[:patch] do ~H""" <.link class={@class} {@rest}> {render_slot(@inner_block)} """ else ~H""" """ end end @doc """ Renders an input with label and error messages. A `Phoenix.HTML.FormField` may be passed as argument, which is used to retrieve the input name, id, and values. Otherwise all attributes may be passed explicitly. ## Types This function accepts all HTML input types, considering that: * You may also set `type="select"` to render a ` """ end def input(%{type: "checkbox"} = assigns) do assigns = assigns |> assign_new(:checked, fn -> Form.normalize_value("checkbox", assigns[:value]) end) |> assign_new(:error_id, fn -> assigns.id && "#{assigns.id}-error" end) ~H"""
<.error :if={@errors != []} id={@error_id}> {msg}
""" end def input(%{type: "select"} = assigns) do assigns = assign_new(assigns, :error_id, fn -> assigns.id && "#{assigns.id}-error" end) ~H"""
<.error :if={@errors != []} id={@error_id}> {msg}
""" end def input(%{type: "textarea"} = assigns) do assigns = assign_new(assigns, :error_id, fn -> assigns.id && "#{assigns.id}-error" end) ~H"""
<.error :if={@errors != []} id={@error_id}> {msg}
""" end # All other inputs text, datetime-local, url, password, etc. are handled here... def input(assigns) do assigns = assign_new(assigns, :error_id, fn -> assigns.id && "#{assigns.id}-error" end) ~H"""
<.error :if={@errors != []} id={@error_id}> {msg}
""" end # Helper used by inputs to generate form errors defp error(assigns) do ~H"""

<.icon name="hero-exclamation-circle" class="h-5 w-5 flex-shrink-0" /> {render_slot(@inner_block)}

""" end @doc """ Renders a header with title. """ slot :inner_block, required: true slot :subtitle slot :actions def header(assigns) do ~H"""

{render_slot(@inner_block)}

{render_slot(@subtitle)}

{render_slot(@actions)}
""" end @doc """ Renders a table with generic styling. ## Examples <.table id="users" rows={@users}> <:col :let={user} label="id">{user.id} <:col :let={user} label="username">{user.username} """ attr :id, :string, required: true attr :rows, :list, required: true attr :row_id, :any, default: nil, doc: "the function for generating the row id" attr :row_click, :any, default: nil, doc: "the function for handling phx-click on each row" attr :row_link, :any, default: nil, doc: "the function for generating a navigate path for each row, renders real tags" attr :row_item, :any, default: &Function.identity/1, doc: "the function for mapping each row before calling the :col and :action slots" slot :col, required: true do attr :label, :string end slot :action, doc: "the slot for showing user actions in the last table column" def table(assigns) do assigns = with %{rows: %Phoenix.LiveView.LiveStream{}} <- assigns do assign(assigns, row_id: assigns.row_id || fn {id, _item} -> id end) end ~H"""
{col[:label]} {gettext("Actions")}
0 && "text-gray-500 dark:text-gray-400", @row_link && "p-0 text-sm whitespace-nowrap", !@row_link && "py-4 pr-3 pl-4 text-sm whitespace-nowrap sm:pl-6", @row_click && "cursor-pointer" ]} > <%= if @row_link do %> <.link navigate={@row_link.(row)} class="block py-4 pr-3 pl-4 sm:pl-6 text-inherit no-underline" > {render_slot(col, @row_item.(row))} <% else %> {render_slot(col, @row_item.(row))} <% end %>
<%= for action <- @action do %> {render_slot(action, @row_item.(row))} <% end %>
""" end @doc """ Renders a data list. ## Examples <.list> <:item title="Title">{@post.title} <:item title="Views">{@post.views} """ slot :item, required: true do attr :title, :string, required: true end def list(assigns) do ~H"""
{item.title}
{render_slot(item)}
""" end @doc """ Renders a [Heroicon](https://heroicons.com). Heroicons come in three styles – outline, solid, and mini. By default, the outline style is used, but solid and mini may be applied by using the `-solid` and `-mini` suffix. You can customize the size and colors of the icons by setting width, height, and background color classes. Icons are extracted from the `deps/heroicons` directory and bundled within your compiled app.css by the plugin in `assets/vendor/heroicons.js`. ## Examples <.icon name="hero-x-mark" /> <.icon name="hero-arrow-path" class="ml-1 size-3 motion-safe:animate-spin" /> """ attr :name, :string, required: true attr :class, :any, default: "size-4" def icon(%{name: "hero-" <> _} = assigns) do ~H""" """ end ## JS Commands def show(js \\ %JS{}, selector) do JS.show(js, to: selector, time: 300, transition: {"transition-all ease-out duration-300", "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95", "opacity-100 translate-y-0 sm:scale-100"} ) end def hide(js \\ %JS{}, selector) do JS.hide(js, to: selector, time: 200, transition: {"transition-all ease-in duration-200", "opacity-100 translate-y-0 sm:scale-100", "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"} ) end @doc """ Renders pagination controls with page numbers and ellipsis. Supports both mobile (Previous/Next only) and desktop (full page numbers) views. ## Examples <.pagination meta={@pagination} path={~p"/admin"} /> <.pagination meta={@pagination} path={~p"/devices"} params={%{"tab" => @current_tab}} /> """ attr :meta, :map, required: true, doc: "Pagination metadata with :page, :per_page, :total_count, :total_pages" attr :path, :string, required: true, doc: "Base path for pagination links" attr :params, :map, default: %{}, doc: "Additional query params to preserve" def pagination(assigns) do ~H""" <%= if @meta.total_pages > 1 do %>
<.link :if={@meta.page > 1} patch={build_pagination_path(@path, @params, @meta.page - 1)} class="relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-white/10 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700" > Previous <.link :if={@meta.page < @meta.total_pages} patch={build_pagination_path(@path, @params, @meta.page + 1)} class="relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-white/10 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700" > Next
<% end %> """ end # Generate pagination range with ellipsis for large page counts # Shows: [1] ... [4] [5] [6] ... [20] when on page 5 of 20 defp pagination_range(current_page, total_pages) do cond do total_pages <= 7 -> # Show all pages if 7 or fewer Enum.to_list(1..total_pages) current_page <= 4 -> # Near the start [1, 2, 3, 4, 5, :ellipsis, total_pages] current_page >= total_pages - 3 -> # Near the end [ 1, :ellipsis, total_pages - 4, total_pages - 3, total_pages - 2, total_pages - 1, total_pages ] true -> # In the middle [1, :ellipsis, current_page - 1, current_page, current_page + 1, :ellipsis, total_pages] end end # Build pagination path with preserved query params defp build_pagination_path(base_path, params, page) do query_params = Map.put(params, "page", page) query_string = URI.encode_query(query_params) if query_string == "" do base_path else "#{base_path}?#{query_string}" end end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate the number of files with plural rules # dngettext("errors", "1 file", "%{count} files", count) # # However the error messages in our forms and APIs are generated # dynamically, so we need to translate them by calling Gettext # with our gettext backend as first argument. Translations are # available in the errors.po file (as we use the "errors" domain). if count = opts[:count] do Gettext.dngettext(ToweropsWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(ToweropsWeb.Gettext, "errors", msg, opts) end end @doc """ Renders a relative timestamp with full timestamp on hover. ## Examples <.timestamp datetime={@device.inserted_at} timezone={@timezone} /> """ attr :datetime, :any, required: true, doc: "DateTime to display" attr :timezone, :string, default: "UTC", doc: "User's timezone for full timestamp" attr :class, :string, default: "", doc: "Additional CSS classes" attr :format, :string, default: "relative", doc: "Display format: 'relative' or 'absolute'" attr :now, :any, default: nil, doc: "Current time for live-ticking relative timestamps" def timestamp(assigns) do assigns = assigns |> assign(:relative_time, ToweropsWeb.TimeHelpers.format_time_ago(assigns.datetime)) |> assign(:full_time, ToweropsWeb.TimeHelpers.format_datetime(assigns.datetime, assigns.timezone)) ~H""" {if @format == "relative", do: @relative_time, else: @full_time} """ end @doc """ Renders a signal strength badge with color-coded quality indicator. ## Thresholds (dBm) - Excellent: -55 or higher (green) - Good: -56 to -65 (blue) - Fair: -66 to -75 (yellow) - Poor: -76 to -85 (orange) - Critical: below -85 (red) ## Examples <.signal_badge value={-60} /> <.signal_badge value={nil} /> """ attr :value, :integer, doc: "Signal strength in dBm" def signal_badge(%{value: nil} = assigns) do ~H""" """ end def signal_badge(assigns) do {color, label} = cond do assigns.value >= -55 -> {"green", "Excellent"} assigns.value >= -65 -> {"blue", "Good"} assigns.value >= -75 -> {"yellow", "Fair"} assigns.value >= -85 -> {"orange", "Poor"} true -> {"red", "Critical"} end assigns = assign(assigns, color: color, label: label) ~H""" {@value} dBm """ end @doc """ Renders a Signal-to-Noise Ratio (SNR) badge with color-coded quality indicator. ## Thresholds (dB) - Excellent: 35+ (green) - Good: 25-34 (blue) - Fair: 15-24 (yellow) - Poor: 10-14 (orange) - Critical: below 10 (red) ## Examples <.snr_badge value={30} /> <.snr_badge value={nil} /> """ attr :value, :integer, doc: "SNR in dB" def snr_badge(%{value: nil} = assigns) do ~H""" """ end def snr_badge(assigns) do {color, label} = cond do assigns.value >= 35 -> {"green", "Excellent"} assigns.value >= 25 -> {"blue", "Good"} assigns.value >= 15 -> {"yellow", "Fair"} assigns.value >= 10 -> {"orange", "Poor"} true -> {"red", "Critical"} end assigns = assign(assigns, color: color, label: label) ~H""" {@value} dB """ end @doc """ Translates the errors for a field from a keyword list of errors. """ def translate_errors(errors, field) when is_list(errors) do for {^field, {msg, opts}} <- errors, do: translate_error({msg, opts}) end end