dommy 0.16.0 → 0.17.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.
Files changed (122) hide show
  1. checksums.yaml +4 -4
  2. data/lib/dommy/animation.rb +1 -0
  3. data/lib/dommy/backend.rb +3 -0
  4. data/lib/dommy/blob.rb +6 -0
  5. data/lib/dommy/browser.rb +12 -4
  6. data/lib/dommy/character_data.rb +1 -13
  7. data/lib/dommy/cookie_store.rb +2 -1
  8. data/lib/dommy/document.rb +67 -30
  9. data/lib/dommy/element.rb +11 -0
  10. data/lib/dommy/element_internals.rb +12 -0
  11. data/lib/dommy/encodings/legacy_multibyte.rb +800 -0
  12. data/lib/dommy/encodings/multibyte_overrides.rb +76 -0
  13. data/lib/dommy/encodings/prescan.rb +234 -0
  14. data/lib/dommy/encodings.rb +121 -57
  15. data/lib/dommy/event.rb +107 -54
  16. data/lib/dommy/event_source.rb +1 -0
  17. data/lib/dommy/fetch.rb +244 -53
  18. data/lib/dommy/file_reader.rb +1 -0
  19. data/lib/dommy/form_data.rb +22 -9
  20. data/lib/dommy/form_entry_list.rb +3 -3
  21. data/lib/dommy/html_canvas_element.rb +85 -12
  22. data/lib/dommy/html_elements/base.rb +1 -0
  23. data/lib/dommy/html_elements/forms/input.rb +3 -0
  24. data/lib/dommy/html_elements/interactive.rb +56 -48
  25. data/lib/dommy/html_elements/metadata.rb +23 -0
  26. data/lib/dommy/interaction/form_submission.rb +24 -42
  27. data/lib/dommy/internal/accessibility_tree.rb +149 -162
  28. data/lib/dommy/internal/accessibility_visibility.rb +16 -17
  29. data/lib/dommy/internal/accessible_name.rb +231 -246
  30. data/lib/dommy/internal/aria_role.rb +182 -195
  31. data/lib/dommy/internal/aria_snapshot.rb +35 -38
  32. data/lib/dommy/internal/aria_state.rb +102 -118
  33. data/lib/dommy/internal/autofill.rb +75 -75
  34. data/lib/dommy/internal/backend_prefilter.rb +127 -130
  35. data/lib/dommy/internal/child_navigable.rb +86 -83
  36. data/lib/dommy/internal/close_watcher_manager.rb +1 -0
  37. data/lib/dommy/internal/css/ancestor_filter.rb +64 -64
  38. data/lib/dommy/internal/css/calc.rb +90 -71
  39. data/lib/dommy/internal/css/cascade.rb +69 -67
  40. data/lib/dommy/internal/css/color.rb +249 -187
  41. data/lib/dommy/internal/css/computed_style_builder.rb +34 -0
  42. data/lib/dommy/internal/css/computed_style_declaration.rb +50 -11
  43. data/lib/dommy/internal/css/counters.rb +67 -67
  44. data/lib/dommy/internal/css/custom_properties.rb +114 -114
  45. data/lib/dommy/internal/css/parser.rb +277 -239
  46. data/lib/dommy/internal/css/property_registry.rb +321 -302
  47. data/lib/dommy/internal/css/renderability.rb +37 -35
  48. data/lib/dommy/internal/css/rule_index.rb +2 -2
  49. data/lib/dommy/internal/css/rule_index_inputs.rb +2 -2
  50. data/lib/dommy/internal/css/supports.rb +115 -113
  51. data/lib/dommy/internal/css/ua_stylesheet.rb +55 -53
  52. data/lib/dommy/internal/css_rule_text.rb +121 -119
  53. data/lib/dommy/internal/css_source.rb +1 -3
  54. data/lib/dommy/internal/css_syntax.rb +157 -92
  55. data/lib/dommy/internal/declarative_shadow_roots.rb +1 -0
  56. data/lib/dommy/internal/directionality.rb +120 -123
  57. data/lib/dommy/internal/document_live_ranges.rb +26 -1
  58. data/lib/dommy/internal/dom_matching.rb +185 -184
  59. data/lib/dommy/internal/element_geometry.rb +8 -1
  60. data/lib/dommy/internal/element_matching.rb +71 -69
  61. data/lib/dommy/internal/element_shadow.rb +1 -13
  62. data/lib/dommy/internal/element_state.rb +255 -265
  63. data/lib/dommy/internal/event_handlers.rb +66 -64
  64. data/lib/dommy/internal/exception_report.rb +88 -86
  65. data/lib/dommy/internal/focusability.rb +205 -205
  66. data/lib/dommy/internal/global_functions.rb +49 -47
  67. data/lib/dommy/internal/idl_reflection.rb +99 -97
  68. data/lib/dommy/internal/js_number.rb +35 -33
  69. data/lib/dommy/internal/light_dismiss.rb +130 -132
  70. data/lib/dommy/internal/literal_lookup.rb +75 -75
  71. data/lib/dommy/internal/mime_type.rb +54 -49
  72. data/lib/dommy/internal/mutation_coordinator.rb +46 -0
  73. data/lib/dommy/internal/mutation_observer_microtask.rb +60 -0
  74. data/lib/dommy/internal/namespaces.rb +51 -49
  75. data/lib/dommy/internal/node_adopter.rb +25 -1
  76. data/lib/dommy/internal/node_equality.rb +61 -59
  77. data/lib/dommy/internal/post_insertion_steps.rb +1 -0
  78. data/lib/dommy/internal/referrer.rb +144 -0
  79. data/lib/dommy/internal/rendered_text/collector.rb +22 -3
  80. data/lib/dommy/internal/rendered_text/computed_box.rb +3 -2
  81. data/lib/dommy/internal/rendered_text/fragment.rb +37 -38
  82. data/lib/dommy/internal/rendered_text/items.rb +7 -5
  83. data/lib/dommy/internal/selector_matcher.rb +361 -359
  84. data/lib/dommy/internal/selector_parser.rb +74 -62
  85. data/lib/dommy/internal/sequential_focus_navigation.rb +150 -151
  86. data/lib/dommy/internal/shadow_root_registry.rb +7 -0
  87. data/lib/dommy/internal/slot_assignment.rb +117 -0
  88. data/lib/dommy/internal/slot_signals.rb +125 -0
  89. data/lib/dommy/internal/unsafe_html.rb +79 -77
  90. data/lib/dommy/internal/url_parser.rb +5 -29
  91. data/lib/dommy/internal/web_idl.rb +158 -153
  92. data/lib/dommy/internal/window_bound.rb +14 -0
  93. data/lib/dommy/internal/window_constructors.rb +3 -0
  94. data/lib/dommy/internal/xml_serialization.rb +298 -296
  95. data/lib/dommy/js/dom_interfaces.rb +13 -1
  96. data/lib/dommy/js/host_bridge.rb +23 -1
  97. data/lib/dommy/js/host_callbacks.rb +7 -0
  98. data/lib/dommy/js/host_runtime.js +625 -61
  99. data/lib/dommy/js/import_map.rb +1 -1
  100. data/lib/dommy/js/observable_runtime.js +295 -128
  101. data/lib/dommy/js/webidl_members.js +1 -1
  102. data/lib/dommy/js/webidl_signatures.js +35 -6
  103. data/lib/dommy/media_query_list.rb +1 -0
  104. data/lib/dommy/message_channel.rb +2 -0
  105. data/lib/dommy/mutation_observer.rb +25 -29
  106. data/lib/dommy/navigator.rb +4 -1
  107. data/lib/dommy/node.rb +4 -0
  108. data/lib/dommy/notification.rb +1 -0
  109. data/lib/dommy/promise.rb +12 -0
  110. data/lib/dommy/range.rb +20 -3
  111. data/lib/dommy/shadow_root.rb +25 -1
  112. data/lib/dommy/streams.rb +18 -0
  113. data/lib/dommy/style_declaration.rb +15 -4
  114. data/lib/dommy/text_codec.rb +7 -5
  115. data/lib/dommy/tree_walker.rb +68 -61
  116. data/lib/dommy/version.rb +1 -1
  117. data/lib/dommy/web_socket.rb +1 -0
  118. data/lib/dommy/window.rb +22 -4
  119. data/lib/dommy/worker.rb +1 -0
  120. data/lib/dommy/xml_http_request.rb +12 -2
  121. data/lib/dommy.rb +17 -2
  122. metadata +11 -3
@@ -175,36 +175,109 @@ module Dommy
175
175
  end
176
176
  end
177
177
 
178
- # `ctx.getImageData(...)` / `createImageData(...)` result: width, height, and a
179
- # zeroed RGBA `data` buffer of length width*height*4 (a plain numeric array,
180
- # which supports the `.length` and `data[i]` reads canvas code does).
178
+ # `ctx.getImageData(...)` / `createImageData(...)` result: a width, a height
179
+ # and pixels. Dommy paints nothing, so the pixels are transparent black until
180
+ # a page writes them, and the page writes into its own `data` typed array
181
+ # (host_runtime.js), which stays in the JS realm.
182
+ #
183
+ # The pixels come here only for an ImageData this side may keep beyond any
184
+ # one JS proxy of it: the clone a message or a history state delivers
185
+ # (`__dommyClone`), or one script handed over (a MessageEvent's `data`). It
186
+ # holds the pixels the page wrote (`__dommyPixels`, packed bytes), given
187
+ # when it is made or when the last proxy that could write them goes.
181
188
  class ImageData
182
189
  attr_reader :width, :height
183
190
 
184
- def initialize(width, height)
191
+ def initialize(width, height, pixels = nil, clone: false)
185
192
  @width = [width.to_i, 0].max
186
193
  @height = [height.to_i, 0].max
187
- @data = Array.new(@width * @height * 4, 0)
194
+ @pixels = pixels
195
+ @clone = clone
188
196
  end
189
197
 
190
- # ImageData's serialization + deserialization steps: same size, a copy of
191
- # the pixels.
198
+ # `new ImageData(sw, sh [, settings])`, transparent black, or
199
+ # `new ImageData(data, sw [, sh [, settings]])` over `data`'s pixels. From
200
+ # script, the realm keeps the Uint8ClampedArray itself as the pixels and
201
+ # hands this the size alone (host_runtime.js constructImageData); bytes
202
+ # given from Ruby are copied, an Array's numbers clamped to bytes as a
203
+ # Uint8ClampedArray stores them.
204
+ #
205
+ # Spec: https://html.spec.whatwg.org/#dom-imagedata
206
+ def self.construct(args)
207
+ raise Bridge::TypeError, "Failed to construct 'ImageData': 2 arguments required" if args.length < 2
208
+
209
+ first = args[0]
210
+ return from_data(first.pack_bytes, args) if first.is_a?(Bridge::Bytes)
211
+ return from_data(clamped_bytes(first), args) if first.is_a?(Array)
212
+
213
+ width = Internal::WebIDL.unsigned_long(first)
214
+ height = Internal::WebIDL.unsigned_long(args[1])
215
+ raise DOMException::IndexSizeError, "Failed to construct 'ImageData': the source width is zero" if width.zero?
216
+ raise DOMException::IndexSizeError, "Failed to construct 'ImageData': the source height is zero" if height.zero?
217
+
218
+ new(width, height)
219
+ end
220
+
221
+ def self.from_data(bytes, args)
222
+ if bytes.empty? || (bytes.bytesize % 4).nonzero?
223
+ raise DOMException::InvalidStateError, "Failed to construct 'ImageData': the data length is not a nonzero multiple of 4"
224
+ end
225
+
226
+ width = Internal::WebIDL.unsigned_long(args[1])
227
+ raise DOMException::IndexSizeError, "Failed to construct 'ImageData': the source width is zero" if width.zero?
228
+
229
+ pixel_count = bytes.bytesize / 4
230
+ raise DOMException::IndexSizeError, "Failed to construct 'ImageData': the data length is not a multiple of the width" if (pixel_count % width).nonzero?
231
+
232
+ height = pixel_count / width
233
+ given = args[2]
234
+ if !given.nil? && !given.equal?(Bridge::UNDEFINED) && Internal::WebIDL.unsigned_long(given) != height
235
+ raise DOMException::IndexSizeError, "Failed to construct 'ImageData': the data length is not width * height * 4"
236
+ end
237
+
238
+ new(width, height, bytes)
239
+ end
240
+ private_class_method :from_data
241
+
242
+ # WebIDL's ToUint8Clamp of each value: NaN is 0, and the rest is clamped
243
+ # to 0..255 and rounded half to even.
244
+ def self.clamped_bytes(values)
245
+ values.map do |value|
246
+ number = Internal::WebIDL.unrestricted_double(value)
247
+ number.nan? ? 0 : number.clamp(0, 255).round(half: :even)
248
+ end.pack("C*")
249
+ end
250
+ private_class_method :clamped_bytes
251
+
252
+ # ImageData's serialization + deserialization steps: the same size and the
253
+ # pixels this side holds (JS adds the ones its typed array holds).
192
254
  def __internal_structured_clone__(_for_storage = false)
193
- copy = ImageData.new(@width, @height)
194
- copy.instance_variable_set(:@data, @data.dup)
195
- copy
255
+ ImageData.new(@width, @height, @pixels, clone: true)
196
256
  end
197
257
 
198
258
  def __js_get__(key)
199
259
  case key
200
260
  when "width" then @width
201
261
  when "height" then @height
202
- when "data" then @data
262
+ when "data" then @pixels ? @pixels.unpack("C*") : Array.new(byte_length, 0)
263
+ when "__dommyPixels" then @pixels && Bridge::Bytes.new(@pixels)
264
+ when "__dommyClone" then @clone
203
265
  when "colorSpace" then "srgb"
204
266
  else Bridge::ABSENT
205
267
  end
206
268
  end
207
269
 
208
- def __js_set__(_key, _value) = Bridge::UNHANDLED
270
+ # The pixels of a deserialized clone, from the serialized record. A buffer
271
+ # of any other length is not this image's.
272
+ def __js_set__(key, value)
273
+ return Bridge::UNHANDLED unless key == "__dommyPixels"
274
+
275
+ @pixels = value.is_a?(Bridge::Bytes) && value.length == byte_length ? value.pack_bytes : nil
276
+ nil
277
+ end
278
+
279
+ private
280
+
281
+ def byte_length = @width * @height * 4
209
282
  end
210
283
  end
@@ -177,6 +177,7 @@ module Dommy
177
177
  case method
178
178
  when "click"
179
179
  click
180
+ Bridge::UNDEFINED
180
181
  when "attachInternals"
181
182
  attach_internals
182
183
  else
@@ -308,6 +308,8 @@ module Dommy
308
308
  return form&.__internal_run_form_submission__(self) if __internal_submit_button__?
309
309
  return form&.reset if type == "reset" && !disabled
310
310
  return unless CHECKABLE_TYPES.include?(type) && is_connected?
311
+ # A radio that was already checked did not change, so it fires neither.
312
+ return if type == "radio" && @__radio_was_checked
311
313
 
312
314
  dispatch_event(Event.new("input", "bubbles" => true).__internal_mark_trusted__)
313
315
  dispatch_event(Event.new("change", "bubbles" => true).__internal_mark_trusted__)
@@ -347,6 +349,7 @@ module Dommy
347
349
  { kind: :checkbox, old_checked: old, old_indeterminate: old_indeterminate }
348
350
  when "radio"
349
351
  old_checked = checked
352
+ @__radio_was_checked = old_checked
350
353
  previously_checked = old_checked ? nil : currently_checked_in_radio_group
351
354
  self.checked = true
352
355
  { kind: :radio, old_checked: old_checked, previously_checked: previously_checked }
@@ -203,6 +203,11 @@ module Dommy
203
203
  if popover_showing?
204
204
  raise DOMException::InvalidStateError, "showModal() called on a dialog that is showing as a popover"
205
205
  end
206
+ # A document with no browsing context (createHTMLDocument's, DOMParser's)
207
+ # is not fully active, and has no top layer to show it in.
208
+ unless @document.default_view&.__internal_fully_active__?
209
+ raise DOMException::InvalidStateError, "showModal() called on a dialog whose document is not fully active"
210
+ end
206
211
 
207
212
  return nil unless fire_beforetoggle(false, true, source)
208
213
  # A beforetoggle listener may have opened, disconnected, or
@@ -486,17 +491,30 @@ module Dommy
486
491
  class HTMLSlotElement < HTMLElement
487
492
  # Own __js_call__ methods, on top of Element's.
488
493
 
489
- # `slot.assignedNodes({ flatten: true|false })` — returns the
490
- # light DOM children currently composed into this slot. With
491
- # `flatten: true` and no assigned nodes, falls back to the
492
- # slot's own children (the default content).
494
+ # `slot.assignedNodes({ flatten })`: the slottables assigned to this slot,
495
+ # or with `flatten`, DOM's "find flattened slottables" — a slot among
496
+ # them (or among the fallback children, when nothing is assigned) is
497
+ # replaced by its own flattened slottables, and a slot outside a shadow
498
+ # tree has none.
493
499
  def assigned_nodes(options = nil)
494
- flatten = options.is_a?(Hash) ? (options["flatten"] || options[:flatten]) : false
495
- nodes = matching_light_nodes
496
- if nodes.empty? && flatten
497
- @__node__.children.map { |n| @document.wrap_node(n) }.compact
498
- else
499
- nodes
500
+ flatten = options.is_a?(Hash) && Internal::WebIDL.boolean(options.key?("flatten") ? options["flatten"] : options[:flatten])
501
+ flatten ? __internal_flattened_slottables__ : Internal::SlotAssignment.find_slottables(@document, self)
502
+ end
503
+
504
+ # Spec: https://dom.spec.whatwg.org/#find-flattened-slotables
505
+ def __internal_flattened_slottables__
506
+ return [] unless @document.__internal_shadow_root_containing__(@__node__)
507
+
508
+ slottables = Internal::SlotAssignment.find_slottables(@document, self)
509
+ if slottables.empty?
510
+ slottables = @__node__.children.filter_map { |n| @document.wrap_node(n) if Internal::SlotAssignment.slottable?(n) }
511
+ end
512
+ slottables.flat_map do |node|
513
+ if node.is_a?(HTMLSlotElement) && @document.__internal_shadow_root_containing__(node.__dommy_backend_node__)
514
+ node.__internal_flattened_slottables__
515
+ else
516
+ [node]
517
+ end
500
518
  end
501
519
  end
502
520
 
@@ -504,16 +522,38 @@ module Dommy
504
522
  assigned_nodes(options).select { |n| n.is_a?(Element) }
505
523
  end
506
524
 
507
- # `slot.assign(...)` — manual assignment (honored only when the
508
- # owning shadow uses `slotAssignment: "manual"`). We accept the
509
- # call and fire `slotchange` in both modes; named mode simply
510
- # ignores the override.
525
+ # `slot.assign(...nodes)`: the slot's manually assigned nodes, which a
526
+ # shadow root with `slotAssignment: "manual"` uses. A node assigned to
527
+ # another slot leaves it. This slot and those the nodes left get their
528
+ # slotchange when their assigned nodes came out different.
529
+ #
530
+ # Spec: https://html.spec.whatwg.org/#dom-slot-assign
511
531
  def assign(*nodes)
512
- @__manual_assignment = nodes.flatten.select { |n| n.is_a?(Node) && n.__dommy_backend_node__ }
513
- dispatch_event(Event.new("slotchange", "bubbles" => true))
532
+ nodes = nodes.flatten.select { |n| n.is_a?(Node) && n.__dommy_backend_node__ }
533
+ affected = [self, *nodes.filter_map(&:__internal_manual_slot__)].uniq(&:object_id)
534
+ before = affected.map { |slot| Internal::SlotAssignment.find_slottables(@document, slot) }
535
+ __internal_manual_assignment__.each { |node| node.__internal_manual_slot__ = nil if node.__internal_manual_slot__.equal?(self) }
536
+ nodes.each do |node|
537
+ previous = node.__internal_manual_slot__
538
+ previous.__internal_drop_manual_assignment__(node) if previous && !previous.equal?(self)
539
+ node.__internal_manual_slot__ = self
540
+ end
541
+ @__manual_assignment = nodes.uniq(&:object_id)
542
+ signals = @document.__internal_slot_signals__
543
+ affected.zip(before).each do |slot, was|
544
+ now = Internal::SlotAssignment.find_slottables(@document, slot)
545
+ signals.signal(slot) unless now.length == was.length && now.zip(was).all? { |a, b| a.equal?(b) }
546
+ end
514
547
  nil
515
548
  end
516
549
 
550
+ # The nodes `assign()` gave this slot, in assignment order.
551
+ def __internal_manual_assignment__ = @__manual_assignment || []
552
+
553
+ def __internal_drop_manual_assignment__(node)
554
+ @__manual_assignment&.reject! { |n| n.equal?(node) }
555
+ end
556
+
517
557
  js_readable :assigned_nodes, :assigned_elements
518
558
 
519
559
  js_methods %w[assignedNodes assignedElements assign]
@@ -529,38 +569,6 @@ module Dommy
529
569
  super
530
570
  end
531
571
  end
532
-
533
- private
534
-
535
- def matching_light_nodes
536
- sr = @document.__internal_shadow_root_containing__(@__node__)
537
- return [] unless sr
538
-
539
- host = sr.host
540
- return [] unless host
541
-
542
- slot_name = name
543
- # Manual mode honors the explicit list.
544
- if sr.slot_assignment == "manual" && @__manual_assignment
545
- return @__manual_assignment
546
- end
547
-
548
- host
549
- .__dommy_backend_node__
550
- .children
551
- .map do |child|
552
- wrapped = @document.wrap_node(child)
553
- next nil unless wrapped
554
-
555
- attr_value = child.element? ? Backend.no_namespace_attribute_value(child, "slot").to_s : ""
556
- if slot_name.empty?
557
- attr_value.empty? ? wrapped : nil
558
- else
559
- (child.element? && attr_value == slot_name) ? wrapped : nil
560
- end
561
- end
562
- .compact
563
- end
564
572
  end
565
573
 
566
574
  # `<select>` — exposes `value` (selected option's value), `options`,
@@ -476,6 +476,29 @@ module Dommy
476
476
  @document.__internal_pragma_default_language__ = language if language
477
477
  end
478
478
 
479
+ # HTML's referrer metadata steps, run when a meta element is inserted into
480
+ # the document or has its name or content changed: one in the document
481
+ # tree named `referrer` whose content (ASCII lowercased, the legacy
482
+ # keywords mapped) is a nonempty referrer policy sets the document's. For
483
+ # historical reasons removing one does nothing and tree order does not
484
+ # matter: the most recently inserted or changed one has the effect.
485
+ #
486
+ # Spec: https://html.spec.whatwg.org/#meta-referrer
487
+ def __internal_run_referrer_metadata__
488
+ return unless __internal_attribute_value__("name").to_s.downcase(:ascii) == "referrer"
489
+
490
+ value = __internal_attribute_value__("content").to_s.downcase(:ascii)
491
+ return if value.empty? || !get_root_node.equal?(@document)
492
+
493
+ value = Internal::Referrer::LEGACY_META_POLICIES.fetch(value, value)
494
+ @document.__internal_referrer_policy__ = value if Internal::Referrer::POLICIES.include?(value)
495
+ end
496
+
497
+ def __internal_attribute_changed__(name, _old_value, _new_value, namespace)
498
+ super
499
+ __internal_run_referrer_metadata__ if namespace.nil? && (name == "name" || name == "content")
500
+ end
501
+
479
502
  private
480
503
 
481
504
  # The Content language state's steps: no content attribute, or one with a
@@ -22,20 +22,22 @@ module Dommy
22
22
  @method_override_param = method_override_param
23
23
  end
24
24
 
25
- # Returns { method:, url:, params:, enctype:, target: }, or nil when the
26
- # form is already constructing its entry list (HTML returns then).
25
+ # Returns { method:, method_override:, url:, params:, enctype:, target: },
26
+ # or nil when the form is already constructing its entry list (HTML
27
+ # returns then). `method_override` says the method is a `_method`
28
+ # field's: the request a browser sends is a POST.
27
29
  def submit!
28
- method = form_method
29
30
  list = entry_list
30
31
  return nil if list.nil?
31
32
 
32
33
  params = reduce_files(list.entries)
33
- method = apply_method_override(method, params)
34
+ method = apply_method_override(form_method, params)
34
35
  params = normalize_line_endings(params)
35
36
  params = apply_charset(params)
36
37
 
37
38
  {
38
39
  method: method,
40
+ method_override: method != form_method,
39
41
  url: resolve_action(form_method),
40
42
  params: params,
41
43
  enctype: form_enctype,
@@ -64,9 +66,7 @@ module Dommy
64
66
  def entry_list
65
67
  return @entry_list if defined?(@entry_list)
66
68
 
67
- @entry_list = Dommy::FormEntryList.new(
68
- @form, submitter: @submitter, encoding: form_charset || Encoding::UTF_8
69
- ).form_data
69
+ @entry_list = Dommy::FormEntryList.new(@form, submitter: @submitter, encoding: form_charset).form_data
70
70
  end
71
71
 
72
72
  # A non-multipart form submits only a file's basename, per browsers. The
@@ -127,56 +127,38 @@ module Dommy
127
127
  # represents every character, so it is a no-op.
128
128
  def apply_charset(pairs)
129
129
  charset = form_charset
130
- return pairs if charset.nil? || charset == Encoding::UTF_8
130
+ return pairs if charset == "UTF-8"
131
131
 
132
132
  pairs.map { |name, value| [encode_in(name, charset), encode_in(value, charset)] }
133
133
  end
134
134
 
135
+ # HTML "pick an encoding for the form": the first `accept-charset` label
136
+ # that names an encoding, else UTF-8 when it has none that does, else
137
+ # (no attribute) the document's character encoding; as an output
138
+ # encoding, so UTF-16 and replacement submit UTF-8.
139
+ #
140
+ # Spec: https://html.spec.whatwg.org/#picking-an-encoding-for-the-form
135
141
  def form_charset
136
- raw = attr(@form, "accept-charset").to_s
137
- token = raw.split(/[\s,]+/).find { |t| !t.empty? }
138
- return nil unless token
139
-
140
- begin
141
- Encoding.find(token)
142
- rescue ArgumentError
143
- nil
142
+ @form_charset ||= begin
143
+ raw = attr(@form, "accept-charset")
144
+ name =
145
+ if raw
146
+ raw.split(/[\t\n\f\r ]+/).filter_map { |label| Encodings.get(label) unless label.empty? }.first || "UTF-8"
147
+ else
148
+ @form.owner_document&.character_encoding || "UTF-8"
149
+ end
150
+ Encodings.output_encoding(name)
144
151
  end
145
152
  end
146
153
 
147
154
  def encode_in(value, charset)
148
155
  case value
149
156
  when Array then value.map { |v| encode_in(v, charset) }
150
- when String then encode_string(value, charset)
157
+ when String then Encodings.encode(charset, value.scrub("\u{FFFD}")) { |code_point| "&##{code_point};".bytes }
151
158
  else value # File/Blob pass through unchanged
152
159
  end
153
160
  end
154
161
 
155
- # Byte string in `charset`, with each code point the charset cannot
156
- # represent emitted as `&#N;` (and a lone surrogate as U+FFFD).
157
- def encode_string(value, charset)
158
- source = value.valid_encoding? ? value : value.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
159
- source.each_codepoint.each_with_object(+"".b) do |code_point, out|
160
- char = code_point_char(code_point)
161
- if char.nil?
162
- out << "&#65533;" # a lone surrogate is U+FFFD
163
- next
164
- end
165
-
166
- begin
167
- out << char.encode(charset).b
168
- rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError
169
- out << "&##{code_point};"
170
- end
171
- end
172
- end
173
-
174
- def code_point_char(code_point)
175
- code_point.chr(Encoding::UTF_8)
176
- rescue RangeError
177
- nil
178
- end
179
-
180
162
  def apply_method_override(method, pairs)
181
163
  return method unless method == "POST" && @respect_method_override
182
164