Skip to content

About

👍 flat skin for activeadmin 3 with light and dark modes

Topics

Resources

Stars

182 stars

Watchers

9 watching

Forks

Repository files navigation

ActiveAdminTheme

A dense desktop theme and a set of shared components for ActiveAdmin 4.

ActiveAdmin 4 keeps its menu in a left sidebar and gives breadcrumbs and titles a lot of room. That works on mobile but wastes width on a laptop with a large table and many filters. This theme keeps the compact desktop layout of theme 3 and keeps ActiveAdmin 4's mobile support:

  • Desktop (768px and wider): a horizontal top menu, compact breadcrumbs and title, filters left of the table (collapsible).
  • Mobile (narrower than 768px): the menu opens in a drawer, filters sit above the table, forms and show pages use the full width.
  • Index tables scroll sideways when they are wider than the screen, and cells stay on one line.
  • Theme 3 colors, density, and typography on top of ActiveAdmin 4's own dark mode.

Theme 4 needs ActiveAdmin 4 (>= 4.0.0.beta23) and Ruby 3.3 or newer. For ActiveAdmin 3, use theme 3.x (branch 3.x). See docs/migrating-from-v3.md.

Screenshots

Pages of the demo app in test/dummy. bundle exec rake screenshots regenerates them.

Index: filters, scopes, batch actions, status tags Index in dark mode
Index page Index page in dark mode
Show: attributes table, tabs, secret reveal, related records and external links Show in dark mode
Show page Show page in dark mode
Form: searchable select Confirm dialog
Form with an open searchable select Confirm dialog
Components: status tags, truncate text, sticky rows, secret reveal, pre wrap Phone width: drawer menu, filters above the table
Components page Index page at phone width

Installation

Theme 4 is in beta and not on RubyGems yet, so install it from its GitHub tag:

gem "active_admin_theme", github: "activeadmin-plugins/active_admin_theme", tag: "v4.0.0.beta1"

The gem requires active_admin first, so its views and partials win over ActiveAdmin's own. Do not reorder that.

CSS

ActiveAdmin 4 builds its CSS with Tailwind CSS 4. Your Tailwind entry file (generated by rails g active_admin:assets, usually app/assets/stylesheets/active_admin.css) must import the theme CSS after Tailwind. Pick one route.

From the installed gem. The gem's location differs between machines (a laptop, a Docker image, CI), so the path must not be committed. The task writes it into a generated file next to your entry file, and the entry file only imports that file by a fixed name:

bin/rails active_admin_theme:css

The entry file gets this block, which is the same on every machine, so commit it:

@import "tailwindcss";
@config "../../../tailwind-active_admin.config.js";

/* active_admin_theme:begin */
@import "./active_admin_theme.generated.css";
/* active_admin_theme:end */

The task writes active_admin_theme.generated.css, which holds the machine-specific path. Add it to .gitignore:

/app/assets/stylesheets/active_admin_theme.generated.css

Run the task before every Tailwind build, because the generated file does not exist on a fresh checkout and its path changes when the gem upgrades. For example, in the build script that runs Tailwind:

bin/rails active_admin_theme:css && npx tailwindcss -i app/assets/stylesheets/active_admin.css -o app/assets/builds/active_admin.css

If that is awkward for your build, use the npm route.

From the npm package. This avoids a machine-specific path and a build step, and fits hosts that already install @activeadmin/activeadmin from npm:

npm install @activeadmin-plugins/active_admin_theme
@import "tailwindcss";
@config "../../../tailwind-active_admin.config.js";
@import "@activeadmin-plugins/active_admin_theme/css";

Keep the npm package and the gem on the same version.

Tailwind only generates the classes it finds in files it scans. Tailwind 4 reads @source lines in CSS. The theme prints them, so you do not call bundle show yourself:

bin/rails active_admin_theme:tailwind:sources

To write them to a file, name it in ACTIVE_ADMIN_THEME_SOURCES. The paths in the file are relative to the file, but they still depend on where the gem is installed, so git-ignore it as you do the generated CSS import, and run the task in the same build step:

ACTIVE_ADMIN_THEME_SOURCES=app/assets/stylesheets/active_admin_theme.sources.css bin/rails active_admin_theme:tailwind:sources
@import "./active_admin_theme.sources.css";

Don't commit the printed output, because its paths are absolute. With a Tailwind config file, ActiveAdminTheme.tailwind_content returns the globs for content, so no execSync is needed.

JavaScript

ActiveAdmin 4 renders its own import map, ActiveAdmin.importmap, not the import map in your config/importmap.rb. A pin in your own config/importmap.rb loads nothing on ActiveAdmin pages.

The theme's engine pins its modules into ActiveAdmin.importmap, so importmap hosts need no setup. To load one of your own scripts on ActiveAdmin pages, pin it into the same map, for example in config/initializers/active_admin.rb:

ActiveAdmin.importmap.pin "my_admin_script", to: "my_admin_script.js"

ActiveAdmin pages import the modules listed in ActiveAdminTheme.javascripts. With an ActiveAdmin that has the javascript_modules setting (activeadmin/activeadmin#9148), the theme adds them to that setting after your initializers run. With an older ActiveAdmin, the theme's own _html_head imports them. The default list is:

%w[
  active_admin_theme/layout
  active_admin_theme/server_clock
  active_admin_theme/tabs
  active_admin_theme/dropdown_menu
  active_admin_theme/table_crisscross
  active_admin_theme/searchable_select
  active_admin_theme/confirm_dialog
  active_admin_theme/panel_toggle
  active_admin_theme/theme_toggle
]

With Sprockets, the engine adds the theme scripts and the vendored Tom Select to config.assets.precompile, so don't list them yourself. Propshaft needs nothing.

Change the list in an initializer to load fewer scripts or to add the optional ones:

ActiveAdminTheme.javascripts -= %w[active_admin_theme/table_crisscross]
ActiveAdminTheme.javascripts += %w[active_admin_theme/secret_reveal]

Your own watched directory. With an ActiveAdmin that has no importmap_watches setting (activeadmin/activeadmin#9153) and with config.importmap.sweep_cache on, each ActiveAdmin.importmap.cache_sweeper(watches:) call replaces the previous watcher. The theme makes that call from an after_initialize block that its initializer registers, so it runs after any config.after_initialize written in an engine or application class, and replaces that call's watcher. To watch your own directory too, register your block from an initializer that runs after the theme's, and pass every directory:

initializer "my_admin.importmap", after: "active_admin_theme.importmap" do |app|
  app.config.after_initialize do
    ActiveAdmin.importmap.cache_sweeper(watches: [
      ActiveAdmin::Engine.root.join("app/javascript"),
      ActiveAdminTheme::Engine.root.join("app/javascript"),
      root.join("app/javascript")
    ].map(&:to_s))
  end
end

jsbundling hosts. The npm package exports each module (@activeadmin-plugins/active_admin_theme/layout, .../server_clock, and so on). Import the ones you want from your active_admin entry file, and override app/views/active_admin/_html_head.html.erb to load your bundle.

Overriding

A host partial with the same path overrides the theme's. Copy the partial from the gem into your app's app/views/active_admin/ and edit it. The theme's partials are:

  • _header_leading: the menu button and the site title.
  • _header_navigation: the top menu.
  • _main_navigation: the mobile drawer menu.
  • _header_actions: the right end of the header. In order: the dark mode switch, the server clock, _header_links, the current user, and the logout icon.
  • _header_links: empty. Override it to add your own links between the clock and the current user.
  • _page_heading, _breadcrumbs, _page_title: the breadcrumbs and the page title, on one row of the dark title band. A host copy must keep light text there: use --aat-titlebar-text and --aat-titlebar-muted.
  • _page_content: the grid that holds the sidebar and the page, and the tab that collapses the sidebar.
  • _sidebar.
  • _flash_messages: the flash bands under the title band.
  • kaminari/*: the page links under an index table, with "First", "Next ›" and "Last »".

The index footer is one line under the table: per page, page links, the count, and the download links. Its English wording ("Displaying Orders 1 - 30 of 60 in total") comes from the theme's config/locales/active_admin_theme.en.yml; your own locale file overrides it, and other languages keep ActiveAdmin's text.

ActiveAdmin renders these partials from its own layout once it has the layout hooks (activeadmin/activeadmin#9149 to #9152). Until then, the theme also ships copies of the layout, _site_header, _page_header, and _html_head in app/views_compat that render the same partials. The engine adds that directory to the view paths only when the installed ActiveAdmin lacks the hooks, so override the small partials above rather than those copies.

A host Arbre component with the same builder method name replaces the theme's, as long as it loads after the theme's. Components in app/admin_components (or any file loaded in a to_prepare block) do.

Colors

All colors are CSS custom properties with a light value on :root and a dark value under .dark. Override any of them in your own CSS:

:root {
  --aat-header-bg: #1b3a57;
  --aat-button: #1f6f4a;
}
.dark {
  --aat-surface: #20242b;
}
Property Used for
--aat-page-bg, --aat-surface, --aat-surface-2, --aat-surface-hover, --aat-selected-row Page; panels, attributes tables and the tab content box; table headers, hover, selected rows
--aat-text, --aat-text-muted, --aat-border Text and borders
--aat-text-success, --aat-text-warning, --aat-text-danger Success, warning and danger text, such as a confirmation, a warning label or an error message. Readable (4.5:1 or better) on the page and panel surfaces in both modes. Use as text-(--aat-text-danger). The --aat-status-* and --aat-flash-* colours are fills and are too light as text on the dark surface.
--aat-input-bg, --aat-input-border Form controls
--aat-accent, --aat-link, --aat-delete-link Accent, links, and delete links
--aat-button, --aat-button-hover, --aat-button-text Buttons and action items. Every action item is a filled button.
--aat-header-bg, --aat-header-text, --aat-header-border, --aat-menu-* Header and top menu
--aat-titlebar-bg, --aat-titlebar-text, --aat-titlebar-muted Title band: background, page title, breadcrumbs. Dark in both modes.
--aat-table-header, --aat-filter-label Index table header; filter and form field labels
--aat-flash-notice, --aat-flash-alert, --aat-flash-warning, --aat-flash-error, each with a -border variant Flash band fill and bottom border, the same in both modes. Warning defaults to the alert colours, as in v3. Any other type is gray (--aat-flash-other); give it a colour with .aat-flash[data-flash="info"] { --aat-flash-color: ...; --aat-flash-border: ...; }.

Two more properties set sizes:

  • --aat-font-size (default 0.75rem, 12px) is the base text size of the page, tables, forms, filters, and buttons. Smaller texts, such as filter labels and status tags, scale from it.
  • --aat-label-cap is the widest the label column of a show page's attributes_table gets. The column takes the width of its labels up to the cap; a longer label wraps.

DSL

columns

ActiveAdmin 4 removed columns and column. The theme restores them, with separate control for mobile and desktop.

columns "1:3" do                 # desktop: 1/4 + 3/4; mobile: stacked
  column { ... }
  column { ... }
end

columns "1:1", mobile: "1:1" do  # side by side on mobile too
  ...
end

columns do                       # no ratio: equal widths, any number of columns
  ...
end
  • The ratio string lists one weight per column. Pixel widths are not supported.
  • On mobile, columns stack unless mobile: sets a ratio.
  • A column has a minimum width of --aat-col-min (14rem). When the row has no room for it, the column moves to the next line instead of clipping its content.
  • column span: N from ActiveAdmin 3 still works and counts as the column's weight.

tabs

tabs do
  tab("Details") { ... }
  tab("History", id: "history") { ... }
end

Tabs use Flowbite's tabs, which ActiveAdmin already loads. A tab's panel id is its parameterized title unless id: sets it. A title already used on the page gets -2, -3 and so on, and an id that does not start with a letter gets a tab- prefix.

A URL hash opens a tab, on page load and when the hash changes. #history opens the tab whose panel id is history. A hash that names an element inside a hidden tab opens that tab, and every tab around it, and scrolls to the element. Clicking a tab writes its panel id to the hash without adding a history entry. The active_admin_theme/tabs script does this. It is in the default list.

panel

ActiveAdmin 4 still has panel, but no longer wraps sidebar content or the show page's attributes_table in one. The theme wraps both again: sidebar sections in a panel titled with the section name, and attributes_table on a show page in a "Model Details" panel. Panel#header_action is not restored.

A panel can collapse. collapsible: true turns the title into a button (aria-expanded, aria-controls) that shows and hides the body, and collapsed: true starts it closed. The body is hidden in the HTML, so the page does not flash it. Enter and Space work because the title is a real button:

panel "JSON", collapsible: true, collapsed: true do
  pre record.payload
end

It works for a panel inside a sidebar block too. The default script active_admin_theme/panel_toggle does the toggling and sends a bubbling aat:panel:toggle event with detail: {panel, expanded}. An app that removes it from ActiveAdminTheme.javascripts leaves a collapsed panel closed for good. A panel without collapsible: is unchanged.

Components

Every component but the select widget is opt-in: nothing changes for an app that does not call it or load its script. In a content do block, wrap the helpers that return strings (with_tooltip, pre_wrap) in text_node.

status_tag

Tags have a solid fill and white text, as in theme 3, the same in light and dark mode. ok (also published, complete, completed, green) is green, yes and info (also notice, blue) are blue, warning (also warn, orange) is amber, error (also errored, red, danger) is red, and anything else, such as no, is gray. empty shows only muted text. For any other value, define a CSS custom property named --aat-status-<value> in your CSS. For a one-off color, pass color: (a hex, named, rgb(), or hsl() color; anything else raises ArgumentError):

status_tag "Shipped"                # uses --aat-status-shipped, if you define it
status_tag "Late", color: "#b91c1c"

Tags are square, small, and shown in uppercase, as in theme 3. The case is CSS only, so the HTML keeps the text you pass, while a browser test driver reads it in uppercase. The StatusTag page object and the base gem's have_cell and have_row compare String text ignoring case.

notice

An inline note: a tinted box with a colored edge, readable in light and dark mode. kind: is info (the default), success, warning or danger; an unknown kind raises ArgumentError. A warning or danger has role="alert", the others role="status". A block builds the body.

notice "The export may take a minute."
notice "Check the dates before you export", kind: :warning
notice(kind: :danger) { para "Payment failed" }

truncate_text

One line of text with an ellipsis and the full value in the title attribute:

truncate_text(order.note, length: 40, max_width: "12rem")

With popup: true the full value shows in a popup on hover and on keyboard focus, in place of the title. The element is focusable and names the popup in aria-describedby. The popup is CSS only, and a scrolling table does not clip it:

truncate_text(order.note, max_width: "12rem", popup: true)

with_tooltip

A plain title hint by default. With html: true, the tooltip is sanitized HTML shown by ActiveAdmin's Flowbite tooltip. The HTML tooltip is positioned inside its container, so a wrapper with overflow (a scrolling table) can clip it.

text_node with_tooltip("42", "Total orders")
text_node with_tooltip("42", "<b>Total</b> orders", html: true)

pre_wrap

Preformatted text that wraps long lines. Blank text renders nothing, so an attributes_table row shows ActiveAdmin's empty marker. max_height: takes a CSS length or a number of pixels, caps the height, and scrolls the rest. The capped block can take keyboard focus:

text_node pre_wrap(response.body)
text_node pre_wrap(response.body, max_height: "20rem")
row(:payload) { |order| pre_wrap(order.payload, max_height: 240) }

secret_reveal

A masked value with an eye icon before it. A click fetches and shows the value, and the icon turns to an eye-off icon that hides it again. The URL must return {"value": "..."}. Needs the active_admin_theme/secret_reveal script.

secret_reveal url: secret_admin_account_path(account), mask: "••••••••"

With value: instead of url:, the value is in the page, in a <template>, and a click shows it with no request. It is always shown as text, and may span lines. A blank value shows "Empty". url: and value: are exclusive.

secret_reveal value: account.token

Prefer url: for credentials. An inline value is in the page HTML, while an endpoint can authorize and log each reveal.

confirm_dialog

A confirmation dialog with optional form fields, built on the Flowbite modal that ActiveAdmin uses for batch actions. It submits a real form with the CSRF token. Its script, active_admin_theme/confirm_dialog, handles focus and field validation and is on by default. Do not place it inside another form.

confirm_dialog "Reject", title: "Reject order", message: "The buyer is notified.",
  url: reject_admin_order_path(order), method: :post,
  fields: [
    {name: :reason, label: "Reason", as: :text, required: true},
    {name: :kind, as: :select, collection: [["Fraud", "fraud"], ["Other", "other"]]},
    {name: :notify, label: "Notify the buyer", as: :boolean, value: true}
  ]

The dialog has a title bar. Its buttons sit at the left, the confirm button first, then Cancel.

Field types are :string, :text, :number, :date, :select, and :boolean. More options:

  • scope: nests every field name, so reason becomes reject[reason], and meta[source] becomes reject[meta][source].
  • A select field takes multiple: true. It sends name[], and value: is an array of the selected values.
  • A field takes input_html:, attributes for its control, such as {min: 0, step: "0.01"} or {maxlength: 20}. The attributes the component sets, such as name and id, win, and class is joined.
  • params: adds hidden fields. Nested hashes and arrays become Rails' bracketed names.
  • class: adds classes to the button, and trigger_html: other attributes. Inside the action items the button looks like the other action items.
  • trigger: false renders the dialog without a button. It needs id:. Any element with data-modal-target and data-modal-show set to that id opens it; confirm_dialog_trigger(text, id, **html_options) renders such a button.
confirm_dialog id: "merge", trigger: false, title: "Merge customers?", url: merge_admin_customers_path,
  params: {ids: [3, 4], options: {keep: "newest"}}
text_node confirm_dialog_trigger("Merge", "merge")

confirm_dialog_tag takes the same arguments and returns HTML, for ERB and for blocks that return a string, such as action_item:

action_item :reject, only: :show do
  confirm_dialog_tag "Reject", title: "Reject order", url: reject_admin_order_path(resource), class: "action-item-button"
end

When a dialog opens, the script sends a bubbling aat:confirm-dialog:open event on it, with detail: {dialog, trigger}. The event goes out before the focus moves, so a listener can fill or add fields:

document.addEventListener("aat:confirm-dialog:open", ({detail: {dialog, trigger}}) => {
  dialog.querySelector("[name=reason]").value = trigger.dataset.reason
})

lazy_load

lazy_load url: path is a placeholder that fetches an HTML fragment when it scrolls into view (a hidden tab loads when opened) and replaces its content with it. Needs the opt-in active_admin_theme/lazy_load script.

lazy_load url: admin_account_history_path(account)
lazy_load url: report_path, loading: "Building the report...", error: "No report", eager: true
  • loading: is the text shown until the reply comes, and error: the text shown when the request fails.
  • method: is the request verb, get by default.
  • eager: true loads at once, without waiting for the placeholder to scroll into view.

The endpoint renders the fragment without the layout, for example render partial: "history", layout: false. A <script> in the reply does not run. The element sends a bubbling aat:lazy-load:loaded event after each load, so an app can set up its own widgets, and it reloads on aat:lazy-load:reload.

dropdown_menu

A button that opens a list of links, as ActiveAdmin 3's dropdown_menu did. It is a Flowbite dropdown. The default active_admin_theme/dropdown_menu script adds aria-expanded, closing on Escape, and the arrow keys. item takes the arguments of link_to, so method: and data: work. Each menu gets a unique id, or the one you pass as id:.

dropdown_menu "Export" do
  item "CSV", export_path(format: :csv)
  item "Purge", purge_path, method: :delete, data: {confirm: "Sure?"}
end

dropdown_menu_tag returns HTML, for blocks that return a string, such as action_item. It takes the items as an array of [text, url, link_options]. With no items it renders nothing.

action_item :export, only: :index do
  dropdown_menu_tag "Export", [["CSV", csv_path], ["Purge", purge_path, {method: :delete}]]
end

String helpers

For decorators and view helpers outside an Arbre context, each component has a helper that returns an html_safe String: status_tag, secret_reveal_tag, notice_tag, confirm_dialog_tag, dropdown_menu_tag and pre_wrap. status_tag builds its tag with Rails tag helpers, which is faster than Arbre in long tables, and gives the same markup as the component; inside Arbre the component wins. arbre { ... } builds any Arbre block the same way and trims Arbre's trailing newline. All of them are available in ActiveAdmin views. A plain object includes ActiveAdminTheme::Helpers::Tags. It must also answer the view methods a component calls, such as link_to for dropdown_menu_tag; a Draper decorator can delegate them to h.

class OrderDecorator < Draper::Decorator
  include ActiveAdminTheme::Helpers::Tags

  def state
    status_tag(object.state, label: object.state_label)
  end

  def token
    secret_reveal_tag(value: object.token)
  end
end

Link sidebars

related_records_sidebar and external_links_sidebar add a sidebar section of links: the records related to the page, and pages in external systems.

ActiveAdmin.register Customer do
  related_records_sidebar do |customer|
    link "Orders", admin_orders_path(q: {customer_id_eq: customer.id})
    link "Invoices", admin_invoices_path(q: {customer_id_eq: customer.id}),
      count: -> { customer.invoices.count }, if: -> { authorized?(:read, Invoice) }
  end

  external_links_sidebar do |customer|
    link "Billing", "https://billing.example/customers/#{customer.id}"
  end
end

The block gets the current record and runs in the view, so path helpers and authorized? work, but the view's instance variables do not. Related links open in the same tab unless they take new_tab: true. External links always open in a new tab. A new-tab link gets target="_blank" and rel="noopener noreferrer". The sections show on the show page by default, external links first (priority 1), then related records (priority 2), above other sidebars. only:, except:, if: and priority: go to ActiveAdmin's sidebar. A link takes count:, shown beside the label, and if:, a lambda or method name run in the view. A link whose condition is false is left out, and a section with no links is not rendered.

count: is a value, a lambda run in the view, or anything that answers count, such as a relation. A lambda may return such an object too. An Integer or a String is shown as it is, any other object is asked for its count, and nil shows no count. The count is worked out only for a link that shows.

Group links with group. Links outside any group come first, in a list of their own:

related_records_sidebar do |customer|
  link "Overview", admin_customer_path(customer)
  group "Shipping" do
    link "Parcels", admin_parcels_path(q: {customer_id_eq: customer.id}), count: customer.parcels
    link "Returns", admin_returns_path(q: {customer_id_eq: customer.id}), count: -> { customer.returns.open }
  end
  group "Billing" do
    link "Invoices", admin_invoices_path(q: {customer_id_eq: customer.id})
  end
end

group_headings: on the sidebar decides whether each group gets a heading and its own list. The default, :auto, shows headings only when there is more than one group and more than five links, so a short sidebar stays one plain list. true always shows them and false never does; without headings the links form one list in the order they were declared. A group whose links are all left out disappears with them. The titles are "Related records" and "External links", from active_admin_theme.sidebars.related_records and .external_links, or from title:.

Sticky first column

Add the with-sticky-rows class to a wide table, and its first column stays in place while the table scrolls sideways:

index do |table|
  table.add_class "with-sticky-rows"
  # columns
end

table_for orders, class: "with-sticky-rows" do
  # columns
end

Selects

Selects are Tom Select widgets, drawn by the active_admin_theme/searchable_select script. The script is in the default list. The gem vendors a pinned tom-select and pins it into ActiveAdmin.importmap; npm hosts add tom-select to their own dependencies.

Every select is upgraded. Without any setup the script upgrades:

Select Widget
Filter selects (.filters-form-field.select select) Search box in the dropdown, remove button, placeholder "Any"
Boolean filters Remove button, no search box
The predicate select of string and numeric filters No search box
Form selects (form.formtastic li.input.select select) Search box in the dropdown; a remove button when the select has a blank option or is multiple
select[data-tom-select] anywhere As a form select

Selects added later, such as has_many rows and dialogs, are upgraded when they enter the page. The contents of a <template> are left alone.

To turn this off for the whole app, so that only as: :searchable_select inputs and selects with tom_select: get the widget:

ActiveAdminTheme.searchable_select_all = false

To drop the script and Tom Select altogether:

ActiveAdminTheme.javascripts -= %w[active_admin_theme/searchable_select]

Per-select settings. tom_select: on any select input or filter takes false (leave the select native), true (upgrade it even when searchable_select_all is off) or a hash of Tom Select settings merged over the theme's. The hash also takes addPlugins and removePlugins.

f.input :size, as: :select, collection: sizes, tom_select: false
filter :event_eq, as: :select, collection: events, tom_select: {create: true, persist: false} # free-text values
f.input :kind, as: :select, include_blank: "None", tom_select: {allowEmptyOption: true} # the blank option is a row
f.input :tags, as: :select, multiple: true, tom_select: {addPlugins: ["checkbox_options"], removePlugins: ["remove_button"]}

The option renders the data-tom-select attribute, which you can also write yourself: "false", "true" or the settings as JSON.

select_tag :color, options_for_select(colors), data: {tom_select: {create: true}}

Settings and texts. The theme's _page_content partial renders them as JSON for the script:

ActiveAdminTheme.searchable_select_all = true # upgrade every select
ActiveAdminTheme.searchable_select_min_chars = 3 # characters to type before an AJAX select searches

The texts come from I18n, with these defaults:

en:
  active_admin_theme:
    searchable_select:
      any: "Any"
      no_results: "No results matched"
      type_to_search: "Type %{count} chars to search..."
      loading: "Loading..."
      loading_more: "Loading more..."
      no_more_results: "No more results"
      select_parent_first: "Select the parent first"
      add: "Add"

A host that overrides _page_content renders them itself with <%= active_admin_theme_config_tag %>. Without that element the script uses the defaults above. A host can also set them in JavaScript, in a script that runs before the theme's script:

<script>window.ActiveAdminTheme = {searchableSelect: {all: false, minChars: 2, texts: {noResults: "Nothing found"}}}</script>

The script exports configure(settings), which changes them for selects not upgraded yet, and upgradeAll(root), which upgrades the selects inside a node.

Searchable select

as: :searchable_select is a select that takes its options from an endpoint. The page holds only the selected records. It works in forms and filters, and on mobile.

f.input :customer, as: :searchable_select
filter :customer, as: :searchable_select

By default it searches once three characters are typed, loads the next page as the dropdown scrolls, and replaces the results when the text changes. Selected items stay. Three spaces ask for the unfiltered list: the length of the raw input counts, and the term is trimmed before it is sent.

Option Example Meaning
min_chars: min_chars: 0 Characters to type before searching. With 0 the first page loads when the select gets focus.
load_all: load_all: true Fetch every page up front and filter in the browser. For small collections.
per_page: per_page: 20 Page size to ask the endpoint for.
placeholder: placeholder: "Search customers" Text shown while nothing is selected.
depends_on: depends_on: :country_id The input this select depends on: :country_id in a form, :country_id_eq in a filter. An array names several parents: depends_on: %i[country_id insured].
depends_param: depends_param: "q[region_id_eq]" Query param that carries the parent's value, q[<depends_on>_eq] by default. With several parents, a Hash of parent to param: depends_param: {country_id: "q[country_id_in]", insured: "insured"}. A String raises ArgumentError.
depends_placeholder: depends_placeholder: "Select a country first" Text shown while the parent is empty.
depends_optional: depends_optional: true The select works with an empty parent, which sends nothing, instead of waiting for it.
auto_select_single: auto_select_single: true With load_all:, selects the option when the endpoint offers only one and nothing is selected.
resource: resource: Account Model or ActiveAdmin resource that has the endpoint, when the input is not an association.
options_name: options_name: :external_id Which searchable_select_options of the resource to use, :all by default.
url: url: -> { all_options_admin_accounts_path } The endpoint, as a string or a lambda run in the view.
tom_select: tom_select: {maxItems: 3} Tom Select settings for this select.

Tom Select carries the classes and the data-filter-extensions-option attribute of each <option> to its rendered option and item, so an app styles options in both the native select and Tom Select. The None and Present choices of active_admin_filter_extensions are italic and muted by default. In a select that searches the endpoint, those choices stay listed above the endpoint's results and match the typed text like any other option.

Dependent selects. A dependent select stays disabled until its parent has a value, and sends that value with every request. When the parent changes or is cleared, the select is cleared and fires change, so a select that depends on it resets too. On page load a preselected value is kept, so deep links and submitted filters survive. With load_all: the options are fetched again for each parent value.

While a load_all: select fetches its options, its <select> has the attribute data-searchable-select-loading. The attribute goes once the options are in and auto_select_single: has made its pick, or the request has failed. A select that depends on a loading one has it too, down the chain. Scripts and specs can wait on it: select:not([data-searchable-select-loading]).

filter :country, as: :searchable_select
filter :city, as: :searchable_select, depends_on: :country_id_eq, depends_placeholder: "Select a country first"
filter :street, as: :searchable_select, depends_on: :city_id_eq, load_all: true

A select can depend on several parents, and stays disabled until each has a value. The parent can be a checkbox, which sends true or false and so always has a value, or a multiple select, which sends its values as param[]. With depends_optional: true an empty parent does not block the select. A change of any parent clears it.

f.input :country, as: :searchable_select, multiple: true
f.input :insured
f.input :city, as: :searchable_select, load_all: true, depends_on: %i[country_id insured],
  depends_param: {country_id: "q[country_id_in]", insured: "insured"}
f.input :street, as: :searchable_select, load_all: true, depends_on: :city_id, depends_optional: true

With active_admin_filter_extensions, a parent filter can offer a "None" option (extensions: { none: true }). The searchable_select_options endpoint reads its marker as that gem's index does: the child lists the records whose parent is empty, or those plus the records of the other values picked. A searchable multi-select filter keeps the values picked beside "None" after the search.

The endpoint. Declare it in the resource that holds the options:

ActiveAdmin.register Customer do
  searchable_select_options
end

searchable_select_options(name = :all, **options) adds the collection action <name>_options, here GET /admin/customers/all_options. The name is positional or name:. The action checks authorize! for reading the resource class, applies the authorization adapter's read scope, and applies q[...] params as Ransack filters, which is how a dependent select sends its parent's value.

Option Default Example
scope: The resource's scoped_collection scope: -> { Customer.active }, or with the request params: scope: ->(params) { Customer.where(kind: params[:kind]) }
label: The first of Formtastic's label methods the record has (display_name, name, ...) label: :email or `label: ->(customer) { "#{customer.id}
search: The model's search(term) class method or scope when it has one, else <label column>_cont search: :name_or_email_cont or search: ->(scope, term) { scope.search_by_name(term) }
allow_empty_search: true allow_empty_search: false: a blank term returns nothing
value: :id value: :external_id, or a lambda taking the record. An input cannot show the selected record of a lambda.
order: Primary key, descending order: :name or order: ->(scope) { scope.order(:position) }
per_page: 50, or ActiveAdminTheme.searchable_select_per_page when set per_page: 25
id_search: off id_search: true finds id:123; id_search: "#" finds #123
additional_payload: none additional_payload: ->(customer) { {email: customer.email} }

Lambdas run in the resource controller. An unknown option raises ArgumentError that names the known ones. The request's per_page overrides the page size up to 500, or up to the declared per_page: when that is larger. ActiveAdminTheme.searchable_select_per_page = 30 sets the page size of endpoints that declare no per_page:.

With id_search:, a term of the form id:123 finds the record with that id, or with that value: attribute when it is a column. The text search is skipped, and the read scope and q[...] filters still apply. For an integer id, a term that is not a number, such as id:abc, is a text search.

With value: other than the id, name the declaration in the input. The input then finds the selected record by that attribute. A lambda value: cannot be looked up, so an input that names such a declaration raises ArgumentError:

searchable_select_options :external_id, value: :external_id
filter :account_external_id_eq, as: :searchable_select, resource: Account, options_name: :external_id

The input looks up the selected records through the same read scope as the endpoint, and through scope: when it takes no params. A selected value the user may not read shows the value itself instead of the record's label.

Names from activeadmin-searchable_select and from older hosts also work: display_text: for label:, text_attribute: for label: and the searched column, filter: for search: with a lambda taking (term, scope), and apply_search: for search: with a lambda taking (scope, term).

The reply. The action takes term, page (starting at 1) and per_page, and answers:

{"results": [{"id": 17, "text": "Customer 17"}], "pagination": {"more": true}}

This is the shape of activeadmin-searchable_select and select2, except that activeadmin-searchable_select counts pages from 0. An endpoint of your own, given with url:, has to answer the same way, or with a bare array that has no paging, [{"id": 17, "text": "Customer 17"}]. In a bare array the id may be named value.

Your own searchable_select_options. If your app or another gem defines searchable_select_options on ActiveAdmin::ResourceDSL, that definition wins in any load order, and the theme's inputs need url:. To use the theme's instead, prepend it: ActiveAdmin::ResourceDSL.prepend ActiveAdminTheme::SearchableSelect::ResourceDSL.

Optional scripts

Script Default What it does
active_admin_theme/layout on Collapsible sidebar
active_admin_theme/server_clock on Header clock
active_admin_theme/table_crisscross on Row and column highlight on a cell click
active_admin_theme/confirm_dialog on Focus and validation for confirm_dialog
active_admin_theme/secret_reveal off secret_reveal
active_admin_theme/lazy_load off lazy_load
active_admin_theme/panel_toggle on collapsible: true on panel
active_admin_theme/theme_toggle on The dark mode switch cycles auto, light and dark
active_admin_theme/tabs on Opens a tab from the URL hash
active_admin_theme/dropdown_menu on aria-expanded, Escape and arrow keys for dropdown_menu
active_admin_theme/searchable_select on Tom Select on every select, and the searchable select

Nested menus

ActiveAdmin 4 supports one submenu level and raises TypeError for a parent chain. The theme brings back the chain from ActiveAdmin 3, so menus can be as deep as you need:

menu parent: ["Customer", "Referral Program"], priority: 30

In the top menu each deeper level flies out beside its item, and in the drawer it expands below its item. A top item is marked current when the page is anywhere below it.

Header

The header shows the site title and the top menu, and at its right end the dark mode switch, a server clock, your own links, the current user, and a logout icon. The dark mode switch cycles auto (follow the OS), light and dark, and stores the choice in ActiveAdmin's localStorage key theme; auto removes the key. The clock, the user, and the logout icon come from the signed-in user (current_active_admin_user?) and config.logout_link_path. Without a current user the header shows only the title, the menu, the dark mode switch, and your links. To add links, override _header_links.html.erb, which is empty. To change the rest, override _header_actions.html.erb, _header_leading.html.erb, or _header_navigation.html.erb.

The site title is plain text. To make it a link, set a path, or a Proc that runs in the view. false or nil leaves it as text:

ActiveAdminTheme.site_title_link = "/admin"
ActiveAdminTheme.site_title_link = -> { admin_root_path }

Footer

By default the footer is ActiveAdmin's "Powered by Active Admin" line. To show your own product, set any of these in an initializer. They replace the default line:

ActiveAdminTheme.footer_product_name = "Acme Admin"
ActiveAdminTheme.footer_version = "2.4.1"
ActiveAdminTheme.footer_extra = -> { link_to "Changelog", changelog_path }

footer_extra is a String, or a Proc that runs in the view. A String is escaped, and a Proc's result is escaped unless it is html_safe. The theme draws the footer in _site_footer.html.erb with data-aat-footer. Its styles sit in a CSS layer, so utility classes in your own copy of the partial win.

Page objects

The gem ships page objects for system specs, built on active_admin_page_objects 2.x. The theme never loads them, and does not depend on that gem: add it to your test group and require the entry point from your spec helper.

# Gemfile
group :test do
  gem "active_admin_page_objects", github: "activeadmin-plugins/active_admin_page_objects"
end

# spec/rails_helper.rb
require "active_admin_theme/page_objects"

The sections of active_admin_page_objects then work on theme pages. Their README describes them; this is what the theme changes and adds. The classes are in ActiveAdminTheme::PageObjects.

Patches to the base sections

  • main_menu is the top menu on desktop and the drawer on a narrow screen, at any depth. labels, has_item? and go take a label path, and current_labels returns one. click hovers each parent of the top menu; in the drawer it opens the drawer and each collapsed parent first.
  • ActiveAdminPageObjects::Tabs drives the theme's tabs. Every page has it as tabs. select, content, has_tab? and has_selected? take a String, the whole title ignoring case, or a Regexp. select_matching is select for a Regexp.
  • form.field(name) and filters.filter(name) return the searchable select classes for an input rendered as: :searchable_select. The theme registers them for that wrapper class with register_field_class and register_filter_class, so a page object that declares the base gem's SelectField or SelectFilter for such an input raises DeclaredClassMismatch.
  • flashes also takes :warning. The theme renders every flash type, while ActiveAdmin 4 drops all but notice, alert and error. For another type your app sets, call ActiveAdminTheme::PageObjects.register_flash_type(:info) in your spec helper; an unregistered type still raises ArgumentError.
  • attributes_table.secret(key) and row.secret(key) return the cell's SecretReveal. has_secret_mask?(key, mask = nil), has_secret_value?(key, value) and their has_no_ forms wait as Capybara does.
  • A panel answers collapsible? and expanded?, and expand, collapse and toggle drive a collapsible: true panel. body waits for a visible body, so call expand first on a collapsed panel.
  • The header has no user menu, so user_menu_button is never found. Pages get current_user, logout_link, server_clock, main_menu_button and sidebar_toggle instead.
page_object.main_menu.click("Customer", "Referral Program", "Payouts")
page_object.main_menu.labels("Customer", "Referral Program") # => ["Payouts", "Rules"]

show.tabs.titles # => ["Details", "History"]
show.tabs.select("History")
show.tabs.select_matching(/\AHist/)
expect(show.tabs).to have_selected("History")
show.tabs.content # the node of the selected tab; content("Details") for another

Sidebar

Every page has sidebar. Its sections are panels.

index.sidebar.titles # => ["Filters"]
show.sidebar.panel("Help").body
show.sidebar.panel(/\AStats/) # a Regexp matches the panel's own title
expect(show.sidebar).to have_panel("Help")
index.collapse_sidebar
index.expand_sidebar
index.sidebar_collapsed?

panel and has_panel? match the title of the sidebar panel itself, so a panel nested in its body does not count. To declare one, give the section the :active_admin_sidebar selector and the title, a String ignoring case or a Regexp:

section :stats, ActiveAdminPageObjects::Panel, :active_admin_sidebar, "Stats"

Selects

The theme prepends a module into ActiveAdminPageObjects::SelectControl, so the base gem's Form::SelectField, SelectFilter, BooleanFilter and the predicate select of StringFilter and NumericFilter pick their option in the Tom Select widget when the select has one, and in the native select when it does not (tom_select: false, or searchable_select_all off). Reading goes to the <select> the widget hides. Specs written for native selects keep working, with a JavaScript driver.

form.field(:status).fill("paid") # clicks the widget
form.field(:status).selected # => "paid"
filters.filter(:status).select_option("paid")
filters.filter(:reference).fill_in(with: "ORD", predicate: :start)

SearchableSelectField and SearchableSelectFilter add the widget's own API. form.field and filters.filter return them for an as: :searchable_select input; declare them on a plain select to use that API there: field :tag, "Tag", ActiveAdminTheme::PageObjects::SearchableSelectField. They need a JavaScript driver.

Picking in a select that loads its options types the label into the search box first. Pass search: to type another text, such as three spaces for the whole list, or search: false to type nothing. A plain select types nothing unless search: is given.

customer = form.field(:customer)
customer.fill("Acme") # choose is the same
customer.fill("Acme", search: "acm")
customer.selected # => "Acme"
customer.chosen # => ["Acme"], every item of a multiple select
customer.remove("Acme") # clear removes every item
customer.placeholder
form.field(:tag).create_option("bulky") # a select with tom_select: {create: true}
expect(form).to have_disabled_field(:city) # a dependent select without its parent

filter = filters.filter(:customer)
filter.select_option("Acme")
expect(filter).to have_item("Acme") # also have_selected and have_disabled
filter.search("ac") # opens the dropdown, replaces the typed text and waits for the reply
filter.message # => "Type 3 chars to search...", or the no-results text
expect(filter).to have_message("No results matched")
expect(filter).to have_option("Acme") # what the open dropdown offers
filter.dropdown_options # the labels the dropdown offers, as loaded so far
filter.options # the labels of the native select, without opening the dropdown
filter.load_more # scrolls to the end, waits for the next page, returns the labels
filter.close

A dependent select reloads when its parent changes. fill, select_option, open and the other methods that open the dropdown wait for that first: until data-searchable-select-loading is gone and the select is enabled. Call wait_until_ready when the spec does not touch the select itself, such as before submitting a form whose child picks its only option (auto_select_single:). ready? tells the state without waiting.

form.field(:country).fill("Poland")
form.field(:city).wait_until_ready # takes wait:, raises when the time is up
form.field(:city).selected # => "Warsaw", picked by auto_select_single
form.submit

A multiple select takes an array in fill, and select_option once per label. fill(nil) removes every item. type("Acme") types the text and presses Enter, which picks the option Tom Select highlights.

filter.search("ac")
expect(filter).to have_options("Acme", "Acme East") # exactly these labels, in any order
expect(filter).to have_no_options("Acme") # waits until the list is another one
expect(filter).to have_no_results # the "no results" message shows and no option does
expect(filter).to have_results # an option is offered

filters.filter(:customer).select_option("Acm", exact: false) # => "Acme"
form.field(:customer).fill("17", exact: false) # same for fill

has_options?, has_no_options?, has_no_results? and has_results? open the dropdown and leave it open. With exact: false, fill and select_option pick the only option whose label contains the text, and return its label. No option, or several, raises. To make that the default, set ActiveAdminTheme::PageObjects.searchable_select_exact = false in your spec helper; an exact: argument still wins. Then form.fill(customer: "Acm") picks Acme too.

Components

A component is found inside any scope: a page, a section, a table cell or an attributes table row.

include ActiveAdminTheme::PageObjects

tag = StatusTag.find_in(index.table.row(order.id).cell(:status))
tag.text # => "Shipped", as the HTML has it, not the CSS uppercase
expect(tag).to have_text("shipped") # a String ignores case
tag.kind # => "shipped", its data-status
tag.color # => "#b91c1c" with color:, or nil

note = TruncateText.find_in(index.table.row(order.id).cell(:note))
note.text # what the cell shows
note.full_text # the whole value, from the title or the popup
note.popup? # rendered with popup: true
note.show_popup # hovers and returns the popup text
note.cut? # length: cut the text
note.clipped? # CSS clips it to the width; needs a JavaScript driver

secret = SecretReveal.find_in(show.attributes_table.row(:token))
secret.reveal # => "s3cr3t"; raises when the request fails
secret.hide

total = Tooltip.find_in(show.attributes_table.row(:total))
total.tooltip # => "Total orders"

PreWrap.find_in(show.panel("Payload")).lines

row = Columns.find_in(show)
row.weights # => [1, 3]
row.columns.first # a section to look inside

dialog = show.confirm_dialog("Reject") # by the text of its button
dialog.open
dialog.title # => "Reject order"
dialog.fill("Reason" => "Fraud", "Notify the buyer" => true) # by field label
dialog.fill("reason" => "Fraud") # a control of the block body, by its label, id or name
dialog.field("reason")[:"aria-invalid"] # the control itself
dialog.confirm # or cancel
dialog.confirm(validate: false) # skips the browser's required check

merge = show.confirm_dialog(dialog: "merge") # by the id of a dialog with trigger: false
merge.params # => {"ids[]" => "4", "options[keep]" => "newest"}, the hidden fields by name
merge.open # clicks the element of the page that points at the dialog
secret = SecretReveal.find_in(show.attributes_table.row(:token))
secret.inline? # true for value:, false for url:

dialog.fill("Tags" => ["Alpha", "Beta"]) # an array for a multiple select; a String or Date for a number or date field

lazy = LazyLoad.find_in(show.panel("History"))
lazy.wait_until_loaded # raises when the request fails or runs out of time
lazy.content_loaded?
lazy.loading?
lazy.error # the message of a failed request, or nil

menu = page_object.action_items.dropdown("Export") # page_object.dropdown_menu("Export") for one in the page
menu.items # => ["CSV", "Purge"]
menu.click("CSV") # opens the list, then clicks the link
menu.open
menu.open?

show.attributes_table.secret(:token).reveal # => "s3cr3t"
expect(show.attributes_table).to have_secret_mask(:token)
expect(show.attributes_table).to have_secret_value(:token, "s3cr3t")
expect(show.attributes_table.secret(:token)).to have_secret_value("s3cr3t")

show.panel("JSON").expand # also collapse, toggle, collapsible?, expanded?

note = Notice.find_in(show)
note.kind # => "warning"
note.text

links = LinkList.find_in(show.sidebar.panel("Related records").body)
links.links.map(&:label) # => ["Orders", "Invoices"]; each also has href, count, external?, new_tab? and group
links.groups # => ["Shipping", "Billing"], the headings; empty when there are none
links.links(group: "Billing")
links.click("Orders")

For RSpec, require "active_admin_theme/page_objects/rspec" and include ActiveAdminTheme::PageObjects::RSpec::Matchers after ActiveAdminPageObjects::RSpec::Matchers. That gives have_secret_mask and have_secret_value.

Status tags can be asked from a row or an attributes table too:

row = index.table.row(order.id)
expect(row).to have_status_tag(:status, "Pending", status: :pending) # label ignoring case
expect(row).to have_no_status_tag(:status, "Pending")
tag = row.status_tag(:status)
tag.label # => "Pending"
tag.status # => "pending"
tag.text, tag.kind, tag.color # as for StatusTag.find_in
tag.has_text?("pending") # a String ignores case

all_in(scope) returns every such component in the scope.

Development

bundle install
bundle exec rake test                 # builds the dummy app's Tailwind CSS, runs smoke and browser tests (needs Chrome)
bundle exec rake screenshots          # regenerates the README screenshots under img/
bundle exec ruby test/screenshot.rb   # any page: PAGES, WIDTHS, MODES, OUT environment variables

test/dummy is an ActiveAdmin 4 app (importmap, propshaft, Tailwind through the npm CLI). Run npm run build in test/dummy to rebuild its CSS.

To run the tests against an unreleased ActiveAdmin, such as a branch with the layout hooks, point Bundler at it:

ACTIVEADMIN_PATH=../activeadmin bundle exec rake test
ACTIVEADMIN_BRANCH=extensible-layout bundle exec rake test   # from ACTIVEADMIN_REPO, default senid231/activeadmin

The theme replaces some of ActiveAdmin's own view files with its copies. test/aa_overrides_test.rb fails when the installed ActiveAdmin changes one of them. It records the originals for both modes, with and without the layout hooks, so run it against both. After you raise the ActiveAdmin version, diff each reported file against the theme's copy in app/views or app/views_compat, port what applies, then refresh the record:

UPDATE_AA_DIGESTS=1 bundle exec ruby test/aa_overrides_test.rb

License

MIT

About

👍 flat skin for activeadmin 3 with light and dark modes

Topics

Resources

Stars

182 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages