inline_forms 8.1.76 → 8.1.79

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: eacea60e38ccfb9921c8418ce25e0568ba271ae9cfbf2eefe446bcc636a2fda6
4
- data.tar.gz: 6dce6e955302de8c8cff17e5531bdfd30671225c535b0a85fabd9350f74e90a2
3
+ metadata.gz: e5e23dce20574f758b57ab81d8a344f0d74b8e969c13e305ab426b6270623b9d
4
+ data.tar.gz: 49eba2b2136e79bd27dbc51c258681c98cbcf718679d22ceced338e0f252bd3d
5
5
  SHA512:
6
- metadata.gz: 24ffd3ceab2f7a28e39f28b11b93a35567dc54537bcc716f551125cc5c93cf84949434008e875707dc3c94269cb5695bfd540901f7ad3b6a8d87d9865e628d2c
7
- data.tar.gz: ad2c1281fb175ce689a4567c5c082cfaffaeb3543bb651d1694d9738199b1078eb608bd81aff1b1f6fa539720990af3c43491007885e1c80f2e7c142aec5bee3
6
+ metadata.gz: 8d40d0a5af35ef3889706d15b667cffd1eb12165b5a87f397a200cdd044a9ac28ecaadcb0639632b317b837a85d8eade09fe0545e28848334d1bc88e30f88721
7
+ data.tar.gz: 239613687ee6ee98a42b9a0997c63af81b0c9e28f326c152363e2edb6cb918b9b0ac430894d0f2c1d440d93e98e23ec23df8129e8754220a371ed06a32ac0287
data/CHANGELOG.md CHANGED
@@ -8,6 +8,53 @@ All notable changes to this project are documented in this file.
8
8
 
9
9
  - Known issues, parked (local note `stuff/2026-10-31-dropdown-rule-3-parked.md`) with dropdown order rule 3: `includes`, `group` or `select` in `inline_forms_list` make `dropdown` and `dropdown_with_other` raise while `/index` works, so 8.1.65's fix for a list order on a joined table holds only for `joins`, `left_joins` and `eager_load`; a has_many join gives duplicate options. Present since 8.1.60. No host's list scope has these today. Parked; not changed.
10
10
 
11
+ ## [8.1.79] - 2026-11-23
12
+
13
+ ### Added
14
+
15
+ - **Search suggestions, in the engine.** The pieces Scouting, StProject and Papiamentu each had, so an app can drop its own copies on an upgrade:
16
+ - `inline_forms/datalist_suggest.js`, in the engine's script bundle: while the user types, it fills the browser's own suggestion list (`<datalist>`) from a JSON URL. It is the apps' file unchanged; its once-guard (`window.datalistSuggestLoaded`) keeps it from running twice when an app still loads its own copy. No library, no inline script; it passes terser on mini_racer.
17
+ - The helper `suggest_field_tag(name, value, url, options)`: a text field with `list`, `autocomplete="off"` and `data-suggest-url`, and an empty `<datalist>`. It has the apps' module name, `DatalistSuggestHelper`, so an app's own copy wins.
18
+ - The controller macro `suggest_names :client, :last_name`, in every controller that inherits from `InlineFormsController`. It defines the action `autocomplete_client_last_name`, which answers `?term=` with at most 12 names (`limit:`), each once (case and surrounding spaces ignored), in A-Z order, only from records the user may read (`accessible_by`). `scope:` narrows them further, run in the controller. The app adds the route and the ability, as before.
19
+ - **`match:` says where the term must be:** `:contains` (anywhere, the default: "ma" finds Martina, tinaMart and tinartma), `:start` (only at the start: Martina) or `:word` (at the start of any word: Martina, Anna Maria). Case is ignored, and `%` and `_` in the term are taken literally.
20
+ - **The engine's search box suggests,** for a model that asks for it: `inline_forms_search_on :name, :email, suggest: true`, or `suggest: { on: :name, match: :start, limit: 8 }`. The list answers the suggestions itself (`?suggest=1&term=…`), from the records the user may see there, so they need no route or ability of their own. Without `suggest:` the box is as before.
21
+ - Installer: a new app's users list suggests names (`inline_forms_search_on :name, :email, suggest: { on: :name }`), with an example-app test.
22
+
23
+ ### Changed
24
+
25
+ - Full gate (CI, run by hand or weekly): the Brakeman ignore entry that 8.1.77 made obsolete is gone, so the gate is green again for the code released as 8.1.78.
26
+
27
+ ## [8.1.78] - 2026-11-22
28
+
29
+ ### Changed
30
+
31
+ - **Installer: one superadmin, user 1, from the start.** A new app gets the rule the apps on inline_forms already follow:
32
+ - The concern `SingleSuperadmin` (`app/models/concerns/single_superadmin.rb`): `superadmin?` is true only for user 1 holding the role "superadmin". `role?` asks by name and is false without roles.
33
+ - Refused with a message, in the model: giving the role to anybody but user 1 (from the user's roles and from the role's users), taking it from user 1, destroying user 1 (or soft-deleting it, in a model with `InlineForms::SoftDeletable`), renaming or destroying the "superadmin" role. The messages are in `config/locales/single_superadmin.en.yml` and `.nl.yml`.
34
+ - `Ability` asks `superadmin?`. At its end nobody else may change user 1 or see the role, and nobody destroys or soft-deletes user 1.
35
+ - Tests: `test/test_helpers/the_superadmin.rb` makes user 1 (`TheSuperadmin.user`, `the_superadmin`) and `test/models/single_superadmin_test.rb` tests the rule. The example app's tests sign in as user 1 and check the messages on the screen.
36
+ - The role name "superadmin" is reserved: no other role is created with it or renamed to it, in any case. Role names are unique regardless of case.
37
+ - Apps made before keep what they have.
38
+
39
+ ### Fixed
40
+
41
+ - **A create refused by an association callback answers 422,** as the apps' own handlers for it did. Since 8.1.77 the engine shows the refusal itself, and a host's `rescue_from` for it no longer runs. A failed validation still answers 200.
42
+ - **`dropdown` refuses an option it shows disabled** (`disabled_for_dropdown?`), unless the record already has it.
43
+ - A refused dropdown value no longer shows two messages when the model's own message is on the foreign key (`phase_id`) instead of the association.
44
+
45
+ ## [8.1.77] - 2026-11-22
46
+
47
+ ### Changed
48
+
49
+ - **`dropdown` and `check_list` accept only the records they offer** (`accessible_by`, for a check list with the `inline_forms_list` filter). Before, any posted id was written, so hiding an option did not refuse it. A posted id that was not offered makes the record invalid and the field or new form shows why: the model's own message for that attribute, else "is not included in the list". The value a record already has may stay. `dropdown_with_other`, which looks its record up by name, is not changed.
50
+ - **`check_list` leaves the records it did not offer.** Saving used to remove every record the user was not shown.
51
+ - **The app's `User#superadmin?` decides,** where it has one: destroy, revert and the header's menu ask `InlineForms.superadmin?`, which falls back to `role?(:superadmin)`.
52
+
53
+ ### Fixed
54
+
55
+ - **A refused destroy, soft delete or soft restore says so.** The result was ignored: a refused destroy showed the undo button of a deleted record. The row now stays, with the record's errors (or "Could not delete" / "Could not restore", new keys `inline_forms.view.destroy_failed` and `restore_failed`), as a 422.
56
+ - **An association callback may refuse.** A `before_add` / `before_remove` that raises `ActiveRecord::RecordInvalid` or `RecordNotSaved` was a 500; create and update now show the errors in the form, as for a failed validation.
57
+
11
58
  ## [8.1.76] - 2026-11-22
12
59
 
13
60
  ### Fixed
@@ -0,0 +1,81 @@
1
+ // Search suggestions with the browser's own <datalist>. No library.
2
+ //
3
+ // <input type="text" name="search" list="search_suggestions" autocomplete="off"
4
+ // data-suggest-url="/members/autocomplete_member_last_name">
5
+ // <datalist id="search_suggestions"></datalist>
6
+ //
7
+ // While the user types, GET <url>?term=<text> and put the answers in the
8
+ // datalist. The answer is JSON: an array of strings, or of objects with
9
+ // "value" or "label". The browser shows the list and does the picking; a pick
10
+ // only fills the text, and the form is submitted as before.
11
+ //
12
+ // `data-suggest-min` on the input sets the number of characters before the
13
+ // first request (default 2).
14
+ (function () {
15
+ "use strict";
16
+
17
+ // A layout that loads this file in <body> runs it again on every Turbo visit.
18
+ if (window.datalistSuggestLoaded) { return; }
19
+ window.datalistSuggestLoaded = true;
20
+
21
+ var DELAY = 200; // ms after the last keystroke
22
+
23
+ function textOf(item) {
24
+ if (typeof item === "string") { return item; }
25
+ if (item && typeof item === "object") { return String(item.value || item.label || ""); }
26
+ return "";
27
+ }
28
+
29
+ function fill(list, items) {
30
+ var seen = {};
31
+ list.textContent = "";
32
+ items.forEach(function (item) {
33
+ var text = textOf(item);
34
+ if (text === "" || seen[text]) { return; }
35
+ seen[text] = true;
36
+ var option = document.createElement("option");
37
+ option.value = text;
38
+ list.appendChild(option);
39
+ });
40
+ }
41
+
42
+ function isOption(list, text) {
43
+ for (var i = 0; i < list.options.length; i++) {
44
+ if (list.options[i].value === text) { return true; }
45
+ }
46
+ return false;
47
+ }
48
+
49
+ function suggest(input) {
50
+ var list = document.getElementById(input.getAttribute("list"));
51
+ var url = input.getAttribute("data-suggest-url");
52
+ var min = parseInt(input.getAttribute("data-suggest-min"), 10);
53
+ var term = input.value.trim();
54
+ if (!list || !url) { return; }
55
+ if (input.suggestRequest) { input.suggestRequest.abort(); }
56
+ if (term.length < (isNaN(min) ? 2 : min)) { list.textContent = ""; return; }
57
+
58
+ var request = new AbortController();
59
+ var address = new URL(url, window.location.href);
60
+ address.searchParams.set("term", term);
61
+ input.suggestRequest = request;
62
+ fetch(address, { headers: { "Accept": "application/json" }, credentials: "same-origin", signal: request.signal })
63
+ .then(function (response) { return response.ok ? response.json() : []; })
64
+ .then(function (items) {
65
+ if (input.suggestRequest === request) { fill(list, Array.isArray(items) ? items : []); }
66
+ })
67
+ .catch(function () { /* aborted or offline: keep what is shown */ });
68
+ }
69
+
70
+ document.addEventListener("input", function (event) {
71
+ var input = event.target;
72
+ if (!input.matches || !input.matches("input[list][data-suggest-url]")) { return; }
73
+ clearTimeout(input.suggestTimer);
74
+ // Picking a suggestion fires "input" too. Nothing to ask then, and filling
75
+ // the list again would open it again.
76
+ var list = document.getElementById(input.getAttribute("list"));
77
+ if (event.inputType === "insertReplacementText") { return; }
78
+ if (event.inputType === undefined && list && isOption(list, input.value)) { return; }
79
+ input.suggestTimer = setTimeout(function () { suggest(input); }, DELAY);
80
+ });
81
+ })();
@@ -1,5 +1,6 @@
1
1
  //= require jquery
2
2
  //= require foundation
3
+ //= require inline_forms/datalist_suggest
3
4
 
4
5
  // Turbo / Hotwire is intentionally NOT required into this Sprockets bundle.
5
6
  // `turbo-rails` ships only an ES-module build of turbo (`app/assets/javascripts/turbo.js`
@@ -503,7 +503,9 @@ turbo-frame {
503
503
 
504
504
  // Inline-edit validation feedback (flash.now[:error] on failed field save).
505
505
  // Shown in field_edit only; _edit deliberately skips flash to avoid session notices.
506
- .inline_forms_field_error {
506
+ // _row_error: a refused destroy / soft delete / restore, above the closed row.
507
+ .inline_forms_field_error,
508
+ .inline_forms_row_error {
507
509
  font-size: 100%;
508
510
  font-weight: normal;
509
511
  line-height: 1.3;
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The JSON behind a search field's suggestions (suggest_field_tag +
4
+ # inline_forms/datalist_suggest.js). In a controller that inherits from
5
+ # InlineFormsController:
6
+ #
7
+ # suggest_names :client, :last_name # term anywhere in the name
8
+ # suggest_names :client, :first_name, match: :start # only at the start
9
+ # suggest_names :member, :last_name, scope: ->(members) { members.where(active: true) }
10
+ #
11
+ # defines the action `autocomplete_<model>_<column>` (the name
12
+ # rails-jquery-autocomplete's `autocomplete` macro used), which answers
13
+ # GET …?term=… with a JSON array of at most `limit` (12) names: see
14
+ # InlineForms::Suggestions for `match:` (:contains, :start, :word) and the
15
+ # order. The app adds the route and the ability, as for any other action:
16
+ #
17
+ # resources :clients do
18
+ # get :autocomplete_client_last_name, on: :collection
19
+ # end
20
+ # can :autocomplete_client_last_name, Client
21
+ #
22
+ # Only names of records the user may read (`accessible_by`) when CanCan is
23
+ # on; `scope:` narrows them further, run in the controller (instance_exec)
24
+ # with the relation, and returns a relation.
25
+ module SuggestionsConcern
26
+ extend ActiveSupport::Concern
27
+
28
+ class_methods do
29
+ def suggest_names(model_name, column, match: :contains, limit: InlineForms::Suggestions::LIMIT, scope: nil)
30
+ match = InlineForms::Suggestions.check_match!(match)
31
+ InlineForms::Suggestions.check_limit!(limit)
32
+ define_method("autocomplete_#{model_name}_#{column}") do
33
+ model = model_name.to_s.camelize.constantize
34
+ names = inline_forms_suggestion_scope(model)
35
+ names = instance_exec(names, &scope) if scope
36
+ render_inline_forms_suggestions InlineForms::Suggestions.values(names, column, params[:term], match: match, limit: limit)
37
+ end
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ def inline_forms_suggestion_scope(model)
44
+ cancan_enabled? ? model.accessible_by(current_ability) : model.all
45
+ end
46
+
47
+ # A JSON string, so a serializer gem (active_model_serializers 0.9) does
48
+ # not wrap the array.
49
+ def render_inline_forms_suggestions(values)
50
+ render json: values.to_json
51
+ end
52
+ end
@@ -27,6 +27,7 @@ class InlineFormsController < ApplicationController
27
27
  include CancanConcern
28
28
  include VersionsConcern
29
29
  include FileSlotsConcern
30
+ include SuggestionsConcern
30
31
 
31
32
  before_action :getKlass
32
33
 
@@ -58,6 +59,9 @@ class InlineFormsController < ApplicationController
58
59
  @objects ||= @Klass.accessible_by(current_ability) if cancan_enabled?
59
60
  @objects ||= @Klass.all
60
61
  @objects = @objects.merge(@Klass.inline_forms_list) if @Klass.respond_to?(:inline_forms_list)
62
+ # The search box's suggestions (?suggest=1&term=…): from the same records
63
+ # as the list, so they need no route or ability of their own.
64
+ return render_search_suggestions if params.key?(:suggest) && fk_conditions.nil?
61
65
  if fk_conditions.nil? && params[:search].present? && @Klass.respond_to?(:inline_forms_search)
62
66
  @objects = @objects.merge(@Klass.inline_forms_search(params[:search]))
63
67
  end
@@ -153,6 +157,7 @@ class InlineFormsController < ApplicationController
153
157
  return head :bad_request unless html_list_flow_allowed?
154
158
 
155
159
  attributes = @inline_forms_attribute_list || @object.inline_forms_attribute_list
160
+ refusals = []
156
161
  attributes.each do | attribute, form_element |
157
162
  # Skip a row whose column is not migrated yet (model edited, migration
158
163
  # not run). Writing it would raise; the new form shows it as a pending
@@ -160,7 +165,9 @@ class InlineFormsController < ApplicationController
160
165
  next if InlineForms.attribute_pending_migration?(@object, attribute, form_element)
161
166
 
162
167
  InlineForms.assert_plain_text_column!(object: @object, attribute: attribute, form_element: form_element)
163
- send("#{form_element}_update", @object, attribute) unless form_element == :associated || (cancan_enabled? && cannot?(:read, @object, attribute))
168
+ next if form_element == :associated || (cancan_enabled? && cannot?(:read, @object, attribute))
169
+
170
+ refusals.concat(assign_field(attribute, form_element))
164
171
  end
165
172
  @parent_id = params[:parent_id]
166
173
  # See #index for the order/search/parent-fk decomposition.
@@ -171,7 +178,7 @@ class InlineFormsController < ApplicationController
171
178
  @object[foreign_key] = @parent_id
172
179
  end
173
180
 
174
- if @object.save
181
+ if refusals.empty? && @object.save
175
182
  flash.now[:success] = t("success", message: @object.class.model_name.human)
176
183
  @objects = cancan_enabled? ? @Klass.accessible_by(current_ability) : @Klass.all
177
184
  @objects = @objects.merge(@Klass.inline_forms_list) if @Klass.respond_to?(:inline_forms_list)
@@ -190,10 +197,15 @@ class InlineFormsController < ApplicationController
190
197
  end
191
198
  else
192
199
  flash.now[:header] = [ t("inline_forms.view.create_failed", model: @object.class.model_name.human) ]
193
- flash.now[:error] = @object.errors.to_a
200
+ flash.now[:error] = refusals.presence || @object.errors.to_a
194
201
  respond_to do |format|
195
202
  @object.inline_forms_attribute_list = attributes
196
- format.html { render_turbo_new }
203
+ # A refusal answers 422, as the hosts' own handlers for it did before
204
+ # the engine rescued it; a failed validation keeps its 200.
205
+ format.html do
206
+ render_turbo_new
207
+ response.status = :unprocessable_entity if refusals.any?
208
+ end
197
209
  end
198
210
  end
199
211
  end
@@ -218,7 +230,7 @@ class InlineFormsController < ApplicationController
218
230
  return
219
231
  end
220
232
  InlineForms.assert_plain_text_column!(object: @object, attribute: @attribute, form_element: @form_element)
221
- send("#{@form_element}_update", @object, @attribute)
233
+ refusals = assign_field(@attribute, @form_element)
222
234
  # Branch on the actual save result. Previously the return value of
223
235
  # `@object.save` was ignored and `field_show` was rendered
224
236
  # unconditionally from the in-memory `@object`. When a save failed
@@ -229,12 +241,12 @@ class InlineFormsController < ApplicationController
229
241
  #
230
242
  # On failure we keep the user in the edit field with their rejected
231
243
  # input visible and surface the validation errors (mirrors `create`).
232
- if @object.save
244
+ if refusals.empty? && @object.save
233
245
  respond_to do |format|
234
246
  format.html { render_turbo_field(:field_show, turbo_field_show: true) }
235
247
  end
236
248
  else
237
- flash.now[:error] = @object.errors.to_a
249
+ flash.now[:error] = refusals.presence || @object.errors.to_a
238
250
  respond_to do |format|
239
251
  format.html { render_turbo_field(:field_edit) }
240
252
  end
@@ -286,7 +298,8 @@ class InlineFormsController < ApplicationController
286
298
  @object = referenced_object
287
299
  return head :bad_request unless row_html_turbo_allowed?
288
300
 
289
- @object.soft_delete(current_user)
301
+ return render_row_refused("inline_forms.view.destroy_failed") if @object.soft_delete(current_user) == false
302
+
290
303
  respond_to do |format|
291
304
  format.html { render_row_turbo(:close) }
292
305
  end
@@ -298,7 +311,8 @@ class InlineFormsController < ApplicationController
298
311
  @object = referenced_object
299
312
  return head :bad_request unless row_html_turbo_allowed?
300
313
 
301
- @object.soft_restore
314
+ return render_row_refused("inline_forms.view.restore_failed") if @object.soft_restore == false
315
+
302
316
  respond_to do |format|
303
317
  format.html { render_row_turbo(:close) }
304
318
  end
@@ -313,7 +327,8 @@ class InlineFormsController < ApplicationController
313
327
  return head :forbidden unless destroy_permitted?
314
328
  return head :bad_request unless row_html_turbo_allowed?
315
329
 
316
- @object.destroy
330
+ return render_row_refused("inline_forms.view.destroy_failed") if @object.destroy == false
331
+
317
332
  # Capture after destroy: `.last` before destroy was the latest *update*
318
333
  # (e.g. a plain_text_area edit), so undo reified the pre-edit state.
319
334
  @undo_version = @object.versions.last
@@ -470,17 +485,37 @@ class InlineFormsController < ApplicationController
470
485
  true
471
486
  end
472
487
 
473
- # Hard-destroy gate. Generated apps restrict destroy to a Devise user with
474
- # `role?(:superadmin)` (Role model + roles HABTM). Hosts without that role
488
+ # Write one field's submitted value to @object; returns the messages of a
489
+ # refusal, empty when there is none. A check_list on a saved record writes
490
+ # its join rows here, before any validation, so a model can only refuse them
491
+ # in an association callback (before_add / before_remove) that raises. The
492
+ # association is reset: its in-memory list may hold the refused change.
493
+ #
494
+ # The send names a method after form_element. In update that comes from
495
+ # params, but field_request_permitted?(:update) has already refused (400)
496
+ # anything that is not a row of the model's attribute list; in create it
497
+ # comes from that list itself. (Brakeman does not follow params into this
498
+ # method, so brakeman.ignore no longer needs an entry for it.)
499
+ def assign_field(attribute, form_element)
500
+ send("#{form_element}_update", @object, attribute)
501
+ []
502
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved => refusal
503
+ @object.association(attribute.to_sym).reset if @object.class.reflect_on_association(attribute.to_sym)
504
+ (refusal.record&.errors&.full_messages || []).presence || [ refusal.message ]
505
+ end
506
+
507
+ # Hard-destroy gate. Generated apps restrict destroy to a Devise user who is
508
+ # the superadmin (InlineForms.superadmin?: the app's own `superadmin?`, else
509
+ # the role). Hosts without that role
475
510
  # system (e.g. the engine's test/dummy harness, or apps using a different
476
511
  # auth stack) have no gatekeeper here beyond CanCan's
477
512
  # `load_and_authorize_resource`; pre-8.1.27 this crashed with
478
513
  # `NoMethodError` on `nil.role?` instead of deciding either way.
479
514
  def destroy_permitted?
480
515
  user = respond_to?(:current_user, true) ? current_user : nil
481
- return true unless user.respond_to?(:role?)
516
+ return true unless user.respond_to?(:superadmin?) || user.respond_to?(:role?)
482
517
 
483
- user.role?(:superadmin)
518
+ InlineForms.superadmin?(user)
484
519
  end
485
520
 
486
521
  # Every reify on the revert path goes through here. +unversioned_attributes:
@@ -660,6 +695,22 @@ class InlineFormsController < ApplicationController
660
695
  render template, layout: layout
661
696
  end
662
697
 
698
+ # The model refused a destroy, soft delete or soft restore: the row as it is
699
+ # in the database, with the reason. +fallback+ is for a model that gave none.
700
+ def render_row_refused(fallback)
701
+ @inline_forms_row_errors = @object.errors.to_a.presence ||
702
+ [ t(fallback, model: @object.class.model_name.human) ]
703
+ @object = referenced_object
704
+ @inline_forms_turbo_row = true
705
+ respond_to do |format|
706
+ format.html do
707
+ render "inline_forms/row_close",
708
+ layout: turbo_frame_request? ? "turbo_rails/frame" : "inline_forms",
709
+ status: 422
710
+ end
711
+ end
712
+ end
713
+
663
714
  def render_row_turbo_destroyed
664
715
  @inline_forms_turbo_row = true
665
716
  layout = turbo_frame_request? ? "turbo_rails/frame" : "inline_forms"
@@ -733,6 +784,17 @@ class InlineFormsController < ApplicationController
733
784
  render "inline_forms/new_record", layout: associated_list_frame_layout
734
785
  end
735
786
 
787
+ # The engine's search box asks the list for suggestions when the model
788
+ # declares `inline_forms_search_on …, suggest: …`; else there are none (404).
789
+ def render_search_suggestions
790
+ options = @Klass.respond_to?(:inline_forms_suggestions) && @Klass.inline_forms_suggestions
791
+ return head(:not_found) unless options
792
+
793
+ render_inline_forms_suggestions InlineForms::Suggestions.values(
794
+ @objects, options[:on], params[:term], match: options[:match], limit: options[:limit]
795
+ )
796
+ end
797
+
736
798
  # Nested +index+ / cancel / +create+ HTML inside a parent-associated +<turbo-frame>+.
737
799
  def render_nested_associated_list_html
738
800
  if turbo_frame_request? && nested_list_frame_id?(params[:update])
@@ -0,0 +1,20 @@
1
+ # A text field with the browser's own suggestion list (<datalist>), filled by
2
+ # app/assets/javascripts/inline_forms/datalist_suggest.js from `url` (JSON)
3
+ # while the user types. Replaces rails-jquery-autocomplete's
4
+ # `autocomplete_field_tag`:
5
+ #
6
+ # <%= suggest_field_tag "search", params[:search], autocomplete_member_last_name_members_path, placeholder: "achternaam" %>
7
+ #
8
+ # Two fields with the same name on one page: give each its own `list:` id.
9
+ #
10
+ # The same module, with the same name, as the copies some apps have in their
11
+ # own app/helpers: an app's file wins over this one.
12
+ module DatalistSuggestHelper
13
+ def suggest_field_tag(name, value, url, options = {})
14
+ options = options.dup
15
+ list_id = options.delete(:list) || "#{name.to_s.gsub(/[^-a-zA-Z0-9:.]/, '_')}_suggestions"
16
+ data = (options.delete(:data) || {}).merge(suggest_url: url)
17
+ field = text_field_tag(name, value, options.merge(list: list_id, autocomplete: "off", data: data))
18
+ safe_join([ field, content_tag(:datalist, "", id: list_id) ])
19
+ end
20
+ end
@@ -4,7 +4,13 @@
4
4
  <%= link_to tag.i(class: "fi-x"), request.path, title: t("inline_forms.search.reset"), class: "button expanded inline_forms_model_top_bar_buttons" %>
5
5
  </div>
6
6
  <div class="large-6 small-6 columns">
7
- <%= text_field_tag :search, params[:search], placeholder: t("inline_forms.search.placeholder"), id: "input_search" %>
7
+ <%# With `inline_forms_search_on …, suggest: …` the list itself answers %>
8
+ <%# the suggestions (index with ?suggest=1&term=…). %>
9
+ <% if @Klass.respond_to?(:inline_forms_suggestions) && @Klass.inline_forms_suggestions %>
10
+ <%= suggest_field_tag :search, params[:search], "#{request.path}?suggest=1", placeholder: t("inline_forms.search.placeholder"), id: "input_search", list: "input_search_suggestions" %>
11
+ <% else %>
12
+ <%= text_field_tag :search, params[:search], placeholder: t("inline_forms.search.placeholder"), id: "input_search" %>
13
+ <% end %>
8
14
  </div>
9
15
  <div class="large-3 small-3 columns">
10
16
  <%= submit_tag t("inline_forms.search.submit"), class: "button expanded inline_forms_model_top_bar_buttons" %>
@@ -9,7 +9,7 @@
9
9
  </div>
10
10
  <div class="top-bar-right">
11
11
  <ul class="dropdown menu" data-dropdown-menu>
12
- <% if current_user.role?(:admin) || current_user.role?(:superadmin) %>
12
+ <% if current_user.role?(:admin) || InlineForms.superadmin?(current_user) %>
13
13
  <li>
14
14
  <a href="#"><%= t 'common.more' %></a>
15
15
  <ul class="menu">
@@ -2,6 +2,11 @@
2
2
  <% object = local_assigns[:object] || @object -%>
3
3
  <% inline_forms_turbo_row = local_assigns.fetch(:inline_forms_turbo_row, @inline_forms_turbo_row) -%>
4
4
  <turbo-frame id="<%= update_span %>">
5
+ <% if @inline_forms_row_errors.present? %>
6
+ <div class="flash error inline_forms_row_error" role="alert">
7
+ <ul><% @inline_forms_row_errors.each do |message| %><li><%= message %></li><% end %></ul>
8
+ </div>
9
+ <% end %>
5
10
  <div class="row odd top-level">
6
11
  <%= render partial: "inline_forms/close",
7
12
  locals: {
@@ -20,11 +20,7 @@ module InlineForms
20
20
  def check_list_edit(object, attribute)
21
21
  object.send(attribute).build if object.send(attribute).empty?
22
22
  klass = object.send(attribute).first.class
23
- values = cancan_enabled? ? klass.accessible_by(current_ability) : klass.all
24
- # check_list has always applied the list scope's filter (a where in
25
- # inline_forms_list hides records here); the order is DropdownOrder's.
26
- values = values.merge(klass.inline_forms_list.unscope(:order)) if klass.respond_to?(:inline_forms_list)
27
- values = InlineForms::DropdownOrder.apply(values)
23
+ values = InlineForms::DropdownOrder.apply(check_list_offered(klass))
28
24
  out = ''
29
25
  values.each do | item |
30
26
  out << "<div class='row #{cycle('odd', 'even')}'>"
@@ -35,9 +31,29 @@ module InlineForms
35
31
  out.html_safe
36
32
  end
37
33
 
34
+ # The records the check list offers; check_list_update accepts no others.
35
+ def check_list_offered(klass)
36
+ values = cancan_enabled? ? klass.accessible_by(current_ability) : klass.all
37
+ # check_list has always applied the list scope's filter (a where in
38
+ # inline_forms_list hides records here); the order is DropdownOrder's.
39
+ values = values.merge(klass.inline_forms_list.unscope(:order)) if klass.respond_to?(:inline_forms_list)
40
+ values
41
+ end
42
+
38
43
  def check_list_update(object, attribute)
39
44
  params[attribute] ||= {}
40
- object.send(attribute.to_s.singularize + '_ids=', params[attribute].keys)
45
+ ids = attribute.to_s.singularize + '_ids'
46
+ posted = params[attribute].keys.map(&:to_s)
47
+ held = object.send(ids).map(&:to_s)
48
+ offered = check_list_offered(object.class.reflect_on_association(attribute.to_sym).klass).map { |item| item.id.to_s }
49
+ # A hidden record is also a refused one. Nothing is assigned: on a saved
50
+ # record that would write the join rows at once.
51
+ if (posted - offered - held).any?
52
+ InlineForms::RefusedValues.add(object, attribute)
53
+ return
54
+ end
55
+ # Records the user was not shown stay: not ticked is not unticked.
56
+ object.send(ids + '=', posted | (held - offered))
41
57
  object.touch unless object.new_record? # Check for new_record needed for Rails > 3; TODO we should have a flag to turn this on or of.
42
58
  end
43
59
  INLINE_FORMS_FORM_ELEMENT
@@ -20,12 +20,7 @@ module InlineForms
20
20
  presentation = "_presentation"
21
21
  presentation = "_dropdown_presentation" if attr.respond_to? "_dropdown_presentation"
22
22
  klass = object.send(attribute).class
23
- if cancan_enabled?
24
- values = klass.accessible_by(current_ability)
25
- else
26
- values = klass.all
27
- end
28
- values = InlineForms::DropdownOrder.apply(values)
23
+ values = InlineForms::DropdownOrder.apply(dropdown_offered(klass))
29
24
  options_disabled = nil
30
25
  if klass.method_defined? :disabled_for_dropdown?
31
26
  # loads values; collection_select below reuses the loaded records
@@ -42,6 +37,17 @@ module InlineForms
42
37
  )
43
38
  end
44
39
 
40
+ # The records the dropdown offers; dropdown_update accepts no others.
41
+ def dropdown_offered(klass)
42
+ cancan_enabled? ? klass.accessible_by(current_ability) : klass.all
43
+ end
44
+
45
+ # An option shown disabled (disabled_for_dropdown?) is not offered either.
46
+ def dropdown_offers?(klass, value)
47
+ record = dropdown_offered(klass).find_by(klass.primary_key => value.to_s)
48
+ record.present? && !(record.respond_to?(:disabled_for_dropdown?) && record.disabled_for_dropdown?)
49
+ end
50
+
45
51
  def dropdown_update(object, attribute)
46
52
  # Inline edit posts the value under the leading-underscore wrapper key
47
53
  # (`params[:_apartment][:owner_id]`); top-level create through a
@@ -51,8 +57,16 @@ module InlineForms
51
57
  # walks do not raise NoMethodError on nil[:owner_id].
52
58
  scope = params[('_' + object.class.to_s.underscore).to_sym]
53
59
  return if scope.blank?
54
- foreign_key = object.class.reflect_on_association(attribute.to_sym).options[:foreign_key] || attribute.to_s.foreign_key.to_sym
55
- object[foreign_key] = scope[attribute.to_s.foreign_key.to_sym]
60
+ reflection = object.class.reflect_on_association(attribute.to_sym)
61
+ foreign_key = reflection.options[:foreign_key] || attribute.to_s.foreign_key.to_sym
62
+ value = scope[attribute.to_s.foreign_key.to_sym]
63
+ # A hidden option is also a refused value. The value the record already
64
+ # has may stay. It is assigned all the same, so that a model that refuses
65
+ # it says so in its own words; RefusedValues keeps it from being saved.
66
+ if value.present? && value.to_s != object[foreign_key].to_s && !dropdown_offers?(reflection.klass, value)
67
+ InlineForms::RefusedValues.add(object, attribute)
68
+ end
69
+ object[foreign_key] = value
56
70
  end
57
71
 
58
72
  def dropdown_info(object, attribute)
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module InlineForms
4
+ # A field got a value it did not offer (a dropdown or check_list id outside
5
+ # the records the user may read). The record stays invalid while that value
6
+ # is on it, whoever saves it: the engine's create / update, or a host's own.
7
+ #
8
+ # The model's own validations run first, so a model that refuses the value
9
+ # with a message of its own keeps that message; :inclusion is only added
10
+ # when the attribute, or its foreign key, has no error yet.
11
+ module RefusedValues
12
+ def self.add(object, attribute)
13
+ object.extend(self)
14
+ object.inline_forms_refused_values << attribute.to_sym
15
+ end
16
+
17
+ def inline_forms_refused_values
18
+ @inline_forms_refused_values ||= Set.new
19
+ end
20
+
21
+ def valid?(...)
22
+ super
23
+ inline_forms_refused_values.each do |attribute|
24
+ foreign_key = self.class.reflect_on_association(attribute)&.foreign_key
25
+ next if errors.include?(attribute) || (foreign_key && errors.include?(foreign_key.to_sym))
26
+
27
+ errors.add(attribute, :inclusion)
28
+ end
29
+ errors.empty?
30
+ end
31
+ alias_method :validate, :valid?
32
+ end
33
+ end
@@ -4,6 +4,17 @@ module InlineForms
4
4
  # Opt-in list search for inline_forms index views. Models declare searchable
5
5
  # columns with `inline_forms_search_on :col, …`; only those models get the
6
6
  # engine's generic search box (or a bespoke `_<model>_search` partial).
7
+ #
8
+ # `suggest:` gives that search box suggestions while the user types (the
9
+ # browser's own list, see InlineForms::Suggestions), from the records the
10
+ # user may see in the list:
11
+ #
12
+ # inline_forms_search_on :name, :email, suggest: true # from both columns
13
+ # inline_forms_search_on :name, :email, suggest: { on: :name, match: :start, limit: 8 }
14
+ #
15
+ # `on:` (default: the search columns), `match:` (:contains, the default,
16
+ # :start or :word) and `limit:` (12). The search itself still finds the
17
+ # text anywhere in any search column.
7
18
  module Searchable
8
19
  extend ActiveSupport::Concern
9
20
 
@@ -12,7 +23,12 @@ module InlineForms
12
23
  @inline_forms_searchable == true
13
24
  end
14
25
 
15
- def inline_forms_search_on(*columns)
26
+ # nil, or { on: [columns], match:, limit: }.
27
+ def inline_forms_suggestions
28
+ @inline_forms_suggestions
29
+ end
30
+
31
+ def inline_forms_search_on(*columns, suggest: nil)
16
32
  cols = columns.flatten.map(&:to_s)
17
33
  if cols.empty?
18
34
  raise ArgumentError, "inline_forms_search_on requires at least one column"
@@ -20,12 +36,35 @@ module InlineForms
20
36
 
21
37
  @inline_forms_searchable = true
22
38
  @inline_forms_search_columns = cols
39
+ @inline_forms_suggestions = inline_forms_suggest_options(suggest, cols)
23
40
  model = self
24
41
  scope :inline_forms_search, ->(q) {
25
42
  where(model.inline_forms_search_clause, q: "%#{sanitize_sql_like(q.to_s)}%")
26
43
  }
27
44
  end
28
45
 
46
+ def inline_forms_suggest_options(suggest, search_columns)
47
+ return nil if suggest.nil? || suggest == false
48
+
49
+ options = suggest == true ? {} : suggest
50
+ unless options.is_a?(Hash)
51
+ raise ArgumentError, "inline_forms_search_on suggest: takes true or a Hash (on:, match:, limit:), not #{suggest.inspect}"
52
+ end
53
+
54
+ unknown = options.keys.map(&:to_sym) - %i[on match limit]
55
+ raise ArgumentError, "inline_forms_search_on suggest: unknown option #{unknown.first.inspect}" if unknown.any?
56
+
57
+ options = options.transform_keys(&:to_sym)
58
+ on = Array(options.fetch(:on, search_columns)).map(&:to_s)
59
+ raise ArgumentError, "inline_forms_search_on suggest: on: needs at least one column" if on.empty?
60
+
61
+ {
62
+ on: on.freeze,
63
+ match: Suggestions.check_match!(options.fetch(:match, :contains)),
64
+ limit: Suggestions.check_limit!(options.fetch(:limit, Suggestions::LIMIT))
65
+ }.freeze
66
+ end
67
+
29
68
  # Built on the first search, not in inline_forms_search_on: quoting
30
69
  # needs a database connection, and the class body runs whenever the
31
70
  # model loads (eager loading, assets:precompile without a database).
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module InlineForms
4
+ # Text suggestions for a search field: the values of one or more columns
5
+ # that match what the user typed, for the browser's own <datalist>
6
+ # (suggest_field_tag + inline_forms/datalist_suggest.js). Used by the
7
+ # controller macro `suggest_names` (SuggestionsConcern) and by the engine's
8
+ # search box for a model with `inline_forms_search_on …, suggest: …`.
9
+ #
10
+ # How a value matches the term (`match:`), case ignored, % and _ in the term
11
+ # taken literally:
12
+ #
13
+ # :contains anywhere in the value ("ma" finds Martina, Tinamart, Tima)
14
+ # :start at the start of the value ("ma" finds Martina only)
15
+ # :word at the start of any word ("ma" finds Martina, Anna Maria)
16
+ #
17
+ # The answer: at most `limit` values, each once (compared stripped and in any
18
+ # case, the first in A-Z order kept), in case-insensitive A-Z order. An empty
19
+ # term gives [].
20
+ module Suggestions
21
+ MATCHES = %i[contains start word].freeze
22
+ LIMIT = 12
23
+
24
+ module_function
25
+
26
+ # Raises ArgumentError for an unknown match; returns it as a Symbol.
27
+ def check_match!(match)
28
+ match = match.to_sym
29
+ return match if MATCHES.include?(match)
30
+
31
+ raise ArgumentError, "match: must be one of #{MATCHES.map(&:inspect).join(', ')}, not #{match.inspect}"
32
+ end
33
+
34
+ def check_limit!(limit)
35
+ return limit if limit.is_a?(Integer) && limit.positive?
36
+
37
+ raise ArgumentError, "limit: must be a positive Integer, not #{limit.inspect}"
38
+ end
39
+
40
+ # relation: what the user may see (already `accessible_by`, scoped, …).
41
+ def values(relation, columns, term, match: :contains, limit: LIMIT)
42
+ match = check_match!(match)
43
+ limit = check_limit!(limit)
44
+ term = term.to_s.strip
45
+ return [] if term.empty?
46
+
47
+ columns = Array(columns)
48
+ found = columns.flat_map { |column| column_values(relation, column, term, match, limit) }
49
+ found = found.map(&:to_s).reject(&:empty?)
50
+ # One column: the database's order (its collation, e.g. accents with
51
+ # their letter). Several: merged here.
52
+ found = found.sort_by { |value| [ value.downcase, value ] } if columns.size > 1
53
+ found.uniq(&:downcase).first(limit)
54
+ end
55
+
56
+ # SELECT MIN(TRIM(value)) … GROUP BY LOWER(TRIM(value)) ORDER BY that:
57
+ # one row per value as the user sees it, so the limit counts distinct
58
+ # names ('Adriana', 'adriana ' and 'Adriana' are one). A plain DISTINCT
59
+ # would keep them apart (case, and MySQL's NO PAD collations keep a
60
+ # trailing space) and fill the limit with them. Valid under MySQL's
61
+ # ONLY_FULL_GROUP_BY and in PostgreSQL. reorder drops a default or list
62
+ # order the relation brings.
63
+ def column_values(relation, column, term, match, limit)
64
+ model = relation.model
65
+ attribute = model.arel_table[column.to_s]
66
+ lowered = Arel::Nodes::NamedFunction.new("LOWER", [ attribute ])
67
+ key = Arel::Nodes::NamedFunction.new("LOWER", [ Arel::Nodes::NamedFunction.new("TRIM", [ attribute ]) ])
68
+ condition = patterns(model, term, match).map { |pattern|
69
+ lowered.matches(Arel::Nodes::NamedFunction.new("LOWER", [ Arel::Nodes.build_quoted(pattern) ]), "\\", true)
70
+ }.reduce(:or)
71
+ relation.where(condition).unscope(:select).group(key).reorder(key.asc).limit(limit)
72
+ .pluck(Arel::Nodes::Min.new([ Arel::Nodes::NamedFunction.new("TRIM", [ attribute ]) ]))
73
+ end
74
+
75
+ def patterns(model, term, match)
76
+ escaped = model.sanitize_sql_like(term, "\\")
77
+ case match
78
+ when :contains then [ "%#{escaped}%" ]
79
+ when :start then [ "#{escaped}%" ]
80
+ when :word then [ "#{escaped}%", "% #{escaped}%" ]
81
+ end
82
+ end
83
+ end
84
+ end
@@ -1,5 +1,5 @@
1
1
  # -*- encoding : utf-8 -*-
2
2
 
3
3
  module InlineForms
4
- VERSION = "8.1.76"
4
+ VERSION = "8.1.79"
5
5
  end
data/lib/inline_forms.rb CHANGED
@@ -9,8 +9,10 @@ require "inline_forms/schema_preview"
9
9
  require "inline_forms/schema_apply"
10
10
  require "inline_forms/schema_label"
11
11
  require "inline_forms/form_element_from_callee"
12
+ require "inline_forms/suggestions"
12
13
  require "inline_forms/searchable"
13
14
  require "inline_forms/dropdown_order"
15
+ require "inline_forms/refused_values"
14
16
  require "inline_forms/archived_form_elements"
15
17
  require "inline_forms/form_element_registry"
16
18
  require "inline_forms/form_elements"
@@ -65,6 +67,15 @@ module InlineForms
65
67
  end
66
68
  end
67
69
 
70
+ # Is this user the superadmin? An app that has its own answer
71
+ # (`User#superadmin?`, e.g. only user 1) is asked first; otherwise it is
72
+ # whoever holds the role. A user class with neither is not a superadmin.
73
+ def self.superadmin?(user)
74
+ return !!user.superadmin? if user.respond_to?(:superadmin?)
75
+
76
+ user.respond_to?(:role?) && !!user.role?(:superadmin)
77
+ end
78
+
68
79
  # The cross-record trash page (superadmin). One line in routes.rb:
69
80
  # InlineForms.draw_file_trash_routes(self)
70
81
  def self.draw_file_trash_routes(router)
@@ -34,6 +34,8 @@ en:
34
34
  close: close
35
35
  add_new: make a new %{model}
36
36
  create_failed: Could not create %{model}.
37
+ destroy_failed: Could not delete %{model}.
38
+ restore_failed: Could not restore %{model}.
37
39
  undo: undo
38
40
  restore: restore
39
41
  trash: trash
@@ -34,6 +34,8 @@ nl:
34
34
  close: sluiten
35
35
  add_new: Maak een nieuw %{model}
36
36
  create_failed: Kan %{model} niet aanmaken.
37
+ destroy_failed: Kan %{model} niet verwijderen.
38
+ restore_failed: Kan %{model} niet terugzetten.
37
39
  undo: terughalen
38
40
  restore: terugzetten
39
41
  trash: weggooien
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: inline_forms
3
3
  version: !ruby/object:Gem::Version
4
- version: 8.1.76
4
+ version: 8.1.79
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ace Suares
@@ -103,6 +103,7 @@ files:
103
103
  - app/assets/fonts/opensans-v44-latin-italic.woff2
104
104
  - app/assets/fonts/opensans-v44-latin-regular.woff2
105
105
  - app/assets/images/inline_forms/glass_plate.gif
106
+ - app/assets/javascripts/inline_forms/datalist_suggest.js
106
107
  - app/assets/javascripts/inline_forms/inline_forms.js
107
108
  - app/assets/stylesheets/inline_forms/_foundation_icons.scss
108
109
  - app/assets/stylesheets/inline_forms/_theme.scss
@@ -112,10 +113,12 @@ files:
112
113
  - app/assets/stylesheets/inline_forms_fonts.css.erb
113
114
  - app/controllers/concerns/cancan_concern.rb
114
115
  - app/controllers/concerns/file_slots_concern.rb
116
+ - app/controllers/concerns/suggestions_concern.rb
115
117
  - app/controllers/concerns/versions_concern.rb
116
118
  - app/controllers/inline_forms/file_trash_controller.rb
117
119
  - app/controllers/inline_forms_application_controller.rb
118
120
  - app/controllers/inline_forms_controller.rb
121
+ - app/helpers/datalist_suggest_helper.rb
119
122
  - app/helpers/inline_forms_file_trash_helper.rb
120
123
  - app/helpers/inline_forms_helper.rb
121
124
  - app/models/concerns/inline_forms/soft_deletable.rb
@@ -255,11 +258,13 @@ files:
255
258
  - lib/inline_forms/form_elements/text_field_helper.rb
256
259
  - lib/inline_forms/form_elements/time_helper.rb
257
260
  - lib/inline_forms/gem_files.rb
261
+ - lib/inline_forms/refused_values.rb
258
262
  - lib/inline_forms/schema_apply.rb
259
263
  - lib/inline_forms/schema_intent.rb
260
264
  - lib/inline_forms/schema_label.rb
261
265
  - lib/inline_forms/schema_preview.rb
262
266
  - lib/inline_forms/searchable.rb
267
+ - lib/inline_forms/suggestions.rb
263
268
  - lib/inline_forms/tabs.rb
264
269
  - lib/inline_forms/turbo_tabs_builder.rb
265
270
  - lib/inline_forms/version.rb