glib-web 8.2.1 → 8.3.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5d088ec6d58820618a3aa36589e438d615e44200e7a0376eddedac20a721d89b
4
- data.tar.gz: 982bb5e1cefe4f064f95e7c8a8407c0a5fa9562bd205610a7e1a04d29fe64810
3
+ metadata.gz: eacabf1b562907ccace552b122acc1f7b8a6e42e8b36c2b53e6cc7d901f0e4f8
4
+ data.tar.gz: add189a2ea6958b00bd5a730bc770cc02cdd661b1e22f9504718d0c7d6d558d9
5
5
  SHA512:
6
- metadata.gz: 569d870e43d67adccbad29c44293d82fe6a0fd77c4d824e395b7a63d2817a605617a2c64cad62814363cf983f7121ea9c3bf9101231fcffda067c459a62efe50
7
- data.tar.gz: b51321994361436a14f3bcc646d4c1aa46f126d345e31e2fd9aec5d945271c92fe7fed8e8443bc2b40ccf9a06574b20a6e9b7a42ba1ffe86b324ee6e72f018ab
6
+ metadata.gz: 84bdf2d49d1c73a4d83237a4cdcf3435829ddf9ada881b9fa05b1146c163748c20e1bded132b245c4f552cb2ab1ab3c2bf0baf1e36827868e18ddb1bd5ceba00
7
+ data.tar.gz: 288b0d4b03afbded4f9cdece339b87e72bdc2e6a74a15b86c48b46696fa5d7921bec97dcd708cb2d5e33b904922c581818b190c121787d9057c28a13eac66395
@@ -37,11 +37,15 @@ module Glib::Auth
37
37
  # Override
38
38
  def policy(record, policy_name = nil, context = nil)
39
39
  policy_name ||= record
40
+ # The record is part of the key: within one request, a second authorize of
41
+ # another record under the same policy name must not reuse the first record's
42
+ # instance (glib-web#524).
43
+ key = [policy_name, record]
40
44
 
41
45
  @__pundit_policies ||= {}
42
- if @__pundit_policies[policy_name]
43
- @__pundit_policies[policy_name].context = context
44
- return @__pundit_policies[policy_name]
46
+ if (cached = @__pundit_policies[key])
47
+ cached.context = context
48
+ return cached
45
49
  end
46
50
 
47
51
  # if policy_name.is_a?(Symbol) && policy_name.to_s.ends_with?('_admin')
@@ -57,7 +61,7 @@ module Glib::Auth
57
61
  policy_instance = policy_class.new(current_user, record, policy_name, self, request, params)
58
62
  policy_instance.context = context
59
63
 
60
- @__pundit_policies[policy_name] = policy_instance
64
+ @__pundit_policies[key] = policy_instance
61
65
  end
62
66
 
63
67
  # Expose protected method
@@ -0,0 +1,131 @@
1
+ module Glib::Params
2
+ # Multi-column table sorting driven by one request param, e.g.
3
+ # `sort=sent-desc,title-asc`: order by sent descending, ties by title.
4
+ #
5
+ # Clicking a header makes that column the PRIMARY key (flipping its
6
+ # direction if it was already sorted, else ascending) and keeps the earlier
7
+ # keys behind it as tie-breakers, most recent first, up to +max+ columns
8
+ # (the oldest falls off). So "sort A, then sort B" orders by B, then A: the
9
+ # param's column order IS the sort, and is never re-sorted.
10
+ #
11
+ # The param comes from the URL, so parsing degrades quietly, like
12
+ # Glib::Params::Allowlist on a GET: a key outside +allowed+, a direction
13
+ # other than asc/desc, and a repeated key (the first occurrence wins) are
14
+ # dropped rather than raised. The direction is split off at the LAST '-',
15
+ # so a hyphenated key survives. Keys stay strings and a direction becomes a
16
+ # symbol only through the DIRECTIONS lookup, so input never mints a symbol.
17
+ #
18
+ # Route- and model-agnostic: it parses, toggles and serialises the param,
19
+ # yields Arel orderings (#arel_orderings) and sorts in-memory rows
20
+ # (#sort_rows). Calling `order` and building URLs stay with the caller; the
21
+ # header side is Glib::JsonUi::SortHelper#glib_sort_header.
22
+ #
23
+ # NULLs (nil) sort last in both directions, in SQL and in Ruby: a missing
24
+ # value is neither smallest nor largest, and flipping the direction must
25
+ # not move blanks to the top.
26
+ class MultiColumnSort
27
+ MAX_COLUMNS = 3
28
+ DIRECTIONS = { 'asc' => :asc, 'desc' => :desc }.freeze
29
+
30
+ Order = Struct.new(:key, :direction)
31
+
32
+ attr_reader :orders
33
+
34
+ # +default+ is a param string used when +param+ is blank, e.g. 'sent-desc'
35
+ # so the header shows its arrow on first load. Only BLANK falls back: a
36
+ # present param whose tokens are all invalid yields no sort at all, not
37
+ # the default (as in mapping-web's class this one replaces).
38
+ def initialize(param, allowed:, default: nil, max: MAX_COLUMNS)
39
+ @allowed = allowed.map(&:to_s)
40
+ @max = max
41
+ @orders = parse(param.presence || default)
42
+ end
43
+
44
+ def present?
45
+ orders.any?
46
+ end
47
+
48
+ # :asc or :desc, nil when +key+ is not sorted.
49
+ def direction(key)
50
+ find(key)&.direction
51
+ end
52
+
53
+ # 1-based precedence of +key+, nil when the column is not sorted.
54
+ def priority(key)
55
+ index = orders.index { |order| order.key == key.to_s }
56
+ index && (index + 1)
57
+ end
58
+
59
+ # The param a click on +key+'s header should produce.
60
+ def toggled_param(key)
61
+ key = key.to_s
62
+ clicked = Order.new(key, direction(key) == :asc ? :desc : :asc)
63
+ serialize([clicked] + orders.reject { |order| order.key == key })
64
+ end
65
+
66
+ def to_param
67
+ serialize(orders)
68
+ end
69
+
70
+ # Orderings for `relation.order(*...)`, in precedence order, each NULLS
71
+ # LAST. The block maps a key to one Arel node or an array of them
72
+ # (attributes, Groupings around a subquery); every node of a key takes
73
+ # that key's direction. Append the caller's own tie-breaker after them.
74
+ # Array.wrap, not Array(): an Arel attribute is a Struct, which Array()
75
+ # would split into its fields.
76
+ def arel_orderings
77
+ orders.flat_map do |order|
78
+ Array.wrap(yield(order.key)).map { |node| node.public_send(order.direction).nulls_last }
79
+ end
80
+ end
81
+
82
+ # Sorts Ruby rows (hashes keyed by symbol) by the orders, each key in its
83
+ # own direction, nil last, then by +tie_breaker+ ascending. Text compares
84
+ # case-insensitively.
85
+ def sort_rows(rows, tie_breaker:)
86
+ rows.sort do |a, b|
87
+ decided = orders.lazy.map { |order| directed_compare(a, b, order) }.find(&:nonzero?)
88
+ decided || compare(a[tie_breaker], b[tie_breaker])
89
+ end
90
+ end
91
+
92
+ private
93
+ def parse(param)
94
+ entries = param.to_s.split(',').filter_map do |entry|
95
+ key, _, direction = entry.strip.rpartition('-')
96
+ symbol = DIRECTIONS[direction]
97
+ Order.new(key, symbol) if symbol && @allowed.include?(key)
98
+ end
99
+ entries.uniq(&:key).first(@max)
100
+ end
101
+
102
+ def serialize(orders)
103
+ orders.first(@max).map { |order| "#{order.key}-#{order.direction}" }.join(',')
104
+ end
105
+
106
+ def find(key)
107
+ orders.find { |order| order.key == key.to_s }
108
+ end
109
+
110
+ # nil sorts last in BOTH directions, matching #arel_orderings' NULLS LAST.
111
+ # Row keys are symbols the CALLER built; the allowlisted key is looked
112
+ # up by `to_sym` only after it matched +allowed+, never raw input.
113
+ def directed_compare(a, b, order)
114
+ left = a[order.key.to_sym]
115
+ right = b[order.key.to_sym]
116
+ return 0 if left.nil? && right.nil?
117
+ return 1 if left.nil?
118
+ return -1 if right.nil?
119
+
120
+ result = compare(left, right)
121
+ order.direction == :desc ? -result : result
122
+ end
123
+
124
+ # Text compares case-insensitively; incomparable values tie.
125
+ def compare(left, right)
126
+ left = left.downcase if left.is_a?(String)
127
+ right = right.downcase if right.is_a?(String)
128
+ (left <=> right) || 0
129
+ end
130
+ end
131
+ end
@@ -10,8 +10,6 @@ module Glib
10
10
  end
11
11
 
12
12
  def json_ui_garage
13
- init_orders
14
-
15
13
  @path_prefix = 'json_ui/garage'
16
14
 
17
15
  @__glib_head_code =<<-eos
@@ -83,41 +81,5 @@ module Glib
83
81
 
84
82
  render template: 'json_ui/garage/empty'
85
83
  end
86
-
87
- def init_orders
88
- @order_headings = {}
89
- @orders = params[:orders] || []
90
- @orders.each do |order|
91
- prop_name, direction = order.split('-')
92
- index_order(prop_name, direction)
93
- end
94
- end
95
-
96
- def index_order(prop_name, direction)
97
- # In a real app, apply ordering to the model. For example:
98
- # @users = @users.order(prop_name => direction)
99
-
100
- # Garage example
101
- @order_headings[prop_name] = direction
102
- end
103
-
104
- def reversed_order(order)
105
- order.to_sym == :asc ? :desc : :asc
106
- end
107
-
108
- def reversed_order_params(prop_name)
109
- prop_value = :asc
110
- remaining = @orders.reject do |o|
111
- tuple = o.split('-')
112
- if tuple.first == prop_name.to_s
113
- prop_value = reversed_order(tuple.second)
114
- true
115
- end
116
- end
117
- # Sort the params to produce predictable URLs which are useful for SEO
118
- (["#{prop_name}-#{prop_value}"] + remaining).sort
119
- end
120
-
121
- helper_method :reversed_order_params
122
84
  end
123
85
  end
@@ -3,6 +3,7 @@ class Glib::JsonUi::ActionBuilder
3
3
  class Copy < Action
4
4
  string :text
5
5
  action :onCopy
6
+ action :onFailure
6
7
  end
7
8
 
8
9
  class Custom < Action
@@ -0,0 +1,30 @@
1
+ module Glib
2
+ module JsonUi
3
+ module SortHelper
4
+ # A clickable table header cell that sorts server-side through a
5
+ # Glib::Params::MultiColumnSort. A click makes this column the primary
6
+ # sort and keeps the others behind it. The text is the label, an arrow
7
+ # on a sorted column and, when more than one column is sorted, its
8
+ # 1-based precedence (`Type ↑1`, `Date ↓2`).
9
+ #
10
+ # +url+ receives the toggled param string and returns the URL to open,
11
+ # so the helper stays route-agnostic. Drop the page param there so a
12
+ # re-sort starts on page 1:
13
+ #
14
+ # section.header cellViews: ->(header) do
15
+ # glib_sort_header header, sort: sort, key: 'name', label: 'Name',
16
+ # url: ->(param) { current_url(sort: param, page: nil) }
17
+ # end
18
+ def glib_sort_header(header, sort:, key:, label:, url:)
19
+ arrow = { asc: ' ↑', desc: ' ↓' }[sort.direction(key)]
20
+ priority = sort.priority(key) if sort.orders.size > 1
21
+
22
+ header.label \
23
+ text: "#{label}#{arrow}#{priority}",
24
+ onClick: ->(action) do
25
+ action.windows_open url: url.call(sort.toggled_param(key))
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
@@ -153,8 +153,20 @@ module Glib
153
153
  def _undo_soft_destroy
154
154
  return unless deleted? # Already restored. Stop here to avoid redundant work and infinite recursion on circular associations.
155
155
 
156
- undo_soft_destroy_associated_records
156
+ # Read the bound from the database rather than trusting the in-memory attribute: a stale
157
+ # in-memory flag (or a concurrent undo that already restored this row) must be caught here,
158
+ # because a nil bound would match every row of the association. Reading the stored value also
159
+ # compares like with like — the children's timestamps as they were written — with no reliance
160
+ # on attribute casting matching the column's precision.
161
+ bound = stored_deleted_at
162
+ return if bound.nil?
163
+
164
+ # Restore this record BEFORE walking its children, mirroring `_soft_destroy` (which marks
165
+ # itself first): the walk below queries fresh instances, so with children first a cycle would
166
+ # reload this still-deleted record and recurse without end.
157
167
  update_columns(deleted_at: nil) # rubocop:disable Rails/SkipsModelValidations
168
+
169
+ undo_soft_destroy_associated_records(bound)
158
170
  end
159
171
 
160
172
  private
@@ -172,6 +184,10 @@ module Glib
172
184
  raise ActiveRecord::ConfigurationError, "Hard deletion is not allowed for #{self.class.name} (error #{code})"
173
185
  end
174
186
 
187
+ # Serves the destroy path only. The cached `public_send` read is what the destroy needs
188
+ # (it must reuse loaded instances so `marked_for_destruction` survives); the undo walk
189
+ # reads through the target's default scope and would miss every row a cascade deleted,
190
+ # so it has its own read in `undo_soft_destroy_associated_records`.
175
191
  def process_soft_deletable_relationship(relationship, &block)
176
192
  association(relationship) # Raises an exception if relationship doesn't exist. This is a security safe guard.
177
193
 
@@ -199,15 +215,42 @@ module Glib
199
215
  end
200
216
  end
201
217
 
202
- def undo_soft_destroy_associated_records
218
+ # Reads each association's deleted rows directly instead of through `process_soft_deletable_relationship`:
219
+ # the cached `public_send` read goes through the target's `auto_hide_soft_deleted_records` default scope,
220
+ # which hides every child a cascade soft-deleted, so a fresh load (how any real undo runs) would find
221
+ # nothing to restore. The read includes deleted rows and is bounded to `deleted_at >= bound` (the parent's
222
+ # own deletion time, taken first), so a child soft-deleted on its own before the parent is left alone.
223
+ # The bound has no upper edge: a child soft-deleted on its own after the parent (only reachable through
224
+ # `with_deleted`) is restored too, accepted because undo cannot distinguish it from a cascade victim.
225
+ def undo_soft_destroy_associated_records(bound)
203
226
  __resolved_soft_deletable_associations.each do |relationship|
204
- process_soft_deletable_relationship(relationship) do |record|
205
- assert_soft_deletable!(relationship, record)
206
- record._undo_soft_destroy
207
- end
227
+ assoc = association(relationship) # Raises an exception if relationship doesn't exist. This is a security safe guard.
228
+
229
+ # A polymorphic belongs_to with no stored target resolves to no class: nothing to
230
+ # restore, like the destroy walk's nil handling. With a target stored, `klass` is the
231
+ # concrete class Rails resolves from the owner's type column, default or custom named.
232
+ next if assoc.klass.nil?
233
+
234
+ # Fail fast BEFORE building the relation: the read below calls `with_deleted` on the
235
+ # target's relation, so a non-soft-deletable target has to fail here, with the clear
236
+ # error, rather than as an obscure NoMethodError from the read itself.
237
+ assert_soft_deletable_class!(relationship, assoc.klass)
238
+
239
+ assoc.scope.with_deleted.where(deleted_at: bound..).each(&:_undo_soft_destroy)
240
+
241
+ # The walk restored fresh instances; a previously loaded association on this owner would
242
+ # still hold the stale, still-deleted copies. Reset so the next read reloads.
243
+ assoc.reset
208
244
  end
209
245
  end
210
246
 
247
+ # The `deleted_at` as stored in the database: the undo compares it against the children's stored
248
+ # timestamps, so both sides come from the same place, and a nil result is the signal that this
249
+ # deletion was never stored (a stale in-memory flag, or a concurrent undo that already ran).
250
+ def stored_deleted_at
251
+ self.class.with_deleted.where(id: id).pick(:deleted_at)
252
+ end
253
+
211
254
  # Resolves the associations to soft-delete. Honours a (deprecated) override of
212
255
  # `soft_deletable_associations` if present, warning the caller; otherwise returns
213
256
  # the associations declared via `soft_deletes_with`.
@@ -228,10 +271,22 @@ module Glib
228
271
  def assert_soft_deletable!(relationship, record)
229
272
  return if record.respond_to?(:_soft_destroy)
230
273
 
231
- raise(
232
- ActiveRecord::ConfigurationError,
274
+ raise __soft_deletable_target_error(relationship, record.class)
275
+ end
276
+
277
+ # Class-level twin of `assert_soft_deletable!`, used where the target is inspected as a class
278
+ # before any record exists — the undo read builds a relation on the target class, so the check
279
+ # has to happen there before `with_deleted` is called on it.
280
+ def assert_soft_deletable_class!(relationship, klass)
281
+ return if klass.include?(Glib::SoftDeletable)
282
+
283
+ raise __soft_deletable_target_error(relationship, klass)
284
+ end
285
+
286
+ def __soft_deletable_target_error(relationship, klass)
287
+ ActiveRecord::ConfigurationError.new(
233
288
  "#{self.class.name} registers `#{relationship}` in `soft_deletable_associations`, " \
234
- "but #{record.class.name} does not include Glib::SoftDeletable"
289
+ "but #{klass.name} does not include Glib::SoftDeletable"
235
290
  )
236
291
  end
237
292
 
@@ -3,7 +3,23 @@ json.title 'Tables'
3
3
  page = json_ui_page json
4
4
  render "#{@path_prefix}/nav_menu", json: json, page: page
5
5
 
6
- column_indexes = (1..5)
6
+ # Server-side multi-column sorting (Glib::Params::MultiColumnSort): click a
7
+ # header to make it the primary sort, then another to sort by that one with
8
+ # the first breaking its ties. Status repeats so the ties are visible, one
9
+ # row has no sign-ups (nil stays last both ways), `sign-ups` is a hyphenated
10
+ # key, and with four sortable columns the fourth click drops the oldest of
11
+ # the three a sort keeps.
12
+ columns = { 'name' => 'Name', 'status' => 'Status', 'sign-ups' => 'Sign-ups', 'joined' => 'Joined' }
13
+ sort = Glib::Params::MultiColumnSort.new(params[:sort], allowed: columns.keys)
14
+ # Listed out of name order on purpose, so the tie-breaker visibly decides.
15
+ items = sort.sort_rows([
16
+ { name: 'Echo', status: 'Active', 'sign-ups': 2, joined: '2026-02-10' },
17
+ { name: 'Charlie', status: 'Active', 'sign-ups': nil, joined: '2026-02-10' },
18
+ { name: 'Alpha', status: 'Active', 'sign-ups': 3, joined: '2026-03-01' },
19
+ { name: 'Delta', status: 'Archived', 'sign-ups': 3, joined: '2026-01-15' },
20
+ { name: 'Bravo', status: 'Archived', 'sign-ups': 1, joined: '2026-01-15' },
21
+ ], tie_breaker: :name)
22
+
7
23
  page.table styleClass: 'table--grid', sections: [
8
24
  ->(section) do
9
25
  section.rows builder: ->(row) do
@@ -17,22 +33,18 @@ page.table styleClass: 'table--grid', sections: [
17
33
  end,
18
34
  ->(section) do
19
35
  section.header cellViews: ->(header) do
20
- column_indexes.each do |i|
21
- order_key = "heading#{i}"
22
- order = @order_headings[order_key]
23
- header.label text: "Heading#{i} (#{order})", onClick: ->(action) do
24
- action.windows_reload url: json_ui_garage_url(path: 'tables/layout', orders: reversed_order_params(order_key))
25
- end
36
+ columns.each do |key, label|
37
+ glib_sort_header header, sort: sort, key: key, label: label,
38
+ url: ->(param) { json_ui_garage_current_url(sort: param) }
26
39
  end
27
40
 
28
41
  header.label text: 'Markdown'
29
42
  end
30
43
 
31
- items = [1, 2, 3]
32
44
  section.rows objects: items, builder: ->(row, item, index) do
33
45
  row.default colStyles: [{ width: 200, backgroundColor: '#eeeeee' }], cellViews: ->(cell) do
34
- column_indexes.each do |i|
35
- cell.label text: "Data #{item}"
46
+ columns.each_key do |key|
47
+ cell.label text: item[key.to_sym].to_s
36
48
  end
37
49
 
38
50
  markdown = "* [Item 1](#{json_ui_garage_url(path: 'home/blank')})\n"\
@@ -43,13 +55,8 @@ page.table styleClass: 'table--grid', sections: [
43
55
  end
44
56
 
45
57
  section.footer cellViews: ->(header) do
46
- column_indexes.each do |i|
47
- # order_key = "footer#{i}"
48
- # order = @order_headings[order_key]
49
- header.label text: "Footer#{i}"
50
- # , onClick: ->(action) do
51
- # action.windows_reload url: json_ui_garage_url(path: 'tables/layout', orders: reversed_order_params(order_key))
52
- # end
58
+ columns.each_value do |label|
59
+ header.label text: "#{label} footer"
53
60
  end
54
61
 
55
62
  header.label text: ''
@@ -81,6 +81,32 @@ page.body(
81
81
  end
82
82
  )
83
83
 
84
+ res.spacer height: 8
85
+ res.button(
86
+ text: 'commands/copy (with onFailure)',
87
+ onClick: ->(action) do
88
+ action.commands_copy(
89
+ text: 'Copied with failure callback',
90
+ onCopy: ->(subaction) do
91
+ subaction.runMultiple(
92
+ childActions: ->(ssaction) do
93
+ ssaction.logics_set targetId: 'commands_status', data: { text: 'Status: copied' }
94
+ ssaction.snackbars_alert message: 'Copied', styleClass: 'success'
95
+ end
96
+ )
97
+ end,
98
+ onFailure: ->(subaction) do
99
+ subaction.runMultiple(
100
+ childActions: ->(ssaction) do
101
+ ssaction.logics_set targetId: 'commands_status', data: { text: 'Status: copy failed' }
102
+ ssaction.snackbars_alert message: 'Copy failed', styleClass: 'danger'
103
+ end
104
+ )
105
+ end
106
+ )
107
+ end
108
+ )
109
+
84
110
  res.spacer height: 8
85
111
  res.button(
86
112
  text: 'commands/custom (with callbacks)',
@@ -12,6 +12,7 @@ module Glib
12
12
  base.helper Glib::JsonUi::ResponseHelper
13
13
  base.helper Glib::JsonUi::PageHelper
14
14
  base.helper Glib::JsonUi::AnalyticsHelper
15
+ base.helper Glib::JsonUi::SortHelper
15
16
  end
16
17
  end
17
18
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: glib-web
3
3
  version: !ruby/object:Gem::Version
4
- version: 8.2.1
4
+ version: 8.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - ''
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-19 00:00:00.000000000 Z
11
+ date: 2026-11-25 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activestorage
@@ -230,6 +230,7 @@ files:
230
230
  - app/controllers/concerns/glib/json/ui.rb
231
231
  - app/controllers/concerns/glib/json/validation.rb
232
232
  - app/controllers/concerns/glib/params/allowlist.rb
233
+ - app/controllers/concerns/glib/params/multi_column_sort.rb
233
234
  - app/controllers/glib/api_controller.rb
234
235
  - app/controllers/glib/blob_url_generators_controller.rb
235
236
  - app/controllers/glib/errors_controller.rb
@@ -270,6 +271,7 @@ files:
270
271
  - app/helpers/glib/json_ui/menu_builder.rb
271
272
  - app/helpers/glib/json_ui/page_helper.rb
272
273
  - app/helpers/glib/json_ui/response_helper.rb
274
+ - app/helpers/glib/json_ui/sort_helper.rb
273
275
  - app/helpers/glib/json_ui/styling_helper.rb
274
276
  - app/helpers/glib/json_ui/table_builders.rb
275
277
  - app/helpers/glib/json_ui/view_builder.rb