glib-web 8.2.1 → 8.2.2

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: 213673ab92ffc514108c0906bef9059e54b942c97f4ca28b26c1258f80cbcecf
4
+ data.tar.gz: 4d430ba703fb6c7078b5f24a4f907c97ec9aab16e930372b7b28b480faf59fed
5
5
  SHA512:
6
- metadata.gz: 569d870e43d67adccbad29c44293d82fe6a0fd77c4d824e395b7a63d2817a605617a2c64cad62814363cf983f7121ea9c3bf9101231fcffda067c459a62efe50
7
- data.tar.gz: b51321994361436a14f3bcc646d4c1aa46f126d345e31e2fd9aec5d945271c92fe7fed8e8443bc2b40ccf9a06574b20a6e9b7a42ba1ffe86b324ee6e72f018ab
6
+ metadata.gz: 2d331c3ac21065411e0affeb2c768b69a6d262fb1da23b25461a82a0eb0db518de8ca9fa47bff4f42266b8480cbe6f6a0db79a4e781b58bf3765344754ef47fd
7
+ data.tar.gz: 9f5f63fe7a91547f739667bf3825c9639aa6fe4fd02f4088f6aa203343b8fb6529bbe53609ab5b6eb1523baddc1916215ed31ca80af378db88dfa1f9af6c92f1
@@ -20,7 +20,10 @@ module Glib
20
20
  end
21
21
 
22
22
  def create
23
- blob = ActiveStorage::Blob.new # generate blob key
23
+ # Unqualified, `ActiveStorage` resolves to Glib::ActiveStorage inside this module. Its Blob
24
+ # subclass would leak into Action Text sgids (rendering as glib/active_storage/blobs/_blob,
25
+ # which doesn't exist) and may connect to the dynamic-text database.
26
+ blob = ::ActiveStorage::Blob.new # generate blob key
24
27
  if blob_args[:prefix].present?
25
28
  blob.key = "#{blob_args[:prefix]}/#{blob.key}"
26
29
  end
@@ -1,20 +1,16 @@
1
1
  module Glib
2
2
  module FormatHelper
3
- require 'redcarpet'
4
-
5
- class CustomRenderer < Redcarpet::Render::XHTML
6
- def strikethrough(text)
7
- "<s>#{text}</s>"
8
- end
3
+ # Kept for existing callers; same output as glib_markdown_to_html.
4
+ def glib_format_markdown(content)
5
+ Glib::Markdown.to_html(content)
6
+ end
9
7
 
10
- def block_quote(quote)
11
- "<blockquote>#{quote}</blockquote>"
12
- end
8
+ def glib_markdown_to_html(markdown, **options)
9
+ Glib::Markdown.to_html(markdown, **options)
13
10
  end
14
11
 
15
- def glib_format_markdown(content)
16
- markdown = Redcarpet::Markdown.new(CustomRenderer, strikethrough: true, underline: false, no_intra_emphasis: true)
17
- markdown.render(content).delete("\n")
12
+ def glib_html_to_markdown(html, **options)
13
+ Glib::Markdown.from_html(html, **options)
18
14
  end
19
15
  end
20
16
  end
@@ -65,18 +65,31 @@ module Glib
65
65
  # `h[k] ||= default` a no-op. Reject such values before wrapping them.
66
66
  #
67
67
  # Returns true when `value` was rejected and the caller should fall back to {}.
68
- # Raises only in development/test: such pages rendered (as {}) before this check
69
- # existed, so production reports instead of turning them into 500s.
70
68
  def reject_non_hash(propName, value)
71
69
  return false if value.respond_to?(:to_hash)
72
70
 
73
71
  message = "Hash property: '#{propName}' must be a hash, got #{value.inspect}"
74
- raise ArgumentError, message if Rails.env.development? || Rails.env.test?
72
+ raise ArgumentError, message if raise_hash_errors?
75
73
 
76
74
  GLog.warn("#{message}; emitting {} instead")
77
75
  true
78
76
  end
79
77
 
78
+ def report_hash_errors(messages)
79
+ return if messages.empty?
80
+
81
+ message = messages.join('; ')
82
+ raise ArgumentError, message if raise_hash_errors?
83
+
84
+ GLog.warn("#{message}; emitting the hash unchanged")
85
+ end
86
+
87
+ # Only development/test raise: pages with these mistakes rendered before the
88
+ # checks existed, so production reports instead of turning them into 500s.
89
+ def raise_hash_errors?
90
+ Rails.env.development? || Rails.env.test?
91
+ end
92
+
80
93
  def self.component_name
81
94
  @component_name ||= self.name.sub('Glib::JsonUi::ActionBuilder::', '')
82
95
  end
@@ -311,7 +324,33 @@ module Glib
311
324
  end
312
325
  end
313
326
 
314
- def self.hash(propName, **options)
327
+ # Shortcuts so `schema:` literals don't need the full HashSchema constant, which
328
+ # files opened as `class Glib::JsonUi::ViewBuilder` can't resolve unqualified.
329
+ def self.schema_enum(*values)
330
+ HashSchema.enum(*values)
331
+ end
332
+
333
+ def self.schema_array_of(type)
334
+ HashSchema.array_of(type)
335
+ end
336
+
337
+ def self.schema_open(spec)
338
+ HashSchema.open(spec)
339
+ end
340
+
341
+ # `schema:` is the typed form (see HashSchema). `required:`/`optional:`/`nested:`
342
+ # are the older untyped shorthand, kept so existing declarations work unchanged.
343
+ def self.hash(propName, schema: nil, required: nil, optional: nil, nested: nil)
344
+ if schema && (required || optional || nested)
345
+ raise ArgumentError, "Hash property: '#{propName}' takes either schema: or required:/optional:/nested:, not both"
346
+ end
347
+
348
+ node = if schema
349
+ HashSchema.compile(schema)
350
+ else
351
+ HashSchema.from_legacy(required: required || [], optional: optional || [], nested: nested || {})
352
+ end
353
+
315
354
  define_method(propName) do |value|
316
355
  return if value.nil?
317
356
 
@@ -321,49 +360,7 @@ module Glib
321
360
  end
322
361
 
323
362
  value = ActiveSupport::HashWithIndifferentAccess.new(value)
324
-
325
- required = options[:required] || []
326
- optional = options[:optional] || []
327
-
328
- required.each do |req|
329
- raise ArgumentError, "Hash property: '#{req}' is required" if value[req.to_s].nil?
330
- end
331
-
332
- if optional.present?
333
- value.except(*required).each do |k, v|
334
- raise ArgumentError, "Unknown hash property: '#{k}'" if !optional.include?(k.to_sym)
335
- end
336
- end
337
-
338
- # Sub-hash validation, one level deep: each `nested` key names a
339
- # sub-hash whose own required/optional lists are checked the same
340
- # way the top level is checked, so a typo inside a composite hash
341
- # (e.g. a field's `draw` options) fails loudly at render time
342
- # instead of passing silently. A nested spec that declares any
343
- # keys (required or optional) CLOSES its sub-hash: keys outside
344
- # required+optional raise. No recursion: sub-hashes of sub-hashes
345
- # are the app's own data.
346
- (options[:nested] || {}).each do |key, sub_options|
347
- sub_value = value[key]
348
- next if sub_value.nil?
349
- raise ArgumentError, "Hash property: '#{key}' must be a hash" if !sub_value.is_a?(Hash)
350
-
351
- sub_value = ActiveSupport::HashWithIndifferentAccess.new(sub_value)
352
- sub_required = sub_options[:required] || []
353
- sub_optional = sub_options[:optional] || []
354
-
355
- sub_required.each do |req|
356
- raise ArgumentError, "Hash property: '#{key}.#{req}' is required" if sub_value[req.to_s].nil?
357
- end
358
-
359
- allowed = sub_required + sub_optional
360
- if allowed.present?
361
- sub_value.each_key do |k|
362
- raise ArgumentError, "Unknown hash property: '#{key}.#{k}'" if !allowed.include?(k.to_sym)
363
- end
364
- end
365
- end
366
-
363
+ report_hash_errors(HashSchema.errors(value, node, propName))
367
364
  json.set! propName, value
368
365
  end
369
366
  end
@@ -16,7 +16,7 @@ class Glib::JsonUi::ActionBuilder
16
16
  int :offset
17
17
  int :width
18
18
  bool :persistent
19
- hash :overlay, required: [:closeOnFocus]
19
+ hash :overlay, schema: { closeOnFocus!: :bool }
20
20
  singleton_array :styleClass, :styleClasses
21
21
  bool :updateExisting
22
22
  end
@@ -0,0 +1,182 @@
1
+ # Typed, recursive validation for `hash` props (see JsonUiElement.hash).
2
+ #
3
+ # hash :draw, schema: {
4
+ # hint: :string,
5
+ # savedSignature: { value!: :string, fileUrl!: :string },
6
+ # saveOption: { name!: :string, value: :bool, tooltip: { text!: :string } }
7
+ # }
8
+ #
9
+ # Validate only as deep as the frontend reads keys. Below that (Chart.js
10
+ # options, app data) stop with `:hash` or `:any`, otherwise glib would have to
11
+ # mirror a third-party schema and every new option would need a glib release.
12
+ module Glib
13
+ module JsonUi
14
+ class HashSchema
15
+ Node = Struct.new(:keys, :open)
16
+ Enum = Struct.new(:values)
17
+ ArrayOf = Struct.new(:type)
18
+
19
+ SCALARS = {
20
+ any: ->(_v) { true },
21
+ string: ->(v) { v.is_a?(String) || v.is_a?(Symbol) },
22
+ int: ->(v) { v.is_a?(Integer) },
23
+ number: ->(v) { v.is_a?(Numeric) },
24
+ bool: ->(v) { v == true || v == false },
25
+ hash: ->(v) { v.respond_to?(:to_hash) },
26
+ array: ->(v) { v.is_a?(Array) }
27
+ }.freeze
28
+
29
+ DESCRIPTIONS = {
30
+ any: 'anything',
31
+ string: 'a string',
32
+ int: 'an integer',
33
+ number: 'a number',
34
+ bool: 'a boolean',
35
+ hash: 'a hash',
36
+ array: 'an array'
37
+ }.freeze
38
+
39
+ def self.enum(*values)
40
+ Enum.new(values.freeze)
41
+ end
42
+
43
+ def self.array_of(type)
44
+ ArrayOf.new(compile(type))
45
+ end
46
+
47
+ # Types the listed keys but still accepts others, for hashes where the
48
+ # frontend reads more keys than glib has typed yet.
49
+ def self.open(spec)
50
+ raise ArgumentError, "HashSchema.open takes a hash, got #{spec.inspect}" if !spec.is_a?(Hash)
51
+
52
+ Node.new(compile(spec).keys, true)
53
+ end
54
+
55
+ # Runs once per `hash` declaration, at class load, so a typo in the schema
56
+ # itself fails when the builder loads rather than when a page renders.
57
+ def self.compile(spec)
58
+ case spec
59
+ when Node, Enum, ArrayOf
60
+ spec
61
+ when Symbol
62
+ raise ArgumentError, "Invalid hash schema type: #{spec.inspect}" if !SCALARS.key?(spec)
63
+
64
+ spec
65
+ when Array
66
+ raise ArgumentError, 'A hash schema union needs at least one type' if spec.empty?
67
+
68
+ spec.map { |type| compile(type) }.freeze
69
+ when Hash
70
+ keys = spec.to_h do |key, type|
71
+ name = key.to_s
72
+ required = name.end_with?('!')
73
+ name = name.delete_suffix('!') if required
74
+ raise ArgumentError, "Invalid hash schema key: #{key.inspect}" if name.empty?
75
+
76
+ [name, [compile(type), required].freeze]
77
+ end
78
+ Node.new(keys.freeze, false)
79
+ else
80
+ raise ArgumentError, "Invalid hash schema type: #{spec.inspect}"
81
+ end
82
+ end
83
+
84
+ # Translates the pre-schema options so both forms share one code path, while
85
+ # keeping their looser rules: the top level is open unless `optional` is
86
+ # given, and a nested spec is open unless it declares keys.
87
+ def self.from_legacy(required: [], optional: [], nested: {})
88
+ keys = legacy_keys(required, optional)
89
+ open = optional.empty?
90
+ nested.each do |key, sub|
91
+ # Legacy `nested` only described a key's sub-hash; it never allowed a key
92
+ # that a closed top level didn't already list.
93
+ next if !open && !keys.key?(key.to_s)
94
+
95
+ sub_required = sub[:required] || []
96
+ sub_optional = sub[:optional] || []
97
+ sub_node = Node.new(legacy_keys(sub_required, sub_optional).freeze, sub_required.empty? && sub_optional.empty?)
98
+ keys[key.to_s] = [sub_node, keys.dig(key.to_s, 1) || false].freeze
99
+ end
100
+
101
+ Node.new(keys.freeze, open)
102
+ end
103
+
104
+ def self.legacy_keys(required, optional)
105
+ keys = {}
106
+ optional.each { |key| keys[key.to_s] = [:any, false].freeze }
107
+ required.each { |key| keys[key.to_s] = [:any, true].freeze }
108
+ keys
109
+ end
110
+
111
+ # Returns error messages rather than raising, so the caller decides how
112
+ # each environment reports them.
113
+ def self.errors(value, type, path)
114
+ case type
115
+ when Symbol
116
+ SCALARS.fetch(type).call(value) ? [] : [mismatch(path, type, value)]
117
+ when Array
118
+ type.any? { |member| errors(value, member, path).empty? } ? [] : [mismatch(path, type, value)]
119
+ when Enum
120
+ enum_match?(type.values, value) ? [] : [mismatch(path, type, value)]
121
+ when ArrayOf
122
+ return [mismatch(path, type, value)] if !value.is_a?(Array)
123
+
124
+ value.each_with_index.flat_map { |item, i| errors(item, type.type, "#{path}[#{i}]") }
125
+ when Node
126
+ node_errors(value, type, path)
127
+ end
128
+ end
129
+
130
+ def self.node_errors(value, node, path)
131
+ return [mismatch(path, node, value)] if !value.respond_to?(:to_hash)
132
+
133
+ value = value.to_hash.stringify_keys if !value.is_a?(ActiveSupport::HashWithIndifferentAccess)
134
+ messages = []
135
+
136
+ if !node.open
137
+ value.each_key do |key|
138
+ messages << "Unknown hash property: '#{path}.#{key}'" if !node.keys.key?(key.to_s)
139
+ end
140
+ end
141
+
142
+ node.keys.each do |key, (type, required)|
143
+ sub_value = value[key]
144
+ if sub_value.nil?
145
+ messages << "Hash property: '#{path}.#{key}' is required" if required
146
+ next
147
+ end
148
+
149
+ messages.concat(errors(sub_value, type, "#{path}.#{key}"))
150
+ end
151
+
152
+ messages
153
+ end
154
+
155
+ def self.enum_match?(allowed, value)
156
+ allowed.any? do |option|
157
+ option == value || (stringish?(option) && stringish?(value) && option.to_s == value.to_s)
158
+ end
159
+ end
160
+
161
+ def self.stringish?(value)
162
+ value.is_a?(String) || value.is_a?(Symbol)
163
+ end
164
+
165
+ def self.mismatch(path, type, value)
166
+ "Hash property: '#{path}' must be #{describe(type)}, got #{value.inspect}"
167
+ end
168
+
169
+ def self.describe(type)
170
+ case type
171
+ when Symbol then DESCRIPTIONS.fetch(type)
172
+ when Array then type.map { |member| describe(member) }.join(' or ')
173
+ when Enum then "one of #{type.values.map(&:inspect).join(', ')}"
174
+ when ArrayOf then "an array of items that are each #{describe(type.type)}"
175
+ when Node then 'a hash'
176
+ end
177
+ end
178
+
179
+ private_class_method :legacy_keys, :node_errors, :enum_match?, :stringish?, :mismatch, :describe
180
+ end
181
+ end
182
+ end
@@ -40,7 +40,7 @@ module Glib
40
40
  action :onLongPress
41
41
  icon :icon
42
42
  # bool :avatar
43
- hash :avatar, optional: [:url, :initials, :backgroundColor]
43
+ hash :avatar, schema: { url: :string, initials: { text!: :string, color: :string }, backgroundColor: :string }
44
44
  # action :onReorder
45
45
  string :paramNameForFormData
46
46
  string :paramNameForNewAbsoluteIndex
@@ -93,7 +93,7 @@ module Glib
93
93
  string :subtitle
94
94
  action :onClick
95
95
  hash :dropData
96
- hash :icon, required: [:name], optional: [:color, :size]
96
+ hash :icon, schema: { name!: :string, color: :string, size: [:number, :string] }
97
97
  array :rows
98
98
  end
99
99
  end
@@ -8,14 +8,19 @@ module Glib
8
8
  class MenuItem < JsonUiElement
9
9
  include Builder::MouseEvents
10
10
 
11
- hash :analytics, optional: [:featured, :disabled, :group, :action]
12
- hash :tooltip, required: [:text], optional: [:placement, :position]
11
+ hash :analytics, schema: { featured: :any, disabled: :bool, group: :string, action: :string }
12
+ hash :tooltip, schema: { text!: :string, placement: :string, position: :string }
13
13
  end
14
14
 
15
15
  class Button < MenuItem
16
16
  badgeable
17
17
 
18
- hash :avatar, optional: [:size, :backgroundColor, :url, :initials]
18
+ hash :avatar, schema: {
19
+ size: [:number, :string],
20
+ backgroundColor: :string,
21
+ url: :string,
22
+ initials: { text!: :string, color: :string }
23
+ }
19
24
  string :text
20
25
  icon :icon
21
26
  action :onClick
@@ -73,8 +73,20 @@ class Glib::JsonUi::ViewBuilder
73
73
  int :min
74
74
  int :max
75
75
  # https://www.chartjs.org/docs/latest/configuration/legend.html
76
- hash :legend, optional: [:position, :align, :display, :maxHeight, :maxWidth, :fullSize, :reverse, :labels, :rtl, :title, :override]
77
- hash :plugins, optional: [:datalabels, :centerLabel, :customTooltip]
76
+ hash :legend, schema: {
77
+ position: [schema_enum(:top, :left, :bottom, :right, :chartArea), :hash],
78
+ align: schema_enum(:start, :center, :end),
79
+ display: :bool,
80
+ maxHeight: :number,
81
+ maxWidth: :number,
82
+ fullSize: :bool,
83
+ reverse: :bool,
84
+ labels: :hash,
85
+ rtl: :bool,
86
+ title: :hash,
87
+ override: :bool
88
+ }
89
+ hash :plugins, schema: { datalabels: [:hash, :bool], centerLabel: { labels: :array }, customTooltip: :bool }
78
90
  end
79
91
  end
80
92
 
@@ -575,7 +575,7 @@ class Glib::JsonUi::ViewBuilder
575
575
 
576
576
  # Image to display instead of standard checkbox.
577
577
  # @example image: { url: '/checkmark.png', template: 'image', width: 24, height: 24 }
578
- hash :image, required: [:url, :template], optional: [:width, :height]
578
+ hash :image, schema: { url!: :string, template!: :string, width: [:number, :string], height: [:number, :string] }
579
579
 
580
580
  # Shows indeterminate state (partially checked).
581
581
  # Useful for "select all" checkboxes when some but not all children are selected.
@@ -611,7 +611,8 @@ class Glib::JsonUi::ViewBuilder
611
611
  #
612
612
  # @deprecated Quill has an unfixed XSS advisory. Use `fields_actionText` for rich text, or
613
613
  # `fields_textarea` where users write markdown themselves. See the glib-web-npm
614
- # `doc/rich_text_migration.md` guide.
614
+ # `doc/rich_text_migration.md` guide. For `produce:`/`accept: :markdown`, convert on the
615
+ # server with `Glib::Markdown.to_html` / `.from_html` (doc/common/cookbook/markdown_with_action_text.md).
615
616
  #
616
617
  # Provides a full-featured text editor with formatting options, image uploads,
617
618
  # and @mention support. Can output HTML or Markdown.
@@ -649,7 +650,7 @@ class Glib::JsonUi::ViewBuilder
649
650
  # directUploadUrl: rails_direct_uploads_path,
650
651
  # accepts: 'image/png,image/jpeg'
651
652
  # }
652
- hash :imageUploader, required: [:name], optional: [:accepts, :directUploadUrl, :blobUrlGenerator]
653
+ hash :imageUploader, schema: { name!: :string, accepts: [:string, :hash], directUploadUrl: :string, blobUrlGenerator: :string }
653
654
 
654
655
  # Output format for the editor content.
655
656
  enum :produce, options: [:html, :markdown]
@@ -690,6 +691,10 @@ class Glib::JsonUi::ViewBuilder
690
691
  # When `prop` refers to a `has_rich_text` attribute, the field is pre-filled with the
691
692
  # attribute's `to_trix_html`.
692
693
  #
694
+ # The field only speaks HTML. To edit Markdown, pre-fill with `Glib::Markdown.to_html` and
695
+ # convert the submitted value with `Glib::Markdown.from_html`
696
+ # (see doc/common/cookbook/markdown_with_action_text.md).
697
+ #
693
698
  # @example Action Text attribute on a model form
694
699
  # form.fields_actionText \
695
700
  # prop: :body,
@@ -765,7 +770,7 @@ class Glib::JsonUi::ViewBuilder
765
770
  bool :multiple, cache: true
766
771
  # bool :manualEntry
767
772
  icon :leftIcon
768
- hash :append, optional: [:icon]
773
+ hash :append, schema: { icon: :string }
769
774
 
770
775
  panels_builder :accessory, :header, :footer
771
776
  bool :clearable
@@ -873,8 +878,8 @@ class Glib::JsonUi::ViewBuilder
873
878
  action :onClick
874
879
  string :offIcon
875
880
  string :onIcon
876
- hash :image, required: [:url, :template], optional: [:width, :height, :subtitle]
877
- hash :icon, required: [:name, :template], optional: [:color, :size, :subtitle]
881
+ hash :image, schema: { url!: :string, template!: :string, width: [:number, :string], height: [:number, :string], subtitle: :string }
882
+ hash :icon, schema: { name!: :string, template!: :string, color: :string, size: [:number, :string], subtitle: :string }
878
883
 
879
884
  views :childViews
880
885
  end
@@ -900,9 +905,15 @@ class Glib::JsonUi::ViewBuilder
900
905
  bool :multiple, cache: true
901
906
  # `url` is the current file's image; `emptyUrl` is shown whenever there is no file
902
907
  # (none attached, or after the field is reset), otherwise a neutral box is shown.
903
- hash :placeholderView, required: [:type, :width, :height], optional: [:url, :emptyUrl]
904
- hash :inputView, optional: [:files, :variant]
905
- hash :clipboardView, optional: [:icon]
908
+ hash :placeholderView, schema: {
909
+ type!: schema_enum(:image, :avatar),
910
+ width!: [:number, :string],
911
+ height!: [:number, :string],
912
+ url: :string,
913
+ emptyUrl: :string
914
+ }
915
+ hash :inputView, schema: { files: :array, variant: :string }
916
+ hash :clipboardView, schema: { icon: :string }
906
917
 
907
918
  def multiProgressView(values)
908
919
  # Consumers naturally write jbuilder hashes with symbol keys, but the
@@ -1067,7 +1078,7 @@ class Glib::JsonUi::ViewBuilder
1067
1078
  # `name` is still accepted but unused: the typed name is submitted
1068
1079
  # through the field's own param (single-param contract), and the
1069
1080
  # server routes it to the name attribute.
1070
- hash :typedName, optional: [:name, :value, :label, :placeholder]
1081
+ hash :typedName, schema: { name: :string, value: :string, label: :string, placeholder: :string }
1071
1082
 
1072
1083
  # Run instead of opening the dialog while the field is BLANK (a filled box
1073
1084
  # always opens the dialog on what it holds). The app composes whatever the
@@ -1092,11 +1103,13 @@ class Glib::JsonUi::ViewBuilder
1092
1103
  # id or the typed name. Distinct from `fileUrl` above: that is the box's OWN
1093
1104
  # value on re-edit, pre-filled and, like any painted drawing, read-only on
1094
1105
  # the canvas until cleared.
1095
- hash :draw, optional: [:hint, :placeholder, :confirmedHint, :savedSignature, :saveOption],
1096
- nested: {
1097
- savedSignature: { required: [:value, :fileUrl] },
1098
- saveOption: { required: [:name], optional: [:label, :value, :tooltip] }
1099
- }
1106
+ hash :draw, schema: {
1107
+ hint: :string,
1108
+ placeholder: :string,
1109
+ confirmedHint: :string,
1110
+ savedSignature: { value!: :string, fileUrl!: :string },
1111
+ saveOption: { name!: :string, label: :string, value: :bool, tooltip: { text!: :string } }
1112
+ }
1100
1113
 
1101
1114
  # Override
1102
1115
  # A stored signature is an attachment -- submit its signed id (mirrors
@@ -1164,7 +1177,7 @@ class Glib::JsonUi::ViewBuilder
1164
1177
  enum :type, options: [:month]
1165
1178
  bool :clearable
1166
1179
  bool :buttonTemplate # TODO: Remove
1167
- hash :template, required: [:type]
1180
+ hash :template, schema: schema_open(type!: :string)
1168
1181
  string :time_zone
1169
1182
  enum :format, options: DATE_FORMAT_OPTIONS
1170
1183
 
@@ -1184,7 +1197,7 @@ class Glib::JsonUi::ViewBuilder
1184
1197
  enum :format, options: DATE_FORMAT_OPTIONS
1185
1198
 
1186
1199
  bool :buttonTemplate # TODO: Remove
1187
- hash :template, required: [:type]
1200
+ hash :template, schema: schema_open(type!: :string)
1188
1201
  end
1189
1202
 
1190
1203
  # Location/address field with Google Places autocomplete integration.
@@ -1226,7 +1239,7 @@ class Glib::JsonUi::ViewBuilder
1226
1239
  # fields: ['formatted_address', 'geometry']
1227
1240
  # }
1228
1241
  # @see https://developers.google.com/maps/documentation/javascript/reference/places-widget#AutocompleteOptions
1229
- hash :autocompleteOptions, optional: [:bounds, :componentRestrictions, :fields, :strictBounds, :types]
1242
+ hash :autocompleteOptions, schema: { bounds: :hash, componentRestrictions: :hash, fields: :array, strictBounds: :bool, types: :array }
1230
1243
  end
1231
1244
 
1232
1245
  # Stripe payment token field for secure card tokenization.
@@ -430,8 +430,8 @@ class Glib::JsonUi::ViewBuilder
430
430
  # deprecated
431
431
  class Table < View
432
432
  hash :nextPage
433
- hash :export, required: [:label, :fileName]
434
- hash :import, required: [:submitUrl, :paramName]
433
+ hash :export, schema: schema_open(label!: :string, fileName!: :string)
434
+ hash :import, schema: schema_open(submitUrl!: :string, paramName!: :string)
435
435
  action :onScrollToTop
436
436
  action :onScrollToBottom
437
437
 
@@ -458,7 +458,7 @@ class Glib::JsonUi::ViewBuilder
458
458
  # retired bulkEdit2 and bulkEditSg -- see the component's header comment
459
459
  # for the full mapping).
460
460
  class BulkEdit3 < View
461
- hash :import, required: [:submitUrl, :paramName]
461
+ hash :import, schema: schema_open(submitUrl!: :string, paramName!: :string)
462
462
 
463
463
  # Override
464
464
  def created
@@ -906,7 +906,7 @@ class Glib::JsonUi::ViewBuilder
906
906
  # Configuration for drag-and-drop reordering support.
907
907
  # Enables users to reorder children by dragging them.
908
908
  # @example dragSupport: { onDrop: { action: 'http/post', url: reorder_path }, paramNameForFormData: 'order' }
909
- hash :dragSupport, optional: [:onDrop, :paramNameForFormData, :paramNameForNewIndex]
909
+ hash :dragSupport, schema: { onDrop: :hash, paramNameForFormData: :string, paramNameForNewIndex: :string }
910
910
  end
911
911
 
912
912
  # Flow layout panel that wraps children like text (left to right, then top to bottom).
@@ -948,35 +948,41 @@ class Glib::JsonUi::ViewBuilder
948
948
  #
949
949
  # @see app/views/json_ui/garage/panels/flow.json.jbuilder Garage examples
950
950
  class Flow < View
951
+ BREAKPOINT_SCHEMA = {
952
+ gap: { all: :number, x: :number, y: :number },
953
+ padding: { top: :number, right: :number, bottom: :number, left: :number, x: :number, y: :number, all: :number }
954
+ }.freeze
955
+
951
956
  # Padding applied to each child element wrapper.
952
957
  # Different from the panel's own padding - this creates gaps between items.
953
958
  # @example innerPadding: { x: 10, y: 10 }
954
959
  # @example innerPadding: { top: 5, right: 10, bottom: 5, left: 10 }
955
- hash :innerPadding, optional: [:top, :right, :bottom, :left, :x, :y]
960
+ # @example innerPadding: { all: 8 }
961
+ hash :innerPadding, schema: { top: :number, right: :number, bottom: :number, left: :number, x: :number, y: :number, all: :number }
956
962
 
957
963
  # Configuration for xxl breakpoint (> 2560px).
958
964
  # @example xxl: { gap: { all: 32 }, padding: { all: 48 } }
959
- hash :xxl, optional: [:gap, :padding]
965
+ hash :xxl, schema: BREAKPOINT_SCHEMA
960
966
 
961
967
  # Configuration for xl breakpoint (1904px - 2560px).
962
968
  # @example xl: { gap: { x: 24, y: 24 } }
963
- hash :xl, optional: [:gap, :padding]
969
+ hash :xl, schema: BREAKPOINT_SCHEMA
964
970
 
965
971
  # Configuration for lg breakpoint (1264px - 1904px).
966
972
  # @example lg: { gap: { all: 16 }, padding: { x: 30, y: 30 } }
967
- hash :lg, optional: [:gap, :padding]
973
+ hash :lg, schema: BREAKPOINT_SCHEMA
968
974
 
969
975
  # Configuration for md breakpoint (960px - 1264px).
970
976
  # @example md: { gap: { y: 8, x: 8 } }
971
- hash :md, optional: [:gap, :padding]
977
+ hash :md, schema: BREAKPOINT_SCHEMA
972
978
 
973
979
  # Configuration for sm breakpoint (600px - 960px).
974
980
  # @example sm: { gap: { y: 4, x: 6 }, padding: { all: 16 } }
975
- hash :sm, optional: [:gap, :padding]
981
+ hash :sm, schema: BREAKPOINT_SCHEMA
976
982
 
977
983
  # Configuration for xs breakpoint (< 600px).
978
984
  # @example xs: { gap: { y: 2, x: 2 }, padding: { left: 10, bottom: 8 } }
979
- hash :xs, optional: [:gap, :padding]
985
+ hash :xs, schema: BREAKPOINT_SCHEMA
980
986
 
981
987
  # Child components to arrange in flow layout.
982
988
  views :childViews
@@ -6,7 +6,13 @@ module Glib
6
6
 
7
7
  included do
8
8
  string :directUploadUrl
9
- hash :accepts, optional: [:fileType, :maxFileSize, :maxFileLength, :maxFileSizeErrorText, :maxFileLengthErrorText]
9
+ hash :accepts, schema: {
10
+ fileType: [:string, :array],
11
+ maxFileSize: [:number, :string],
12
+ maxFileLength: [:number, :string],
13
+ maxFileSizeErrorText: [:string, :hash],
14
+ maxFileLengthErrorText: [:string, :hash]
15
+ }
10
16
  enum :strategy, options: [:delegate, :dropUpload]
11
17
  string :storagePrefix
12
18
  hash :metadata
@@ -123,7 +129,7 @@ module Glib
123
129
  length :width
124
130
  length :height
125
131
  color :backgroundColor
126
- hash :padding, optional: [:top, :right, :bottom, :left, :x, :y, :all]
132
+ hash :padding, schema: { top: :number, right: :number, bottom: :number, left: :number, x: :number, y: :number, all: :number }
127
133
  singleton_array :styleClass, :styleClasses
128
134
 
129
135
  hash :showIf # Deprecated: use logics_set instead
@@ -134,10 +140,10 @@ module Glib
134
140
  bool :displayed
135
141
  bool :submitWhenNotDisplayed
136
142
 
137
- hash :analytics, optional: [:featured, :disabled]
143
+ hash :analytics, schema: { featured: :any, disabled: :bool }
138
144
  hash :dragData
139
145
 
140
- hash :tooltip, required: [:text], optional: [:placement, :position]
146
+ hash :tooltip, schema: { text!: :string, placement: :string, position: :string }
141
147
  action :onLoad
142
148
  action :onRerender
143
149
 
@@ -283,7 +289,7 @@ module Glib
283
289
  string :base64Data
284
290
  action :onClick
285
291
  color :backgroundColor
286
- hash :initials, required: [:text], optional: [:color]
292
+ hash :initials, schema: { text!: :string, color: :string }
287
293
  end
288
294
 
289
295
  class Icon < View
@@ -0,0 +1,172 @@
1
+ require 'redcarpet'
2
+ require 'reverse_markdown'
3
+
4
+ module Glib
5
+ # Server-side Markdown <-> HTML conversion for `fields_actionText`, which only speaks HTML.
6
+ #
7
+ # @example Editing a Markdown column with fields_actionText
8
+ # form.fields_actionText name: 'post[body]', value: Glib::Markdown.to_html(post.body)
9
+ # # On submit:
10
+ # post.update!(body: Glib::Markdown.from_html(params.dig(:post, :body)))
11
+ module Markdown
12
+ EXTENSIONS = {
13
+ fenced_code_blocks: true,
14
+ tables: true,
15
+ strikethrough: true,
16
+ autolink: true,
17
+ no_intra_emphasis: true,
18
+ lax_spacing: true
19
+ }.freeze
20
+
21
+ INLINE_SYNTAX = /[\\`\[\]~]/
22
+
23
+ # Everything from_html can turn into Markdown. Other tags, <script> and <style> included, are
24
+ # dropped together with their text.
25
+ ALLOWED_TAGS = (
26
+ Rails::HTML::Sanitizer.best_supported_vendor.safe_list_sanitizer.allowed_tags.to_a +
27
+ %w[figure figcaption table thead tbody tr th td]
28
+ ).freeze
29
+ # No `title`: ReverseMarkdown writes it into the Markdown without escaping quotes.
30
+ ALLOWED_ATTRIBUTES = %w[href src alt].freeze
31
+
32
+ # ReverseMarkdown always fences code with one backtick or ```, so a backtick in the code ends
33
+ # the fence early and the rest is read as Markdown. These converters pick a fence longer than
34
+ # any backtick run in the code, as CommonMark specifies. They are registered under their own
35
+ # tag names so the host app's ReverseMarkdown keeps its stock `code` and `pre` converters.
36
+ module CodeFence
37
+ def fence_for(code, min_length:)
38
+ longest_run = code.scan(/`+/).map(&:length).max || 0
39
+ '`' * [min_length, longest_run + 1].max
40
+ end
41
+ end
42
+
43
+ class CodeSpanConverter < ReverseMarkdown::Converters::Base
44
+ include CodeFence
45
+
46
+ TAG = 'glib-markdown-code'.freeze
47
+
48
+ def convert(node, state = {})
49
+ code = node.text
50
+ fence = fence_for(code, min_length: 1)
51
+ # Without the padding, a backtick at either end would merge into the fence.
52
+ code = " #{code} " if code.start_with?('`') || code.end_with?('`')
53
+ preserve_literal("#{fence}#{code}#{fence}", state)
54
+ end
55
+ end
56
+
57
+ class CodeBlockConverter < ReverseMarkdown::Converters::Pre
58
+ include CodeFence
59
+
60
+ TAG = 'glib-markdown-pre'.freeze
61
+
62
+ def convert(node, state = {})
63
+ code = treat_children(node, state).strip
64
+ fence = fence_for(code, min_length: 3)
65
+ "\n#{preserve_literal("#{fence}\n#{code}\n#{fence}", state)}\n"
66
+ end
67
+ end
68
+
69
+ ReverseMarkdown::Converters.register CodeSpanConverter::TAG, CodeSpanConverter.new
70
+ ReverseMarkdown::Converters.register CodeBlockConverter::TAG, CodeBlockConverter.new
71
+
72
+ class << self
73
+ # `hard_wrap: true` turns every newline into a <br>, for chat-style input where people
74
+ # don't leave blank lines between paragraphs.
75
+ def to_html(markdown, hard_wrap: false)
76
+ return '' if markdown.blank?
77
+
78
+ # The output is often rendered as-is (an `html` view, a non-Trix field) rather than only
79
+ # through Action Text's sanitizer, so raw HTML and javascript: links are never emitted.
80
+ renderer = Redcarpet::Render::HTML.new(escape_html: true, safe_links_only: true, hard_wrap: hard_wrap)
81
+ # Redcarpet's default <del> for ~~strike~~ is what Trix uses too; Action Text's
82
+ # sanitizer strips <s>.
83
+ Redcarpet::Markdown.new(renderer, EXTENSIONS).render(markdown.to_s)
84
+ end
85
+
86
+ # `input` may be raw Trix HTML (as submitted by fields_actionText), an ActionText::Content
87
+ # or an ActionText::RichText. Attachments become Markdown too: image blobs as images,
88
+ # other blobs as links, and anything else (e.g. mentions) as its plain-text
89
+ # representation, so mention models should define `attachable_plain_text_representation`.
90
+ #
91
+ # `blob_url` turns a blob into the URL written into the Markdown. It defaults to
92
+ # `rails_blob_path`, which needs Active Storage's routes to be drawn.
93
+ def from_html(input, blob_url: nil)
94
+ content = action_text_content(input)
95
+ return '' if content.blank?
96
+
97
+ blob_url ||= ->(blob) { Rails.application.routes.url_helpers.rails_blob_path(blob, only_path: true) }
98
+ html = content.render_attachments { |attachment| attachment_html(attachment, blob_url) }.to_html
99
+ ReverseMarkdown.convert(markdown_ready_fragment(html), unknown_tags: :bypass, github_flavored: true).strip
100
+ end
101
+
102
+ private
103
+ # ReverseMarkdown only escapes `*` and `_`, and writes hrefs, srcs and alts verbatim. Without
104
+ # this, text that reads as Markdown (`[a](javascript:...)`, `# heading`, `1. item`) or a
105
+ # `)` in a URL would turn into different, attacker-chosen Markdown on the next to_html.
106
+ def markdown_ready_fragment(html)
107
+ sanitized = sanitizer.sanitize(html, tags: ALLOWED_TAGS, attributes: ALLOWED_ATTRIBUTES)
108
+ fragment = Nokogiri::HTML::DocumentFragment.parse(sanitized)
109
+
110
+ fragment.xpath('.//text()[not(ancestor::code or ancestor::pre)]').each do |node|
111
+ node.content = escape_text(node.content)
112
+ end
113
+ fragment.css('a[href]').each { |link| link['href'] = escape_url(link['href']) }
114
+ fragment.css('img').each do |image|
115
+ image['src'] = escape_url(image['src']) if image['src']
116
+ image['alt'] = image['alt'].gsub(INLINE_SYNTAX) { |char| "\\#{char}" } if image['alt']
117
+ end
118
+ fragment.xpath('.//code[not(ancestor::pre)]').each { |code| code.name = CodeSpanConverter::TAG }
119
+ fragment.css('pre').each { |pre| pre.name = CodeBlockConverter::TAG }
120
+
121
+ fragment
122
+ end
123
+
124
+ def sanitizer
125
+ @sanitizer ||= Rails::HTML::Sanitizer.best_supported_vendor.safe_list_sanitizer.new(prune: true)
126
+ end
127
+
128
+ # Over-escaping is harmless: Redcarpet renders `\#` mid-line as `#`. So every text node is
129
+ # treated as a possible line start rather than tracking where lines really begin.
130
+ def escape_text(text)
131
+ text
132
+ .gsub(INLINE_SYNTAX) { |char| "\\#{char}" }
133
+ .sub(/\A(\s*)([#>+=-])/) { "#{Regexp.last_match(1)}\\#{Regexp.last_match(2)}" }
134
+ .sub(/\A(\s*\d+)\./) { "#{Regexp.last_match(1)}\\." }
135
+ end
136
+
137
+ def escape_url(url)
138
+ url.gsub(/[\s()<>]/) { |char| ERB::Util.url_encode(char) }
139
+ end
140
+
141
+ def action_text_content(input)
142
+ case input
143
+ when ::ActionText::RichText then input.body || ::ActionText::Content.new('')
144
+ when ::ActionText::Content then input
145
+ else ::ActionText::Content.new(input.to_s)
146
+ end
147
+ end
148
+
149
+ def attachment_html(attachment, blob_url)
150
+ attachable = attachment.attachable
151
+
152
+ case attachable
153
+ when ::ActiveStorage::Blob
154
+ label = attachment.caption || attachable.filename.to_s
155
+ url = blob_url.call(attachable)
156
+ attachable.image? ? helpers.tag.img(src: url, alt: label) : helpers.link_to(label, url)
157
+ when ::ActionText::Attachables::RemoteImage
158
+ helpers.tag.img(src: attachable.url, alt: attachment.caption)
159
+ else
160
+ text = attachment.to_plain_text
161
+ # ContentAttachment returns its HTML fragment rather than a string.
162
+ text = text.text if text.respond_to?(:text)
163
+ ERB::Util.html_escape(text.to_s)
164
+ end
165
+ end
166
+
167
+ def helpers
168
+ ActionController::Base.helpers
169
+ end
170
+ end
171
+ end
172
+ end
@@ -1,4 +1,4 @@
1
- markdown = ReverseMarkdown.convert(html, unknown_tags: :bypass, github_flavored: true).strip
1
+ markdown = glib_html_to_markdown(html)
2
2
 
3
3
  view.panels_vertical id: 'action_text_conversion', width: 'matchParent', childViews: ->(panel) do
4
4
  panel.h3 text: 'Output HTML (what the field submits)'
@@ -47,7 +47,7 @@ page.form url: json_ui_garage_url(path: 'forms/basic_post'), method: 'post', pad
47
47
  label: 'Content',
48
48
  name: 'user[message]',
49
49
  # value: "<p>Test <img src='{{image1}}'</p>",
50
- # value: glib_format_markdown(initial_message),
50
+ # value: glib_markdown_to_html(initial_message),
51
51
  value: initial_message,
52
52
  mentionList: mention_list,
53
53
  imageUploader: {
@@ -137,7 +137,8 @@ page.body(
137
137
  res.h2 text: 'Markdown and HTML output'
138
138
  res.spacer height: 8
139
139
  res.p text: "Replaces fields_richText's produce/accept. The field only speaks HTML, so the server converts: " \
140
- 'stored Markdown becomes the HTML value, and the submitted HTML becomes Markdown.'
140
+ 'Glib::Markdown.to_html turns stored Markdown into the value, and Glib::Markdown.from_html ' \
141
+ 'turns the submitted HTML (mentions and attachments included) back into Markdown.'
141
142
  res.spacer height: 8
142
143
  res.h3 text: 'Stored Markdown (input)'
143
144
  res.markdown text: "```markdown\n#{stored_markdown.strip}\n```"
@@ -152,7 +153,7 @@ page.body(
152
153
  width: 'matchParent',
153
154
  label: 'Value converted from Markdown on the server',
154
155
  name: 'post[body]',
155
- value: glib_format_markdown(stored_markdown)
156
+ value: glib_markdown_to_html(stored_markdown)
156
157
  )
157
158
  form.spacer height: 8
158
159
  form.fields_submit text: 'Convert output'
@@ -4,6 +4,7 @@ module Glib
4
4
  base.helper Glib::UrlsHelper
5
5
  base.helper Glib::FormsHelper
6
6
  base.helper Glib::EnumHelper
7
+ base.helper Glib::FormatHelper
7
8
  base.helper Glib::DynamicTextsHelper
8
9
  base.helper Glib::DynamicImagesHelper
9
10
  base.helper Glib::AppFeatureSupportHelper
metadata CHANGED
@@ -1,14 +1,13 @@
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.2.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - ''
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2026-11-19 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: activestorage
@@ -150,6 +149,20 @@ dependencies:
150
149
  - - ">="
151
150
  - !ruby/object:Gem::Version
152
151
  version: '0'
152
+ - !ruby/object:Gem::Dependency
153
+ name: reverse_markdown
154
+ requirement: !ruby/object:Gem::Requirement
155
+ requirements:
156
+ - - "~>"
157
+ - !ruby/object:Gem::Version
158
+ version: '3.1'
159
+ type: :runtime
160
+ prerelease: false
161
+ version_requirements: !ruby/object:Gem::Requirement
162
+ requirements:
163
+ - - "~>"
164
+ - !ruby/object:Gem::Version
165
+ version: '3.1'
153
166
  - !ruby/object:Gem::Dependency
154
167
  name: ostruct
155
168
  requirement: !ruby/object:Gem::Requirement
@@ -206,7 +219,6 @@ dependencies:
206
219
  - - ">="
207
220
  - !ruby/object:Gem::Version
208
221
  version: '0'
209
- description:
210
222
  email: ''
211
223
  executables: []
212
224
  extensions: []
@@ -265,6 +277,7 @@ files:
265
277
  - app/helpers/glib/json_ui/default.rb
266
278
  - app/helpers/glib/json_ui/dynamic_field_builders.rb
267
279
  - app/helpers/glib/json_ui/generic_builders.rb
280
+ - app/helpers/glib/json_ui/hash_schema.rb
268
281
  - app/helpers/glib/json_ui/json_logic_lint.rb
269
282
  - app/helpers/glib/json_ui/list_builders.rb
270
283
  - app/helpers/glib/json_ui/menu_builder.rb
@@ -295,6 +308,7 @@ files:
295
308
  - app/models/glib/country_list.rb
296
309
  - app/models/glib/dummy_job_application.rb
297
310
  - app/models/glib/dynamic_text_record.rb
311
+ - app/models/glib/markdown.rb
298
312
  - app/models/glib/model.rb
299
313
  - app/models/glib/plain_model.rb
300
314
  - app/models/glib/scheduled_job_run.rb
@@ -778,10 +792,8 @@ files:
778
792
  - lib/glib/time_returning_mailer.rb
779
793
  - lib/glib/value.rb
780
794
  - lib/tasks/db.rake
781
- homepage:
782
795
  licenses: []
783
796
  metadata: {}
784
- post_install_message:
785
797
  rdoc_options: []
786
798
  require_paths:
787
799
  - lib
@@ -796,8 +808,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
796
808
  - !ruby/object:Gem::Version
797
809
  version: '0'
798
810
  requirements: []
799
- rubygems_version: 3.5.22
800
- signing_key:
811
+ rubygems_version: 4.0.6
801
812
  specification_version: 4
802
813
  summary: ''
803
814
  test_files: []