From 8e82d51eb16a6f3f29c550bbe84c7baf779bd08a Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Fri, 4 Dec 2026 13:59:09 +0200 Subject: [PATCH 1/5] Page objects: test against the v2.0.0.beta3 tag Co-Authored-By: Clanker --- Gemfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index a492f25..34cdaf1 100644 --- a/Gemfile +++ b/Gemfile @@ -27,7 +27,7 @@ group :development, :test do gem 'rspec-expectations' # Drives the dummy app in the tests of active_admin_theme/page_objects. Not on # RubyGems yet, so pinned to its tag. - gem 'active_admin_page_objects', github: 'activeadmin-plugins/active_admin_page_objects', tag: 'v2.0.0.beta2' + gem 'active_admin_page_objects', github: 'activeadmin-plugins/active_admin_page_objects', tag: 'v2.0.0.beta3' # Tests the searchable select with its None and Present filter options. Not on RubyGems, so pinned to its tag. gem 'active_admin_filter_extensions', github: 'activeadmin-plugins/active_admin_filter_extensions', tag: 'v1.3.0' end From 1e5ff9c02761d6a1d0f65393d4a01507c9636ce8 Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Fri, 4 Dec 2026 16:35:23 +0200 Subject: [PATCH 2/5] Columns chooser for index tables ActiveAdmin 4 puts no column classes on index cells, so the chooser keys a column by its position and names it by its header text. Co-Authored-By: Clanker --- README.md | 20 ++++ .../active_admin_theme/column_chooser.js | 100 ++++++++++++++++++ app/tailwind/active_admin_theme.css | 1 + app/tailwind/components/column_chooser.css | 51 +++++++++ app/views/active_admin/_page_content.html.erb | 3 +- lib/active_admin_theme.rb | 9 +- lib/active_admin_theme/helpers/config.rb | 11 ++ test/dummy/app/admin/menu_orders.rb | 6 +- test/dummy/app/admin/quiet_orders.rb | 4 +- test/layout_test.rb | 48 +++++++++ 10 files changed, 246 insertions(+), 7 deletions(-) create mode 100644 app/javascript/active_admin_theme/column_chooser.js create mode 100644 app/tailwind/components/column_chooser.css diff --git a/README.md b/README.md index 00da90f..34eac2b 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,7 @@ ActiveAdmin pages import the modules listed in `ActiveAdminTheme.javascripts`. W active_admin_theme/tabs active_admin_theme/dropdown_menu active_admin_theme/table_crisscross + active_admin_theme/column_chooser active_admin_theme/searchable_select active_admin_theme/confirm_dialog active_admin_theme/panel_toggle @@ -525,6 +526,24 @@ ActiveAdminTheme.row_click_selects = false The setting needs the `active_admin_theme/table_crisscross` script, which is on by default. +### Columns chooser + +A columns button, an icon at the right of the table toolbar, opens a menu that hides index columns, and the browser remembers the choice for each index in `localStorage`. The selection column, the id column and columns without a title always show. It is off by default. To turn it on for every index, set this in an initializer: + +```ruby +ActiveAdminTheme.column_chooser = true +``` + +The `column_chooser:` option of `index` turns it on or off for one index: + +```ruby +index column_chooser: true do + # columns +end +``` + +The button's tooltip and accessible name, "Columns", come from `active_admin_theme.column_chooser.label` in your locale files. + ### 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: @@ -719,6 +738,7 @@ This is the shape of activeadmin-searchable_select and select2, except that acti | `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/column_chooser` | on | The columns menu, where `column_chooser` turns it on | | `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` | diff --git a/app/javascript/active_admin_theme/column_chooser.js b/app/javascript/active_admin_theme/column_chooser.js new file mode 100644 index 0000000..223ce1d --- /dev/null +++ b/app/javascript/active_admin_theme/column_chooser.js @@ -0,0 +1,100 @@ +// Columns chooser for index tables. When the page content has +// data-aat-column-chooser (ActiveAdminTheme.column_chooser, or +// `index column_chooser: true`), a "Columns" menu in the table toolbar hides +// columns, and localStorage remembers them per index. ActiveAdmin 4 puts no +// column classes on the cells, so a column is its position, named by its +// header text. The selection, id and unnamed columns always show. The +// button is an icon; the attribute's value is its tooltip and accessible name. +const ICON = '' + +const storageKey = () => `aat:columns:${location.pathname}` + +const readHidden = () => { + try { + return new Set(JSON.parse(localStorage.getItem(storageKey())) || []) + } catch { + return new Set() + } +} + +const writeHidden = (hidden) => { + try { + localStorage.setItem(storageKey(), JSON.stringify([...hidden])) + } catch { + // Storage can be full or blocked; the choice then lasts for this page only. + } +} + +const fixed = (th) => + !th.textContent.trim() || + th.querySelector(".batch-actions-toggle-all") || + [...th.querySelectorAll("a[href]")].some((a) => /[?&]order=id_/.test(a.getAttribute("href"))) + +const showColumn = (table, index, show) => { + for (const row of table.rows) { + const cell = row.cells[index] + if (cell) cell.hidden = !show + } +} + +const build = (page) => { + const table = page.querySelector(".index-as-table > .data-table") + if (!table || page.querySelector(".aat-columns")) return + const headers = [...table.tHead.rows[0].cells] + const columns = headers.map((th, index) => ({ index, name: th.textContent.trim() })).filter(({ index }) => !fixed(headers[index])) + if (!columns.length) return + + let toolbar = page.querySelector(".index-data-table-toolbar") + if (!toolbar) { + toolbar = document.createElement("div") + toolbar.className = "index-data-table-toolbar" + table.closest(".paginated-collection").before(toolbar) + } + + const menuId = `${table.id || "index-table"}-columns` + const chooser = document.createElement("div") + chooser.className = "aat-columns" + chooser.innerHTML = ` + ` + const toggle = chooser.firstElementChild + const menu = chooser.lastElementChild + toggle.innerHTML = ICON + toggle.title = page.dataset.aatColumnChooser + toggle.setAttribute("aria-label", page.dataset.aatColumnChooser) + + const hidden = readHidden() + for (const { index, name } of columns) { + const label = document.createElement("label") + const box = document.createElement("input") + box.type = "checkbox" + box.checked = !hidden.has(name) + box.addEventListener("change", () => { + showColumn(table, index, box.checked) + box.checked ? hidden.delete(name) : hidden.add(name) + writeHidden(hidden) + }) + label.append(box, ` ${name}`) + menu.append(label) + if (!box.checked) showColumn(table, index, false) + } + + const open = (show) => { + menu.hidden = !show + toggle.setAttribute("aria-expanded", String(show)) + } + toggle.addEventListener("click", () => open(menu.hidden)) + document.addEventListener("click", (event) => { + if (!chooser.contains(event.target)) open(false) + }) + chooser.addEventListener("keydown", (event) => { + if (event.key !== "Escape" || menu.hidden) return + open(false) + toggle.focus() + }) + toolbar.append(chooser) +} + +const init = () => document.querySelectorAll("[data-aat-column-chooser]").forEach(build) + +if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init) +else init() diff --git a/app/tailwind/active_admin_theme.css b/app/tailwind/active_admin_theme.css index d0f5eb5..4729f95 100644 --- a/app/tailwind/active_admin_theme.css +++ b/app/tailwind/active_admin_theme.css @@ -7,6 +7,7 @@ @import "./components/confirm_dialog.css"; @import "./components/dropdown_menu.css"; +@import "./components/column_chooser.css"; @import "./components/status_tag.css"; @import "./components/truncate_text.css"; @import "./components/secret_reveal.css"; diff --git a/app/tailwind/components/column_chooser.css b/app/tailwind/components/column_chooser.css new file mode 100644 index 0000000..e4ee2e2 --- /dev/null +++ b/app/tailwind/components/column_chooser.css @@ -0,0 +1,51 @@ +/* Columns chooser (column_chooser.js): a toolbar button with a list of column checkboxes. */ +.aat-columns { + position: relative; + margin-inline-start: auto; +} +.aat-columns-toggle { + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.875rem; + height: 1.875rem; + padding: 0; +} +.aat-columns-toggle > svg { + width: 1rem; + height: 1rem; +} +.aat-columns-toggle[aria-expanded="true"] { + background-color: var(--aat-surface-hover); +} +.aat-columns-menu { + position: absolute; + top: calc(100% + 0.3125rem); + inset-inline-end: 0; + z-index: 40; + min-width: 12rem; + max-height: 20rem; + overflow-y: auto; + padding: 0.25rem 0; + font-size: var(--aat-font-size); + line-height: 1.5; + color: var(--aat-text); + background-color: var(--aat-surface); + border: 1px solid var(--aat-border); + border-radius: 0.375rem; + box-shadow: 0 6px 18px rgb(0 0 0 / 0.18); +} +.aat-columns-menu[hidden] { + display: none; +} +.aat-columns-menu > label { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.375rem 0.75rem; + white-space: nowrap; + cursor: pointer; +} +.aat-columns-menu > label:hover { + background-color: var(--aat-surface-hover); +} diff --git a/app/views/active_admin/_page_content.html.erb b/app/views/active_admin/_page_content.html.erb index d145888..afb556c 100644 --- a/app/views/active_admin/_page_content.html.erb +++ b/app/views/active_admin/_page_content.html.erb @@ -1,6 +1,7 @@ <%= active_admin_theme_config_tag %> <% has_sidebar = !(skip_sidebar? || sidebar_sections_for_action.blank?) %> -
<%= "data-aat-sticky-thead" if ActiveAdminTheme.sticky_table_header %> <%= "data-aat-row-click-selects" if ActiveAdminTheme.row_click_selects %> class="px-2.5 md:px-4 grid grid-cols-1 gap-3 md:gap-4 md:data-aat-has-sidebar:grid-cols-[270px_minmax(0,1fr)] md:data-aat-sidebar-collapsed:grid-cols-1"> +<% column_chooser = active_admin_theme_column_chooser_label %> +
<%= "data-aat-sticky-thead" if ActiveAdminTheme.sticky_table_header %> <%= "data-aat-row-click-selects" if ActiveAdminTheme.row_click_selects %> <%= tag.attributes("data-aat-column-chooser": column_chooser) if column_chooser %> class="px-2.5 md:px-4 grid grid-cols-1 gap-3 md:gap-4 md:data-aat-has-sidebar:grid-cols-[270px_minmax(0,1fr)] md:data-aat-sidebar-collapsed:grid-cols-1"> <%= render "active_admin/sidebar" %>
<% if has_sidebar %> diff --git a/lib/active_admin_theme.rb b/lib/active_admin_theme.rb index 90f81ad..5e02f5b 100644 --- a/lib/active_admin_theme.rb +++ b/lib/active_admin_theme.rb @@ -25,6 +25,7 @@ module ActiveAdminTheme active_admin_theme/tabs active_admin_theme/dropdown_menu active_admin_theme/table_crisscross + active_admin_theme/column_chooser active_admin_theme/searchable_select active_admin_theme/confirm_dialog active_admin_theme/panel_toggle @@ -36,7 +37,7 @@ class << self attr_accessor :searchable_select_per_page attr_writer :javascripts, :searchable_select_all, :searchable_select_min_chars, :sticky_table_header, - :row_click_selects + :row_click_selects, :column_chooser # nil keeps ActiveAdmin's "Powered by" footer; any of the three replaces it. # footer_extra and site_title_link are a String, or a Proc run in the view. # site_title_link false or nil leaves the title as plain text. @@ -64,6 +65,12 @@ def row_click_selects @row_click_selects.nil? ? true : @row_click_selects end + # True when every index table gets a "Columns" menu that hides columns. + # `index column_chooser:` overrides it for one index. + def column_chooser + @column_chooser.nil? ? false : @column_chooser + end + # Characters to type before a searchable select asks its endpoint. def searchable_select_min_chars @searchable_select_min_chars || 3 diff --git a/lib/active_admin_theme/helpers/config.rb b/lib/active_admin_theme/helpers/config.rb index eb871de..aec4b6c 100644 --- a/lib/active_admin_theme/helpers/config.rb +++ b/lib/active_admin_theme/helpers/config.rb @@ -22,6 +22,17 @@ def active_admin_theme_config_tag content_tag(:script, json_escape(config.to_json).html_safe, type: "application/json", id: "active-admin-theme-config") end + # The "Columns" menu label for an index page with the chooser on, or nil. + # `index column_chooser:` wins over ActiveAdminTheme.column_chooser. + def active_admin_theme_column_chooser_label + return unless controller.action_name == "index" && active_admin_config.is_a?(ActiveAdmin::Resource) + + option = active_admin_config.get_page_presenter(:index, params[:as])&.options&.[](:column_chooser) + return unless option.nil? ? ActiveAdminTheme.column_chooser : option + + I18n.t("active_admin_theme.column_chooser.label", default: "Columns") + end + # ActiveAdminTheme.footer_extra: a String, or a Proc run in the view. def active_admin_theme_footer_extra active_admin_theme_resolve(ActiveAdminTheme.footer_extra) diff --git a/test/dummy/app/admin/menu_orders.rb b/test/dummy/app/admin/menu_orders.rb index 4368a77..892697a 100644 --- a/test/dummy/app/admin/menu_orders.rb +++ b/test/dummy/app/admin/menu_orders.rb @@ -1,6 +1,6 @@ # An index with an action-item dropdown whose items hang over the table -# toolbar, which the batch actions render, a confirm dialog, and a table in a cell -# (test/layout_test.rb). +# toolbar, which the batch actions render, a confirm dialog, a table in a cell +# and the columns chooser (test/layout_test.rb). ActiveAdmin.register Order, as: "MenuOrder" do menu false config.batch_actions = true @@ -29,7 +29,7 @@ class: "action-item-button" end - index do + index column_chooser: true do selectable_column id_column column :reference diff --git a/test/dummy/app/admin/quiet_orders.rb b/test/dummy/app/admin/quiet_orders.rb index 4a0e3b8..7db63c0 100644 --- a/test/dummy/app/admin/quiet_orders.rb +++ b/test/dummy/app/admin/quiet_orders.rb @@ -1,6 +1,6 @@ # An index with batch actions on but none shown and no scopes: ActiveAdmin # still renders the toolbar, empty (test/form_look_test.rb). The edit form has -# a sidebar (test/layout_test.rb). +# a sidebar (test/layout_test.rb). Its index turns the columns chooser off. ActiveAdmin.register Order, as: "QuietOrder" do menu false config.batch_actions = true @@ -22,7 +22,7 @@ f.actions end - index do + index column_chooser: false do selectable_column id_column column :reference diff --git a/test/layout_test.rb b/test/layout_test.rb index 3103a13..6b4b9a3 100644 --- a/test/layout_test.rb +++ b/test/layout_test.rb @@ -204,6 +204,54 @@ def test_a_confirm_dialog_from_an_index_title_bar_takes_clicks assert_equal "sticky", page.evaluate_script("getComputedStyle(document.getElementById('page-header')).position") end + def test_column_chooser_hides_columns_and_remembers_them + visit "/admin/menu_orders" + page.execute_script("localStorage.clear()") + visit "/admin/menu_orders" + click_button "Columns" + assert_equal %w[Reference Status Lines], all(".aat-columns-menu label").map { |label| label.text.strip } + status = "Array.from(document.querySelector('.index-as-table > .data-table').rows).map((row) => row.cells[3].hidden)" + assert_equal [false], page.evaluate_script(status).uniq + within(".aat-columns-menu") { uncheck "Status" } + assert_equal [true], page.evaluate_script(status).uniq + visit "/admin/menu_orders" + assert_equal [true], page.evaluate_script(status).uniq + click_button "Columns" + within(".aat-columns-menu") { check "Status" } + assert_equal [false], page.evaluate_script(status).uniq + find("[data-test-page-header] h2").click + assert_no_selector ".aat-columns-menu", visible: :visible + end + + def test_column_chooser_is_off_by_default_and_an_index_can_override_it + visit "/admin/customers" + assert_selector "[data-aat-page]" + assert_no_selector ".aat-columns" + ActiveAdminTheme.column_chooser = true + visit "/admin/customers" + assert_selector ".aat-columns button[title='Columns'][aria-label='Columns'] svg" + visit "/admin/quiet_orders" + assert_selector "[data-aat-page]" + assert_no_selector ".aat-columns" + ensure + ActiveAdminTheme.column_chooser = nil + end + + def test_column_chooser_items_take_clicks_on_a_scrolled_index + page.current_window.resize_to(1000, 700) + visit "/admin/menu_orders?flash=1" + page.execute_script("window.scrollTo({left: 100, top: 100, behavior: 'instant'})") + click_button "Columns" + hits = page.evaluate_script(<<~JS) + [...document.querySelectorAll(".aat-columns-menu label")].map((label) => { + const box = label.getBoundingClientRect() + const hit = document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2) + return label.contains(hit) ? label.textContent.trim() : String(hit.className) + }) + JS + assert_equal %w[Reference Status Lines], hits + end + def test_index_table_header_sticks_under_the_top_bar page.current_window.resize_to(1280, 500) visit "/admin/customers" From 9ca5f68d8eeef85474eb019d176f82d8be2b67af Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Fri, 4 Dec 2026 18:47:57 +0200 Subject: [PATCH 3/5] Batch action form: in the ActiveAdmin 3 format ActiveAdmin 4 replaced the form: option with a partial. The theme renders the fields as a confirm_dialog whose form ActiveAdmin 4's batch script submits, so the inputs keep their ActiveAdmin 3 keys and values. Co-Authored-By: Clanker --- README.md | 27 +++++- docs/migrating-from-v3.md | 1 + lib/active_admin_theme/batch_action_form.rb | 78 ++++++++++++++++ lib/active_admin_theme/engine.rb | 4 + lib/active_admin_theme/page_objects.rb | 1 + .../page_objects/batch_actions.rb | 33 +++++++ .../views/confirm_dialog.rb | 16 ++-- test/batch_action_form_test.rb | 90 +++++++++++++++++++ test/dummy/app/admin/batch_form_orders.rb | 39 ++++++++ 9 files changed, 282 insertions(+), 7 deletions(-) create mode 100644 lib/active_admin_theme/batch_action_form.rb create mode 100644 lib/active_admin_theme/page_objects/batch_actions.rb create mode 100644 test/batch_action_form_test.rb create mode 100644 test/dummy/app/admin/batch_form_orders.rb diff --git a/README.md b/README.md index 34eac2b..5de8c1b 100644 --- a/README.md +++ b/README.md @@ -367,7 +367,9 @@ The dialog has a title bar. Its buttons sit at the left, the confirm button firs 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 select field takes `multiple: true`. It sends `name[]`, and `value:` is an array of the selected values. `include_blank: false` drops the empty first option. +- A boolean field sends `"1"` when ticked and `"0"` when not. `checked_value:` and `unchecked_value:` change them, and `unchecked_value: nil` sends nothing. +- `form_html:` adds attributes to the dialog's form. - 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. @@ -395,6 +397,28 @@ document.addEventListener("aat:confirm-dialog:open", ({detail: {dialog, trigger} }) ``` +### Batch action forms + +ActiveAdmin 4 dropped the `form:` option of `batch_action`, which asked for values in a dialog before the action ran. The theme brings it back in the ActiveAdmin 3 format, so these actions need no change: + +```ruby +batch_action :flag, confirm: "Flag the selected orders?", form: { + "Reason" => :text, + notes: :textarea, + count: :number, + due_on: :datepicker, + notify: :checkbox, + kind: [["Fraud", "fraud"], ["Other", "other"]] +} do |ids, inputs| + # inputs => {"Reason" => "Spam", "notes" => "", "count" => "3", "due_on" => "2026-12-24", "notify" => "on", "kind" => "fraud"} +end + +batch_action :set_status, form: -> { {status: Order::STATUSES} } do |ids, inputs| +end +``` + +The fields open in a `confirm_dialog` titled like the menu item, and `confirm:` becomes its message. The types are `text`, `number`, `textarea`, `datepicker` (a native date input that sends `YYYY-MM-DD`) and `checkbox`, plus an Array for a select with no blank option. As in ActiveAdmin 3, each key is both the input name and the label with its first letter capitalized, a ticked checkbox sends `"on"` and an unticked one sends nothing. A Proc runs in the view. ActiveAdmin 4's own batch script submits the dialog, so `partial:` actions keep working beside these. + ### `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. @@ -806,6 +830,7 @@ The sections of active_admin_page_objects then work on theme pages. Their README - `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. +- `batch_actions.apply(label, with: {"Reason" => "Spam", "Notify" => true})` runs a batch action with a `form:`: it opens the dialog, fills it by label as `ConfirmDialog#fill` does, and confirms it. `batch_actions.form_dialog(label)` opens the dialog and returns its `ConfirmDialog`. - 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. ```ruby diff --git a/docs/migrating-from-v3.md b/docs/migrating-from-v3.md index aa7267b..22bfbc1 100644 --- a/docs/migrating-from-v3.md +++ b/docs/migrating-from-v3.md @@ -68,6 +68,7 @@ ActiveAdmin 4 dropped menus deeper than one submenu level, but the theme keeps t | `tabs` / `tab` | Restored by the theme. | | `panel` around `sidebar` and show `attributes_table` | Restored by the theme. | | `Panel#header_action` | Removed. | +| `batch_action form:` | Removed by ActiveAdmin 4, restored by the theme in the ActiveAdmin 3 format as a `confirm_dialog`. `confirm:` becomes the dialog message. | | `dropdown_menu` in action items | Restored by the theme as `dropdown_menu_tag`, because an `action_item` block returns a string. `dropdown_menu` works in page bodies. | | `index_as_blog`, `index_as_block`, `index_as_grid`, `index_column` | Removed by ActiveAdmin 4. | | Sortable has-many forms | Removed by ActiveAdmin 4. | diff --git a/lib/active_admin_theme/batch_action_form.rb b/lib/active_admin_theme/batch_action_form.rb new file mode 100644 index 0000000..0dd1045 --- /dev/null +++ b/lib/active_admin_theme/batch_action_form.rb @@ -0,0 +1,78 @@ +module ActiveAdminTheme + # ActiveAdmin 3's `batch_action form:` on ActiveAdmin 4, which replaced it + # with a partial holding a modal. The fields become a confirm_dialog whose + # form carries data-batch-action-form, so ActiveAdmin 4's batch script + # submits it and the block gets the values as `inputs`, keyed as in + # ActiveAdmin 3. A `confirm:` on the action becomes the dialog message. + module BatchActionForm + # ActiveAdmin 3 input types and the confirm_dialog field types they map to. + FIELD_TYPES = {"text" => :string, "number" => :number, "textarea" => :text, "datepicker" => :date, "checkbox" => :boolean}.freeze + + def confirm + form_inputs ? nil : super + end + + def partial + form_inputs ? Modal.new(self) : super + end + + def link_html_options + return super unless form_inputs + + super.merge("data-modal-target": form_dialog_id, "data-modal-show": form_dialog_id) + end + + # The `form:` option: a Hash of name => type, or a Proc run in the view that returns one. + def form_inputs + @options[:form] + end + + # The confirmation text, which the dialog shows as its message. + def form_message + (@confirm == true) ? ActiveAdmin::BatchAction::DEFAULT_CONFIRM_MESSAGE : @confirm + end + + def form_dialog_id + "batch-action-form-#{sym.to_s.parameterize}" + end + + # Renders the dialog where ActiveAdmin renders a batch action's partial. + class Modal + def initialize(batch_action) + @batch_action = batch_action + end + + def render_in(view, &) + action = @batch_action + title = view.render_or_call_method_or_proc_on(view, action.title) + title = I18n.t("active_admin.batch_actions.labels.#{action.sym}", default: title) + options = { + title: I18n.t("active_admin.batch_actions.action_label", title: title), + message: view.render_or_call_method_or_proc_on(view, action.form_message).presence, + id: action.form_dialog_id, trigger: false, url: "#", method: :get, + form_html: {"data-batch-action-form": ""}, fields: fields(view.render_in_context(view, action.form_inputs)) + } + Arbre::Context.new({}, view) { confirm_dialog(options) }.to_s + end + + private + + # ActiveAdmin 3 used each key as the input name and, with its first + # letter capitalized, as the label. + def fields(inputs) + inputs.to_h.map do |name, type| + name = name.to_s + field = {name: name, label: name.sub(/\A./, &:upcase)} + next field.merge(as: :select, collection: type, include_blank: false) if type.is_a?(Array) + + as = FIELD_TYPES.fetch(type.to_s) { raise ArgumentError, "batch_action form: unsupported input type {#{name}: #{type.inspect}}" } + # ActiveAdmin 3 sent "on" for a ticked box and nothing for an unticked one. + as == :boolean ? field.merge(as: as, checked_value: "on", unchecked_value: nil) : field.merge(as: as) + end + end + end + end +end + +# ActiveAdmin defines BatchAction in its own before_load hook, which runs first. +ActiveAdmin.before_load { ActiveAdmin::BatchAction.prepend(ActiveAdminTheme::BatchActionForm) } diff --git a/lib/active_admin_theme/engine.rb b/lib/active_admin_theme/engine.rb index e323e72..606117a 100644 --- a/lib/active_admin_theme/engine.rb +++ b/lib/active_admin_theme/engine.rb @@ -63,6 +63,10 @@ def self.sprockets_precompile require "active_admin_theme/sidebar_title" end + initializer "active_admin_theme.batch_action_form" do + require "active_admin_theme/batch_action_form" + end + # Before any resource registers its menu item. initializer "active_admin_theme.nested_menu" do require "active_admin_theme/nested_menu" diff --git a/lib/active_admin_theme/page_objects.rb b/lib/active_admin_theme/page_objects.rb index 0753fba..e8d7a30 100644 --- a/lib/active_admin_theme/page_objects.rb +++ b/lib/active_admin_theme/page_objects.rb @@ -29,6 +29,7 @@ def searchable_select_exact require "active_admin_theme/page_objects/sidebar" require "active_admin_theme/page_objects/searchable_select" require "active_admin_theme/page_objects/confirm_dialog" +require "active_admin_theme/page_objects/batch_actions" require "active_admin_theme/page_objects/dropdown_menu" require "active_admin_theme/page_objects/secret_reveal" require "active_admin_theme/page_objects/lazy_load" diff --git a/lib/active_admin_theme/page_objects/batch_actions.rb b/lib/active_admin_theme/page_objects/batch_actions.rb new file mode 100644 index 0000000..85c2b74 --- /dev/null +++ b/lib/active_admin_theme/page_objects/batch_actions.rb @@ -0,0 +1,33 @@ +module ActiveAdminTheme + module PageObjects + # Batch actions with a `form:` (ActiveAdminTheme::BatchActionForm), whose + # fields open in a confirm dialog: + # + # index.batch_actions.apply("Flag Selected", with: {"Reason" => "Spam", "Notify buyer" => true}) + # index.batch_actions.form_dialog(:flag).cancel + module BatchActionsForm + # With +with+, opens the action's dialog, fills it by label as + # ConfirmDialog#fill does, and confirms it. Without, as before. + def apply(label, with: nil) + return super(label) if with.nil? + + dialog = form_dialog(label) + dialog.fill(with) + dialog.confirm + end + + # Opens the dialog of the action labelled or named +label+. + # @return [ConfirmDialog] + def form_dialog(label) + item = open_menu_item(label) + dialog_id = item[:"data-modal-target"] + raise ArgumentError, "batch action #{label.inspect} has no form" if dialog_id.to_s.empty? + + item.click + ConfirmDialog.find_in(root_element.session, dialog: dialog_id).open + end + end + end +end + +ActiveAdminPageObjects::BatchActions.prepend(ActiveAdminTheme::PageObjects::BatchActionsForm) diff --git a/lib/active_admin_theme/views/confirm_dialog.rb b/lib/active_admin_theme/views/confirm_dialog.rb index f832b53..95e0c20 100644 --- a/lib/active_admin_theme/views/confirm_dialog.rb +++ b/lib/active_admin_theme/views/confirm_dialog.rb @@ -16,8 +16,10 @@ module Views # which ActiveAdmin already loads) holding a real form that submits to `url` # with the CSRF token, and `_method` for put/patch/delete. A block adds # content after the fields. Fields also take `input_html:` attributes, and - # `multiple: true` on a select; `scope: :reject` nests every field name as - # reject[name]. The README lists the other options. Do not place it inside another form. Load + # `multiple: true` or `include_blank: false` on a select, and + # `checked_value:` / `unchecked_value:` on a boolean (nil sends nothing + # when unchecked); `scope: :reject` nests every field name as + # reject[name]. `form_html:` adds attributes to the form. The README lists the other options. Do not place it inside another form. Load # `active_admin_theme/confirm_dialog` (ActiveAdminTheme.javascripts) for focus # handling and field validation; texts come from # `active_admin_theme.confirm_dialog.*` with English defaults. @@ -50,7 +52,8 @@ def build(trigger_text = nil, options = {}) "aria-hidden": "true", "aria-labelledby": "#{dialog_id}-title", "aria-describedby": (options[:message] ? "#{dialog_id}-message" : nil) do div class: "aat-confirm-panel" do - form action: options.fetch(:url), method: (get ? "get" : "post"), class: "aat-confirm-form", "accept-charset": "UTF-8" do + form(**(options[:form_html] || {}).to_h.symbolize_keys, action: options.fetch(:url), method: (get ? "get" : "post"), + class: "aat-confirm-form", "accept-charset": "UTF-8") do build_hidden_inputs(options) unless get build_params(options[:params]) if options[:params].present? h2 options.fetch(:title), id: "#{dialog_id}-title", class: "aat-confirm-title" @@ -119,8 +122,9 @@ def build_field(dialog_id, field, scope = nil) case type when :boolean label for: field_id, class: "aat-confirm-check" do - input type: "hidden", name: name, value: "0" - input(**control_attributes(field, type: "checkbox", id: field_id, name: name, value: "1", required: required, + unchecked = field.fetch(:unchecked_value, "0") + input type: "hidden", name: name, value: unchecked unless unchecked.nil? + input(**control_attributes(field, type: "checkbox", id: field_id, name: name, value: field.fetch(:checked_value, "1"), required: required, checked: ("checked" if field[:value].present? && field[:value].to_s != "0"))) span text end @@ -129,7 +133,7 @@ def build_field(dialog_id, field, scope = nil) multiple = field[:multiple] select(**control_attributes(field, id: field_id, name: (multiple ? "#{name}[]" : name), required: required, multiple: ("multiple" if multiple), class: "aat-confirm-input")) do - option "", value: "" unless multiple + option "", value: "" unless multiple || field[:include_blank] == false Array(field[:collection]).each do |item| item_text, item_value = item.is_a?(Array) ? item : [item, item] chosen = multiple ? Array(field[:value]).map(&:to_s).include?(item_value.to_s) : item_value.to_s == field[:value].to_s diff --git a/test/batch_action_form_test.rb b/test/batch_action_form_test.rb new file mode 100644 index 0000000..c42ee13 --- /dev/null +++ b/test/batch_action_form_test.rb @@ -0,0 +1,90 @@ +# Browser test (headless Chrome): ActiveAdmin 3's `batch_action form:` opens a +# confirm dialog that ActiveAdmin 4's batch script submits, through the page objects. +require_relative "page_objects_helper" + +class BatchActionFormTest < PageObjectsTestCase + class BatchFormIndex < ActiveAdminPageObjects::Page + set_url "/admin/batch_form_orders{?query*}" + + section :table, ActiveAdminPageObjects::Table + section :batch_actions, ActiveAdminPageObjects::BatchActions + end + + def index + @index ||= BatchFormIndex.new.tap(&:load) + end + + def select_two + boxes = all(".batch-actions-resource-selection", minimum: 2).first(2) + boxes.each(&:check) + boxes.map(&:value).map(&:to_i).sort.join(",") + end + + def test_the_menu_item_opens_a_dialog_instead_of_a_confirm + index + item = find("[data-action='flag']", visible: :all) + assert_nil item[:"data-confirm"] + assert_equal "batch-action-form-flag", item[:"data-modal-target"] + select_two + dialog = index.batch_actions.form_dialog(:flag) + assert_equal "Flag Selected", dialog.title + assert_equal "Flag the selected orders?", dialog.message + assert_equal ["Reason", "Notes", "Items", "Due on", "Notify buyer", "Kind"], dialog.field_labels + assert_equal ["Fraud", "Other"], dialog.field("Kind").all("option").map(&:text) + assert_equal "fraud", dialog.field("Kind").value + assert_equal "date", dialog.field("Due on")[:type] + assert_equal "number", dialog.field("Items")[:type] + end + + def test_apply_with_fields_sends_the_inputs_keyed_as_in_active_admin_3 + index + ids = select_two + index.batch_actions.apply("Flag Selected", with: {"Reason" => "Spam", "Notes" => "Two lines", "Items" => "3", + "Due on" => Date.new(2026, 12, 24), "Notify buyer" => true, "Kind" => "Other"}) + inputs = {"Reason" => "Spam", "notes" => "Two lines", "Items" => "3", "Due on" => "2026-12-24", "Notify buyer" => "on", "kind" => "other"} + assert_selector ".aat-flash[data-flash=notice]", exact_text: "flag #{ids} #{inputs.to_json}" + end + + def test_an_unticked_checkbox_sends_nothing_and_a_proc_form_runs_in_the_view + index + ids = select_two + index.batch_actions.apply(:set_status, with: {"Status" => "paid"}) + assert_selector ".aat-flash[data-flash=notice]", exact_text: "set_status #{ids} #{{"status" => "paid"}.to_json}" + + visit "/admin/batch_form_orders" + ids = select_two + index.batch_actions.apply(:flag, with: {"Reason" => "Spam"}) + assert_selector ".aat-flash[data-flash=notice]", exact_text: "flag #{ids} #{{"Reason" => "Spam", "notes" => "", "Items" => "", "Due on" => "", "kind" => "fraud"}.to_json}" + end + + def test_cancel_submits_nothing + index + select_two + index.batch_actions.form_dialog(:flag).cancel + assert_no_selector ".aat-flash" + assert_equal 2, all(".batch-actions-resource-selection:checked").size + end + + def test_dialog_fields_take_clicks_on_a_scrolled_index + page.current_window.resize_to(1000, 600) + @index = BatchFormIndex.new.tap { |po| po.load(query: {flash: 1}) } + select_two + page.execute_script("window.scrollTo({left: 0, top: 150, behavior: 'instant'})") + index.batch_actions.form_dialog(:flag) + hits = page.evaluate_script(<<~JS) + [...document.querySelectorAll("#batch-action-form-flag :is(input:not([type=hidden]), textarea, select, button)")].map((el) => { + const box = el.getBoundingClientRect() + const hit = document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2) + return el === hit || el.contains(hit) || (el.labels && [...el.labels].some((l) => l.contains(hit))) ? "ok" : `${el.name || el.textContent}: ${hit && hit.className}` + }) + JS + assert_equal ["ok"], hits.uniq + end + + def test_an_unsupported_type_raises + ActiveAdmin.application.load! # defines ActiveAdmin::BatchAction when this test runs first + action = ActiveAdmin::BatchAction.new(:bogus, "Bogus", form: {a: :color}) + error = assert_raises(ArgumentError) { ActiveAdminTheme::BatchActionForm::Modal.new(action).send(:fields, action.form_inputs) } + assert_match(/unsupported input type \{a: :color\}/, error.message) + end +end diff --git a/test/dummy/app/admin/batch_form_orders.rb b/test/dummy/app/admin/batch_form_orders.rb new file mode 100644 index 0000000..c27b440 --- /dev/null +++ b/test/dummy/app/admin/batch_form_orders.rb @@ -0,0 +1,39 @@ +# Batch actions with ActiveAdmin 3's `form:` option, which the theme renders as +# a confirm_dialog (test/batch_action_form_test.rb). Each action echoes the +# selected ids and its inputs in a flash notice. +ActiveAdmin.register Order, as: "BatchFormOrder" do + menu false + config.batch_actions = true + config.filters = false + + # ?flash=1 shows flash messages under the title bar. + controller do + before_action(only: :index) do + flash.now[:notice] = "Export queued" if params[:flash] + flash.now[:alert] = "Another export is running" if params[:flash] + end + end + + batch_action :flag, confirm: "Flag the selected orders?", form: { + "Reason" => :text, + "notes" => :textarea, + "Items" => :number, + "Due on" => :datepicker, + "Notify buyer" => :checkbox, + "kind" => [["Fraud", "fraud"], ["Other", "other"]] + } do |ids, inputs| + redirect_to collection_path, notice: "flag #{ids.sort.join(",")} #{inputs.to_json}" + end + + # A Proc runs in the view, as in ActiveAdmin 3. + batch_action :set_status, form: -> { {status: Order::STATUSES} } do |ids, inputs| + redirect_to collection_path, notice: "set_status #{ids.sort.join(",")} #{inputs.to_json}" + end + + index do + selectable_column + id_column + column :reference + column :status + end +end From cb73fb3362ebcc4d1fedeae62f471c343cad3d6a Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Fri, 4 Dec 2026 19:33:56 +0200 Subject: [PATCH 4/5] ModalDialog shim and a cancelable batch form open event ActiveAdmin 4 dropped ActiveAdmin.ModalDialog with jQuery UI. Apps that check a batch selection on the server before the dialog opens can cancel aat:batch-form:open and open the dialog later. Co-Authored-By: Clanker --- README.md | 28 ++++- .../active_admin_theme/confirm_dialog.js | 30 ++++- .../active_admin_theme/modal_dialog.js | 117 +++++++++++++++++ docs/migrating-from-v3.md | 3 +- lib/active_admin_theme/batch_action_form.rb | 4 +- lib/active_admin_theme/helpers/config.rb | 7 +- .../dummy/config/initializers/active_admin.rb | 1 + test/modal_dialog_test.rb | 118 ++++++++++++++++++ 8 files changed, 298 insertions(+), 10 deletions(-) create mode 100644 app/javascript/active_admin_theme/modal_dialog.js create mode 100644 test/modal_dialog_test.rb diff --git a/README.md b/README.md index 5de8c1b..ab161c4 100644 --- a/README.md +++ b/README.md @@ -419,6 +419,31 @@ end The fields open in a `confirm_dialog` titled like the menu item, and `confirm:` becomes its message. The types are `text`, `number`, `textarea`, `datepicker` (a native date input that sends `YYYY-MM-DD`) and `checkbox`, plus an Array for a select with no blank option. As in ActiveAdmin 3, each key is both the input name and the label with its first letter capitalized, a ticked checkbox sends `"on"` and an unticked one sends nothing. A Proc runs in the view. ActiveAdmin 4's own batch script submits the dialog, so `partial:` actions keep working beside these. +The dialog opens from the `active_admin_theme/confirm_dialog` script, which loads by default. Before it opens, the menu item dispatches a bubbling, cancelable `aat:batch-form:open` event with `detail` `{action, ids, dialog, open}`. To check the selection on the server first, cancel the event and call `open()` once the check passes: + +```js +document.addEventListener("aat:batch-form:open", async (event) => { + if (event.detail.action !== "flag") return + event.preventDefault() + const response = await fetch(`${location.pathname}/flag_validation?selected_ids=${event.detail.ids.join(",")}`) + if (response.ok) event.detail.open() +}) +``` + +After it opens, the dialog dispatches `aat:confirm-dialog:open` with `detail` `{dialog, trigger}`, where `trigger.dataset.action` names the batch action. + +### `ActiveAdmin.ModalDialog` + +The opt-in `active_admin_theme/modal_dialog` script brings back ActiveAdmin 3's `ActiveAdmin.ModalDialog(message, inputs, callback)`, which ActiveAdmin 4 dropped with jQuery UI. Add it to `ActiveAdminTheme.javascripts`. It sets `window.ActiveAdmin.ModalDialog` and is also the module's default export. + +```js +ActiveAdmin.ModalDialog("Complete order?", {"Billing Cycles": "number", Period: [["Month", "1m"], ["Year", "1y"]], Refill: "checkbox"}, (inputs) => { + // inputs => {"Billing Cycles": "3", "Period": "1y", "Refill": "on"} +}) +``` + +The input types are those of [batch action forms](#batch-action-forms), and `{}` asks for confirmation only. The dialog has the `confirm_dialog` look, with **Confirm** and **Cancel** buttons. It is removed when it closes, and the function returns its form. Before and after it opens, the form dispatches bubbling `aat:modal-dialog:before-open` and `aat:modal-dialog:open` events with `detail` `{form, title}`. With jQuery on the page, `body` also gets ActiveAdmin 3's `modal_dialog:before_open` and `modal_dialog:after_open` jQuery events, with the form as their argument. + ### `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. @@ -763,9 +788,10 @@ This is the shape of activeadmin-searchable_select and select2, except that acti | `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/column_chooser` | on | The columns menu, where `column_chooser` turns it on | -| `active_admin_theme/confirm_dialog` | on | Focus and validation for `confirm_dialog` | +| `active_admin_theme/confirm_dialog` | on | Focus and validation for `confirm_dialog`, and opening batch action forms | | `active_admin_theme/secret_reveal` | off | `secret_reveal` | | `active_admin_theme/lazy_load` | off | `lazy_load` | +| `active_admin_theme/modal_dialog` | off | `ActiveAdmin.ModalDialog` | | `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 | diff --git a/app/javascript/active_admin_theme/confirm_dialog.js b/app/javascript/active_admin_theme/confirm_dialog.js index 5ceae6d..40f36f8 100644 --- a/app/javascript/active_admin_theme/confirm_dialog.js +++ b/app/javascript/active_admin_theme/confirm_dialog.js @@ -5,6 +5,10 @@ // sit on document, so it works for dialogs rendered at any time. // When a dialog opens it dispatches a bubbling "aat:confirm-dialog:open" event on // the dialog, with detail { dialog, trigger }. +// A batch action's form dialog (ActiveAdminTheme::BatchActionForm) opens from +// here: its menu item first dispatches a bubbling, cancelable +// "aat:batch-form:open" with detail { action, ids, dialog, open }. A listener +// that cancels it, such as to check the selection on the server, calls open() later. const FOCUSABLE = [ "a[href]", "area[href]", "button:not([disabled])", "input:not([type=hidden]):not([disabled])", "select:not([disabled])", "textarea:not([disabled])", "summary", "iframe", "[contenteditable]:not([contenteditable=false])", @@ -30,11 +34,7 @@ const watchClose = (dialog) => { observer.observe(dialog, { attributes: true, attributeFilter: ["aria-hidden"] }) } -document.addEventListener("click", (event) => { - // The component's own button, or any element that opens the dialog by id. - const trigger = event.target.closest("[data-modal-show], [data-modal-toggle]") - const dialog = trigger && document.getElementById(trigger.dataset.modalShow || trigger.dataset.modalToggle) - if (!dialog || !dialog.matches(".aat-confirm-modal")) return +const opened = (dialog, trigger) => { openers.set(dialog, trigger) watchClose(dialog) // Flowbite's own click listener on the trigger shows the dialog first; wait a tick so it is visible. @@ -44,6 +44,26 @@ document.addEventListener("click", (event) => { const first = dialog.querySelector(".aat-confirm-body :is(input, select, textarea):not([type=hidden])") || dialog.querySelector(".aat-confirm-cancel") first.focus() }) +} + +document.addEventListener("click", (event) => { + // The component's own button, or any element that opens the dialog by id. + const trigger = event.target.closest("[data-modal-show], [data-modal-toggle]") + const dialog = trigger && document.getElementById(trigger.dataset.modalShow || trigger.dataset.modalToggle) + if (dialog?.matches(".aat-confirm-modal")) opened(dialog, trigger) +}) + +document.addEventListener("click", (event) => { + const item = event.target.closest("[data-aat-batch-form]") + const dialog = item && document.getElementById(item.dataset.aatBatchForm) + if (!dialog) return + const ids = [...document.querySelectorAll(".batch-actions-resource-selection:checked")].map((box) => box.value) + const open = () => { + window.FlowbiteInstances.getInstance("Modal", dialog.id).show() + opened(dialog, item) + } + const detail = { action: item.dataset.action, ids, dialog, open } + if (item.dispatchEvent(new CustomEvent("aat:batch-form:open", { bubbles: true, cancelable: true, detail }))) open() }) document.addEventListener("keydown", (event) => { diff --git a/app/javascript/active_admin_theme/modal_dialog.js b/app/javascript/active_admin_theme/modal_dialog.js new file mode 100644 index 0000000..a649331 --- /dev/null +++ b/app/javascript/active_admin_theme/modal_dialog.js @@ -0,0 +1,117 @@ +// ActiveAdmin 3's ActiveAdmin.ModalDialog(message, inputs, callback) on +// ActiveAdmin 4, which dropped it with jQuery UI. Opt-in. The dialog has the +// confirm_dialog look and opens with Flowbite's Modal. +// +// inputs maps each name to "text", "number", "textarea", "datepicker", +// "checkbox" or an Array of options (a value, or [text, value]); {} asks for +// confirmation only. OK calls callback(values) with the values ActiveAdmin 3 +// sent: a ticked checkbox is "on", an unticked one is left out. The dialog is +// removed when it closes. The function returns the dialog's form. +// +// Before and after it opens, the dialog dispatches bubbling +// "aat:modal-dialog:before-open" and "aat:modal-dialog:open" events with +// detail { form, title }. With jQuery on the page, body also gets ActiveAdmin +// 3's "modal_dialog:before_open" and "modal_dialog:after_open" jQuery events, +// with the form as their argument. +const TYPES = { text: "text", number: "number", datepicker: "date", checkbox: "checkbox" } + +const texts = () => { + try { + return JSON.parse(document.getElementById("active-admin-theme-config")?.textContent || "{}").confirmDialog?.texts || {} + } catch { + return {} + } +} + +const element = (tag, attributes = {}, children = []) => { + const node = document.createElement(tag) + for (const [name, value] of Object.entries(attributes)) node.setAttribute(name, value) + node.append(...children) + return node +} + +const field = (dialogId, name, type, index) => { + const id = `${dialogId}-field-${index}` + const text = name.charAt(0).toUpperCase() + name.slice(1) + let control + if (Array.isArray(type)) { + control = element("select", { id, name, class: "aat-confirm-input" }, + type.map((item) => Array.isArray(item) ? element("option", { value: item[1] }, [String(item[0])]) : element("option", {}, [String(item)]))) + } else if (type === "textarea") { + control = element("textarea", { id, name, rows: 3, class: "aat-confirm-input" }) + } else if (type === "checkbox") { + const box = element("input", { id, name, type: "checkbox" }) + return element("div", { class: "aat-confirm-field", "data-field-type": "boolean" }, [ + element("label", { for: id, class: "aat-confirm-check" }, [box, element("span", {}, [text])]) + ]) + } else if (TYPES[type]) { + control = element("input", { id, name, type: TYPES[type], class: `aat-confirm-input${type === "datepicker" ? " datepicker" : ""}`, autocomplete: "off" }) + } else { + throw new Error(`Unsupported input type: {${name}: ${type}}`) + } + return element("div", { class: "aat-confirm-field", "data-field-type": Array.isArray(type) ? "select" : type }, [ + element("label", { for: id, class: "aat-confirm-label" }, [text]), + control + ]) +} + +// jQuery's serializeObject, as ActiveAdmin 3 used it: a repeated name becomes an array. +const values = (form) => { + const result = {} + for (const [name, value] of new FormData(form)) { + if (!(name in result)) result[name] = value + else result[name] = [].concat(result[name], value) + } + return result +} + +let count = 0 + +export default function ModalDialog(message, inputs, callback) { + const dialogId = `aat-modal-dialog-${++count}` + const { confirm = "Confirm", cancel = "Cancel" } = texts() + const form = element("form", { class: "aat-confirm-form", "data-aat-modal-dialog": "" }, [ + element("h2", { id: `${dialogId}-title`, class: "aat-confirm-title" }, [String(message ?? "")]), + element("div", { class: "aat-confirm-body" }, Object.entries(inputs || {}).map(([name, type], index) => field(dialogId, name, type, index))), + element("div", { class: "aat-confirm-actions" }, [ + element("button", { type: "submit", class: "aat-confirm-submit" }, [confirm]), + element("button", { type: "button", class: "aat-confirm-cancel" }, [cancel]) + ]) + ]) + const dialog = element("div", { + id: dialogId, class: "aat-confirm-modal hidden", tabindex: "-1", role: "dialog", "aria-modal": "true", + "aria-hidden": "true", "aria-labelledby": `${dialogId}-title` + }, [element("div", { class: "aat-confirm-panel" }, [form])]) + document.body.append(dialog) + + const opener = document.activeElement + const modal = new window.Modal(dialog, { + backdrop: "dynamic", + closable: true, + onHide: () => { + dialog.remove() + window.FlowbiteInstances?.removeInstance("Modal", dialogId) + opener?.focus?.() + } + }, { id: dialogId, override: true }) + form.addEventListener("submit", (event) => { + event.preventDefault() + const result = values(form) + modal.hide() + callback?.(result) + }) + form.querySelector(".aat-confirm-cancel").addEventListener("click", () => modal.hide()) + + const announce = (name, legacy) => { + form.dispatchEvent(new CustomEvent(name, { bubbles: true, detail: { form, title: String(message ?? "") } })) + window.jQuery?.(document.body).trigger(legacy, [window.jQuery(form)]) + } + announce("aat:modal-dialog:before-open", "modal_dialog:before_open") + modal.show() + announce("aat:modal-dialog:open", "modal_dialog:after_open") + const first = form.querySelector(".aat-confirm-body :is(input, select, textarea)") || form.querySelector(".aat-confirm-submit") + first.focus() + return form +} + +window.ActiveAdmin = Object.assign(window.ActiveAdmin || {}, { ModalDialog }) diff --git a/docs/migrating-from-v3.md b/docs/migrating-from-v3.md index 22bfbc1..0803854 100644 --- a/docs/migrating-from-v3.md +++ b/docs/migrating-from-v3.md @@ -57,6 +57,7 @@ ActiveAdmin 4 dropped menus deeper than one submenu level, but the theme keeps t - The theme loads as ES modules through `ActiveAdmin.importmap`, not through Sprockets. A pin in your own `config/importmap.rb` does not load on ActiveAdmin pages; pin your scripts into `ActiveAdmin.importmap` (README, "JavaScript"). - `theme_toggle.js` is rewritten as `active_admin_theme/theme_toggle`. The header switch cycles auto, light and dark, and keeps ActiveAdmin 4's `theme` key in `localStorage`, so a choice made in theme 3 is not carried over. - `scrollbar_width.js` is gone. The header no longer uses `100vw`, so it is not needed. +- `ActiveAdmin.ModalDialog` is gone with jQuery UI. The opt-in `active_admin_theme/modal_dialog` script brings it back with the same signature. Code that found the dialog through jQuery UI's markup should use the form the function returns, or the `aat:modal-dialog:open` event. - `table_crisscross.js` is rewritten without jQuery as `active_admin_theme/table_crisscross`, and loads by default. The `td.selected` marker is now `td[data-selected]`. A cell click now also ticks the row's batch checkbox; `ActiveAdminTheme.row_click_selects = false` restores the v3 behavior. - `server_clock.js` is rewritten as `active_admin_theme/server_clock`. It reads `data-servertime-epoch` and `data-servertime-zone` from `[data-server-clock]`; the old `data-servertime` wall-clock format is not supported. @@ -83,7 +84,7 @@ Extensions that depend on ActiveAdmin 3 internals (calendar, table footer, and o ## Not ported - Trix and ActionText theming. -- Pinned bars and sticky table headers. +- Pinned bars. - The `$skin*` sizing variables. Open an issue if you need one of these. diff --git a/lib/active_admin_theme/batch_action_form.rb b/lib/active_admin_theme/batch_action_form.rb index 0dd1045..2e87360 100644 --- a/lib/active_admin_theme/batch_action_form.rb +++ b/lib/active_admin_theme/batch_action_form.rb @@ -19,7 +19,9 @@ def partial def link_html_options return super unless form_inputs - super.merge("data-modal-target": form_dialog_id, "data-modal-show": form_dialog_id) + # No data-modal-show: active_admin_theme/confirm_dialog opens the dialog + # after a cancelable "aat:batch-form:open" event. + super.merge("data-modal-target": form_dialog_id, "data-aat-batch-form": form_dialog_id) end # The `form:` option: a Hash of name => type, or a Proc run in the view that returns one. diff --git a/lib/active_admin_theme/helpers/config.rb b/lib/active_admin_theme/helpers/config.rb index aec4b6c..98b7000 100644 --- a/lib/active_admin_theme/helpers/config.rb +++ b/lib/active_admin_theme/helpers/config.rb @@ -13,12 +13,15 @@ module Config }.freeze # The settings the theme's scripts read, as a JSON element. Texts come - # from `active_admin_theme.searchable_select.*` with English defaults. + # from `active_admin_theme.searchable_select.*` and + # `active_admin_theme.confirm_dialog.*` with English defaults. def active_admin_theme_config_tag texts = SEARCHABLE_SELECT_TEXTS.to_h do |key, default| [key.to_s.camelize(:lower), I18n.t("active_admin_theme.searchable_select.#{key}", default: default)] end - config = {searchableSelect: {all: ActiveAdminTheme.searchable_select_all, minChars: ActiveAdminTheme.searchable_select_min_chars, texts: texts}} + dialog_texts = {confirm: "Confirm", cancel: "Cancel"}.to_h { |key, default| [key, I18n.t("active_admin_theme.confirm_dialog.#{key}", default: default)] } + config = {searchableSelect: {all: ActiveAdminTheme.searchable_select_all, minChars: ActiveAdminTheme.searchable_select_min_chars, texts: texts}, + confirmDialog: {texts: dialog_texts}} content_tag(:script, json_escape(config.to_json).html_safe, type: "application/json", id: "active-admin-theme-config") end diff --git a/test/dummy/config/initializers/active_admin.rb b/test/dummy/config/initializers/active_admin.rb index 9aafc5c..ead5f29 100644 --- a/test/dummy/config/initializers/active_admin.rb +++ b/test/dummy/config/initializers/active_admin.rb @@ -14,6 +14,7 @@ # The optional modules the demo pages use. ActiveAdminTheme.javascripts += %w[ active_admin_theme/secret_reveal + active_admin_theme/modal_dialog ] # test/layout_test.rb: the footer and the title link. diff --git a/test/modal_dialog_test.rb b/test/modal_dialog_test.rb new file mode 100644 index 0000000..dec4252 --- /dev/null +++ b/test/modal_dialog_test.rb @@ -0,0 +1,118 @@ +# Browser test (headless Chrome): the opt-in ActiveAdmin.ModalDialog shim +# (active_admin_theme/modal_dialog) and the cancelable "aat:batch-form:open". +require_relative "capybara_boot" +require "minitest/autorun" +require "capybara/minitest" + +class ModalDialogTest < Minitest::Test + include Capybara::DSL + include Capybara::Minitest::Assertions + + INPUTS = { + "Billing Cycles Count" => :number, "Period" => [["Month", "1m"], ["Year", "1y"]], "Description" => :textarea, + "Refill Balance" => :checkbox, "Bulk Order" => :checkbox, "Expires On" => :datepicker, "note" => :text + }.freeze + + def setup + page.current_window.resize_to(1280, 900) + end + + def teardown + Capybara.reset_sessions! + end + + # Opens the shim from the page and keeps what it reports on window. + def open_dialog(message, inputs) + page.execute_script(<<~JS, message, inputs.to_json) + window.events = [] + document.addEventListener("aat:modal-dialog:before-open", (e) => window.events.push(["before", e.detail.title])) + document.addEventListener("aat:modal-dialog:open", (e) => window.events.push(["open", e.detail.title, e.detail.form.tagName])) + window.ActiveAdmin.ModalDialog(arguments[0], JSON.parse(arguments[1]), (values) => { window.result = values }) + JS + assert_selector ".aat-confirm-modal [data-aat-modal-dialog]", visible: :visible + end + + def test_fields_values_and_events_match_active_admin_3 + visit "/admin/confirm_dialog" + open_dialog("Complete Order?", INPUTS) + within(".aat-confirm-modal:has([data-aat-modal-dialog])") do + assert_equal "Complete Order?", find(".aat-confirm-title").text + assert_equal ["Billing Cycles Count", "Period", "Description", "Refill Balance", "Bulk Order", "Expires On", "Note"], all("label").map(&:text) + assert_equal "date", find_field("Expires On")[:type] + assert_equal "Billing Cycles Count", page.evaluate_script("document.activeElement.labels[0].textContent") + fill_in "Billing Cycles Count", with: "3" + select "Year", from: "Period" + fill_in "Description", with: "Two" + check "Refill Balance" + find_field("Expires On").set(Date.new(2026, 12, 24)) + click_button "Confirm" + end + assert_no_selector "[data-aat-modal-dialog]", visible: :all + expected = {"Billing Cycles Count" => "3", "Period" => "1y", "Description" => "Two", "Refill Balance" => "on", "Expires On" => "2026-12-24", "note" => ""} + assert_equal expected, page.evaluate_script("window.result") + assert_equal [["before", "Complete Order?"], ["open", "Complete Order?", "FORM"]], page.evaluate_script("window.events") + end + + def test_confirm_only_cancel_escape_and_jquery_events + visit "/admin/confirm_dialog" + page.execute_script(<<~JS) + window.legacy = [] + window.jQuery = (node) => ({ trigger: (name, args) => window.legacy.push([name, node === document.body, typeof args[0]]) }) + JS + open_dialog("Are you sure?", {}) + assert_equal 0, all("[data-aat-modal-dialog] .aat-confirm-field").size + assert_equal [["modal_dialog:before_open", true, "object"], ["modal_dialog:after_open", true, "object"]], page.evaluate_script("window.legacy") + click_button "Cancel" + assert_no_selector "[data-aat-modal-dialog]", visible: :all + assert_nil page.evaluate_script("window.result") + + open_dialog("Are you sure?", {}) + find("[data-aat-modal-dialog] .aat-confirm-submit").send_keys(:escape) + assert_no_selector "[data-aat-modal-dialog]", visible: :all + assert_no_selector "[modal-backdrop]", visible: :all + + open_dialog("Are you sure?", {}) + click_button "Confirm" + assert_equal({}, page.evaluate_script("window.result")) + end + + def test_an_unsupported_type_throws + visit "/admin/confirm_dialog" + message = page.evaluate_script("(() => { try { window.ActiveAdmin.ModalDialog('x', {a: 'color'}, () => {}) } catch (e) { return e.message } })()") + assert_equal "Unsupported input type: {a: color}", message + end + + def test_dialog_controls_take_clicks_on_a_scrolled_page + page.current_window.resize_to(1000, 600) + visit "/admin/menu_orders?flash=1" + page.execute_script("window.scrollTo({left: 100, top: 150, behavior: 'instant'})") + open_dialog("Complete Order?", INPUTS) + hits = page.evaluate_script(<<~JS) + [...document.querySelectorAll("[data-aat-modal-dialog] :is(input, textarea, select, button)")].map((el) => { + const box = el.getBoundingClientRect() + const hit = document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2) + return el === hit || el.contains(hit) || [...(el.labels || [])].some((l) => l.contains(hit)) ? "ok" : `${el.name || el.textContent}: ${hit && hit.className}` + }) + JS + assert_equal ["ok"], hits.uniq + end + + def test_a_batch_form_waits_for_a_canceled_open_event + visit "/admin/batch_form_orders" + all(".batch-actions-resource-selection", minimum: 2).first(2).each(&:check) + ids = all(".batch-actions-resource-selection:checked").map(&:value) + page.execute_script(<<~JS) + document.addEventListener("aat:batch-form:open", (event) => { + event.preventDefault() + window.pending = event.detail + }) + JS + find(".batch-actions-dropdown-toggle").click + find("[data-action='flag']").click + assert_equal ["flag", ids], page.evaluate_script("[window.pending.action, window.pending.ids]") + assert_selector "#batch-action-form-flag", visible: :hidden + page.execute_script("window.pending.open()") + assert_selector "#batch-action-form-flag", visible: :visible + assert_equal "Reason", page.evaluate_script("document.activeElement.labels[0].textContent") + end +end From 6e30e7595fc6df0067abb7dd7e41c39bf4369619 Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Fri, 4 Dec 2026 20:28:29 +0200 Subject: [PATCH 5/5] Searchable select: sortable, clear and search switches, kept values Covers what apps migrating from select2 used: a dragged order that the form submits, a value kept across a parent change when still offered, a param sent for an empty parent, and result attrs on the picked option. Co-Authored-By: Clanker --- README.md | 16 +++ .../active_admin_theme/searchable_select.js | 50 ++++++++-- app/tailwind/components/searchable_select.css | 11 +++ lib/active_admin_theme.rb | 4 + lib/active_admin_theme/helpers/config.rb | 3 +- .../inputs/searchable_select_input.rb | 24 ++++- .../dummy/app/admin/searchable_select_demo.rb | 26 +++++ test/searchable_select_switches_test.rb | 97 +++++++++++++++++++ 8 files changed, 222 insertions(+), 9 deletions(-) create mode 100644 test/searchable_select_switches_test.rb diff --git a/README.md b/README.md index ab161c4..4ebec78 100644 --- a/README.md +++ b/README.md @@ -645,6 +645,17 @@ f.input :kind, as: :select, include_blank: "None", tom_select: {allowEmptyOption f.input :tags, as: :select, multiple: true, tom_select: {addPlugins: ["checkbox_options"], removePlugins: ["remove_button"]} ``` +The hash also takes three switches of the theme's own: + +- `sortable: true` lets you drag the items of a multiple select. The form sends the values in the order of the items, and on page load the items follow the order of the selected options, so list the saved order first. It uses Tom Select's `drag_drop` plugin, which needs no jQuery; touch screens may not drag. +- `clear: false` drops the remove button of a single select. +- `search: false` drops the search box. + +```ruby +f.input :codec_ids, as: :select, multiple: true, collection: codecs_in_saved_order, tom_select: {sortable: true} +f.input :kind, as: :select, collection: kinds, tom_select: {clear: false, search: false} +``` + The option renders the `data-tom-select` attribute, which you can also write yourself: `"false"`, `"true"` or the settings as JSON. ```ruby @@ -656,6 +667,7 @@ select_tag :color, options_for_select(colors), data: {tom_select: {create: true} ```ruby ActiveAdminTheme.searchable_select_all = true # upgrade every select ActiveAdminTheme.searchable_select_min_chars = 3 # characters to type before an AJAX select searches +ActiveAdminTheme.searchable_select_search_min_options = 5 # fewer options show no search box; nil (default) always shows it ``` The texts come from I18n, with these defaults: @@ -703,6 +715,8 @@ By default it searches once three characters are typed, loads the next page as t | `depends_param:` | `depends_param: "q[region_id_eq]"` | Query param that carries the parent's value, `q[_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. | +| `depends_empty_param:` | `depends_empty_param: "q[country_id_null]"` | The select works with an empty parent, and sends this param as `true` instead. With several parents, a Hash of parent to param. | +| `depends_keep_value:` | `depends_keep_value: true` | When the parent changes, the select keeps its value if the new options still have it. Needs `load_all: true`. | | `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. | @@ -755,6 +769,8 @@ end | `id_search:` | off | `id_search: true` finds `id:123`; `id_search: "#"` finds `#123` | | `additional_payload:` | none | `additional_payload: ->(customer) { {email: customer.email} }` | +A payload key `attrs`, a Hash of attribute name to value, becomes attributes of the `