Skip to content
Merged
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
138 changes: 137 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ filter :created_at, as: :date_time_range,
floors on two-ended filters.
* [`message:`](#value-policies-sanitize-and-validate) and plain-i18n defaults for every
violation text.
* [`none:` / `present:`](#none-and-present-options) - None and Present options on a select
filter, and None and Present predicates on a string or numeric one, for the records whose
attribute is empty and the ones where it is not.
* [`default_filters_notice`](#telling-the-admin-why) - the flash that tells the admin why the
page shows a slice; [`require_any_filter`](#resource-level-guard) - an index that waits to
be asked.
Expand Down Expand Up @@ -336,6 +339,138 @@ lands in `flash[:error]` (and rides the redirect), and the filter's declared `de
any - refills through the ordinary merge. The defaults notice stays quiet on that render:
the error already explains why the page shows the default slice.

## None and Present options

A select filter cannot ask for the records whose attribute is empty, or for the ones where it
holds anything at all: no value of its collection means either. `none:` and `present:` add the
options, first in the list after the blank one, None before Present:

```ruby
filter :account, as: :select, collection: proc { Account.order(:name) },
extensions: { none: true, present: true }
filter :status, as: :select, multiple: true, collection: %w[draft published],
extensions: { none: "No status" } # the option's label
```

`true` labels the option from the i18n keys `active_admin_filter_extensions.none` ("None") and
`active_admin_filter_extensions.present` ("Present"); a String is the label itself. None
searches `_null` on the filter's attribute, Present searches `_not_null`. On a multiple select:

* None beside other values searches "any of these, or empty".
* Present beside other values searches Present alone: every value is a present one.
* None and Present together search every record, so no condition is applied.

The select submits a marker under its own key - `q[account_id_eq]=__none__` or
`q[account_id_eq]=__present__` - and only the search is handed the condition. The URL, the form
and the other extensions read the request as submitted: `required:` counts either option as an
answer, `sanitize:` and `validate:` are not handed the marker, and
`default: -> { ActiveAdminFilterExtensions.none_value }` opens the index on the empty records.
The Current Filters panel shows the label: "Account equals None", "Account equals Present".
Move a marker where a real value could spell the same thing:

```ruby
ActiveAdminFilterExtensions.none_value = "__empty__"
ActiveAdminFilterExtensions.present_value = "__filled__"
```

### On a string or numeric filter

A `:string` or `:numeric` filter that picks its predicate from a dropdown takes the same two
options, as two more predicates closing the list:

```ruby
filter :title, extensions: { none: true, present: true }
filter :position, as: :numeric, extensions: { none: "No position" }
```

A string filter searches `_blank` and `_present`, so an empty string counts as none; a numeric
one searches `_null` and `_not_null`. These are Ransack's own predicates and the URL says them
as they are searched: `q[title_blank]=1`. `required:` counts them as an answer, `sanitize:` and
`validate:` are not handed the `1`, and the Current Filters panel reads "Title equals None".
A default such as `default: { blank: "1" }` is not handed to them either.

So the same string column splits differently on a select and in the dropdown. Ransack does not
trim, so a value of only spaces counts as present:

| `title` | Select None (`_null`) | Select Present (`_not_null`) | Dropdown None (`_blank`) | Dropdown Present (`_present`) |
| --- | --- | --- | --- | --- |
| `"john"` | | yes | | yes |
| `""` | | yes | yes | |
| `" "` | | yes | | yes |
| `NULL` | yes | | yes | |

Such a predicate has nothing to type, and Active Admin leaves an empty box out of the submit.
The gem's script fills the box and hides it. Without the script the two predicates filter
nothing, so load it on every page with a filters form.

Active Admin 3 (Sprockets), in `app/assets/javascripts/active_admin.js`:

```javascript
//= require active_admin_filter_extensions
```

Active Admin 4 (import map): the gem pins the module `active_admin_filter_extensions` into
`ActiveAdmin.importmap`. If your Active Admin has the `javascript_modules` setting, the gem adds
itself to it and pages import it automatically. Otherwise override
`app/views/active_admin/_html_head.html.erb` (copy it from Active Admin) and add after the
`javascript_importmap_tags` line:

```erb
<%= javascript_import_module_tag "active_admin_filter_extensions" %>
```

If you use active_admin_theme 4, add the module to its list in an initializer instead:

```ruby
ActiveAdminTheme.javascripts += %w[active_admin_filter_extensions]
```

The script listens on `document`, so it does not depend on the order it is loaded in. For a
filters form the page inserts on its own, call `ActiveAdminFilterExtensions.sync(form)`.

Any other filter raises on `none:` or `present:`: check boxes, a date range, a select that
submits `_not_eq` or `_not_in`, a string filter named after its predicate (`filter :title_cont`).

### Styling the options

The gem ships no CSS. Every option it adds, to a select or to a predicate dropdown, carries
classes and a data attribute to style:

```html
<option class="filter-extensions-option filter-extensions-none" data-filter-extensions-option="none" value="__none__">None</option>
<option class="filter-extensions-option filter-extensions-present" data-filter-extensions-option="present" value="__present__">Present</option>
```

A Hash gives the option classes of its own beside the label, appended to the gem's:

```ruby
filter :account, as: :select,
extensions: { none: { label: "No account", class: "text-red-700 italic" },
present: { class: "font-bold" } }
```

```css
.filter-extensions-none { font-style: italic; }
[data-filter-extensions-option] { color: #b91c1c; }
```

A browser styles an `<option>` only so far. A Tom Select widget - the active_admin_theme
searchable select - copies the option's classes onto the option it renders in the dropdown and
onto the selected item, so the same selectors style both.

### Dependent selects

A dependent select - the active_admin_theme searchable select with `depends_on:`, say - sends
its parent's value to its options endpoint, so that endpoint is sent the marker too. It is
applied there when the endpoint is an Active Admin index that declares the same filter with
`none:` or `present:`. An endpoint that searches `q` on its own is handed the marker as a plain
value, and can have it rewritten:

```ruby
markers = ActiveAdminFilterExtensions.markers # { none: "__none__", present: "__present__" }
q = ActiveAdminFilterExtensions::MarkerOptions.search_params(q, %w[account_id_eq], markers[:none], markers[:present])
```

## The redirect

A bare visit to the index redirects once to itself with the effective filters spelled out in
Expand Down Expand Up @@ -372,7 +507,8 @@ Four prints in small type:

## Active Admin 4

The gem works on Active Admin 3.5 and 4 from the same release; it ships no JavaScript or CSS.
The gem works on Active Admin 3.5 and 4 from the same release. It ships no CSS, and one
script, which only the [None and Present predicates](#on-a-string-or-numeric-filter) need.
On Active Admin 4 the filters section keeps Active Admin's own `h3.filters-form-title`, and
the Current Filters section (`#active_search_sidebar_section`) also shows when only defaults
apply. Page objects can select the filters form by `[data-filter-extensions-form]` and, on
Expand Down
70 changes: 70 additions & 0 deletions app/assets/javascripts/active_admin_filter_extensions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Plain script with no imports or exports, so the same file runs as a classic script (Sprockets
// on Active Admin 3) and as an ES module (the import map on Active Admin 4).
//
// A None or Present choice in a filter's predicate dropdown has nothing to type, and Active
// Admin does not submit an empty box. So the box of such a predicate holds "1" - what the
// predicate is answered with - and is hidden. Active Admin's own handler renames the box after
// the predicate; this one does too, as a page the browser restores fires no change event. A held
// box turns type="hidden", so the host's min, max or pattern cannot block the submit.
(function () {
if (window.ActiveAdminFilterExtensions) { return; }

var PREDICATE = "option[data-filter-extensions-predicate]";
var HELD = "data-filter-extensions-held";
// Ransack's false values: a restored predicate answered with one searches the opposite.
var FALSE = /^(0|f|false|n|no|off)$/i;

// The box Active Admin renames: the first input after the dropdown. A select widget may sit
// between the two.
function boxOf(select) {
var sibling = select.nextElementSibling;
while (sibling && !sibling.matches("input")) { sibling = sibling.nextElementSibling; }
return sibling;
}

// chosen: the admin just picked the predicate, so its answer is "1" whatever the box held.
function syncSelect(select, chosen) {
if (!select.querySelector(PREDICATE)) { return; }
var box = boxOf(select);
if (!box) { return; }

var name = "q[" + select.value + "]";
var restored = !chosen && box.name === name && FALSE.test(box.value);
if (select.value) { box.name = name; }
var option = select.options[select.selectedIndex];
if (option && option.matches(PREDICATE)) {
if (!box.hasAttribute(HELD)) { box.setAttribute(HELD, box.type); }
box.type = "hidden";
if (!restored) { box.value = "1"; }
} else if (box.hasAttribute(HELD)) {
box.type = box.getAttribute(HELD) || "text";
box.value = "";
box.removeAttribute(HELD);
}
}

function sync(root) {
var scope = root && root.querySelectorAll ? root : document;
Array.prototype.forEach.call(scope.querySelectorAll("select"), function (select) { syncSelect(select, false); });
}

// Delegated, so a form rendered after this script ran is covered too.
document.addEventListener("change", function (event) {
var select = event.target;
if (select && select.matches && select.matches("select")) { syncSelect(select, true); }
});

// In the capture phase, ahead of Active Admin's handler that disables the empty fields: a
// form that arrived without any of the events below is still submitted with its box filled.
document.addEventListener("submit", function (event) { sync(event.target); }, true);

// A form restored after a submit, whichever way the page arrived.
["DOMContentLoaded", "turbo:load", "turbo:render", "turbo:frame-load", "turbolinks:load"].forEach(function (name) {
document.addEventListener(name, function () { sync(document); });
});
window.addEventListener("pageshow", function () { sync(document); });
if (document.readyState !== "loading") { sync(document); }

// For a filters form the application inserts itself: ActiveAdminFilterExtensions.sync(form).
window.ActiveAdminFilterExtensions = { sync: sync };
})();
4 changes: 4 additions & 0 deletions config/importmap.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# frozen_string_literal: true

# Pinned into ActiveAdmin.importmap, the map the Active Admin 4 layout renders.
pin "active_admin_filter_extensions", to: "active_admin_filter_extensions.js", preload: false
4 changes: 4 additions & 0 deletions config/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ en:
before_floor: "%{filter} filter cannot start before %{floor}."
given_together: "%{filters} filters must be given together."
require_any_filter: "You must specify at least one filter"
# The labels of a select filter's None and Present options
# (`extensions: { none: true, present: true }`).
none: "None"
present: "Present"
29 changes: 28 additions & 1 deletion lib/active_admin_filter_extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
require "active_admin_filter_extensions/search_keys"
require "active_admin_filter_extensions/required_filters"
require "active_admin_filter_extensions/filter_defaults"
require "active_admin_filter_extensions/marker_options"
require "active_admin_filter_extensions/filters_form"
require "active_admin_filter_extensions/redirect"
require "active_admin_filter_extensions/policies"
require "active_admin_filter_extensions/notice"
require "active_admin_filter_extensions/engine"

module ActiveAdminFilterExtensions
class << self
Expand All @@ -33,6 +35,26 @@ def notice_flash_key
@notice_flash_key ||= :notice
end

# What the None option of a select filter submits (`extensions: { none: true }`). Move it
# where a real value of a filtered column could spell the same thing.
attr_writer :none_value

def none_value
@none_value ||= "__none__"
end

# What the Present option submits (`extensions: { present: true }`).
attr_writer :present_value

def present_value
@present_value ||= "__present__"
end

# @return [Hash] :none / :present => what that option submits
def markers
{ none: none_value, present: present_value }
end

# Active Admin 4 moved the filters form helper and the Current Filters section.
def aa_v4?
return @aa_v4 if defined?(@aa_v4)
Expand All @@ -58,8 +80,10 @@ def warning_flash_key
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::SearchKeys
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::RequiredFilters
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::FilterDefaults
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::MarkerOptions
ActiveAdmin::ResourceController.helper_method :filtering_params, :applied_filter_params,
:filter_default_values, :visible_filters
:filter_default_values, :visible_filters,
:marker_filter_form_options

ActiveAdmin::ResourceDSL.include ActiveAdminFilterExtensions::Policies::ResourcePolicyDSL
ActiveAdmin::Resource.include ActiveAdminFilterExtensions::Policies::ResourcePolicySettings
Expand All @@ -69,6 +93,9 @@ def warning_flash_key
# decision - and therefore the URL - is computed from.
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::Policies::Controller
ActiveAdmin::ResourceController.include ActiveAdminFilterExtensions::Redirect
ActiveAdmin::Filters::Active.prepend ActiveAdminFilterExtensions::CurrentFilters
ActiveAdmin::Inputs::Filters::StringInput.prepend ActiveAdminFilterExtensions::PredicateSelect
ActiveAdmin::Inputs::Filters::NumericInput.prepend ActiveAdminFilterExtensions::PredicateSelect
if ActiveAdminFilterExtensions.aa_v4?
ActiveAdmin::Resource.prepend ActiveAdminFilterExtensions::ResourceExtensionV4
ActiveAdmin::FormHelper.prepend ActiveAdminFilterExtensions::ViewHelper
Expand Down
6 changes: 4 additions & 2 deletions lib/active_admin_filter_extensions/data_access.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
module ActiveAdminFilterExtensions
# The single method this gem replaces: Active Admin searches the collection on `params[:q]`
# read directly, and it searches #filtering_params instead. Everything that method means is
# in FilterDefaults.
# in FilterDefaults. A None or Present option's marker becomes its condition here and no
# earlier - see MarkerOptions.
module DataAccess
protected

def apply_filtering(chain)
@search = chain.ransack(filtering_params, **filter_ransack_options)
@search = chain.ransack(marker_filter_search_params(filtering_params), **filter_ransack_options)
label_marker_filters(@search)
# An :empty policy keeps the request intact - the form still shows what the admin
# typed - and blanks the collection instead.
return @search.result.none if filter_policy_render_empty?
Expand Down
33 changes: 33 additions & 0 deletions lib/active_admin_filter_extensions/engine.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# frozen_string_literal: true

module ActiveAdminFilterExtensions
JAVASCRIPT_MODULE = "active_admin_filter_extensions"

# Serves the gem's one script, app/assets/javascripts/active_admin_filter_extensions.js. An
# engine's app/assets is on the asset paths, which is all Sprockets needs on Active Admin 3
# and all Propshaft needs on Active Admin 4.
class Engine < ::Rails::Engine
# Active Admin 4 renders an import map of its own, so the module is pinned there.
initializer "active_admin_filter_extensions.importmap", after: "active_admin.importmap" do |app|
next unless ActiveAdminFilterExtensions.aa_v4? && app.config.respond_to?(:importmap)

ActiveAdmin.importmap.draw(root.join("config", "importmap.rb"))
end

# The import map resolves every pin, and Sprockets raises for a file outside the precompile
# list. Propshaft has no such list.
initializer "active_admin_filter_extensions.precompile", group: :all do |app|
next unless ActiveAdminFilterExtensions.aa_v4? && app.config.respond_to?(:assets)

precompile = app.config.assets.precompile
precompile << "#{JAVASCRIPT_MODULE}.js" if precompile.is_a?(Array)
end

# javascript_modules is pending upstream (activeadmin/activeadmin#9148).
config.after_initialize do
if ActiveAdmin.application.respond_to?(:javascript_modules)
ActiveAdmin.application.javascript_modules |= [JAVASCRIPT_MODULE]
end
end
end
end
16 changes: 11 additions & 5 deletions lib/active_admin_filter_extensions/filter_defaults.rb
Original file line number Diff line number Diff line change
Expand Up @@ -199,20 +199,26 @@ def validate_default_against_value_policies(attribute, options, result, keys)
validator = options[:validate]
return unless sanitizer || validator

# A boolean predicate the filter does not derive itself goes unpoliced when submitted
# (#sibling_predicate_keys), so as a default it is not judged either.
declared = policy_search_keys(attribute, options).map(&:to_s)
keys.each do |key|
value = result[key]
next if value.nil?
next if boolean_predicate?(key) && !declared.include?(key.to_s)

exempt = policy_exempt_markers(attribute, options, key)

# Judged the way the URL will say it: a scalar as the String it becomes, an Array
# element by element - the shape a multi-valued input submits.
if sanitizer
resolved = Policies::Sanitizers.resolve(sanitizer)
result[key] = sanitize_default_value(attribute, resolved, value)
result[key] = sanitize_default_value(attribute, resolved, value, exempt)
end
next unless validator

resolved_validator = Policies::Validators.resolve(validator)
next unless default_value_strings(result[key])
next unless (default_value_strings(result[key]) - exempt)
.any? { |string| ::MethodOrProcHelper.render_in_context(self, resolved_validator, string) }

raise ArgumentError,
Expand All @@ -233,9 +239,9 @@ def default_value_strings(value)
Array.wrap(value).map(&:to_s).reject(&:blank?)
end

def sanitize_default_value(attribute, sanitizer, value)
return value.map { |element| sanitize_default_value(attribute, sanitizer, element) } if value.is_a?(Array)
return value if value.is_a?(Enumerable)
def sanitize_default_value(attribute, sanitizer, value, exempt = [])
return value.map { |element| sanitize_default_value(attribute, sanitizer, element, exempt) } if value.is_a?(Array)
return value if value.is_a?(Enumerable) || exempt.include?(value)

sanitized = ::MethodOrProcHelper.render_in_context(self, sanitizer, value.to_s.dup).to_s
# The same fixpoint check submitted values face: without it the CSV searches the
Expand Down
Loading
Loading