dommy 0.15.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 (207) hide show
  1. checksums.yaml +4 -4
  2. data/lib/dommy/animation.rb +1 -0
  3. data/lib/dommy/backend.rb +19 -15
  4. data/lib/dommy/blob.rb +23 -0
  5. data/lib/dommy/bridge/values.rb +29 -2
  6. data/lib/dommy/bridge/wire_tags.rb +8 -4
  7. data/lib/dommy/browser.rb +335 -52
  8. data/lib/dommy/character_data.rb +21 -40
  9. data/lib/dommy/class_list.rb +24 -9
  10. data/lib/dommy/cookie_jar.rb +408 -0
  11. data/lib/dommy/cookie_store.rb +105 -49
  12. data/lib/dommy/css.rb +34 -8
  13. data/lib/dommy/custom_elements.rb +362 -114
  14. data/lib/dommy/data_transfer.rb +22 -2
  15. data/lib/dommy/document.rb +1114 -206
  16. data/lib/dommy/dom_exception.rb +6 -0
  17. data/lib/dommy/dom_parser.rb +46 -14
  18. data/lib/dommy/dom_string_list.rb +36 -0
  19. data/lib/dommy/element.rb +228 -102
  20. data/lib/dommy/element_internals.rb +227 -0
  21. data/lib/dommy/encodings/legacy_multibyte.rb +800 -0
  22. data/lib/dommy/encodings/multibyte_overrides.rb +76 -0
  23. data/lib/dommy/encodings/prescan.rb +234 -0
  24. data/lib/dommy/encodings.rb +126 -52
  25. data/lib/dommy/event.rb +472 -163
  26. data/lib/dommy/event_source.rb +5 -30
  27. data/lib/dommy/fetch.rb +244 -53
  28. data/lib/dommy/file_reader.rb +6 -29
  29. data/lib/dommy/form_data.rb +62 -15
  30. data/lib/dommy/form_entry_list.rb +108 -139
  31. data/lib/dommy/fragment.rb +11 -10
  32. data/lib/dommy/history.rb +247 -90
  33. data/lib/dommy/html_canvas_element.rb +95 -42
  34. data/lib/dommy/html_collection.rb +49 -30
  35. data/lib/dommy/html_elements/base.rb +112 -69
  36. data/lib/dommy/html_elements/embedded.rb +349 -105
  37. data/lib/dommy/html_elements/forms/form.rb +407 -368
  38. data/lib/dommy/html_elements/forms/input.rb +336 -174
  39. data/lib/dommy/html_elements/forms/select.rb +90 -74
  40. data/lib/dommy/html_elements/interactive.rb +329 -111
  41. data/lib/dommy/html_elements/media.rb +71 -30
  42. data/lib/dommy/html_elements/metadata.rb +238 -71
  43. data/lib/dommy/html_elements/miscellaneous.rb +58 -14
  44. data/lib/dommy/html_elements/tables.rb +7 -9
  45. data/lib/dommy/html_elements.rb +23 -1
  46. data/lib/dommy/hyperlink_utils.rb +15 -4
  47. data/lib/dommy/interaction/drag_and_drop.rb +187 -0
  48. data/lib/dommy/interaction/event_synthesis.rb +182 -24
  49. data/lib/dommy/interaction/field_interactor.rb +17 -5
  50. data/lib/dommy/interaction/form_submission.rb +31 -43
  51. data/lib/dommy/interaction/key_sender.rb +101 -16
  52. data/lib/dommy/interaction.rb +1 -0
  53. data/lib/dommy/internal/accessibility_tree.rb +149 -150
  54. data/lib/dommy/internal/accessibility_visibility.rb +16 -17
  55. data/lib/dommy/internal/accessible_description.rb +1 -1
  56. data/lib/dommy/internal/accessible_name.rb +231 -253
  57. data/lib/dommy/internal/aria_role.rb +182 -195
  58. data/lib/dommy/internal/aria_snapshot.rb +35 -38
  59. data/lib/dommy/internal/aria_state.rb +102 -118
  60. data/lib/dommy/internal/autofill.rb +75 -75
  61. data/lib/dommy/internal/backend_prefilter.rb +126 -133
  62. data/lib/dommy/internal/ce_reactions.rb +285 -0
  63. data/lib/dommy/internal/ce_reactions_table.rb +296 -0
  64. data/lib/dommy/internal/child_list.rb +7 -43
  65. data/lib/dommy/internal/child_navigable.rb +158 -0
  66. data/lib/dommy/internal/child_node.rb +44 -41
  67. data/lib/dommy/internal/close_watcher_manager.rb +239 -0
  68. data/lib/dommy/internal/complex_match.rb +3 -1
  69. data/lib/dommy/internal/constraint_validation.rb +130 -0
  70. data/lib/dommy/internal/css/ancestor_filter.rb +107 -0
  71. data/lib/dommy/internal/css/calc.rb +90 -71
  72. data/lib/dommy/internal/css/cascade.rb +72 -70
  73. data/lib/dommy/internal/css/cascaded_declarations.rb +4 -1
  74. data/lib/dommy/internal/css/color.rb +249 -187
  75. data/lib/dommy/internal/css/computed_style_builder.rb +43 -3
  76. data/lib/dommy/internal/css/computed_style_declaration.rb +50 -11
  77. data/lib/dommy/internal/css/counters.rb +67 -67
  78. data/lib/dommy/internal/css/custom_properties.rb +115 -103
  79. data/lib/dommy/internal/css/parser.rb +273 -257
  80. data/lib/dommy/internal/css/property_registry.rb +321 -302
  81. data/lib/dommy/internal/css/renderability.rb +39 -31
  82. data/lib/dommy/internal/css/rule_index.rb +151 -100
  83. data/lib/dommy/internal/css/rule_index_inputs.rb +135 -0
  84. data/lib/dommy/internal/css/selector_dependencies.rb +8 -2
  85. data/lib/dommy/internal/css/style_cache.rb +7 -4
  86. data/lib/dommy/internal/css/supports.rb +115 -113
  87. data/lib/dommy/internal/css/ua_stylesheet.rb +60 -24
  88. data/lib/dommy/internal/css_rule_text.rb +121 -119
  89. data/lib/dommy/internal/css_source.rb +1 -3
  90. data/lib/dommy/internal/css_syntax.rb +157 -92
  91. data/lib/dommy/internal/declarative_shadow_roots.rb +183 -0
  92. data/lib/dommy/internal/directionality.rb +120 -123
  93. data/lib/dommy/internal/document_generations.rb +55 -2
  94. data/lib/dommy/internal/document_interaction_state.rb +293 -9
  95. data/lib/dommy/internal/document_live_ranges.rb +26 -1
  96. data/lib/dommy/internal/dom_matching.rb +185 -184
  97. data/lib/dommy/internal/element_aria.rb +25 -19
  98. data/lib/dommy/internal/element_geometry.rb +8 -1
  99. data/lib/dommy/internal/element_matching.rb +71 -69
  100. data/lib/dommy/internal/element_popover.rb +226 -25
  101. data/lib/dommy/internal/element_shadow.rb +98 -39
  102. data/lib/dommy/internal/element_state.rb +264 -181
  103. data/lib/dommy/internal/element_top_layer.rb +15 -1
  104. data/lib/dommy/internal/enumerated_keyword_sets.rb +40 -0
  105. data/lib/dommy/internal/event_handler_tables.rb +241 -0
  106. data/lib/dommy/internal/event_handlers.rb +151 -0
  107. data/lib/dommy/internal/exception_report.rb +89 -87
  108. data/lib/dommy/internal/focusability.rb +267 -0
  109. data/lib/dommy/internal/form_associated_custom_elements.rb +127 -0
  110. data/lib/dommy/internal/global_functions.rb +49 -47
  111. data/lib/dommy/internal/html_or_svg_or_mathml_element.rb +34 -23
  112. data/lib/dommy/internal/html_serialization.rb +292 -0
  113. data/lib/dommy/internal/idl_reflection.rb +204 -0
  114. data/lib/dommy/internal/idl_reflection_table.rb +589 -0
  115. data/lib/dommy/internal/infra.rb +9 -0
  116. data/lib/dommy/internal/input_type.rb +76 -18
  117. data/lib/dommy/internal/insertion_point.rb +27 -3
  118. data/lib/dommy/internal/js_number.rb +62 -0
  119. data/lib/dommy/internal/light_dismiss.rb +176 -0
  120. data/lib/dommy/internal/literal_lookup.rb +75 -75
  121. data/lib/dommy/internal/mime_type.rb +55 -42
  122. data/lib/dommy/internal/mutation_coordinator.rb +140 -62
  123. data/lib/dommy/internal/mutation_observer_microtask.rb +60 -0
  124. data/lib/dommy/internal/namespaces.rb +51 -49
  125. data/lib/dommy/internal/node_adopter.rb +77 -5
  126. data/lib/dommy/internal/node_equality.rb +61 -59
  127. data/lib/dommy/internal/node_factory.rb +111 -7
  128. data/lib/dommy/internal/node_identity.rb +1 -1
  129. data/lib/dommy/internal/node_traversal.rb +22 -4
  130. data/lib/dommy/internal/node_wrapper_cache.rb +6 -38
  131. data/lib/dommy/internal/observer_options.rb +24 -14
  132. data/lib/dommy/internal/origin.rb +86 -0
  133. data/lib/dommy/internal/parent_node.rb +10 -8
  134. data/lib/dommy/internal/popover_invoker_element.rb +67 -0
  135. data/lib/dommy/internal/popover_stack.rb +120 -0
  136. data/lib/dommy/internal/post_insertion_steps.rb +141 -71
  137. data/lib/dommy/internal/referrer.rb +144 -0
  138. data/lib/dommy/internal/reflected_attributes.rb +128 -18
  139. data/lib/dommy/internal/rendered_text/collector.rb +23 -8
  140. data/lib/dommy/internal/rendered_text/computed_box.rb +3 -2
  141. data/lib/dommy/internal/rendered_text/fragment.rb +37 -34
  142. data/lib/dommy/internal/rendered_text/items.rb +7 -5
  143. data/lib/dommy/internal/selector_arguments.rb +2 -1
  144. data/lib/dommy/internal/selector_match.rb +1 -1
  145. data/lib/dommy/internal/selector_matcher.rb +361 -354
  146. data/lib/dommy/internal/selector_parser.rb +88 -63
  147. data/lib/dommy/internal/sequential_focus_navigation.rb +209 -0
  148. data/lib/dommy/internal/shadow_root_registry.rb +14 -0
  149. data/lib/dommy/internal/slot_assignment.rb +117 -0
  150. data/lib/dommy/internal/slot_signals.rb +125 -0
  151. data/lib/dommy/internal/template_content_registry.rb +7 -1
  152. data/lib/dommy/internal/text_selection.rb +185 -32
  153. data/lib/dommy/internal/toggle_events.rb +6 -4
  154. data/lib/dommy/internal/unsafe_html.rb +109 -0
  155. data/lib/dommy/internal/url_parser.rb +89 -37
  156. data/lib/dommy/internal/user_activation.rb +192 -0
  157. data/lib/dommy/internal/web_idl.rb +176 -38
  158. data/lib/dommy/internal/window_bound.rb +14 -0
  159. data/lib/dommy/internal/window_constructors.rb +29 -6
  160. data/lib/dommy/internal/xml_serialization.rb +298 -296
  161. data/lib/dommy/js/constructor_resolver.rb +18 -0
  162. data/lib/dommy/js/custom_element_bridge.rb +57 -82
  163. data/lib/dommy/js/dom_interfaces.rb +63 -16
  164. data/lib/dommy/js/host_bridge.rb +212 -41
  165. data/lib/dommy/js/host_callbacks.rb +7 -0
  166. data/lib/dommy/js/host_runtime.js +2494 -448
  167. data/lib/dommy/js/import_map.rb +1 -1
  168. data/lib/dommy/js/marshaller.rb +13 -4
  169. data/lib/dommy/js/module_loader.rb +37 -6
  170. data/lib/dommy/js/module_preload.rb +107 -29
  171. data/lib/dommy/js/observable_runtime.js +295 -128
  172. data/lib/dommy/js/script_boot.rb +197 -115
  173. data/lib/dommy/js/serialized_record.rb +32 -0
  174. data/lib/dommy/js/webidl_event_handlers.js +45 -0
  175. data/lib/dommy/js/webidl_members.js +196 -0
  176. data/lib/dommy/js/webidl_signatures.js +2084 -0
  177. data/lib/dommy/js/webidl_tables.js +47 -100
  178. data/lib/dommy/js/window_wiring.rb +9 -5
  179. data/lib/dommy/location.rb +129 -76
  180. data/lib/dommy/media_query_list.rb +5 -13
  181. data/lib/dommy/message_channel.rb +139 -64
  182. data/lib/dommy/mutation_observer.rb +27 -29
  183. data/lib/dommy/navigation.rb +59 -9
  184. data/lib/dommy/navigator.rb +135 -6
  185. data/lib/dommy/node.rb +23 -11
  186. data/lib/dommy/notification.rb +10 -1
  187. data/lib/dommy/promise.rb +20 -0
  188. data/lib/dommy/range.rb +25 -37
  189. data/lib/dommy/resources.rb +38 -3
  190. data/lib/dommy/scheduler.rb +176 -48
  191. data/lib/dommy/shadow_root.rb +141 -19
  192. data/lib/dommy/storage.rb +135 -25
  193. data/lib/dommy/streams.rb +18 -0
  194. data/lib/dommy/structured_data.rb +45 -0
  195. data/lib/dommy/style_declaration.rb +31 -4
  196. data/lib/dommy/text_codec.rb +9 -19
  197. data/lib/dommy/tree_walker.rb +78 -79
  198. data/lib/dommy/url.rb +11 -4
  199. data/lib/dommy/validity_state.rb +109 -107
  200. data/lib/dommy/version.rb +1 -1
  201. data/lib/dommy/web_socket.rb +6 -28
  202. data/lib/dommy/window.rb +833 -103
  203. data/lib/dommy/worker.rb +5 -28
  204. data/lib/dommy/xml_http_request.rb +43 -46
  205. data/lib/dommy.rb +52 -3
  206. metadata +45 -6
  207. data/lib/dommy/internal/cookie_jar.rb +0 -29
data/lib/dommy/css.rb CHANGED
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "internal/bounded_cache"
3
4
  require_relative "internal/css/supports"
4
5
 
5
6
  module Dommy
@@ -18,6 +19,13 @@ module Dommy
18
19
  class CSSStyleSheet
19
20
  attr_reader :owner_node, :css_rules
20
21
 
22
+ # A sheet's source text split into its top-level rule texts, shared by
23
+ # every sheet built from the same text: a page's <link> stylesheets are
24
+ # the same files on every page load, and splitting a large one is most of
25
+ # what building its sheet costs. The slices are frozen, and each sheet
26
+ # still makes CSSRule objects of its own, so the CSSOM stays per sheet.
27
+ SPLIT_CACHE = Internal::BoundedCache.new(16)
28
+
21
29
  # A stylesheet constructed by `new CSSStyleSheet()` has no owner node.
22
30
  # Element-owned sheets still pass their <style> / <link> node explicitly.
23
31
  def initialize(owner_node: nil, href: nil, media: nil, title: nil, type: "text/css", source_text: nil)
@@ -27,12 +35,18 @@ module Dommy
27
35
  @title = title
28
36
  @type = type
29
37
  @disabled = false
38
+ # The text the sheet was made from, which the cascade reads until a
39
+ # CSSOM change makes the rules the truth (see #cascade_text).
40
+ @source_text = source_text.to_s.freeze
30
41
  @css_rules = CSSRuleList.new
31
42
  # The owner node's CSS text at sheet creation, split into one CSSRule
32
43
  # per top-level rule (source order) so cssRules mirrors the parsed
33
44
  # sheet — selectorText / style / nested cssRules read off each slice.
34
45
  # insertRule(0) lands before them, appends after, as a real sheet would.
35
- Internal::CSSRuleText.split_rules(source_text).each_with_index do |slice, i|
46
+ slices = SPLIT_CACHE.fetch(source_text.to_s) do
47
+ Internal::CSSRuleText.split_rules(source_text).map(&:freeze).freeze
48
+ end
49
+ slices.each_with_index do |slice, i|
36
50
  @css_rules.__internal_insert__(i, CSSRule.new(slice, self))
37
51
  end
38
52
  end
@@ -50,10 +64,14 @@ module Dommy
50
64
  end
51
65
 
52
66
  # The sheet's full CSS text in document order — what the cascade
53
- # parses in place of the owner `<style>`'s raw text once the sheet
54
- # has been mutated through the CSSOM.
67
+ # parses in place of the owner `<style>`'s raw text. Until the CSSOM
68
+ # changes the sheet that is the text it was made from, as for a <style>
69
+ # with no sheet; after a change, every rule's text, memoized until the
70
+ # next one (serializing every rule of a large sheet is not free).
55
71
  def cascade_text
56
- @css_rules.map(&:css_text).join("\n")
72
+ return @source_text unless @cssom_changed
73
+
74
+ @cascade_text ||= @css_rules.map(&:css_text).join("\n").freeze
57
75
  end
58
76
 
59
77
  def href
@@ -89,7 +107,7 @@ module Dommy
89
107
  raise DOMException::IndexSizeError, "out of range" if idx < 0 || idx > @css_rules.length
90
108
 
91
109
  @css_rules.__internal_insert__(idx, CSSRule.new(rule_text.to_s, self))
92
- __internal_bump_owner_style_generation__
110
+ __internal_note_rules_changed__
93
111
  idx
94
112
  end
95
113
 
@@ -101,7 +119,7 @@ module Dommy
101
119
  raise DOMException::IndexSizeError, "out of range" if idx < 0 || idx >= @css_rules.length
102
120
 
103
121
  @css_rules.__internal_delete_at__(idx)
104
- __internal_bump_owner_style_generation__
122
+ __internal_note_rules_changed__
105
123
  nil
106
124
  end
107
125
 
@@ -128,7 +146,7 @@ module Dommy
128
146
  def replace_sync(text)
129
147
  @css_rules.__internal_clear__
130
148
  @css_rules.__internal_insert__(0, CSSRule.new(text.to_s, self)) unless text.to_s.empty?
131
- __internal_bump_owner_style_generation__
149
+ __internal_note_rules_changed__
132
150
  nil
133
151
  end
134
152
 
@@ -199,11 +217,19 @@ module Dommy
199
217
  # invalidates the owner document's computed style the same way
200
218
  # insertRule/deleteRule do — its rebuilt cssText feeds `cascade_text`.
201
219
  def __internal_notify_rule_changed__
202
- __internal_bump_owner_style_generation__
220
+ __internal_note_rules_changed__
203
221
  end
204
222
 
205
223
  private
206
224
 
225
+ # The rules changed through the CSSOM: from now on they, not the source
226
+ # text, are what the cascade reads.
227
+ def __internal_note_rules_changed__
228
+ @cssom_changed = true
229
+ @cascade_text = nil
230
+ __internal_bump_owner_style_generation__
231
+ end
232
+
207
233
  # CSSOM mutations must invalidate the owner document's computed-style
208
234
  # cache — the rule index re-reads `cascade_text` on the next lookup.
209
235
  def __internal_bump_owner_style_generation__
@@ -1,23 +1,193 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Dommy
4
- # `window.customElements` — registry mapping custom element tag
5
- # names to Ruby classes that extend `HTMLElement`. Lifecycle
6
- # callbacks (`connected_callback` / `disconnected_callback` /
7
- # `attribute_changed_callback` / `adopted_callback`) are invoked by
8
- # the document's mutation pipeline when registered elements are
9
- # added, removed, or have observed attributes mutated.
4
+ # A custom element definition (HTML §4.13.4): the name and local name, the
5
+ # constructor, the observed attributes and the lifecycle callbacks a
6
+ # registry holds for a custom element, and the steps that run them. Two
7
+ # kinds exist: one whose constructor is a Ruby class extending
8
+ # `HTMLElement` (RubyCustomElementDefinition, what `define` registers), and
9
+ # one whose constructor is a page's JS class (Js::JsCustomElementDefinition).
10
+ class CustomElementDefinition
11
+ attr_reader :name, :local_name, :registry, :observed_attributes
12
+
13
+ def initialize(registry:, name:, local_name:, observed_attributes:, callbacks:, disable_shadow: false,
14
+ disable_internals: false, form_associated: false)
15
+ @registry = registry
16
+ @name = name
17
+ @local_name = local_name
18
+ @observed_attributes = observed_attributes.map(&:to_s).freeze
19
+ @callbacks = callbacks.map(&:to_s).to_set.freeze
20
+ @disable_shadow = disable_shadow
21
+ @disable_internals = disable_internals
22
+ @form_associated = form_associated
23
+ end
24
+
25
+ def autonomous? = @name == @local_name
26
+
27
+ def disable_shadow? = @disable_shadow
28
+ def disable_internals? = @disable_internals
29
+ def form_associated? = @form_associated
30
+
31
+ def callback?(callback_name) = @callbacks.include?(callback_name)
32
+
33
+ def observes?(attribute_name) = @observed_attributes.include?(attribute_name)
34
+
35
+ # HTML "upgrade an element", given the element's custom element data.
36
+ # Raises what the construction raised (the reaction invoker reports it).
37
+ def upgrade(data)
38
+ return unless %w[undefined uncustomized].include?(data.state)
39
+
40
+ data.definition = self
41
+ data.state = "failed"
42
+ element = data.wrapper
43
+ element.__internal_attribute_entries__.each do |local_name, value, namespace|
44
+ Internal::CEReactions.enqueue_callback(element, "attributeChangedCallback", [local_name, nil, value, namespace])
45
+ end
46
+ Internal::CEReactions.enqueue_callback(element, "connectedCallback", []) if element.is_connected?
47
+ begin
48
+ if @disable_shadow && element.respond_to?(:__internal_shadow_root__) && element.__internal_shadow_root__
49
+ raise DOMException::NotSupportedError, "the definition disables shadow, but the element has a shadow root"
50
+ end
51
+
52
+ data.state = "precustomized"
53
+ construct_for_upgrade(data)
54
+ rescue StandardError
55
+ data.definition = nil
56
+ data.reactions.clear
57
+ raise
58
+ end
59
+ if form_associated?
60
+ # Step 9: the form owner is reset, and the callbacks it and the
61
+ # disabled state call for are enqueued.
62
+ form = element.__internal_form_owner__
63
+ disabled = element.__internal_has_attribute__?("disabled") || element.disabled_by_ancestor_fieldset?
64
+ data.form_owner = form
65
+ data.disabled = disabled
66
+ Internal::CEReactions.enqueue_callback(element, "formAssociatedCallback", [form]) if form
67
+ Internal::CEReactions.enqueue_callback(element, "formDisabledCallback", [true]) if disabled
68
+ end
69
+ mark_custom(data)
70
+ # The element is `:defined` now, which selectors observe: a cached
71
+ # query or computed style that looked at it is stale.
72
+ data.wrapper.owner_document&.__internal_note_selector_state_change__
73
+ end
74
+
75
+ # The element is custom now: its state says so, and an element of a
76
+ # form-associated definition takes on a form control's constraint
77
+ # validation surface.
78
+ def mark_custom(data)
79
+ data.definition = self
80
+ data.state = "custom"
81
+ element = data.wrapper
82
+ element.extend(Internal::FormAssociatedCustomElements::Behavior) if form_associated? && element.is_a?(HTMLElement)
83
+ data
84
+ end
85
+
86
+ # WHATWG "report an exception" for the definition's constructor's global.
87
+ def report(error)
88
+ window = registry&.window
89
+ return unless window.respond_to?(:__internal_report_exception__)
90
+
91
+ Internal::ExceptionReport.report_at(window, error)
92
+ end
93
+ end
94
+
95
+ # A definition whose constructor is a Ruby class extending HTMLElement. Its
96
+ # elements ARE instances of the class: constructing one wraps the node as
97
+ # the class (and calls its `construct`, when it has one), and the callbacks
98
+ # are its methods — `connected_callback`, `disconnected_callback`,
99
+ # `adopted_callback`, `connected_move_callback`,
100
+ # `attribute_changed_callback(name, old, new[, namespace])` and the
101
+ # form-associated ones (`form_associated_callback(form)`,
102
+ # `form_disabled_callback(disabled)`, `form_reset_callback`). The class
103
+ # methods `observed_attributes`, `disabled_features` and
104
+ # `form_associated` stand for the JS statics.
105
+ class RubyCustomElementDefinition < CustomElementDefinition
106
+ RUBY_METHODS = {
107
+ "connectedCallback" => :connected_callback,
108
+ "disconnectedCallback" => :disconnected_callback,
109
+ "connectedMoveCallback" => :connected_move_callback,
110
+ "adoptedCallback" => :adopted_callback,
111
+ "attributeChangedCallback" => :attribute_changed_callback,
112
+ "formAssociatedCallback" => :form_associated_callback,
113
+ "formResetCallback" => :form_reset_callback,
114
+ "formDisabledCallback" => :form_disabled_callback
115
+ }.freeze
116
+
117
+ attr_reader :klass
118
+
119
+ def initialize(registry:, name:, klass:)
120
+ @klass = klass
121
+ observed = klass.respond_to?(:observed_attributes) ? Array(klass.observed_attributes) : []
122
+ callbacks = RUBY_METHODS.select { |_, method| klass.method_defined?(method) }.keys
123
+ disabled = klass.respond_to?(:disabled_features) ? Array(klass.disabled_features).map(&:to_s) : []
124
+ super(registry: registry, name: name, local_name: name, observed_attributes: observed, callbacks: callbacks,
125
+ disable_shadow: disabled.include?("shadow"), disable_internals: disabled.include?("internals"),
126
+ form_associated: klass.respond_to?(:form_associated) && klass.form_associated ? true : false)
127
+ end
128
+
129
+ def constructor = @klass
130
+
131
+ def invoke(element, callback_name, args)
132
+ method = RUBY_METHODS.fetch(callback_name)
133
+ return unless element.respond_to?(method)
134
+
135
+ if callback_name == "attributeChangedCallback"
136
+ # The 4th argument (the attribute's namespace) only reaches a callback
137
+ # that takes it, so a 3-argument one keeps working.
138
+ arity = element.method(method).arity
139
+ args = args.first(3) unless arity.negative? || arity >= 4
140
+ end
141
+ element.public_send(method, *args)
142
+ end
143
+
144
+ # "Create an element" with the synchronous custom elements flag: a fresh
145
+ # node wrapped as the class.
146
+ def construct_synchronously(document)
147
+ node = Backend.create_element(@local_name, Element::HTML_NAMESPACE, document.backend_doc)
148
+ wrap_as_class(document, node, nil) { |data| mark_custom(data) }
149
+ end
150
+
151
+ private
152
+
153
+ # Re-wrap the node as the class, handing the element's data on to the new
154
+ # wrapper, which is told which wrapper it replaces.
155
+ def construct_for_upgrade(data)
156
+ previous = data.wrapper
157
+ wrap_as_class(previous.owner_document, previous.__dommy_backend_node__, data) { nil }
158
+ end
159
+
160
+ def wrap_as_class(document, node, data)
161
+ previous = document.__internal_peek_wrapper__(node)
162
+ document.__internal_reset_wrapper__(node)
163
+ instance = @klass.new(document, node)
164
+ document.__internal_register_wrapper__(node, instance)
165
+ instance.__internal_adopt_ce_data__(data) if data
166
+ yield instance.__internal_ce_data__
167
+ instance.__internal_upgraded_from__(previous) if previous && instance.respond_to?(:__internal_upgraded_from__)
168
+ instance.construct if instance.respond_to?(:construct)
169
+ instance
170
+ end
171
+ end
172
+
173
+ # `window.customElements` — the window's CustomElementRegistry: custom
174
+ # element definitions by name.
175
+ #
176
+ # From Ruby, `define(name, klass)` registers a Ruby class (see
177
+ # RubyCustomElementDefinition); a page's `customElements.define(name,
178
+ # JSClass)` registers a JS definition through the bridge. Either way the
179
+ # elements already in the document with that name are upgraded, and the
180
+ # reactions (constructor, connected/disconnected/adopted/attributeChanged
181
+ # callbacks) run through Internal::CEReactions.
10
182
  #
11
- # Names must contain a hyphen per the HTML spec (e.g., `my-button`).
183
+ # Names must be valid custom element names (lower-case, with a hyphen, e.g.
184
+ # `my-button`).
12
185
  class CustomElementRegistry
13
- # https://html.spec.whatwg.org/#valid-custom-element-name
14
- # PCENChar — the characters allowed after the first (ASCII-lower) char: a
15
- # superset of [-._0-9a-z] plus wide Unicode ranges. A valid name is
16
- # `[a-z] PCENChar* - PCENChar*` (i.e. lower-alpha start + at least one "-").
17
- PCEN = "\\-._0-9a-z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D" \
18
- "\\u037F-\\u1FFF\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F" \
19
- "\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u{10000}-\\u{EFFFF}"
20
- NAME_RE = Regexp.new("\\A[a-z][#{PCEN}]*-[#{PCEN}]*\\z")
186
+ # https://html.spec.whatwg.org/#valid-custom-element-name — a valid element
187
+ # local name (DOM) whose first code point is an ASCII lower alpha (so the
188
+ # rest may be anything but ASCII whitespace, NULL, "/" and ">"), with no
189
+ # ASCII upper alpha and at least one "-".
190
+ NAME_RE = %r{\A[a-z][^\t\n\f\r \0/>A-Z]*\z}
21
191
 
22
192
  # Hyphenated names that the HTML spec reserves (SVG / MathML elements), so
23
193
  # they are NOT valid custom element names even though they match NAME_RE.
@@ -26,58 +196,139 @@ module Dommy
26
196
  font-face-format font-face-name missing-glyph
27
197
  ].to_set.freeze
28
198
 
29
- def initialize(window)
199
+ attr_reader :window
200
+
201
+ # `scoped`: made by `new CustomElementRegistry()` (HTML "is scoped"),
202
+ # rather than a window's own (a global custom element registry).
203
+ def initialize(window, scoped: false)
30
204
  @window = window
31
- # name → klass
205
+ @scoped = scoped
206
+ # The documents with elements of this scoped registry connected to
207
+ # them, which define() searches for upgrade candidates.
208
+ @scoped_documents = {}.compare_by_identity
209
+ # name → definition
32
210
  @definitions = {}
33
- # name → Array<{ resolve, reject }>
211
+ # name → Array<PromiseValue>
34
212
  @pending_promises = {}
35
213
  end
36
214
 
215
+ def scoped? = @scoped
216
+
217
+ # Add `document` to the scoped document set (DOM insert step 7.7.1).
218
+ def __internal_note_scoped_document__(document)
219
+ @scoped_documents[document] = true if @scoped && document
220
+ end
221
+
37
222
  # Whether `name` is a valid custom element name. Also consulted by
38
223
  # `element_class_for`: an unrecognized HTML-namespace name that is valid here
39
224
  # is an *undefined custom element* (interface HTMLElement), not an unknown
40
225
  # element (HTMLUnknownElement).
41
226
  def self.valid_name?(name)
42
227
  key = name.to_s
43
- key.match?(NAME_RE) && !RESERVED_NAMES.include?(key)
228
+ key.match?(NAME_RE) && key.include?("-") && !RESERVED_NAMES.include?(key)
229
+ end
230
+
231
+ # A document's custom element registry: the one initialize() gave it,
232
+ # else its window's when it has a browsing context, else none (a
233
+ # template's contents, a document made by createHTMLDocument or
234
+ # DOMParser).
235
+ def self.for_document(document)
236
+ return document.__internal_custom_element_registry__ if document.respond_to?(:__internal_custom_element_registry__)
237
+
238
+ window = document.default_view if document.respond_to?(:default_view)
239
+ window.custom_elements if window.respond_to?(:custom_elements)
44
240
  end
45
241
 
242
+ # DOM "effective global custom element registry" of a document's: the
243
+ # registry when it is a global one, else none.
244
+ def self.effective_global_for(document)
245
+ registry = for_document(document)
246
+ registry unless registry.nil? || registry.scoped?
247
+ end
248
+
249
+ # HTML "look up a custom element registry" given a node: an element's or
250
+ # a shadow root's own, a document's.
251
+ def self.for_node(node)
252
+ case node
253
+ when Element then node.__internal_ce_registry__
254
+ when ShadowRoot then node.__internal_custom_element_registry__
255
+ when Document then for_document(node)
256
+ end
257
+ end
258
+
259
+ # HTML "look up a custom element definition" in `registry`, for an
260
+ # element of the given namespace, local name and is value.
261
+ def self.lookup(registry, namespace, local_name, is_value = nil)
262
+ return nil unless registry && namespace == Element::HTML_NAMESPACE
263
+
264
+ registry.lookup_definition(local_name, is_value)
265
+ end
266
+
267
+ # Register a Ruby class extending HTMLElement as the definition for
268
+ # `name`.
46
269
  def define(name, klass, _options = nil)
270
+ raise Bridge::TypeError, "the custom element constructor must be a class" unless klass.is_a?(Class)
271
+
47
272
  key = name.to_s
48
- unless key.match?(NAME_RE)
273
+ unless CustomElementRegistry.valid_name?(key)
49
274
  raise DOMException::SyntaxError, "#{name.inspect} is not a valid custom element name"
50
275
  end
51
- if RESERVED_NAMES.include?(key)
52
- raise DOMException::SyntaxError, "#{name.inspect} is a reserved element name"
53
- end
54
276
 
55
277
  raise DOMException::NotSupportedError, "#{key} already defined" if @definitions.key?(key)
56
278
 
57
- @definitions[key] = klass
58
- # Resolve any pending whenDefined() promises and re-wrap
59
- # already-existing nodes (upgrade).
60
- resolve_pending(key, klass)
61
- upgrade_existing(key)
279
+ __internal_add_definition__(RubyCustomElementDefinition.new(registry: self, name: key, klass: klass))
280
+ nil
281
+ end
282
+
283
+ # The define() steps after the definition is made (its checks are the
284
+ # caller's): append it, enqueue an upgrade for each element of the
285
+ # document it applies to, and resolve whenDefined(). A [CEReactions]
286
+ # member, so the upgrades have run when it returns.
287
+ def __internal_add_definition__(definition)
288
+ Internal::FormAssociatedCustomElements.register(definition)
289
+ Internal::CEReactions.scope do
290
+ @definitions[definition.name] = definition
291
+ upgrade_particular_elements(definition)
292
+ resolve_pending(definition.name, definition.constructor)
293
+ end
62
294
  nil
63
295
  end
64
296
 
297
+ # The constructor defined for `name`, or nil.
65
298
  def get(name)
66
- @definitions[name.to_s]
299
+ @definitions[name.to_s]&.constructor
67
300
  end
68
301
 
69
302
  def get_name(klass)
70
- @definitions.each { |k, v| return k if v == klass }
303
+ @definitions.each_value { |d| return d.name if d.constructor == klass }
71
304
  nil
72
305
  end
73
306
 
307
+ def any_definitions? = !@definitions.empty?
308
+
309
+ def definition_for(name)
310
+ @definitions[name.to_s]
311
+ end
312
+
313
+ # HTML "look up a custom element definition" in this registry for an
314
+ # HTML element: the autonomous definition named `local_name`, or else the
315
+ # customized built-in one named `is_value` that extends `local_name`.
316
+ def lookup_definition(local_name, is_value = nil)
317
+ definition = @definitions[local_name.to_s]
318
+ return definition if definition&.autonomous?
319
+ return nil if is_value.nil?
320
+
321
+ definition = @definitions[is_value.to_s]
322
+ definition if definition && !definition.autonomous? && definition.local_name == local_name.to_s
323
+ end
324
+
74
325
  # Returns a Dommy::PromiseValue that resolves with the registered
75
326
  # constructor when `name` is defined (immediately if already so).
76
327
  def when_defined(name)
77
328
  key = name.to_s
78
329
  promise = PromiseValue.new(@window)
79
- if (klass = @definitions[key])
80
- promise.fulfill(klass)
330
+ if (definition = @definitions[key])
331
+ promise.fulfill(definition.constructor)
81
332
  else
82
333
  @pending_promises[key] ||= []
83
334
  @pending_promises[key] << promise
@@ -86,106 +337,103 @@ module Dommy
86
337
  promise
87
338
  end
88
339
 
89
- # Walk `root`'s shadow-including subtree and re-wrap any nodes whose tag is now
90
- # registered; fires `connectedCallback` for each upgraded node
91
- # that's currently attached to a document tree.
340
+ # `customElements.upgrade(root)`: try to upgrade each element among
341
+ # root's shadow-including inclusive descendants that this registry is the
342
+ # one for, in shadow-including tree order. A [CEReactions] member.
92
343
  def upgrade(root)
93
- return nil unless root.respond_to?(:__dommy_backend_node__)
344
+ root_node = root.__dommy_backend_node__ if root.is_a?(Node)
345
+ return nil unless root_node
346
+
347
+ document = root.is_a?(Document) ? root : root.owner_document
348
+ return nil unless document
349
+
350
+ Internal::CEReactions.scope do
351
+ document.__internal_each_shadow_including_element__(root_node) do |node|
352
+ element = document.wrap_node(node)
353
+ next unless element && element.__internal_ce_registry__.equal?(self)
94
354
 
95
- @window.document.__internal_each_shadow_including_element__(root.__dommy_backend_node__) do |nk|
96
- next unless @definitions.key?(nk.name)
355
+ document.__internal_try_to_upgrade__(element)
356
+ end
357
+ end
358
+ nil
359
+ end
97
360
 
98
- wrapped = rewrap_for_upgrade(@window.document, nk)
99
- next unless wrapped
361
+ # `initialize(root)` (HTML §4.13.4): give `root` (a document or a shadow
362
+ # root without one) and the elements of its subtree without one this
363
+ # registry, and try to upgrade those it is now the registry of.
364
+ def initialize_registry(root)
365
+ root_node = root.is_a?(Document) ? root.backend_doc : (root.__dommy_backend_node__ if root.is_a?(Node))
366
+ raise Bridge::TypeError, "CustomElementRegistry.initialize: parameter 1 is not of type 'Node'" unless root_node
100
367
 
101
- replay_observed_attributes(wrapped)
102
- # connectedCallback is enqueued only for an element that is actually in
103
- # a document tree — `customElements.upgrade()` on a detached subtree
104
- # upgrades it without connecting it.
105
- @window.document.__internal_notify_connected__(wrapped) if wrapped.is_connected?
368
+ document = root.is_a?(Document) ? root : root.owner_document
369
+ if !@scoped && (root.is_a?(Document) || !CustomElementRegistry.for_document(document).equal?(self))
370
+ raise DOMException::NotSupportedError, "a global registry initializes only its own document's nodes"
106
371
  end
107
372
 
373
+ Internal::CEReactions.scope do
374
+ if root.is_a?(Document) && CustomElementRegistry.for_document(root).nil?
375
+ root.__internal_custom_element_registry__ = self
376
+ elsif root.is_a?(ShadowRoot) && root.__internal_custom_element_registry__.nil?
377
+ root.__internal_custom_element_registry__ = self
378
+ end
379
+ Internal::NodeTraversal.subtree_nodes(root_node).each do |node|
380
+ next unless node.element?
381
+
382
+ element = document.wrap_node(node)
383
+ next unless element
384
+
385
+ if element.__internal_ce_registry__.nil?
386
+ element.__internal_ce_data__.registry = self
387
+ __internal_note_scoped_document__(element.owner_document)
388
+ end
389
+ next unless element.__internal_ce_registry__.equal?(self)
390
+
391
+ document.__internal_try_to_upgrade__(element)
392
+ end
393
+ end
108
394
  nil
109
395
  end
110
396
 
397
+ # The registry's operations are JS-side (host_runtime.js: its definitions'
398
+ # constructors and callbacks are JS functions), on the
399
+ # CustomElementRegistry prototype; the host object answers no property.
111
400
  def __js_get__(_key)
112
- Bridge::ABSENT # method-only registry; any property read is absent
113
- end
114
-
115
- include Bridge::Methods
116
- js_methods %w[define get whenDefined upgrade]
117
- def __js_call__(method, args)
118
- case method
119
- when "define"
120
- define(args[0], args[1], args[2])
121
- when "get"
122
- get(args[0])
123
- when "whenDefined"
124
- when_defined(args[0])
125
- when "upgrade"
126
- upgrade(args[0])
127
- end
401
+ Bridge::ABSENT
128
402
  end
129
403
 
130
404
  private
131
405
 
132
- def resolve_pending(name, klass)
406
+ def resolve_pending(name, constructor)
133
407
  list = @pending_promises.delete(name)
134
- list&.each { |p| p.fulfill(klass) }
135
- end
136
-
137
- # Re-wrap `nk` as its definition's class, or nil when there is nothing to
138
- # upgrade. An element that is already an instance of the class is left alone:
139
- # upgrading an element that is already custom does nothing. The new wrapper
140
- # is told which one it replaces, because a script may hold the element — a
141
- # JS-defined element upgrades that reference in place.
142
- def rewrap_for_upgrade(doc, nk)
143
- previous = doc.__internal_peek_wrapper__(nk)
144
- klass = @definitions[nk.name]
145
- return nil if klass.is_a?(Module) && previous.is_a?(klass)
146
-
147
- doc.__internal_reset_wrapper__(nk)
148
- wrapped = doc.wrap_node(nk)
149
- wrapped.__internal_upgraded_from__(previous) if previous && wrapped.respond_to?(:__internal_upgraded_from__)
150
- wrapped
151
- end
152
-
153
- # When define() lands after the matching element is already in
154
- # the document, those nodes need upgrading: re-wrap them with the
155
- # new class and fire connectedCallback.
156
- def upgrade_existing(name)
157
- doc = @window.document
158
- # Match by tag name rather than interpolating `name` into a CSS selector:
159
- # a spec-valid custom element name may contain "." (a CSS class selector
160
- # char) or other metacharacters, which would corrupt the query.
161
- # Shadow trees included, in shadow-including tree order (define step 18).
162
- doc.__internal_each_shadow_including_element__(doc.backend_doc) do |nk|
163
- next unless nk.name == name
164
-
165
- wrapped = rewrap_for_upgrade(doc, nk)
166
- next unless wrapped
167
-
168
- replay_observed_attributes(wrapped)
169
- doc.__internal_notify_connected__(wrapped)
170
- end
408
+ list&.each { |p| p.fulfill(constructor) }
171
409
  end
172
410
 
173
- # "Upgrade an element" step 6: each attribute in the element's attribute
174
- # list, in order, is replayed through attributeChangedCallback with its
175
- # local name, a null old value, its value and its namespace, before
176
- # connectedCallback, so a definition registered after the markup was
177
- # parsed still sees the attributes that were already there. Routed
178
- # through the coordinator, which decides what is observed and how many
179
- # arguments the callback takes, as for any other attribute change.
180
- def replay_observed_attributes(element)
181
- return unless element.class.respond_to?(:observed_attributes)
182
-
183
- Backend.attribute_nodes(element.__dommy_backend_node__).each do |attr|
184
- info = Backend.attribute_ns_info(attr)
185
- @window.document.__internal_notify_attribute_changed__(
186
- element, info[:local_name], nil, info[:value], info[:namespace_uri]
187
- )
411
+ # HTML "upgrade particular elements within a document": every element
412
+ # among the document's shadow-including descendants in the HTML namespace
413
+ # with the definition's local name, in shadow-including tree order. (A
414
+ # spec-valid custom element name may contain "." or other CSS selector
415
+ # metacharacters, so this matches local names rather than querying.)
416
+ def upgrade_particular_elements(definition)
417
+ documents = @scoped ? @scoped_documents.keys : [(@window.document if @window.respond_to?(:document))].compact
418
+ documents.each do |document|
419
+ document.__internal_each_shadow_including_element__(document.backend_doc) do |node|
420
+ next unless node.name == definition.local_name && Backend.namespace_uri(node) == Element::HTML_NAMESPACE
421
+
422
+ element = document.wrap_node(node)
423
+ next unless element && element.__internal_ce_registry__.equal?(self)
424
+ next unless definition.autonomous? || element.__internal_is_value__ == definition.name
425
+
426
+ Internal::CEReactions.enqueue_upgrade(element, definition)
427
+ end
188
428
  end
189
429
  end
190
430
  end
191
431
  end
432
+
433
+ # The composite operations Ruby callers reach directly, made [CEReactions]
434
+ # (see Internal::CEReactions.scoped): markup parsed and inserted, a subtree
435
+ # cloned or imported, a node adopted.
436
+ Dommy::Internal::CEReactions.scoped(Dommy::Element, :inner_html=, :outer_html=, :insert_adjacent_html, :clone_node)
437
+ Dommy::Internal::CEReactions.scoped(Dommy::ShadowRoot, :inner_html=)
438
+ Dommy::Internal::CEReactions.scoped(Dommy::Fragment, :clone_node)
439
+ Dommy::Internal::CEReactions.scoped(Dommy::Document, :import_node, :adopt_node, :write, :writeln)