dommy 0.15.0 → 0.16.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 (171) hide show
  1. checksums.yaml +4 -4
  2. data/lib/dommy/backend.rb +16 -15
  3. data/lib/dommy/blob.rb +17 -0
  4. data/lib/dommy/bridge/values.rb +29 -2
  5. data/lib/dommy/bridge/wire_tags.rb +8 -4
  6. data/lib/dommy/browser.rb +324 -49
  7. data/lib/dommy/character_data.rb +20 -27
  8. data/lib/dommy/class_list.rb +24 -9
  9. data/lib/dommy/cookie_jar.rb +408 -0
  10. data/lib/dommy/cookie_store.rb +104 -49
  11. data/lib/dommy/css.rb +34 -8
  12. data/lib/dommy/custom_elements.rb +362 -114
  13. data/lib/dommy/data_transfer.rb +22 -2
  14. data/lib/dommy/document.rb +1071 -200
  15. data/lib/dommy/dom_exception.rb +6 -0
  16. data/lib/dommy/dom_parser.rb +46 -14
  17. data/lib/dommy/dom_string_list.rb +36 -0
  18. data/lib/dommy/element.rb +217 -102
  19. data/lib/dommy/element_internals.rb +215 -0
  20. data/lib/dommy/encodings.rb +10 -0
  21. data/lib/dommy/event.rb +378 -122
  22. data/lib/dommy/event_source.rb +4 -30
  23. data/lib/dommy/file_reader.rb +5 -29
  24. data/lib/dommy/form_data.rb +40 -6
  25. data/lib/dommy/form_entry_list.rb +106 -137
  26. data/lib/dommy/fragment.rb +11 -10
  27. data/lib/dommy/history.rb +247 -90
  28. data/lib/dommy/html_canvas_element.rb +15 -35
  29. data/lib/dommy/html_collection.rb +49 -30
  30. data/lib/dommy/html_elements/base.rb +111 -69
  31. data/lib/dommy/html_elements/embedded.rb +349 -105
  32. data/lib/dommy/html_elements/forms/form.rb +407 -368
  33. data/lib/dommy/html_elements/forms/input.rb +333 -174
  34. data/lib/dommy/html_elements/forms/select.rb +90 -74
  35. data/lib/dommy/html_elements/interactive.rb +274 -64
  36. data/lib/dommy/html_elements/media.rb +71 -30
  37. data/lib/dommy/html_elements/metadata.rb +215 -71
  38. data/lib/dommy/html_elements/miscellaneous.rb +58 -14
  39. data/lib/dommy/html_elements/tables.rb +7 -9
  40. data/lib/dommy/html_elements.rb +23 -1
  41. data/lib/dommy/hyperlink_utils.rb +15 -4
  42. data/lib/dommy/interaction/drag_and_drop.rb +187 -0
  43. data/lib/dommy/interaction/event_synthesis.rb +182 -24
  44. data/lib/dommy/interaction/field_interactor.rb +17 -5
  45. data/lib/dommy/interaction/form_submission.rb +10 -4
  46. data/lib/dommy/interaction/key_sender.rb +101 -16
  47. data/lib/dommy/interaction.rb +1 -0
  48. data/lib/dommy/internal/accessibility_tree.rb +15 -3
  49. data/lib/dommy/internal/accessible_description.rb +1 -1
  50. data/lib/dommy/internal/accessible_name.rb +10 -17
  51. data/lib/dommy/internal/aria_role.rb +1 -1
  52. data/lib/dommy/internal/autofill.rb +2 -2
  53. data/lib/dommy/internal/backend_prefilter.rb +1 -5
  54. data/lib/dommy/internal/ce_reactions.rb +285 -0
  55. data/lib/dommy/internal/ce_reactions_table.rb +296 -0
  56. data/lib/dommy/internal/child_list.rb +7 -43
  57. data/lib/dommy/internal/child_navigable.rb +155 -0
  58. data/lib/dommy/internal/child_node.rb +44 -41
  59. data/lib/dommy/internal/close_watcher_manager.rb +238 -0
  60. data/lib/dommy/internal/complex_match.rb +3 -1
  61. data/lib/dommy/internal/constraint_validation.rb +130 -0
  62. data/lib/dommy/internal/css/ancestor_filter.rb +107 -0
  63. data/lib/dommy/internal/css/cascade.rb +7 -7
  64. data/lib/dommy/internal/css/cascaded_declarations.rb +4 -1
  65. data/lib/dommy/internal/css/computed_style_builder.rb +9 -3
  66. data/lib/dommy/internal/css/custom_properties.rb +41 -29
  67. data/lib/dommy/internal/css/parser.rb +0 -22
  68. data/lib/dommy/internal/css/renderability.rb +6 -0
  69. data/lib/dommy/internal/css/rule_index.rb +149 -98
  70. data/lib/dommy/internal/css/rule_index_inputs.rb +135 -0
  71. data/lib/dommy/internal/css/selector_dependencies.rb +8 -2
  72. data/lib/dommy/internal/css/style_cache.rb +7 -4
  73. data/lib/dommy/internal/css/ua_stylesheet.rb +34 -0
  74. data/lib/dommy/internal/declarative_shadow_roots.rb +182 -0
  75. data/lib/dommy/internal/document_generations.rb +55 -2
  76. data/lib/dommy/internal/document_interaction_state.rb +293 -9
  77. data/lib/dommy/internal/dom_matching.rb +2 -2
  78. data/lib/dommy/internal/element_aria.rb +25 -19
  79. data/lib/dommy/internal/element_popover.rb +226 -25
  80. data/lib/dommy/internal/element_shadow.rb +97 -26
  81. data/lib/dommy/internal/element_state.rb +98 -5
  82. data/lib/dommy/internal/element_top_layer.rb +15 -1
  83. data/lib/dommy/internal/enumerated_keyword_sets.rb +40 -0
  84. data/lib/dommy/internal/event_handler_tables.rb +241 -0
  85. data/lib/dommy/internal/event_handlers.rb +149 -0
  86. data/lib/dommy/internal/exception_report.rb +1 -1
  87. data/lib/dommy/internal/focusability.rb +267 -0
  88. data/lib/dommy/internal/form_associated_custom_elements.rb +127 -0
  89. data/lib/dommy/internal/html_or_svg_or_mathml_element.rb +34 -23
  90. data/lib/dommy/internal/html_serialization.rb +292 -0
  91. data/lib/dommy/internal/idl_reflection.rb +202 -0
  92. data/lib/dommy/internal/idl_reflection_table.rb +589 -0
  93. data/lib/dommy/internal/infra.rb +9 -0
  94. data/lib/dommy/internal/input_type.rb +76 -18
  95. data/lib/dommy/internal/insertion_point.rb +27 -3
  96. data/lib/dommy/internal/js_number.rb +60 -0
  97. data/lib/dommy/internal/light_dismiss.rb +178 -0
  98. data/lib/dommy/internal/mime_type.rb +8 -0
  99. data/lib/dommy/internal/mutation_coordinator.rb +94 -62
  100. data/lib/dommy/internal/node_adopter.rb +52 -4
  101. data/lib/dommy/internal/node_factory.rb +111 -7
  102. data/lib/dommy/internal/node_identity.rb +1 -1
  103. data/lib/dommy/internal/node_traversal.rb +22 -4
  104. data/lib/dommy/internal/node_wrapper_cache.rb +6 -38
  105. data/lib/dommy/internal/observer_options.rb +24 -14
  106. data/lib/dommy/internal/origin.rb +86 -0
  107. data/lib/dommy/internal/parent_node.rb +10 -8
  108. data/lib/dommy/internal/popover_invoker_element.rb +67 -0
  109. data/lib/dommy/internal/popover_stack.rb +120 -0
  110. data/lib/dommy/internal/post_insertion_steps.rb +140 -71
  111. data/lib/dommy/internal/reflected_attributes.rb +128 -18
  112. data/lib/dommy/internal/rendered_text/collector.rb +1 -5
  113. data/lib/dommy/internal/rendered_text/fragment.rb +6 -2
  114. data/lib/dommy/internal/selector_arguments.rb +2 -1
  115. data/lib/dommy/internal/selector_match.rb +1 -1
  116. data/lib/dommy/internal/selector_matcher.rb +11 -6
  117. data/lib/dommy/internal/selector_parser.rb +14 -1
  118. data/lib/dommy/internal/sequential_focus_navigation.rb +210 -0
  119. data/lib/dommy/internal/shadow_root_registry.rb +7 -0
  120. data/lib/dommy/internal/template_content_registry.rb +7 -1
  121. data/lib/dommy/internal/text_selection.rb +185 -32
  122. data/lib/dommy/internal/toggle_events.rb +6 -4
  123. data/lib/dommy/internal/unsafe_html.rb +107 -0
  124. data/lib/dommy/internal/url_parser.rb +84 -8
  125. data/lib/dommy/internal/user_activation.rb +192 -0
  126. data/lib/dommy/internal/web_idl.rb +149 -16
  127. data/lib/dommy/internal/window_constructors.rb +26 -6
  128. data/lib/dommy/internal/xml_serialization.rb +3 -3
  129. data/lib/dommy/js/constructor_resolver.rb +18 -0
  130. data/lib/dommy/js/custom_element_bridge.rb +57 -82
  131. data/lib/dommy/js/dom_interfaces.rb +50 -15
  132. data/lib/dommy/js/host_bridge.rb +189 -40
  133. data/lib/dommy/js/host_runtime.js +1897 -415
  134. data/lib/dommy/js/marshaller.rb +13 -4
  135. data/lib/dommy/js/module_loader.rb +37 -6
  136. data/lib/dommy/js/module_preload.rb +107 -29
  137. data/lib/dommy/js/script_boot.rb +197 -115
  138. data/lib/dommy/js/serialized_record.rb +32 -0
  139. data/lib/dommy/js/webidl_event_handlers.js +45 -0
  140. data/lib/dommy/js/webidl_members.js +196 -0
  141. data/lib/dommy/js/webidl_signatures.js +2055 -0
  142. data/lib/dommy/js/webidl_tables.js +47 -100
  143. data/lib/dommy/js/window_wiring.rb +9 -5
  144. data/lib/dommy/location.rb +129 -76
  145. data/lib/dommy/media_query_list.rb +4 -13
  146. data/lib/dommy/message_channel.rb +137 -64
  147. data/lib/dommy/mutation_observer.rb +2 -0
  148. data/lib/dommy/navigation.rb +59 -9
  149. data/lib/dommy/navigator.rb +131 -5
  150. data/lib/dommy/node.rb +19 -11
  151. data/lib/dommy/notification.rb +9 -1
  152. data/lib/dommy/promise.rb +8 -0
  153. data/lib/dommy/range.rb +5 -34
  154. data/lib/dommy/resources.rb +38 -3
  155. data/lib/dommy/scheduler.rb +176 -48
  156. data/lib/dommy/shadow_root.rb +117 -19
  157. data/lib/dommy/storage.rb +135 -25
  158. data/lib/dommy/structured_data.rb +45 -0
  159. data/lib/dommy/style_declaration.rb +16 -0
  160. data/lib/dommy/text_codec.rb +2 -14
  161. data/lib/dommy/tree_walker.rb +10 -18
  162. data/lib/dommy/url.rb +11 -4
  163. data/lib/dommy/validity_state.rb +109 -107
  164. data/lib/dommy/version.rb +1 -1
  165. data/lib/dommy/web_socket.rb +5 -28
  166. data/lib/dommy/window.rb +811 -99
  167. data/lib/dommy/worker.rb +4 -28
  168. data/lib/dommy/xml_http_request.rb +32 -45
  169. data/lib/dommy.rb +35 -1
  170. metadata +35 -4
  171. data/lib/dommy/internal/cookie_jar.rb +0 -29
@@ -30,6 +30,11 @@ module Dommy
30
30
  # reflect_string view_box: "viewBox", class_name: { attr: "class" }
31
31
  # reflect_boolean :disabled, :required
32
32
  #
33
+ # Most declarations are not written in the element classes at all:
34
+ # Internal::IdlReflection makes them from the specs' IDL once every
35
+ # class is defined, for each reflected attribute a class does not
36
+ # declare (or write an accessor for) itself.
37
+ #
33
38
  # Identifier defaults (override via a String or Hash value):
34
39
  # - js_key (camelCase IDL name) = camelize(ruby_name)
35
40
  # - attr (content attribute) = camelize(ruby_name)
@@ -63,9 +68,11 @@ module Dommy
63
68
  url: %i[reflected_url set_reflected_string],
64
69
  long: %i[reflected_long set_reflected_long],
65
70
  ulong: %i[reflected_ulong set_reflected_ulong],
71
+ double: %i[reflected_double set_reflected_double],
66
72
  token_list: %i[reflected_token_list set_reflected_token_list],
67
73
  boolean: %i[reflected_boolean set_reflected_boolean],
68
74
  enumerated: %i[reflected_enumerated set_reflected_enumerated],
75
+ element_ref: %i[reflected_element set_reflected_element],
69
76
  setter_only: [nil, :set_reflected_string],
70
77
  long_setter: [nil, :set_reflected_long],
71
78
  ulong_setter: [nil, :set_reflected_ulong],
@@ -81,6 +88,12 @@ module Dommy
81
88
  _reflect(:boolean, names, mapped)
82
89
  end
83
90
 
91
+ # An `Element?` attribute (HTML §2.6.1 "reflecting element
92
+ # references"): `button.commandForElement`, `popoverTargetElement`.
93
+ def reflect_element(*names, **mapped)
94
+ _reflect(:element_ref, names, mapped)
95
+ end
96
+
84
97
  # An IDL attribute the specs reflect "limited to only known values" —
85
98
  # HTML §2.6.1's enumerated-DOMString algorithm, defined against the
86
99
  # states HTML §2.3.3 gives the content attribute. Unlike the other
@@ -119,6 +132,8 @@ module Dommy
119
132
 
120
133
  # A [SameObject] DOMTokenList over a space-separated attribute
121
134
  # (`a.relList`, `iframe.sandbox`). Read-only: the list mutates itself.
135
+ # `supported:` is the attribute's supported tokens (an
136
+ # Internal::SupportedTokens list); without it `supports()` throws.
122
137
  def reflect_token_list(*names, **mapped)
123
138
  _reflect(:token_list, names, mapped)
124
139
  end
@@ -135,7 +150,8 @@ module Dommy
135
150
 
136
151
  # An `unsigned long` attribute. `range:` is [ReflectRange], which clamps
137
152
  # an out-of-range value to the nearest end instead of falling back;
138
- # `default:` is [ReflectDefault] and `positive:` is [ReflectPositive].
153
+ # `default:` is [ReflectDefault] and `positive:` is [ReflectPositive]
154
+ # (with `fallback: true`, [ReflectPositiveWithFallback]).
139
155
  #
140
156
  # reflect_ulong :width, :height # default 0
141
157
  # reflect_ulong col_span: { attr: "colspan", default: 1,
@@ -144,6 +160,14 @@ module Dommy
144
160
  _reflect(:ulong, names, mapped)
145
161
  end
146
162
 
163
+ # A `double` attribute. `positive:` is [ReflectPositive] and `default:`
164
+ # [ReflectDefault]:
165
+ #
166
+ # reflect_double max: { positive: true, default: 1.0 } # progress.max
167
+ def reflect_double(*names, **mapped)
168
+ _reflect(:double, names, mapped)
169
+ end
170
+
147
171
  # The same, for a setter that takes a number: `[ReflectSetter]` says only
148
172
  # that the getter is prose, not what the setter converts, and that comes
149
173
  # from the IDL type — `img.width` is an `unsigned long` and `meter.value`
@@ -266,7 +290,9 @@ module Dommy
266
290
  end
267
291
  end
268
292
 
269
- def _reflect(type, names, mapped)
293
+ # `generated:` marks a declaration Internal::IdlReflection made from the
294
+ # IDL rather than one the class wrote.
295
+ def _reflect(type, names, mapped, generated: false)
270
296
  @__reflected_props__ ||= {}
271
297
  @__writable_props__ ||= {}
272
298
  @__reflect_specs__ ||= {}
@@ -288,7 +314,8 @@ module Dommy
288
314
  @__writable_props__[js] = ruby_name
289
315
  end
290
316
  @__reflected_props__[js] = ruby_name
291
- @__reflect_specs__[js] = { type: DECLARED_AS.fetch(type, type), attr: attr }
317
+ @__reflect_specs__[js] = { type: DECLARED_AS.fetch(type, type), attr: attr, options: options,
318
+ generated: generated }.freeze
292
319
  end
293
320
  end
294
321
 
@@ -381,6 +408,70 @@ module Dommy
381
408
  parsed if parsed && !parsed.negative?
382
409
  end
383
410
 
411
+ # HTML's "rules for parsing floating-point number values" (§2.3.4.3):
412
+ # leading ASCII whitespace, an optional sign, digits with an optional
413
+ # fraction and exponent — and, like the integer rules, it stops at the
414
+ # first character that does not fit rather than failing on it ("1.5px"
415
+ # is 1.5, "2e" is 2, "1e3x" is 1000). Only a missing number is an error
416
+ # (nil): "", "-", ".", ".e1", "e1", "\v7" (U+000B is not ASCII
417
+ # whitespace). The result is rounded to the nearest double, -0 becomes 0,
418
+ # and a value that rounds past the largest double is an error too.
419
+ # Ruby's own Float() is NOT this: it takes "1_0", "0x1A" and "\v7", and
420
+ # rejects trailing junk.
421
+ def parse_html_float(value)
422
+ ReflectedAttributes.parse_floating_point_number(value)
423
+ end
424
+
425
+ # The same, callable without an element (forms, meter, progress). The
426
+ # steps collect the number's sign, digits, fraction and exponent; the
427
+ # decimal they spell is then rounded once, by Float(), as the
428
+ # "conversion" step asks.
429
+ def self.parse_floating_point_number(value)
430
+ return nil if value.nil?
431
+
432
+ input = value.to_s
433
+ position = input.index(/[^ \t\n\f\r]/) or return nil
434
+ negative = false
435
+ case input[position]
436
+ when "-"
437
+ negative = true
438
+ position += 1
439
+ when "+"
440
+ position += 1
441
+ end
442
+
443
+ integer = input[position..][/\A\d+/]
444
+ if integer
445
+ position += integer.length
446
+ elsif input[position] == "." && input[position + 1]&.match?(/\d/)
447
+ integer = "0"
448
+ else
449
+ return nil
450
+ end
451
+
452
+ fraction = "0"
453
+ if input[position] == "."
454
+ digits = input[(position + 1)..][/\A\d+/]
455
+ if digits
456
+ fraction = digits
457
+ position += 1 + digits.length
458
+ elsif input[position + 1]&.match?(/[eE]/)
459
+ position += 1
460
+ end
461
+ end
462
+
463
+ exponent = "0"
464
+ if input[position]&.match?(/[eE]/)
465
+ exponent_match = input[(position + 1)..][/\A[-+]?\d+/]
466
+ exponent = exponent_match if exponent_match
467
+ end
468
+
469
+ number = Float("#{negative ? "-" : ""}#{integer}.#{fraction}e#{exponent}")
470
+ return nil if number.infinite?
471
+
472
+ number.zero? ? 0.0 : number
473
+ end
474
+
384
475
  # A `long` attribute's getter (HTML §2.6.1): the parsed value when it is
385
476
  # one and fits a long, else the declared default, else -1 when the
386
477
  # attribute is limited to non-negative numbers, else 0.
@@ -441,7 +532,11 @@ module Dommy
441
532
  # negative value round, which is why `colSpan = -1` also stores "1".
442
533
  def set_reflected_ulong(name, value, options = EMPTY_OPTIONS)
443
534
  given = to_webidl_ulong(value)
444
- raise DOMException::IndexSizeError, "#{name} must be positive" if options[:positive] && given.zero?
535
+ # [ReflectPositive] throws on 0; [ReflectPositiveWithFallback]
536
+ # (`fallback: true`) writes the default instead.
537
+ if options[:positive] && !options[:fallback] && given.zero?
538
+ raise DOMException::IndexSizeError, "#{name} must be positive"
539
+ end
445
540
 
446
541
  minimum = options[:positive] ? 1 : 0
447
542
  new_value = options.fetch(:default, minimum)
@@ -449,6 +544,16 @@ module Dommy
449
544
  __internal_set_attribute_value__(name, new_value.to_s)
450
545
  end
451
546
 
547
+ # A `double` attribute's getter (HTML §2.6.1): the content attribute by
548
+ # the floating-point rules — when it parses, and is greater than zero for
549
+ # a [ReflectPositive] one — else the default, else 0.
550
+ def reflected_double(name, options = EMPTY_OPTIONS)
551
+ parsed = parse_html_float(__internal_attribute_value__(name))
552
+ return parsed if parsed && (parsed.positive? || !options[:positive])
553
+
554
+ options.fetch(:default, 0.0).to_f
555
+ end
556
+
452
557
  # A `double` attribute's setter: the value converted to the best
453
558
  # representation of the number as a floating-point number — which is the
454
559
  # SHORTEST one, so 5.0 writes "5" and not "5.0".
@@ -464,22 +569,16 @@ module Dommy
464
569
  # WebIDL's `double` (the restricted one): every ES value converts, but a
465
570
  # non-finite result is a TypeError rather than an attribute saying "NaN".
466
571
  def to_webidl_double(value)
467
- number =
468
- case value
469
- when Numeric then value.to_f
470
- when nil then 0.0
471
- when true then 1.0
472
- when false then 0.0
473
- when String then value.strip.empty? ? 0.0 : (Float(value.strip) rescue ::Float::NAN)
474
- else ::Float::NAN
475
- end
572
+ number = WebIDL.unrestricted_double(value)
476
573
  raise Bridge::TypeError, "The provided double value is non-finite." if number.nan? || number.infinite?
477
574
 
478
575
  number
479
576
  end
480
577
 
578
+ # HTML's "best representation of the number as a floating-point number"
579
+ # is ECMAScript's ToString: 5.0 writes "5", 1e25 "1e+25", 1e-7 "1e-7".
481
580
  def format_webidl_double(number)
482
- number == number.to_i ? number.to_i.to_s : number.to_s
581
+ JsNumber.to_string(number)
483
582
  end
484
583
 
485
584
  # WebIDL's integer conversions, which run before any of the above sees the
@@ -500,16 +599,27 @@ module Dommy
500
599
  # A [SameObject] DOMTokenList over `name`, memoized so `el.relList` is the
501
600
  # same object every time — which is what lets a page keep a reference to it
502
601
  # and watch the attribute through it.
503
- def reflected_token_list(name, _options = nil)
504
- (@reflected_token_lists ||= {})[name] ||= ClassList.new(self, name)
602
+ def reflected_token_list(name, options = EMPTY_OPTIONS)
603
+ (@reflected_token_lists ||= {})[name] ||= ClassList.new(self, name, options[:supported])
505
604
  end
506
605
 
507
606
  # WebIDL [PutForwards=value]: a token-list attribute is readonly, but
508
607
  # assigning to it assigns to the list's `value`, which rewrites the whole
509
608
  # content attribute — so `iframe.sandbox = "allow-scripts"` works, and
510
609
  # `iframe.sandbox` is still the same DOMTokenList afterwards.
511
- def set_reflected_token_list(name, value, _options = nil)
512
- reflected_token_list(name).value = value
610
+ def set_reflected_token_list(name, value, options = EMPTY_OPTIONS)
611
+ reflected_token_list(name, options).value = value
612
+ end
613
+
614
+ # The attr-associated element: the element set through the IDL
615
+ # attribute while it stays in a valid scope, else the first element in
616
+ # this element's tree whose ID is the content attribute's value (the
617
+ # ARIA element reflection, Internal::ElementAria, keyed by the content
618
+ # attribute).
619
+ def reflected_element(name, _options = nil) = aria_element_get(name, name)
620
+
621
+ def set_reflected_element(name, value, _options = nil)
622
+ aria_element_set(name, name, value)
513
623
  end
514
624
 
515
625
  def reflected_boolean(name, _options = nil)
@@ -217,11 +217,7 @@ module Dommy
217
217
  @boxes[element] ||= ComputedBox.from(style(element))
218
218
  end
219
219
 
220
- def style(element)
221
- CSS::Cascade.computed_style(element)
222
- rescue CSS::Parser::Unavailable
223
- {}
224
- end
220
+ def style(element) = CSS::Cascade.computed_style(element)
225
221
  end
226
222
  end
227
223
  end
@@ -26,7 +26,10 @@ module Dommy
26
26
  nodes = fragment(element.document, value.to_s)
27
27
  nodes = [element.document.create_text_node("")] if nodes.empty?
28
28
  element.replace_with(*nodes)
29
- merge_next_text_node(following)
29
+ # `next`'s previous sibling is now the fragment's last node; when it
30
+ # is a Text node it absorbs the Text node after it (which is `next`
31
+ # itself when `next` is a Text node).
32
+ merge_next_text_node(following.previous_sibling) if following
30
33
  merge_next_text_node(preceding) if preceding.is_a?(TextNode)
31
34
  nil
32
35
  end
@@ -43,7 +46,8 @@ module Dommy
43
46
  following = node.next_sibling
44
47
  return unless following.is_a?(TextNode)
45
48
 
46
- node.data = node.data + following.data
49
+ # "Replace data" with node, its length, 0, and next's data.
50
+ node.append_data(following.data)
47
51
  following.remove
48
52
  end
49
53
 
@@ -20,7 +20,8 @@ module Dommy
20
20
  fullscreen future has host hover in-range indeterminate invalid is lang
21
21
  last-child last-of-type left link local-link modal not nth-child nth-col
22
22
  nth-last-child nth-last-col nth-last-of-type nth-of-type only-child
23
- only-of-type optional out-of-range past placeholder-shown playing paused
23
+ only-of-type open optional out-of-range past placeholder-shown playing paused
24
+ popover-open
24
25
  read-only read-write required right root scope target target-within
25
26
  user-invalid user-valid valid visited where dir
26
27
  before after first-line first-letter
@@ -25,7 +25,7 @@ module Dommy
25
25
  # #complex?; only fast_query's single-selector paths pass it, where the
26
26
  # one prefilter belongs to the one complex selector in the list.
27
27
  def list?(element, selector_ast, verified: nil)
28
- return false unless element&.respond_to?(:__dommy_backend_node__)
28
+ return false unless element.is_a?(Node) && element.__dommy_backend_node__
29
29
 
30
30
  selector_ast.selectors.any? { |complex| complex?(element, complex, verified: verified) }
31
31
  end
@@ -12,7 +12,7 @@ module Dommy
12
12
 
13
13
  # `verified:` — see Match#list?.
14
14
  def matches?(element, selector_ast, scope: nil, verified: nil)
15
- return false unless element&.respond_to?(:__dommy_backend_node__)
15
+ return false unless element.is_a?(Node) && element.__dommy_backend_node__
16
16
 
17
17
  Match.for(element.owner_document, scope).list?(element, selector_ast, verified: verified)
18
18
  end
@@ -275,10 +275,9 @@ module Dommy
275
275
  when "checked" then Internal.checked_state?(element)
276
276
  when "enabled" then ElementState.enableable_element?(element) && !ElementState.disabled_element?(element)
277
277
  when "disabled" then ElementState.enableable_element?(element) && ElementState.disabled_element?(element)
278
- when "focus", "focus-visible" then element.owner_document&.__internal_focused_element__.equal?(element)
279
- when "focus-within"
280
- focused = element.owner_document&.__internal_focused_element__
281
- focused && (element.equal?(focused) || element.contains?(focused))
278
+ when "focus" then ElementState.has_focus?(element)
279
+ when "focus-visible" then ElementState.focus_visible?(element)
280
+ when "focus-within" then ElementState.focus_within?(element)
282
281
  when "hover"
283
282
  hovered = element.owner_document&.__internal_hovered_element__
284
283
  hovered && (element.equal?(hovered) || element.contains?(hovered))
@@ -294,6 +293,12 @@ module Dommy
294
293
  when "lang" then ElementState.lang_match?(element, pseudo.argument)
295
294
  when "link" then ElementState.link_element?(element)
296
295
  when "any-link" then ElementState.link_element?(element)
296
+ when "popover-open" then ElementState.popover_open?(element)
297
+ when "open" then ElementState.open_element?(element)
298
+ when "modal" then ElementState.modal_element?(element)
299
+ when "fullscreen" then ElementState.fullscreen_element?(element)
300
+ when "defined" then ElementState.defined_element?(element)
301
+ when "state" then ElementState.custom_state?(element, pseudo.argument)
297
302
  else
298
303
  false
299
304
  end
@@ -370,7 +375,7 @@ module Dommy
370
375
  def default_scope(root)
371
376
  return root.document_element if root.is_a?(Document)
372
377
 
373
- root if root.respond_to?(:__dommy_backend_node__)
378
+ root if root.__dommy_backend_node__
374
379
  end
375
380
 
376
381
  # `:target` — the element the document's URL fragment points at. It has to
@@ -39,7 +39,7 @@ module Dommy
39
39
  # are functional pseudo-elements handled in the `::` path.
40
40
  SELECTOR_LIST_FUNCTIONS = %w[not is where has matches].to_set.freeze
41
41
  NTH_FUNCTIONS = %w[nth-child nth-last-child nth-of-type nth-last-of-type nth-col nth-last-col].to_set.freeze
42
- IDENT_FUNCTIONS = %w[lang dir].to_set.freeze
42
+ IDENT_FUNCTIONS = %w[lang dir state].to_set.freeze
43
43
  NESTED_SELECTOR_FUNCTIONS = %w[host host-context current].to_set.freeze
44
44
 
45
45
  # A parsed AST is a pure function of (selector string, namespaces) and never
@@ -490,6 +490,8 @@ module Dommy
490
490
  rels
491
491
  elsif NTH_FUNCTIONS.include?(name)
492
492
  parse_nth_argument(arg, allow_of: %w[nth-child nth-last-child].include?(name))
493
+ elsif name == "state"
494
+ parse_custom_ident_argument(arg)
493
495
  elsif IDENT_FUNCTIONS.include?(name)
494
496
  parse_ident_argument(arg)
495
497
  elsif NESTED_SELECTOR_FUNCTIONS.include?(name)
@@ -682,6 +684,17 @@ module Dommy
682
684
  end
683
685
  end
684
686
 
687
+ # `:state(<custom-ident>)`: exactly one CSS identifier (an escape
688
+ # stands for its character).
689
+ CUSTOM_IDENT = /\A(?:--|-?(?:[_a-zA-Z]|[^\x00-\x7F]|\\.))(?:[-_a-zA-Z0-9]|[^\x00-\x7F]|\\.)*\z/m
690
+
691
+ def parse_custom_ident_argument(source)
692
+ ident = source.strip
693
+ fail!("expected an identifier") unless ident.match?(CUSTOM_IDENT)
694
+
695
+ ident.gsub(/\\(.)/m, "\\1")
696
+ end
697
+
685
698
  def parse_ident_argument(source)
686
699
  parts = source.split(/\s*,\s*|\s+/).reject(&:empty?)
687
700
  fail!("expected identifier") if parts.empty?
@@ -0,0 +1,210 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dommy
4
+ module Internal
5
+ # HTML §6.6.3/§6.6.5 sequential focus navigation — what Tab and
6
+ # Shift+Tab do: the document's sequential focus navigation order (its
7
+ # flattened tabindex-ordered focus navigation scope), the sequential
8
+ # navigation search algorithm, and the steps that move the focus
9
+ # forward or backward from the focused area or the sequential focus
10
+ # navigation starting point.
11
+ #
12
+ # Focus navigation scopes: the Document; a shadow host (its shadow
13
+ # tree's elements); a slot (the elements assigned to it); and the popover
14
+ # trigger of a showing popover, whose contents are navigated right after
15
+ # the trigger. In each scope, elements with a positive tabindex come
16
+ # first, in increasing order, then those with tabindex 0 or none, in
17
+ # shadow-including tree order; a scope owner that is no focusable area
18
+ # (a slot, a host that delegates focus) stands for its scope's contents.
19
+ #
20
+ # Dommy has no browser controls to hand the focus to past either end of
21
+ # the order, so — as HTML allows a user agent without such controls —
22
+ # navigation restarts from the document there and wraps around. Child
23
+ # navigables are not entered: an iframe is a focusable area like any
24
+ # other, since Dommy keeps a frame's focus out of its parent's.
25
+ module SequentialFocusNavigation
26
+ module_function
27
+
28
+ # Move the focus as the user's Tab (`direction` :forward) or Shift+Tab
29
+ # (:backward) in `document` does. Answers the element focused, or nil.
30
+ def navigate(document, direction)
31
+ focused = document.__internal_focused_element__
32
+ starting_point = focused || document
33
+ point = document.__internal_sequential_focus_navigation_starting_point__
34
+ if point && point_usable?(point, document) &&
35
+ (focused.nil? || Retargeting.shadow_including_inclusive_ancestor?(focused, point))
36
+ starting_point = point
37
+ end
38
+
39
+ restarted = false
40
+ loop do
41
+ order = navigation_order(document)
42
+ mechanism = starting_point.equal?(document) || order.any? { |e| e.equal?(starting_point) } ? :sequential : :dom
43
+ candidate = search(document, order, starting_point, direction, mechanism)
44
+ if candidate
45
+ document.__internal_with_focus_type__(:keyboard) { Focusability.run_focusing_steps(candidate) }
46
+ return candidate
47
+ end
48
+
49
+ document.__internal_sequential_focus_navigation_starting_point__ = nil
50
+ # No controls of our own to move to: start over from the document.
51
+ return nil if restarted || starting_point.equal?(document)
52
+
53
+ restarted = true
54
+ starting_point = document
55
+ end
56
+ end
57
+
58
+ # The sequential navigation search algorithm over `order` (the
59
+ # document's sequential focus navigation order).
60
+ def search(document, order, starting_point, direction, mechanism)
61
+ suitable = order.select { |element| suitable?(element) }
62
+ if starting_point.equal?(document)
63
+ return direction == :forward ? suitable.first : suitable.last
64
+ end
65
+
66
+ if mechanism == :sequential
67
+ index = order.index { |e| e.equal?(starting_point) }
68
+ before = order[0...index]
69
+ after = order[(index + 1)..]
70
+ return direction == :forward ? after.find { |e| suitable?(e) } : before.reverse.find { |e| suitable?(e) }
71
+ end
72
+
73
+ # DOM: the suitable area nearest the starting point in shadow-including
74
+ # tree order.
75
+ positions = tree_positions(document)
76
+ start = positions[starting_point]
77
+ return nil if start.nil?
78
+
79
+ ranked = suitable.filter_map { |e| (pos = positions[e]) && [pos, e] }
80
+ if direction == :forward
81
+ ranked.select { |pos, _| pos > start }.min_by(&:first)&.last
82
+ else
83
+ ranked.select { |pos, _| pos < start }.max_by(&:first)&.last
84
+ end
85
+ end
86
+
87
+ # HTML "suitable sequentially focusable area": not inert, and
88
+ # sequentially focusable.
89
+ def suitable?(element) = !Focusability.inert?(element) && Focusability.sequentially_focusable?(element)
90
+
91
+ # The document's sequential focus navigation order: its flattened
92
+ # tabindex-ordered focus navigation scope.
93
+ def navigation_order(document)
94
+ root = document.document_element
95
+ return [] if root.nil?
96
+
97
+ triggers = {}.compare_by_identity
98
+ each_element(root) do |element|
99
+ triggers[element.__internal_popover_trigger__] = true if popover_with_trigger?(element)
100
+ end
101
+ scopes = {}.compare_by_identity
102
+ collect(root, document, scopes)
103
+ flatten(document, scopes, {}.compare_by_identity, triggers)
104
+ end
105
+
106
+ # Every element of the shadow-including tree under `element`.
107
+ def each_element(element, &block)
108
+ yield element
109
+ shadow = element.respond_to?(:__internal_shadow_root__) ? element.__internal_shadow_root__ : nil
110
+ shadow&.children&.to_a&.each { |child| each_element(child, &block) }
111
+ element.children.to_a.each { |child| each_element(child, &block) }
112
+ end
113
+
114
+ # Walk the shadow-including tree, filing each element under its
115
+ # associated focus navigation owner (HTML's algorithm), in tree order.
116
+ def collect(element, owner, scopes)
117
+ owner = element.__internal_popover_trigger__ if popover_with_trigger?(element)
118
+ (scopes[owner] ||= []) << element
119
+
120
+ shadow = element.respond_to?(:__internal_shadow_root__) ? element.__internal_shadow_root__ : nil
121
+ if shadow
122
+ shadow.children.to_a.each { |child| collect(child, element, scopes) }
123
+ element.children.to_a.each do |child|
124
+ slot = child.respond_to?(:assigned_slot) ? child.assigned_slot : nil
125
+ collect(child, slot, scopes) if slot
126
+ end
127
+ elsif slot?(element) && in_shadow_tree?(element)
128
+ # Fallback content is not rendered while the slot has assigned
129
+ # nodes; otherwise it is the slot's scope. (HTML's owner algorithm
130
+ # would file it under the slot's own owner; browsers and WPT's
131
+ # shadow-dom/focus-navigation tests navigate it as the slot's.)
132
+ element.children.to_a.each { |child| collect(child, element, scopes) } if element.assigned_nodes.to_a.empty?
133
+ else
134
+ element.children.to_a.each { |child| collect(child, owner, scopes) }
135
+ end
136
+ end
137
+
138
+ # HTML "flattened tabindex-ordered focus navigation scope" of `owner`.
139
+ def flatten(owner, scopes, visited, triggers)
140
+ visited[owner] = true
141
+ result = []
142
+ tabindex_ordered(scopes[owner] || [], triggers).each do |item|
143
+ if scope_owner?(item, triggers) && !visited[item]
144
+ result << item if Focusability.focusable_area?(item)
145
+ result.concat(flatten(item, scopes, visited, triggers))
146
+ else
147
+ result << item
148
+ end
149
+ end
150
+ result
151
+ end
152
+
153
+ # HTML "tabindex-ordered focus navigation scope": the scope owners and
154
+ # focusable areas of a scope, minus those with a negative tabindex,
155
+ # positive tabindex values first in increasing order, then the rest;
156
+ # tree order otherwise.
157
+ def tabindex_ordered(members, triggers)
158
+ kept = members.select do |element|
159
+ next false unless scope_owner?(element, triggers) || Focusability.focusable_area?(element)
160
+
161
+ value = Focusability.tabindex_value(element)
162
+ value.nil? || value >= 0
163
+ end
164
+ kept.each_with_index.sort_by do |element, index|
165
+ value = Focusability.tabindex_value(element) || 0
166
+ value.positive? ? [0, value, index] : [1, 0, index]
167
+ end.map(&:first)
168
+ end
169
+
170
+ # HTML "focus navigation scope owner" (an element one: the Document is
171
+ # the root's owner).
172
+ def scope_owner?(element, triggers)
173
+ return true if element.respond_to?(:__internal_shadow_root__) && element.__internal_shadow_root__
174
+ return true if slot?(element)
175
+
176
+ triggers.key?(element)
177
+ end
178
+
179
+ def slot?(element) = element.is_a?(HTMLSlotElement)
180
+
181
+ def in_shadow_tree?(element) = element.get_root_node.is_a?(ShadowRoot)
182
+
183
+ def popover_with_trigger?(element)
184
+ element.respond_to?(:__internal_popover_trigger__) && element.__internal_popover_showing__? &&
185
+ !element.__internal_popover_trigger__.nil?
186
+ end
187
+
188
+ def point_usable?(point, document)
189
+ point.respond_to?(:owner_document) && point.owner_document.equal?(document) && point.is_connected?
190
+ end
191
+
192
+ # Each node's position in shadow-including tree order.
193
+ def tree_positions(document)
194
+ positions = {}.compare_by_identity
195
+ counter = 0
196
+ walk = lambda do |node|
197
+ positions[node] = (counter += 1)
198
+ shadow = node.respond_to?(:__internal_shadow_root__) ? node.__internal_shadow_root__ : nil
199
+ walk.call(shadow) if shadow
200
+ node.child_nodes.to_a.each { |child| walk.call(child) } if node.respond_to?(:child_nodes)
201
+ end
202
+ walk.call(document)
203
+ positions
204
+ end
205
+
206
+ private_class_method :search, :suitable?, :each_element, :collect, :flatten, :tabindex_ordered,
207
+ :scope_owner?, :slot?, :in_shadow_tree?, :popover_with_trigger?, :point_usable?, :tree_positions
208
+ end
209
+ end
210
+ end
@@ -40,6 +40,13 @@ module Dommy
40
40
  @shadow_roots.values
41
41
  end
42
42
 
43
+ # Whether any shadow root is registered at all. The flat-tree check
44
+ # short-circuits on this: with none, no element can be a shadow host, so
45
+ # nothing is outside the flat tree and no ancestor walk is needed.
46
+ def any?
47
+ !@shadow_roots.empty?
48
+ end
49
+
43
50
  # The ShadowRoot whose tree the node is in, its own fragment aside. A
44
51
  # shadow root's fragment is the root of its tree, so it can only be the
45
52
  # node's root.
@@ -31,10 +31,16 @@ module Dommy
31
31
  # and a MutationObserver watching it sees the swap. Only the fragment's
32
32
  # children change.
33
33
  #
34
+ # The markup is parsed with the template element itself as the context
35
+ # element (the fragment parsing algorithm's "in template" insertion
36
+ # mode), so `<td>a</td>` keeps its `<td>` instead of being parsed as body
37
+ # content.
38
+ #
34
39
  # Spec: https://html.spec.whatwg.org/#dom-innerhtml
35
40
  def attach(template_element, html)
36
41
  content = fragment_for(template_element)
37
- parsed = Parser.fragment(html.to_s, owner_doc: @document.backend_doc)
42
+ parsed = Parser.fragment(html.to_s, owner_doc: @document.backend_doc,
43
+ context: template_element.__dommy_backend_node__)
38
44
  nodes = parsed.children.to_a
39
45
  content.__internal_replace_all__(nodes)
40
46
  mark_parser_inserted_scripts(nodes)