active_admin_scoped_collection_actions 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,282 @@
1
+ // ActiveAdmin 4 dialog; ActiveAdmin 3 keeps the jQuery UI one in vendor/assets.
2
+ // Posts the same params as that one: changes[name], collection_selection[],
3
+ // authenticity_token and batch_action.
4
+ import "flowbite"
5
+
6
+ const BUTTON = ".scoped_collection_action_button"
7
+ const COUNT_ACTION = "scoped_collection_records_count"
8
+
9
+ const PRIMARY_BUTTON = "text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-hidden focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 cursor-pointer disabled:opacity-50 disabled:cursor-default dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
10
+ const SECONDARY_BUTTON = "action-item-button cursor-pointer"
11
+ const INPUT = "block w-full mt-1 rounded-md border border-gray-300 bg-white text-sm text-gray-900 disabled:opacity-50 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
12
+ const CHECKBOX = "rounded-sm border-gray-300 dark:border-gray-600 dark:bg-gray-700"
13
+
14
+ const element = (tag, attributes = {}, text = null) => {
15
+ const el = document.createElement(tag)
16
+ for (const [name, value] of Object.entries(attributes)) {
17
+ if (value !== null && value !== undefined) el.setAttribute(name, value)
18
+ }
19
+ if (text !== null) el.textContent = text
20
+ return el
21
+ }
22
+
23
+ const batchActionUrl = () => window.location.pathname + "/batch_action" + window.location.search
24
+
25
+ const selection = () =>
26
+ Array.from(document.querySelectorAll('input[name="collection_selection[]"]:checked'), (input) => input.value)
27
+
28
+ const post = (token, batchAction, changes = {}) => {
29
+ const body = new URLSearchParams()
30
+ for (const [name, value] of Object.entries(changes)) body.append(`changes[${name}]`, value)
31
+ for (const id of selection()) body.append("collection_selection[]", id)
32
+ body.append("authenticity_token", token)
33
+ body.append("batch_action", batchAction)
34
+
35
+ return fetch(batchActionUrl(), {
36
+ method: "POST",
37
+ body,
38
+ credentials: "same-origin",
39
+ headers: { "X-Requested-With": "XMLHttpRequest" }
40
+ })
41
+ }
42
+
43
+ const recordsCount = (token) =>
44
+ post(token, COUNT_ACTION).then((response) => (response.ok ? response.json() : Promise.reject(response)))
45
+
46
+ // "You are going to delete {count} record(s).", hidden behind a spinner until
47
+ // the count is known, so nobody reads half a message.
48
+ const recordsSummary = (template, token) => {
49
+ const summary = element("p", { class: "dialog_records_summary mb-2 text-gray-900 dark:text-gray-100", "data-scoped-collection-action-summary": "" })
50
+ const spinner = element("div", { class: "dialog_spinner mx-auto my-4 size-6 animate-spin rounded-full border-3 border-current border-r-transparent text-gray-500 dark:text-gray-400", "data-scoped-collection-action-spinner": "" })
51
+ const show = (count) => { summary.textContent = template.replace("{count}", count) }
52
+
53
+ summary.hidden = true
54
+ const request = recordsCount(token)
55
+ .then((data) => show(data.count))
56
+ .catch(() => show("?"))
57
+ .finally(() => {
58
+ spinner.remove()
59
+ summary.hidden = false
60
+ })
61
+
62
+ return { summary, spinner, request }
63
+ }
64
+
65
+ // One field of the `form:` option: a checkbox that enables it, a label and
66
+ // the input. Unchecked fields stay disabled and are not submitted.
67
+ const field = (name, type) => {
68
+ const id = `mass_update_dialog_${name}`
69
+ const item = element("li", { class: "mt-3", "data-scoped-collection-action-field": name })
70
+ const toggle = element("input", { type: "checkbox", class: `mass_update_protect_fild_flag ${CHECKBOX}`, value: "Y", id })
71
+ const label = element("label", { for: id, id: `${id}_label`, class: "ms-2 text-sm font-medium text-gray-900 dark:text-white" }, name.charAt(0).toUpperCase() + name.slice(1))
72
+ let input
73
+
74
+ if (Array.isArray(type)) {
75
+ input = element("select", { name, class: INPUT })
76
+ for (const option of type) {
77
+ const [text, value] = Array.isArray(option) ? option : [option, option]
78
+ // ['None', nil]: without a value attribute the browser would submit the label
79
+ input.append(element("option", { value: value ?? "" }, text))
80
+ }
81
+ } else if (type !== null && typeof type === "object") {
82
+ // {type: 'text', class: 'my-widget'}: a plain input carrying the host's
83
+ // class, so its own JavaScript can turn it into any widget.
84
+ input = element("input", { name, type: type.type || "text", class: `${type.class || ""} ${INPUT}` })
85
+ } else if (type === "text") {
86
+ input = element("input", { name, type: "text", class: INPUT })
87
+ } else if (type === "checkbox") {
88
+ input = element("input", { name, type: "checkbox", class: `ms-2 ${CHECKBOX}` })
89
+ } else if (type === "datepicker") {
90
+ // ActiveAdmin 4 uses the native date input instead of a datepicker widget.
91
+ input = element("input", { name, type: "date", class: `datepicker ${INPUT}` })
92
+ } else {
93
+ throw new Error(`Unsupported input type: {${name}: ${type}}`)
94
+ }
95
+
96
+ // The label's `for` names the checkbox, so the value control needs its own link
97
+ input.setAttribute("aria-labelledby", label.id)
98
+ input.disabled = true
99
+ toggle.addEventListener("change", () => { input.disabled = !toggle.checked })
100
+ item.append(toggle, label, input)
101
+ return item
102
+ }
103
+
104
+ // The checked fields as the dialog shows them: [{label: 'Name', value: 'test'}]
105
+ const checkedChanges = (form) =>
106
+ Array.from(form.querySelectorAll(".mass_update_protect_fild_flag:checked"), (toggle) => {
107
+ const item = toggle.closest("[data-scoped-collection-action-field]")
108
+ const input = item.querySelector("[name]")
109
+ let value
110
+ if (input.tagName === "SELECT") {
111
+ value = Array.from(input.selectedOptions, (option) => option.text.trim()).join(", ")
112
+ } else if (input.type === "checkbox") {
113
+ value = input.checked
114
+ } else {
115
+ value = input.value
116
+ }
117
+ return { label: item.querySelector("label").textContent.trim(), value }
118
+ })
119
+
120
+ const formChanges = (form) => {
121
+ const changes = {}
122
+ for (const [name, value] of new FormData(form)) changes[name] = value
123
+ // FormData skips an unchecked box, but the confirm step shows it as false
124
+ for (const input of form.querySelectorAll('input[type="checkbox"][name]:not(:disabled):not(:checked)')) {
125
+ changes[input.name] = "off"
126
+ }
127
+ return changes
128
+ }
129
+
130
+ const openDialog = (button) => {
131
+ const data = JSON.parse(button.getAttribute("data"))
132
+ const token = data.auth_token
133
+ const batchAction = data.batch_action
134
+ // confirm_submit adds a second step, and confirm_summary then only words it
135
+ const confirmSubmit = data.confirm_submit
136
+ ? { title: data.confirm_submit, summary: data.confirm_summary || data.confirm_submit_summary }
137
+ : null
138
+ const summaryText = confirmSubmit ? null : data.confirm_summary
139
+
140
+ const modalEl = element("div", {
141
+ id: "scoped-collection-action-modal",
142
+ tabindex: "-1",
143
+ "aria-hidden": "true",
144
+ "aria-labelledby": "scoped-collection-action-modal-title",
145
+ class: "fixed inset-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto h-full max-h-full",
146
+ "data-scoped-collection-action-modal": batchAction,
147
+ "data-step": "fields"
148
+ })
149
+ const dialog = element("div", { class: "relative w-full max-w-md max-h-full" })
150
+ const content = element("div", { class: "relative bg-white rounded-lg shadow dark:bg-gray-800 dark:border dark:border-white/10 px-6 py-6 lg:px-8" })
151
+ const title = element("h3", { id: "scoped-collection-action-modal-title", class: "mb-4 text-xl font-medium text-gray-900 dark:text-white", "data-scoped-collection-action-title": "" }, data.confirm)
152
+ const form = element("form", { "data-scoped-collection-action-form": batchAction })
153
+ const fields = element("ul", { "data-scoped-collection-action-fields": "" })
154
+ const footer = element("div", { class: "mt-6 flex justify-end gap-2" })
155
+ const ok = element("button", { type: "submit", class: PRIMARY_BUTTON, "data-scoped-collection-action-ok": "" }, "OK")
156
+ const cancel = element("button", { type: "button", class: SECONDARY_BUTTON, "data-scoped-collection-action-cancel": "" }, "Cancel")
157
+
158
+ for (const [name, type] of Object.entries(data.inputs || {})) fields.append(field(name, type))
159
+ footer.append(ok, cancel)
160
+ form.append(fields, footer)
161
+ content.append(title, form)
162
+ dialog.append(content)
163
+ modalEl.append(dialog)
164
+ document.body.append(modalEl)
165
+
166
+ // OK stays disabled while the count is pending, so nothing is confirmed
167
+ // before the user sees what they confirm.
168
+ let waiting = null
169
+ const waitFor = (request) => {
170
+ waiting = request
171
+ ok.disabled = true
172
+ request.finally(() => {
173
+ if (waiting !== request) return
174
+ waiting = null
175
+ ok.disabled = false
176
+ })
177
+ }
178
+
179
+ if (summaryText) {
180
+ const { summary, spinner, request } = recordsSummary(summaryText, token)
181
+ form.prepend(spinner, summary)
182
+ waitFor(request)
183
+ }
184
+
185
+ const modal = new window.Modal(modalEl, {
186
+ backdrop: "dynamic",
187
+ closable: true,
188
+ onHide: () => {
189
+ setTimeout(() => {
190
+ modal.destroyAndRemoveInstance()
191
+ modalEl.remove()
192
+ button.focus()
193
+ })
194
+ }
195
+ }, { id: modalEl.id, override: true })
196
+
197
+ cancel.addEventListener("click", () => modal.hide())
198
+
199
+ const focusFirstControl = () =>
200
+ form.querySelector("input:not(:disabled), select:not(:disabled), button:not(:disabled)")?.focus()
201
+
202
+ // Escape and the backdrop call hide() too; once the action is sent the modal
203
+ // stays until the page reloads.
204
+ let submitted = false
205
+ const hide = modal.hide.bind(modal)
206
+ modal.hide = () => { if (!submitted) hide() }
207
+ const submit = () => {
208
+ submitted = true
209
+ const changes = formChanges(form)
210
+ footer.replaceChildren(element("span", { class: "text-sm text-gray-700 dark:text-gray-300" }, "Processing. Please wait..."))
211
+ post(token, batchAction, changes)
212
+ .then((response) => {
213
+ const location = response.headers.get("Location")
214
+ if (location) window.location.assign(location)
215
+ else window.location.reload()
216
+ })
217
+ .catch(() => window.location.reload())
218
+ }
219
+
220
+ // Second step: the fields give way to what is going to change and on how
221
+ // many records. Back returns to the filled-in fields.
222
+ const showConfirmStep = (changes) => {
223
+ const step = element("div", { class: "dialog_confirm_submit", "data-scoped-collection-action-confirm": "" })
224
+ const list = element("ul", { class: "dialog_confirm_submit_changes mt-1 text-sm text-gray-900 dark:text-gray-100" })
225
+ for (const change of changes) {
226
+ const item = element("li", { class: "mt-1" })
227
+ item.append(element("b", {}, change.label), document.createTextNode(`: ${change.value}`))
228
+ list.append(item)
229
+ }
230
+ const { summary, spinner, request } = recordsSummary(confirmSubmit.summary, token)
231
+ list.hidden = true
232
+ request.finally(() => { list.hidden = false })
233
+ step.append(spinner, summary, list)
234
+
235
+ const back = element("button", { type: "button", class: SECONDARY_BUTTON, "data-scoped-collection-action-back": "" }, "Back")
236
+ const fieldsTitle = title.textContent
237
+ back.addEventListener("click", () => {
238
+ waiting = null
239
+ ok.disabled = false
240
+ step.remove()
241
+ back.replaceWith(cancel)
242
+ fields.hidden = false
243
+ title.textContent = fieldsTitle
244
+ modalEl.dataset.step = "fields"
245
+ focusFirstControl()
246
+ })
247
+
248
+ fields.hidden = true
249
+ fields.after(step)
250
+ cancel.replaceWith(back)
251
+ title.textContent = confirmSubmit.title
252
+ modalEl.dataset.step = "confirm"
253
+ waitFor(request)
254
+ }
255
+
256
+ form.addEventListener("submit", (event) => {
257
+ event.preventDefault()
258
+ if (waiting || submitted) return
259
+
260
+ if (modalEl.dataset.step === "confirm") return submit()
261
+
262
+ const changes = checkedChanges(form)
263
+ // nothing is checked, so there is nothing to confirm
264
+ if (!confirmSubmit || !changes.length) return submit()
265
+ showConfirmStep(changes)
266
+ })
267
+
268
+ document.body.dispatchEvent(new CustomEvent("mass_update_modal_dialog:before_open", { bubbles: true, detail: { form } }))
269
+ modal.show()
270
+ focusFirstControl()
271
+ document.body.dispatchEvent(new CustomEvent("mass_update_modal_dialog:after_open", { bubbles: true, detail: { form } }))
272
+ }
273
+
274
+ document.addEventListener("click", (event) => {
275
+ const button = event.target.closest(BUTTON)
276
+ if (!button) return
277
+
278
+ event.preventDefault()
279
+ // Enter on the still-focused button would stack a second modal with the same ids
280
+ if (document.getElementById("scoped-collection-action-modal")) return
281
+ openDialog(button)
282
+ })
@@ -0,0 +1,5 @@
1
+ # Drawn into ActiveAdmin.importmap by the engine on ActiveAdmin 4. Not
2
+ # preloaded, so a host that does not import the module does not fetch it.
3
+ # The file is not named after the gem: that name is the Sprockets bundle in
4
+ # vendor/assets, which Propshaft would serve instead.
5
+ pin 'active_admin_scoped_collection_actions', to: 'active_admin_scoped_collection_actions/dialog.js', preload: false
@@ -2,6 +2,9 @@ de:
2
2
  active_admin_scoped_collection_actions:
3
3
  sidebar_msg: 'Diese Aktion betrifft alle ausgewählten Datensätze. Wenn keine ausgewählt sind, betrifft sie alle gefilterten Datensätze.'
4
4
  confirm_action_message: 'Sind Sie sicher?'
5
+ confirm_submit_summary: 'Sie werden {count} Datensätze aktualisieren mit:'
6
+ confirm_destroy_summary: 'Sie werden {count} Datensätze löschen.'
7
+ confirm_action_summary: 'Sie werden diese Aktion für {count} Datensätze ausführen.'
5
8
  actions:
6
9
  delete: 'Löschen'
7
10
  update: 'Aktualisieren'
@@ -2,6 +2,10 @@ en:
2
2
  active_admin_scoped_collection_actions:
3
3
  sidebar_msg: 'This batch operations affect selected records. Or if none is selected, it will involve all records by current filters and scopes.'
4
4
  confirm_action_message: 'Are you sure?'
5
+ # {count} is replaced with amount of affected records
6
+ confirm_submit_summary: 'You are going to update {count} record(s) with:'
7
+ confirm_destroy_summary: 'You are going to delete {count} record(s).'
8
+ confirm_action_summary: 'You are going to perform this action on {count} record(s).'
5
9
  actions:
6
10
  delete: 'Delete batch'
7
11
  update: 'Update batch'
@@ -2,6 +2,9 @@ es:
2
2
  active_admin_scoped_collection_actions:
3
3
  sidebar_msg: 'Estas operaciones afectan las filas seleccionadas o en caso que no halla seleccionado ninguna, afectará a todo los registros afectados por los filtros aplicados.'
4
4
  confirm_action_message: '¿Está seguro que quiere realizar esta acción?'
5
+ confirm_submit_summary: 'Va a actualizar {count} registro(s) con:'
6
+ confirm_destroy_summary: 'Va a eliminar {count} registro(s).'
7
+ confirm_action_summary: 'Va a realizar esta acción sobre {count} registro(s).'
5
8
  actions:
6
9
  delete: 'Batch Borrado'
7
10
  update: 'Batch Actualizado'
@@ -2,6 +2,9 @@ sv:
2
2
  active_admin_scoped_collection_actions:
3
3
  sidebar_msg: 'Den här bulkoperationen påverkar markerade poster. Eller om inget är markerat så kommer det påverka alla poster i nuvarande filter och scope.'
4
4
  confirm_action_message: 'Är du säker?'
5
+ confirm_submit_summary: 'Du kommer att uppdatera {count} post(er) med:'
6
+ confirm_destroy_summary: 'Du kommer att ta bort {count} post(er).'
7
+ confirm_action_summary: 'Du kommer att utföra den här åtgärden på {count} post(er).'
5
8
  actions:
6
9
  delete: 'Ta bort batch'
7
10
  update: 'Uppdatera batch'
@@ -2,6 +2,7 @@ module ActiveAdminScopedCollectionActions
2
2
  module DSL
3
3
 
4
4
  def scoped_collection_action(name, options = {}, &block)
5
+ add_scoped_collection_records_count_action
5
6
  if name == :scoped_collection_destroy
6
7
  options[:title] = I18n.t('active_admin_scoped_collection_actions.actions.delete') if options[:title].nil?
7
8
  add_scoped_collection_action_default_destroy(options, &block)
@@ -15,6 +16,24 @@ module ActiveAdminScopedCollectionActions
15
16
  config.add_scoped_collection_action(name, options)
16
17
  end
17
18
 
19
+ # Amount of records affected by a scoped collection action. Used by the confirmation
20
+ # dialog of an action with :confirm_submit option. Collection is already limited by
21
+ # authorization scope, so it exposes nothing the user can not see on the index page.
22
+ def add_scoped_collection_records_count_action
23
+ batch_action :scoped_collection_records_count, if: proc { false } do
24
+ # Count the rows this relation yields, not the rows its WHERE matches.
25
+ # The action walks the same relation with find_each, which honours
26
+ # limit and offset, so stripping them here would promise more records
27
+ # than it goes on to touch. Counting through a subquery keeps every
28
+ # clause and collapses a grouped scope -- whose bare .count answers
29
+ # with a Hash the dialog would render as [object Object] -- into the
30
+ # single number the dialog needs.
31
+ scope = scoped_collection_records.except(:eager_load, :select, :order)
32
+ count = scope.model.unscoped.from(scope.select('1'), :subquery_for_count).count
33
+ render json: { count: count }
34
+ end
35
+ end
36
+
18
37
  def add_scoped_collection_action_default_update(options, &block)
19
38
  batch_action :scoped_collection_update, if: proc { false } do
20
39
  unless authorized?(:batch_edit, resource_class)
@@ -4,6 +4,36 @@ module ActiveAdminScopedCollectionActions
4
4
  config.after_initialize do
5
5
  ActiveAdmin::ResourceController.send :include, ActiveAdminScopedCollectionActions::Controller
6
6
  end
7
+
8
+ # ActiveAdmin 4 renders its own import map, ActiveAdmin.importmap, so the
9
+ # dialog module is pinned there rather than in the host's importmap.
10
+ initializer 'active_admin_scoped_collection_actions.importmap', after: 'active_admin.importmap' do |app|
11
+ next unless ActiveAdmin.respond_to?(:importmap) && app.config.respond_to?(:importmap)
12
+
13
+ ActiveAdmin.importmap.draw(root.join('config', 'importmap.rb'))
14
+ if app.config.respond_to?(:assets)
15
+ app.config.assets.paths << root.join('app/javascript')
16
+ # Sprockets raises AssetNotPrecompiledError for modules outside its precompile list.
17
+ app.config.assets.precompile += %w[active_admin_scoped_collection_actions/dialog.js]
18
+ end
19
+ if ActiveAdmin.application.respond_to?(:importmap_watches)
20
+ ActiveAdmin.application.importmap_watches << root.join('app/javascript')
21
+ elsif app.config.importmap.sweep_cache
22
+ # Without importmap_watches (activeadmin/activeadmin#9153) each
23
+ # cache_sweeper(watches:) call replaces the watcher, so rebuild
24
+ # ActiveAdmin's with both directories.
25
+ watches = [ActiveAdmin::Engine.root.join('app/javascript'), root.join('app/javascript')].map(&:to_s)
26
+ app.config.after_initialize { ActiveAdmin.importmap.cache_sweeper(watches: watches) }
27
+ end
28
+ end
29
+
30
+ # javascript_modules is pending upstream (activeadmin/activeadmin#9148).
31
+ # Without it the host imports the module itself, see the README.
32
+ config.after_initialize do
33
+ if ActiveAdmin.application.respond_to?(:javascript_modules)
34
+ ActiveAdmin.application.javascript_modules |= %w[active_admin_scoped_collection_actions]
35
+ end
36
+ end
7
37
  end
8
38
  end
9
- end
39
+ end
@@ -51,10 +51,18 @@ module ActiveAdminScopedCollectionActions
51
51
 
52
52
  def scoped_collection_actions_sidebar_section
53
53
  ActiveAdmin::SidebarSection.new :collection_actions, only: :index, if: scoped_collection_sidebar_condition do
54
+ aa_v4 = ActiveAdminScopedCollectionActions.aa_v4?
54
55
 
55
- div I18n.t('active_admin_scoped_collection_actions.sidebar_msg')
56
+ if aa_v4
57
+ # ActiveAdmin 4 no longer wraps sidebar sections in a panel.
58
+ div I18n.t('active_admin_scoped_collection_actions.sidebar_msg'), class: 'mb-3 text-sm text-gray-700 dark:text-gray-300'
59
+ else
60
+ div I18n.t('active_admin_scoped_collection_actions.sidebar_msg')
61
+ end
62
+
63
+ buttons = div(class: 'flex flex-wrap gap-2', 'data-scoped-collection-actions': '') if aa_v4
56
64
 
57
- active_admin_config.scoped_collection_actions.each do |key, options={}|
65
+ actions = active_admin_config.scoped_collection_actions.each do |key, options={}|
58
66
  next if options.key?(:if) && !call_method_or_exec_proc(options[:if])
59
67
 
60
68
  b_title = options.fetch(:title, ::ActiveSupport::Inflector.humanize(key))
@@ -62,6 +70,9 @@ module ActiveAdminScopedCollectionActions
62
70
  b_options[:class] = options[:class] if options[:class].present?
63
71
  # Important: If user did not specify html_class, then use default
64
72
  b_options[:class] = 'scoped_collection_action_button' unless b_options[:class]
73
+ b_options[:class] += ' action-item-button cursor-pointer' if aa_v4 && options[:class].blank?
74
+ b_options[:type] = 'button'
75
+ b_options['data-scoped-collection-action'] = key.to_s
65
76
  b_data = { auth_token: form_authenticity_token.to_s }
66
77
  b_data[:batch_action] = key.to_s
67
78
  if options[:form].present?
@@ -69,9 +80,27 @@ module ActiveAdminScopedCollectionActions
69
80
  end
70
81
  b_data[:confirm] = options.fetch(:confirm, I18n.t('active_admin_scoped_collection_actions.confirm_action_message'))
71
82
  b_data[:confirm] = b_data[:confirm].call if b_data[:confirm].is_a?(Proc)
83
+ confirm_submit = options.fetch(:confirm_submit, false)
84
+ confirm_submit = confirm_submit.call if confirm_submit.is_a?(Proc)
85
+ if confirm_submit
86
+ b_data[:confirm_submit] = confirm_submit.is_a?(String) ? confirm_submit : I18n.t('active_admin_scoped_collection_actions.confirm_action_message')
87
+ b_data[:confirm_submit_summary] = I18n.t('active_admin_scoped_collection_actions.confirm_submit_summary')
88
+ end
89
+ confirm_summary = options.fetch(:confirm_summary, false)
90
+ confirm_summary = confirm_summary.call if confirm_summary.is_a?(Proc)
91
+ if confirm_summary
92
+ default_key = key.to_sym == :scoped_collection_destroy ? 'confirm_destroy_summary' : 'confirm_action_summary'
93
+ b_data[:confirm_summary] = confirm_summary.is_a?(String) ? confirm_summary : I18n.t("active_admin_scoped_collection_actions.#{default_key}")
94
+ end
72
95
  b_options[:data] = b_data.to_json
73
- button b_title, b_options
96
+ if aa_v4
97
+ within(buttons) { button b_title, b_options }
98
+ else
99
+ button b_title, b_options
100
+ end
74
101
  end
102
+ # ActiveAdmin 4 prints a block result that is not an Arbre element.
103
+ aa_v4 ? buttons : actions
75
104
  end
76
105
  end
77
106
 
@@ -1,3 +1,3 @@
1
1
  module ActiveAdminScopedCollectionActions
2
- VERSION = '2.0.0'.freeze
2
+ VERSION = '2.2.0'.freeze
3
3
  end
@@ -1,4 +1,13 @@
1
1
  require 'activeadmin'
2
+
3
+ module ActiveAdminScopedCollectionActions
4
+ # ActiveAdmin 4 replaced jQuery UI and Sprockets with Flowbite, Tailwind and
5
+ # importmaps, so the sidebar markup and the dialog script differ per version.
6
+ def self.aa_v4?
7
+ Gem::Version.new(ActiveAdmin::VERSION) >= Gem::Version.new('4.0.0.beta1')
8
+ end
9
+ end
10
+
2
11
  require 'active_admin_scoped_collection_actions/engine'
3
12
  require 'active_admin_scoped_collection_actions/version'
4
13
  require 'active_admin_scoped_collection_actions/dsl'
@@ -1,4 +1,26 @@
1
+ //= require ./lib/dialog_records_summary
1
2
  //= require ./lib/dialog_mass_fields_update
3
+ //= require ./lib/dialog_confirm_submit
4
+
5
+ ActiveAdmin.scopedCollectionBatchActionUrl = function(){
6
+ return window.location.pathname + '/batch_action' + window.location.search;
7
+ };
8
+
9
+ ActiveAdmin.scopedCollectionSelection = function(){
10
+ const selection = [];
11
+ $('.paginated_collection').find('input.collection_selection:checked').each((i, el) => selection.push($(el).val()));
12
+ return selection;
13
+ };
14
+
15
+ // Amount of records the action is going to be performed on. Same scope(filters,
16
+ // current scope and checked records) as the action itself uses.
17
+ ActiveAdmin.scopedCollectionRecordsCount = function(authToken){
18
+ return $.post(ActiveAdmin.scopedCollectionBatchActionUrl(), {
19
+ batch_action: 'scoped_collection_records_count',
20
+ authenticity_token: authToken,
21
+ collection_selection: ActiveAdmin.scopedCollectionSelection()
22
+ });
23
+ };
2
24
 
3
25
  $(document).ready(() =>
4
26
 
@@ -6,16 +28,30 @@ $(document).ready(() =>
6
28
  e.preventDefault();
7
29
  const fields = JSON.parse( $(this).attr('data') );
8
30
 
31
+ const count = () => ActiveAdmin.scopedCollectionRecordsCount(fields['auth_token']);
32
+ const options = {};
33
+
34
+ if (fields['confirm_submit']) {
35
+ // fields dialog gets a second step with the summary of what is going to be done
36
+ options['confirmSubmit'] = {
37
+ title: fields['confirm_submit'],
38
+ summary: fields['confirm_summary'] || fields['confirm_submit_summary'],
39
+ count: count
40
+ };
41
+ } else if (fields['confirm_summary']) {
42
+ // dialog itself tells what is going to be done
43
+ options['summary'] = { text: fields['confirm_summary'], count: count };
44
+ }
45
+
9
46
  return ActiveAdmin.dialogMassFieldsUpdate(fields['confirm'], fields['inputs'],
10
47
  inputs=> {
11
- const url = window.location.pathname + '/batch_action' + window.location.search;
48
+ const url = ActiveAdmin.scopedCollectionBatchActionUrl();
12
49
  const form_data = {
13
50
  changes: inputs,
14
- collection_selection: [],
51
+ collection_selection: ActiveAdmin.scopedCollectionSelection(),
15
52
  authenticity_token: fields['auth_token'],
16
53
  batch_action: fields['batch_action']
17
54
  };
18
- $('.paginated_collection').find('input.collection_selection:checked').each((i, el) => form_data["collection_selection"].push($(el).val()));
19
55
 
20
56
  return $.post(url, form_data).always(function(data, textStatus, jqXHR) {
21
57
  if (jqXHR.getResponseHeader('Location')) {
@@ -24,6 +60,6 @@ $(document).ready(() =>
24
60
  return window.location.reload();
25
61
  }
26
62
  });
27
- });
63
+ }, options);
28
64
  })
29
65
  );
@@ -0,0 +1,52 @@
1
+ // Second step of the fields dialog: instead of the fields it shows what is going to be
2
+ // changed and how many records are affected. "Back" returns to the filled form.
3
+ // form: dialog of ActiveAdmin.dialogMassFieldsUpdate
4
+ // options: {title: 'Are you sure?', summary: 'You are going to update {count} record(s) with:',
5
+ // count: function returning jqXHR with {count: 100500}}
6
+ // changes: [{label: 'Name', value: 'test'}, ...]
7
+ ActiveAdmin.dialogConfirmSubmit = function(form, options, changes, callback){
8
+ const widget = form.dialog('widget');
9
+ const fieldsStep = { content: form.children(), title: form.dialog('option', 'title'), buttons: form.dialog('option', 'buttons') };
10
+
11
+ const step = $('<div class="dialog_confirm_submit"></div>');
12
+ const summary = options['summary'] ?
13
+ ActiveAdmin.dialogRecordsSummary(options['summary'], options['count']).appendTo(step) : null;
14
+ const list = $('<ul class="dialog_confirm_submit_changes"></ul>').appendTo(step);
15
+
16
+ for (let change of Array.from(changes)) {
17
+ $('<li></li>')
18
+ .append($('<b></b>').text(change['label']))
19
+ .append(document.createTextNode(`: ${change['value']}`))
20
+ .appendTo(list);
21
+ }
22
+
23
+ fieldsStep.content.hide();
24
+ step.appendTo(form);
25
+ widget.addClass('active_admin_dialog_confirm_submit');
26
+
27
+ form.dialog('option', {
28
+ title: options['title'] || fieldsStep.title,
29
+ buttons: {
30
+ OK() {
31
+ // amount of affected records is not known yet
32
+ if (form.data('waiting')) { return; }
33
+
34
+ return callback();
35
+ },
36
+ Back() {
37
+ form.data('waiting', false);
38
+ step.remove();
39
+ fieldsStep.content.show();
40
+ widget.removeClass('active_admin_dialog_confirm_submit');
41
+ return form.dialog('option', { title: fieldsStep.title, buttons: fieldsStep.buttons });
42
+ }
43
+ }
44
+ });
45
+
46
+ if (summary) {
47
+ ActiveAdmin.dialogSpinnerUntil(step.children(), summary.data('countRequest'));
48
+ ActiveAdmin.dialogWaitFor(form, summary.data('countRequest'));
49
+ }
50
+
51
+ return form;
52
+ };