Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
91 changes: 89 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -366,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.
Expand Down Expand Up @@ -394,6 +397,53 @@ 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.

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.
Expand Down Expand Up @@ -525,6 +575,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:
Expand Down Expand Up @@ -577,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
Expand All @@ -588,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:
Expand Down Expand Up @@ -635,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[<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. |
| `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. |
Expand Down Expand Up @@ -687,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 `<option>` that a pick adds, so page scripts can read them from the selected option. A value that is not a String is written as JSON: `additional_payload: ->(address) { {attrs: {"data-payload" => {kind: address.kind}}} }`.

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.
Expand Down Expand Up @@ -719,9 +803,11 @@ 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/confirm_dialog` | on | Focus and validation for `confirm_dialog` |
| `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`, 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 |
Expand Down Expand Up @@ -786,6 +872,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
Expand Down
100 changes: 100 additions & 0 deletions app/javascript/active_admin_theme/column_chooser.js
Original file line number Diff line number Diff line change
@@ -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 = '<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="1.75" y="2.75" width="12.5" height="10.5" rx="1.5"/><path d="M8 2.75v10.5"/></svg>'

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 = `<button type="button" class="index-button aat-columns-toggle" aria-expanded="false" aria-controls="${menuId}"></button>
<div class="aat-columns-menu" id="${menuId}" hidden></div>`
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()
30 changes: 25 additions & 5 deletions app/javascript/active_admin_theme/confirm_dialog.js
Original file line number Diff line number Diff line change
Expand Up @@ -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])",
Expand All @@ -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.
Expand All @@ -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) => {
Expand Down
Loading
Loading