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
@@ -8,6 +8,7 @@ module Dommy
8
8
  # Spec: https://notifications.spec.whatwg.org/
9
9
  class Notification
10
10
  include EventTarget
11
+ include Internal::EventHandlers::IdlAttributeBridge
11
12
 
12
13
  @permission = "default"
13
14
 
@@ -63,10 +64,17 @@ module Dommy
63
64
  when "data"
64
65
  @data
65
66
  else
66
- Bridge::ABSENT
67
+ event_handler_idl_attribute?(key) ? event_handler_idl_get(key) : Bridge::ABSENT
67
68
  end
68
69
  end
69
70
 
71
+ # onclick / onshow / onerror / onclose.
72
+ def __js_set__(key, value)
73
+ return Bridge::UNHANDLED unless event_handler_idl_attribute?(key)
74
+
75
+ event_handler_idl_set(key, value)
76
+ end
77
+
70
78
  include Bridge::Methods
71
79
  js_methods %w[close addEventListener removeEventListener dispatchEvent]
72
80
  def __js_call__(method, args)
data/lib/dommy/promise.rb CHANGED
@@ -100,6 +100,14 @@ module Dommy
100
100
  @state != :pending
101
101
  end
102
102
 
103
+ # Call `on_fulfilled` / `on_rejected` with the outcome once settled (from a
104
+ # microtask), without a chained promise: how a JS realm Promise standing
105
+ # for this one learns its outcome.
106
+ def __internal_subscribe__(on_fulfilled, on_rejected)
107
+ attach_then(on_fulfilled, on_rejected)
108
+ nil
109
+ end
110
+
103
111
  private
104
112
 
105
113
  # Drive the event loop over the work that is ready NOW until this promise
data/lib/dommy/range.rb CHANGED
@@ -236,7 +236,7 @@ module Dommy
236
236
  end
237
237
 
238
238
  def collapse(to_start = false)
239
- if to_start
239
+ if Internal::WebIDL.boolean(to_start)
240
240
  @end_container = @start_container
241
241
  @end_offset = @start_offset
242
242
  else
@@ -428,8 +428,8 @@ module Dommy
428
428
  # matters for records).
429
429
  sc.replace_data(so, length_of(sc) - so, "") if character_data?(sc)
430
430
  to_remove.each do |node|
431
- if node.respond_to?(:__dommy_backend_node__)
432
- @document.remove_node_with_notify(node.__dommy_backend_node__)
431
+ if (backend = node.__dommy_backend_node__)
432
+ @document.remove_node_with_notify(backend)
433
433
  elsif node.respond_to?(:remove)
434
434
  node.remove
435
435
  end
@@ -566,7 +566,7 @@ module Dommy
566
566
  parent = reference.nil? ? start_node : parent_of(reference)
567
567
  # Step 6, ahead of the split: an insertion pre-insert would reject must
568
568
  # not leave the Text node split behind it.
569
- ref_bn = reference.respond_to?(:__dommy_backend_node__) ? reference.__dommy_backend_node__ : nil
569
+ ref_bn = reference&.__dommy_backend_node__
570
570
  parent.__internal_ensure_insertion_validity__([node], ref_bn)
571
571
 
572
572
  # Step 7: a Text start node is ALWAYS split, including at offset 0 and at
@@ -620,7 +620,7 @@ module Dommy
620
620
  # `how` is a WebIDL `unsigned short`: coerce first (NaN/±0/±Infinity → 0,
621
621
  # otherwise truncate toward zero and take modulo 2^16), then require one of
622
622
  # the four named constants, else NotSupportedError.
623
- how = to_unsigned_short(how)
623
+ how = Internal::WebIDL.unsigned_short(how)
624
624
  Internal::WebIDL.interface!(other, Range)
625
625
  unless [START_TO_START, START_TO_END, END_TO_END, END_TO_START].include?(how)
626
626
  raise DOMException::NotSupportedError, "invalid comparison type: #{how}"
@@ -871,35 +871,6 @@ module Dommy
871
871
  end
872
872
  end
873
873
 
874
- # WebIDL `unsigned short` conversion: ToNumber, then NaN/±0/±Infinity → 0,
875
- # otherwise truncate toward zero and take modulo 2^16.
876
- def to_unsigned_short(value)
877
- num = web_to_number(value)
878
- return 0 if num.nan? || num.zero? || num.infinite?
879
-
880
- ((num.negative? ? -1 : 1) * num.abs.floor) % 65536
881
- end
882
-
883
- # WebIDL ToNumber for the values that reach a bridged argument.
884
- def web_to_number(value)
885
- case value
886
- when Numeric then value.to_f
887
- when nil, false then 0.0
888
- when true then 1.0
889
- when String
890
- stripped = value.strip
891
- return 0.0 if stripped.empty?
892
-
893
- begin
894
- Float(stripped)
895
- rescue ArgumentError
896
- Float::NAN
897
- end
898
- else
899
- Float::NAN
900
- end
901
- end
902
-
903
874
  # Two nodes share a root iff their topmost ancestors are the same node.
904
875
  def same_root?(node)
905
876
  ancestor_chain(node).last.equal?(ancestor_chain(@start_container).last)
@@ -47,10 +47,19 @@ module Dommy
47
47
  # adapter supports `request_job`, fetch / XHR run the request on a worker
48
48
  # and resolve through a DeferredResponse. Without them everything stays
49
49
  # synchronous (the deterministic default the tests rely on).
50
- def initialize(resources, executor: nil, scheduler: nil)
50
+ #
51
+ # `cookie_jar` (a Dommy::CookieJar) and `origin` (a callable answering the
52
+ # requesting page's serialized origin) make requests credentialed the
53
+ # Fetch way: a request whose credentials mode is "include", or
54
+ # "same-origin" (the default; XHR without withCredentials) to the page's
55
+ # own origin, carries the jar's `Cookie` header and has its response's
56
+ # `Set-Cookie` stored.
57
+ def initialize(resources, executor: nil, scheduler: nil, cookie_jar: nil, origin: nil)
51
58
  @resources = resources
52
59
  @executor = executor
53
60
  @scheduler = scheduler
61
+ @cookie_jar = cookie_jar
62
+ @origin = origin
54
63
  end
55
64
 
56
65
  def call(url, init = nil)
@@ -58,10 +67,16 @@ module Dommy
58
67
  method = (init["method"] || "GET").to_s.upcase
59
68
  headers = init["headers"].is_a?(Hash) ? init["headers"] : {}
60
69
  body = init["body"]&.to_s
70
+ credentialed = credentialed?(url, init)
71
+ if credentialed
72
+ cookies = @cookie_jar.cookie_string(url.to_s)
73
+ headers = headers.merge("Cookie" => cookies) unless cookies.empty?
74
+ end
61
75
 
62
76
  return call_async(method, url, headers, body) if async?
63
77
 
64
78
  response = @resources.request(method: method, url: url.to_s, headers: headers, body: body)
79
+ @cookie_jar.store_response_headers(response.headers || {}, url.to_s) if response && credentialed
65
80
  response && to_entry(response, url)
66
81
  end
67
82
 
@@ -71,6 +86,16 @@ module Dommy
71
86
  !@executor.nil? && @resources.respond_to?(:request_job)
72
87
  end
73
88
 
89
+ def credentialed?(url, init)
90
+ return false unless @cookie_jar
91
+
92
+ mode = (init["credentials"] || (init["withCredentials"] ? "include" : "same-origin")).to_s
93
+ return true if mode == "include"
94
+ return false unless mode == "same-origin" && @origin
95
+
96
+ Internal::Origin.of_url(url.to_s) == @origin.call
97
+ end
98
+
74
99
  # The page-thread serve/decline decision still runs synchronously (so an
75
100
  # unserved URL falls through to the stub maps exactly as in the sync path);
76
101
  # only a served request is handed to a worker. The DeferredResponse
@@ -81,8 +106,18 @@ module Dommy
81
106
  return nil unless job
82
107
 
83
108
  deferred = Dommy::DeferredResponse.new(@scheduler)
84
- @executor.submit(job) do |response|
85
- deferred.complete(response && to_entry(response, url))
109
+ # In flight from here until the worker has posted the completion, so
110
+ # a host waiting on the page sees the response coming.
111
+ @scheduler.begin_external_work
112
+ begin
113
+ @executor.submit(job) do |response|
114
+ deferred.complete(response && to_entry(response, url))
115
+ ensure
116
+ @scheduler.end_external_work
117
+ end
118
+ rescue StandardError
119
+ @scheduler.end_external_work
120
+ raise
86
121
  end
87
122
  deferred
88
123
  end
@@ -4,7 +4,18 @@ module Dommy
4
4
  # Deterministic host-side scheduler for timers, rAF, and microtasks.
5
5
  # Time advances only when the host explicitly calls `advance_time`.
6
6
  class Scheduler
7
- Timer = Struct.new(:id, :kind, :callback, :due_at, :interval_ms, :active, :nesting)
7
+ # `id` is the handle the page sees, unique within its kind's id space
8
+ # (timers, animation frames and idle callbacks each number their own);
9
+ # `seq` is unique across all of them and orders same-instant tasks.
10
+ Timer = Struct.new(:id, :kind, :callback, :due_at, :interval_ms, :active, :nesting, :args, :this, :seq)
11
+
12
+ # HTML keeps three separate identifier spaces: setTimeout/setInterval share
13
+ # the map of active timers, requestAnimationFrame has its own animation
14
+ # frame callback identifier, and requestIdleCallback its own idle callback
15
+ # identifier — so `clearTimeout(rafId)` cancels nothing.
16
+ # The rendering-update steps (render_before / render) are internal, so
17
+ # their handles are a space of their own that no page call can name.
18
+ ID_SPACES = {timeout: :timer, interval: :timer, raf: :raf, idle: :idle, render_before: :render, render: :render}.freeze
8
19
 
9
20
  FRAME_MS = 16
10
21
 
@@ -18,15 +29,46 @@ module Dommy
18
29
 
19
30
  # requestIdleCallback has no real idle period here; the callback always
20
31
  # sees a fixed budget and didTimeout: false.
21
- IDLE_DEADLINE = {"timeRemaining" => 50.0, "didTimeout" => false}.freeze
32
+ IDLE_TIME_REMAINING_MS = 50.0
33
+
34
+ # The IdleDeadline a requestIdleCallback callback is handed:
35
+ # `timeRemaining()` (a method, as the IDL has it) and `didTimeout`.
36
+ class IdleDeadline
37
+ include Bridge::Methods
38
+ js_methods %w[timeRemaining]
39
+
40
+ def initialize(time_remaining, did_timeout)
41
+ @time_remaining = time_remaining
42
+ @did_timeout = did_timeout
43
+ end
44
+
45
+ def time_remaining = @time_remaining
46
+ def did_timeout = @did_timeout
47
+
48
+ def __js_get__(key)
49
+ key == "didTimeout" ? @did_timeout : nil
50
+ end
51
+
52
+ def __js_call__(method, _args)
53
+ case method
54
+ when "timeRemaining" then @time_remaining
55
+ end
56
+ end
57
+ end
22
58
 
23
59
  def initialize
24
60
  @now_ms = 0
25
- @next_id = 1
61
+ @next_seq = 1
62
+ @next_ids = Hash.new(1)
26
63
  @timers = {}
64
+ @handles = Hash.new { |h, k| h[k] = {} }
27
65
  @microtasks = []
28
66
  @native_microtask_scheduler = nil
29
67
  @external_inbox = Thread::Queue.new
68
+ # Work handed to another thread whose completion has not come back yet
69
+ # (#begin_external_work / #end_external_work).
70
+ @external_work = 0
71
+ @external_work_mutex = Mutex.new
30
72
  # The nesting level of the timer task currently running (0 at top level);
31
73
  # a timer scheduled while it runs nests one deeper. Drives the 4ms clamp.
32
74
  @nesting_level = 0
@@ -69,6 +111,24 @@ module Dommy
69
111
  # keep the loop alive (ticking) until in-flight network responses are applied.
70
112
  def external_pending? = !@external_inbox.empty?
71
113
 
114
+ # A worker took on work it will hand back through #post_external (a fetch
115
+ # on a network executor), and #end_external_work when it has. Between the
116
+ # two the page can still change without the clock moving: a host waiting
117
+ # on the page waits for it in real time. THREAD-SAFE.
118
+ def begin_external_work
119
+ @external_work_mutex.synchronize { @external_work += 1 }
120
+ nil
121
+ end
122
+
123
+ def end_external_work
124
+ @external_work_mutex.synchronize { @external_work -= 1 }
125
+ nil
126
+ end
127
+
128
+ # Whether work handed to a worker has not come back yet. Once it has, its
129
+ # completion is #external_pending? until the loop delivers it.
130
+ def external_work_in_flight? = @external_work_mutex.synchronize { @external_work.positive? }
131
+
72
132
  # An optional hook (set by a JS runtime) that enqueues a microtask onto the
73
133
  # engine's NATIVE promise-job queue. When present, `queue_microtask` routes
74
134
  # through it so host-side microtasks (e.g. MutationObserver delivery)
@@ -110,44 +170,54 @@ module Dommy
110
170
  # animation frames (test harnesses driving async frameworks).
111
171
  attr_accessor :raf_checkpoint_each
112
172
 
113
- def set_timeout(callback, delay_ms)
114
- register_timer(:timeout, callback, delay_ms.to_i, nil)
173
+ # `args` are the arguments the callback is invoked with and `this` its
174
+ # callback this value (the window, for the page's own timers).
175
+ def set_timeout(callback, delay_ms, args = [], this: nil)
176
+ register_timer(:timeout, callback, delay_ms.to_i, nil, args, this)
115
177
  end
116
178
 
117
179
  def clear_timeout(id)
118
- cancel_timer(id)
180
+ cancel_timer(:timer, id)
119
181
  end
120
182
 
121
- def set_interval(callback, interval_ms)
183
+ def set_interval(callback, interval_ms, args = [], this: nil)
122
184
  ms = [interval_ms.to_i, 0].max
123
- register_timer(:interval, callback, ms, ms)
185
+ register_timer(:interval, callback, ms, ms, args, this)
124
186
  end
125
187
 
126
188
  def clear_interval(id)
127
- cancel_timer(id)
189
+ cancel_timer(:timer, id)
128
190
  end
129
191
 
130
192
  def request_animation_frame(callback)
131
193
  frames = ((@now_ms / FRAME_MS) + 1) * FRAME_MS
132
- id = next_id
133
194
  # rAF is frame-aligned (never the same instant twice), so it needs no
134
195
  # nesting clamp; nesting 0.
135
- @timers[id] = Timer.new(id, :raf, callback, frames, nil, true, 0)
136
- id
196
+ add_timer(Timer.new(nil, :raf, callback, frames, nil, true, 0, [], nil))
137
197
  end
138
198
 
139
199
  def cancel_animation_frame(id)
140
- cancel_timer(id)
200
+ cancel_timer(:raf, id)
201
+ end
202
+
203
+ # The parts of HTML's "update the rendering" that are not animation
204
+ # frame callbacks, at the next frame boundary: `phase` :before runs ahead
205
+ # of that frame's rAF callbacks (flushing autofocus candidates), :after
206
+ # behind them (the focus fixup). A document asks for one only when it
207
+ # has such work, so an idle page schedules nothing.
208
+ def request_rendering_update(callback, phase: :after)
209
+ frames = ((@now_ms / FRAME_MS) + 1) * FRAME_MS
210
+ add_timer(Timer.new(nil, phase == :before ? :render_before : :render, callback, frames, nil, true, 0, [], nil))
141
211
  end
142
212
 
143
213
  # WHATWG requestIdleCallback — modeled as a deferred timer that hands the
144
- # callback an IdleDeadline-shaped Hash. No real idle period in dommy.
214
+ # callback an IdleDeadline. No real idle period in dommy.
145
215
  def request_idle_callback(callback, timeout = 0)
146
- register_timer(:idle, callback, timeout.to_i, nil)
216
+ register_timer(:idle, callback, timeout.to_i, nil, [], nil)
147
217
  end
148
218
 
149
219
  def cancel_idle_callback(id)
150
- cancel_timer(id)
220
+ cancel_timer(:idle, id)
151
221
  end
152
222
 
153
223
  def queue_microtask(callback)
@@ -199,6 +269,30 @@ module Dommy
199
269
  advance_time(advance)
200
270
  end
201
271
 
272
+ # Run the tasks due at the current instant, one at a time and in the order
273
+ # they were queued (each followed by a microtask checkpoint), until the
274
+ # block answers true or no task is due — without advancing the clock and
275
+ # without running a rendering update. Script boot uses it to run the tasks
276
+ # queued ahead of a document's `load` event (its own, and whatever the page
277
+ # queued before it), so a host that boots a page sees it loaded. Returns
278
+ # the block's last answer.
279
+ def run_tasks_until
280
+ deliver_external
281
+ loop do
282
+ return true if yield
283
+
284
+ timer = @timers.values
285
+ .select { |t| t.active && t.due_at <= @now_ms && TASK_KINDS.include?(t.kind) }
286
+ .min_by(&:seq)
287
+ return false unless timer
288
+
289
+ run_task_timer(timer)
290
+ deliver_external
291
+ end
292
+ end
293
+
294
+ TASK_KINDS = %i[timeout interval idle].freeze
295
+
202
296
  # Public accessor for eval-time auto-drain: keep advancing the
203
297
  # clock until no timers remain (or a safety budget runs out).
204
298
  def next_due_timer_at
@@ -215,19 +309,29 @@ module Dommy
215
309
 
216
310
  private
217
311
 
218
- def next_id
219
- id = @next_id
220
- @next_id += 1
221
- id
222
- end
223
-
224
- def register_timer(kind, callback, delay_ms, interval_ms)
225
- id = next_id
312
+ def register_timer(kind, callback, delay_ms, interval_ms, args, this)
226
313
  nesting = @nesting_level + 1
227
314
  delay = clamp_nested_delay([delay_ms, 0].max, nesting)
228
315
  due_at = @now_ms + delay
229
- @timers[id] = Timer.new(id, kind, callback, due_at, interval_ms, true, nesting)
230
- id
316
+ add_timer(Timer.new(nil, kind, callback, due_at, interval_ms, true, nesting, Array(args), this))
317
+ end
318
+
319
+ # File the timer under a fresh handle in its kind's id space; returns the
320
+ # handle.
321
+ def add_timer(timer)
322
+ space = ID_SPACES.fetch(timer.kind)
323
+ timer.id = @next_ids[space]
324
+ @next_ids[space] += 1
325
+ timer.seq = @next_seq
326
+ @next_seq += 1
327
+ @timers[timer.seq] = timer
328
+ @handles[space][timer.id] = timer
329
+ timer.id
330
+ end
331
+
332
+ def remove_timer(timer)
333
+ @timers.delete(timer.seq)
334
+ @handles[ID_SPACES.fetch(timer.kind)].delete(timer.id)
231
335
  end
232
336
 
233
337
  # HTML timer initialization step: a timer nested deeper than 5 with a sub-4ms
@@ -236,22 +340,26 @@ module Dommy
236
340
  nesting > MAX_NESTING_BEFORE_CLAMP && delay < MIN_NESTED_DELAY_MS ? MIN_NESTED_DELAY_MS : delay
237
341
  end
238
342
 
239
- def cancel_timer(id)
343
+ def cancel_timer(space, id)
240
344
  # WHATWG: clearTimeout/clearInterval with a missing or non-numeric handle
241
345
  # (e.g. `clearTimeout(undefined)`, which React's scheduler emits) is a
242
346
  # silent no-op rather than an error.
243
347
  return unless id.respond_to?(:to_i)
244
348
 
245
- key = id.to_i
246
- timer = @timers[key]
247
- timer.active = false if timer
248
- @timers.delete(key)
349
+ timer = @handles[space][id.to_i]
350
+ return unless timer
351
+
352
+ timer.active = false
353
+ remove_timer(timer)
249
354
  nil
250
355
  end
251
356
 
252
357
  def run_due_timers
253
358
  due = @timers.values.select { |timer| timer.active && timer.due_at <= @now_ms }
254
- due.sort_by!(&:id)
359
+ # A frame's rendering-update steps come before or after its rAF
360
+ # callbacks.
361
+ phase_order = { render_before: 0, render: 2 }
362
+ due.sort_by! { |timer| [phase_order.fetch(timer.kind, 1), timer.seq] }
255
363
  # Each ordinary timer task is followed by a microtask checkpoint (WHATWG
256
364
  # §8.1.7.3). The animation-frame callbacks of one rendering update are an
257
365
  # exception: they run consecutively and share a single checkpoint after the
@@ -263,34 +371,54 @@ module Dommy
263
371
 
264
372
  case timer.kind
265
373
  when :raf
266
- @timers.delete(timer.id)
374
+ remove_timer(timer)
267
375
  invoke_timer(timer, @now_ms.to_f)
268
376
  raf_ran = true
269
377
  # Opt-in (test harness): settle this callback's microtask chain before
270
378
  # the next same-frame rAF callback runs (see @raf_checkpoint_each).
271
379
  perform_microtask_checkpoint if @raf_checkpoint_each
272
- when :interval
380
+ when :interval, :idle
381
+ run_task_timer(timer)
382
+ when :render_before
383
+ remove_timer(timer)
273
384
  invoke_timer(timer)
274
- if timer.active
275
- # Each interval iteration nests one deeper, so a setInterval(0) is
276
- # clamped to 4ms once past the nesting threshold (HTML timer steps).
277
- timer.nesting += 1
278
- timer.due_at = @now_ms + clamp_nested_delay(timer.interval_ms, timer.nesting)
279
- end
280
- perform_microtask_checkpoint
281
- when :idle
282
- @timers.delete(timer.id)
283
- invoke_timer(timer, IDLE_DEADLINE.dup)
284
385
  perform_microtask_checkpoint
285
- else
286
- @timers.delete(timer.id)
386
+ when :render
387
+ # The rAF batch's shared checkpoint comes first.
388
+ perform_microtask_checkpoint if raf_ran
389
+ raf_ran = false
390
+ remove_timer(timer)
287
391
  invoke_timer(timer)
288
392
  perform_microtask_checkpoint
393
+ else
394
+ run_task_timer(timer)
289
395
  end
290
396
  end
291
397
  perform_microtask_checkpoint if raf_ran
292
398
  end
293
399
 
400
+ # Run one timer task (a timeout, an interval iteration, an idle callback),
401
+ # then a microtask checkpoint.
402
+ def run_task_timer(timer)
403
+ case timer.kind
404
+ when :interval
405
+ invoke_timer(timer, *timer.args)
406
+ if timer.active
407
+ # Each interval iteration nests one deeper, so a setInterval(0) is
408
+ # clamped to 4ms once past the nesting threshold (HTML timer steps).
409
+ timer.nesting += 1
410
+ timer.due_at = @now_ms + clamp_nested_delay(timer.interval_ms, timer.nesting)
411
+ end
412
+ when :idle
413
+ remove_timer(timer)
414
+ invoke_timer(timer, IdleDeadline.new(IDLE_TIME_REMAINING_MS, false))
415
+ else
416
+ remove_timer(timer)
417
+ invoke_timer(timer, *timer.args)
418
+ end
419
+ perform_microtask_checkpoint
420
+ end
421
+
294
422
 
295
423
  # Run a single timer's callback. The callback is invoked in its RAISING form
296
424
  # so a JS throw surfaces here instead of being swallowed by the bridge —
@@ -306,7 +434,7 @@ module Dommy
306
434
  # nests one deeper (driving the 4ms clamp). Restored even if it throws.
307
435
  prev_nesting = @nesting_level
308
436
  @nesting_level = timer.nesting || 0
309
- CallableInvoker.invoke_raising(timer.callback, *args)
437
+ CallableInvoker.invoke_raising(timer.callback, *args, this: timer.this)
310
438
  rescue StandardError => e
311
439
  # A page exception is reported and the timer keeps its schedule, like a
312
440
  # browser: an interval whose callback throws goes on firing.
@@ -317,7 +445,7 @@ module Dommy
317
445
  raise unless @timer_error_handler&.call(e, timer)
318
446
 
319
447
  timer.active = false
320
- @timers.delete(timer.id)
448
+ remove_timer(timer)
321
449
  nil
322
450
  ensure
323
451
  @nesting_level = prev_nesting