capybara-lightpanda 0.19.1 → 0.20.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.
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "network/exchange"
4
+
3
5
  module Capybara
4
6
  module Lightpanda
5
7
  class Network
@@ -14,10 +16,14 @@ module Capybara
14
16
  # the first navigation completes. Backs Browser#status_code /
15
17
  # #response_headers. Captured by #subscribe's handlers.
16
18
  attr_reader :last_navigation_response
19
+ alias response last_navigation_response
20
+
21
+ def status = response&.status
17
22
 
18
23
  def initialize(browser)
19
24
  @browser = browser
20
25
  @traffic = []
26
+ @pending = {}
21
27
  @traffic_mutex = Mutex.new
22
28
  @enabled = false
23
29
  @request_handler = @response_handler = @failure_handler = nil
@@ -61,6 +67,8 @@ module Capybara
61
67
  # wait_for_idle's pending count on a future call.
62
68
  browser.command("Network.disable")
63
69
  unsubscribe
70
+ # Completion events for these requests may arrive while observation is off.
71
+ @traffic_mutex.synchronize { @pending.clear }
64
72
  @enabled = false
65
73
  end
66
74
 
@@ -68,8 +76,18 @@ module Capybara
68
76
  @traffic_mutex.synchronize { @traffic.dup }
69
77
  end
70
78
 
71
- def clear
72
- @traffic_mutex.synchronize { @traffic.clear }
79
+ def clear(type = nil)
80
+ case type
81
+ when nil, :traffic
82
+ # Forget observations while continuing to track active network I/O.
83
+ @traffic_mutex.synchronize { @traffic.clear }
84
+ return [] if type.nil?
85
+ when :cache
86
+ browser.command("Network.clearBrowserCache")
87
+ else
88
+ raise ArgumentError, "expected :traffic or :cache, got #{type.inspect}"
89
+ end
90
+ true
73
91
  end
74
92
 
75
93
  # Wipe local state without sending Network.disable. Called by
@@ -80,7 +98,10 @@ module Capybara
80
98
  # cleared the Subscriber first.
81
99
  def reset
82
100
  unsubscribe
83
- clear
101
+ @traffic_mutex.synchronize do
102
+ @traffic.clear
103
+ @pending.clear
104
+ end
84
105
  @enabled = false
85
106
  @extra_headers = nil # the fresh context never received setExtraHTTPHeaders
86
107
  @last_navigation_response = nil
@@ -95,26 +116,46 @@ module Capybara
95
116
  # `network.enable` (or `wait_for_network_idle`).
96
117
  def headers=(headers)
97
118
  enable
98
- @extra_headers = headers
99
- browser.page_command("Network.setExtraHTTPHeaders", headers: headers)
119
+ warn_on_refused_user_agent(headers)
120
+ apply_extra_headers(headers)
100
121
  end
101
122
 
102
123
  def add_headers(headers)
103
124
  enable
104
- @extra_headers = (@extra_headers || {}).merge(headers)
105
- browser.page_command("Network.setExtraHTTPHeaders", headers: @extra_headers)
125
+ warn_on_refused_user_agent(headers)
126
+ apply_extra_headers(extra_headers.merge(headers))
106
127
  end
107
128
 
108
129
  def clear_headers
109
130
  enable
110
- @extra_headers = {}
111
- browser.page_command("Network.setExtraHTTPHeaders", headers: {})
131
+ apply_extra_headers({})
132
+ end
133
+
134
+ # Lightpanda refuses a user agent containing "Mozilla" by design, and
135
+ # answers {} either way.
136
+ def self.refused_user_agent?(value)
137
+ value.to_s.match?(/mozilla/i)
138
+ end
139
+
140
+ # Sets the User-Agent request header AND navigator.userAgent, which a
141
+ # User-Agent in headers= does not touch. The override ends with the
142
+ # BrowserContext, so reset! restores "Lightpanda/1.0". Raises on a value
143
+ # the browser would silently drop, rather than let a spec run on the
144
+ # default user agent.
145
+ def user_agent=(value)
146
+ if Network.refused_user_agent?(value)
147
+ raise ArgumentError,
148
+ "Lightpanda refuses a user agent containing \"Mozilla\" (got #{value.inspect}). Keep the device " \
149
+ "tokens and drop the prefix, e.g. \"Lightpanda/1.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Mobile\"."
150
+ end
151
+
152
+ browser.page_command("Emulation.setUserAgentOverride", userAgent: value.to_s)
112
153
  end
113
154
 
114
- # Count of in-flight requests (no response and no failure recorded yet).
155
+ # Count through body completion, including requests evicted from the traffic history.
115
156
  # Cheap predicate-friendly accessor (ferrum parity).
116
157
  def pending_connections
117
- @traffic_mutex.synchronize { @traffic.count { |t| open?(t) } }
158
+ @traffic_mutex.synchronize { @pending.size }
118
159
  end
119
160
 
120
161
  # True when no more than `connections` requests are in-flight.
@@ -122,8 +163,8 @@ module Capybara
122
163
  pending_connections <= connections
123
164
  end
124
165
 
125
- def wait_for_idle(timeout: 5, connections: 0)
126
- wait_for_idle!(timeout: timeout, connections: connections)
166
+ def wait_for_idle(timeout: 5, connections: 0, duration: 0.1)
167
+ wait_for_idle!(timeout: timeout, connections: connections, duration: duration)
127
168
  rescue TimeoutError
128
169
  false
129
170
  end
@@ -131,10 +172,10 @@ module Capybara
131
172
  # Raising variant of #wait_for_idle (ferrum parity). Returns true on
132
173
  # success, raises TimeoutError on timeout so callers that treat the
133
174
  # idle wait as a precondition don't have to remember to check a bool.
134
- def wait_for_idle!(timeout: 5, connections: 0) # rubocop:disable Naming/PredicateMethod
175
+ def wait_for_idle!(timeout: 5, connections: 0, duration: 0.1) # rubocop:disable Naming/PredicateMethod
135
176
  Utils::Wait.until(
136
177
  timeout: timeout,
137
- interval: 0.1,
178
+ interval: duration,
138
179
  message: "Network did not become idle within #{timeout}s " \
139
180
  "(pending=#{pending_connections}, allowed=#{connections})"
140
181
  ) { idle?(connections) }
@@ -143,6 +184,18 @@ module Capybara
143
184
 
144
185
  private
145
186
 
187
+ def apply_extra_headers(headers)
188
+ browser.page_command("Network.setExtraHTTPHeaders", headers: headers).tap { @extra_headers = headers.dup }
189
+ end
190
+
191
+ def warn_on_refused_user_agent(headers)
192
+ value = headers.find { |name, _| name.to_s.casecmp?("user-agent") }&.last
193
+ return unless Network.refused_user_agent?(value)
194
+
195
+ warn "[capybara-lightpanda] Lightpanda ignores a User-Agent containing \"Mozilla\" (#{value.inspect}): " \
196
+ "requests keep the default user agent. Drop the \"Mozilla/5.0\" prefix, or use page.driver.user_agent=."
197
+ end
198
+
146
199
  # CDP events arrive on the message thread while wait_for_idle /
147
200
  # pending_connections read from the main thread; serialize all
148
201
  # @traffic mutations and reads through @traffic_mutex.
@@ -151,16 +204,18 @@ module Capybara
151
204
  # (mirrors capybara-playwright-driver's navigation_request? hook). CDP
152
205
  # normally marks the main-document response via
153
206
  # `Network.responseReceived.type`. Lightpanda only started emitting that
154
- # field on responses in build 8318 (#3037) — far above the gem's floor —
155
- # so match the long way instead: remember the document requestId, store
156
- # the response whose requestId equals it. Works on every supported build;
157
- # don't "simplify" it to read response.type until the floor clears 8318.
207
+ # field on responses in build 8318 (#3037), which the floor now clears,
208
+ # but the gem still matches the long way: remember the document
209
+ # requestId, store the response whose requestId equals it. Switching to
210
+ # response.type is possible now; it has not been validated.
158
211
  def subscribe
159
212
  @request_handler = build_request_handler
160
213
  @response_handler = build_response_handler
161
214
  @failure_handler = build_failure_handler
215
+ @finished_handler = ->(params) { @traffic_mutex.synchronize { finish_request(params["requestId"]) } }
162
216
  browser.on("Network.requestWillBeSent", &@request_handler)
163
217
  browser.on("Network.responseReceived", &@response_handler)
218
+ browser.on("Network.loadingFinished", &@finished_handler)
164
219
  browser.on("Network.loadingFailed", &@failure_handler)
165
220
  end
166
221
 
@@ -180,18 +235,12 @@ module Capybara
180
235
  @document_request_id = params["requestId"]
181
236
  @last_navigation_response = nil
182
237
  end
183
- entry = {
184
- request_id: params["requestId"],
185
- url: params.dig("request", "url"),
186
- method: params.dig("request", "method"),
187
- timestamp: params["timestamp"],
188
- response: nil,
189
- error: nil,
190
- }
238
+ entry = Exchange.new(params)
239
+ id = entry[:request_id]
191
240
  @traffic_mutex.synchronize do
192
- if (redirect = params["redirectResponse"]) && (previous = last_open_entry(params["requestId"]))
193
- previous[:response] = response_summary(redirect)
194
- end
241
+ previous = finish_request(id)
242
+ previous[:response] = Response.new(params["redirectResponse"]) if previous && params["redirectResponse"]
243
+ @pending[id] = entry
195
244
  @traffic << entry
196
245
  @traffic.shift(@traffic.size - TRAFFIC_LIMIT) if @traffic.size > TRAFFIC_LIMIT
197
246
  end
@@ -200,19 +249,11 @@ module Capybara
200
249
 
201
250
  def build_response_handler
202
251
  lambda do |params|
203
- if params["requestId"] == @document_request_id
204
- @last_navigation_response = {
205
- status: params.dig("response", "status"),
206
- headers: params.dig("response", "headers") || {},
207
- }
208
- end
252
+ summary = Response.new(params["response"])
253
+ @last_navigation_response = summary if params["requestId"] == @document_request_id
209
254
  @traffic_mutex.synchronize do
210
- # Last open entry, not `find`: after a redirect chain several
211
- # entries share the requestId and only the newest is still open.
212
- request = last_open_entry(params["requestId"])
213
- next unless request
214
-
215
- request[:response] = response_summary(params["response"])
255
+ request = @pending[params["requestId"]]
256
+ request[:response] = summary if request
216
257
  end
217
258
  end
218
259
  end
@@ -227,7 +268,7 @@ module Capybara
227
268
  def build_failure_handler
228
269
  lambda do |params|
229
270
  @traffic_mutex.synchronize do
230
- request = last_open_entry(params["requestId"])
271
+ request = finish_request(params["requestId"])
231
272
  next unless request
232
273
 
233
274
  request[:error] = params["errorText"].to_s
@@ -244,30 +285,21 @@ module Capybara
244
285
  end
245
286
 
246
287
  # Caller holds @traffic_mutex.
247
- def last_open_entry(request_id)
248
- @traffic.reverse_each.find { |t| t[:request_id] == request_id && open?(t) }
249
- end
250
-
251
- def open?(entry)
252
- entry[:response].nil? && entry[:error].nil?
253
- end
254
-
255
- def response_summary(response)
256
- response ||= {}
257
- {
258
- status: response["status"],
259
- headers: response["headers"],
260
- mime_type: response["mimeType"],
261
- }
288
+ def finish_request(id)
289
+ entry = @pending.delete(id)
290
+ entry&.finish!
291
+ entry
262
292
  end
263
293
 
264
294
  def unsubscribe
265
295
  browser.off("Network.requestWillBeSent", @request_handler) if @request_handler
266
296
  browser.off("Network.responseReceived", @response_handler) if @response_handler
297
+ browser.off("Network.loadingFinished", @finished_handler) if @finished_handler
267
298
  browser.off("Network.loadingFailed", @failure_handler) if @failure_handler
268
299
  @request_handler = nil
269
300
  @response_handler = nil
270
301
  @failure_handler = nil
302
+ @finished_handler = nil
271
303
  end
272
304
  end
273
305
  end
@@ -54,15 +54,29 @@ module Capybara
54
54
  # hands the rendered-text collection (block line breaks + display:none
55
55
  # descendant skipping) to native innerText (#2785/#2795). We normalize the
56
56
  # whitespace here to match Capybara's expected Chrome semantics.
57
+ #
58
+ # innerText puts a tab between table cells. The two Chrome drivers
59
+ # disagree on it (verified 2026-11-19, Chrome for Testing 158): Cuprite
60
+ # returns the tab ("Total due\t$0.00"), Selenium's WebDriver text a
61
+ # space ("Total due $0.00"). The stock driver keeps the space, which is
62
+ # what every released version returned and what `driven_by :selenium`
63
+ # suites assert (Solidus "Tracking Number FOOBAR"); the opt-in Cuprite
64
+ # registration keeps the tab (Driver#keep_cell_tabs?).
57
65
  def visible_text
66
+ blanks, line_break = driver.keep_cell_tabs? ? TAB_KEEPING_BLANKS : BLANKS
58
67
  call(VISIBLE_TEXT_JS).to_s
59
68
  .gsub(/\A[[:space:]&&[^\u00A0]]+/, "")
60
69
  .gsub(/[[:space:]&&[^\u00A0]]+\z/, "")
61
- .gsub(/[ \t\f\v]+/, " ")
62
- .gsub(/[ \t\f\v]*\n[ \t\f\v\n]*/, "\n")
70
+ .gsub(blanks, " ")
71
+ .gsub(line_break, "\n")
63
72
  .tr("\u00A0", " ")
64
73
  end
65
74
 
75
+ # [run of blanks, line break with the blanks around it]
76
+ BLANKS = [/[ \t\f\v]+/, /[ \t\f\v]*\n[ \t\f\v\n]*/].freeze
77
+ TAB_KEEPING_BLANKS = [/[ \f\v]+/, /[ \f\v]*\n[ \f\v\n]*/].freeze
78
+ private_constant :BLANKS, :TAB_KEEPING_BLANKS
79
+
66
80
  def rect
67
81
  call(GET_RECT_JS)
68
82
  end
@@ -126,6 +140,12 @@ module Capybara
126
140
  call(PROPERTY_OR_ATTRIBUTE_JS, name.to_s)
127
141
  end
128
142
 
143
+ # Selenium's native element reads live properties such as validationMessage
144
+ # and returns strings. Capybara's [] has its own boolean and URL contract.
145
+ def attribute(name)
146
+ call(WEBDRIVER_ATTRIBUTE_JS, name.to_s)
147
+ end
148
+
129
149
  def value
130
150
  call(GET_VALUE_JS)
131
151
  end
@@ -134,17 +154,19 @@ module Capybara
134
154
  styles.to_h { |style| [style, call(GET_STYLE_JS, style)] }
135
155
  end
136
156
 
137
- def click(_keys = [], **_options)
138
- call(CLICK_JS)
157
+ def click(keys = [], **_options)
158
+ call(CLICK_JS, mouse_event_options(keys))
139
159
  driver.browser.wait_for_idle
140
160
  end
141
161
 
142
- def right_click(_keys = [], **_options)
143
- call("function() { this.dispatchEvent(new MouseEvent('contextmenu', {bubbles: true, cancelable: true})) }")
162
+ def right_click(keys = [], **_options)
163
+ call(CLICK_JS, mouse_event_options(keys, button: 2))
164
+ driver.browser.wait_for_idle
144
165
  end
145
166
 
146
- def double_click(_keys = [], **_options)
147
- call("function() { this.dispatchEvent(new MouseEvent('dblclick', {bubbles: true, cancelable: true})) }")
167
+ def double_click(keys = [], **_options)
168
+ call(CLICK_JS, mouse_event_options(keys, detail: 2))
169
+ driver.browser.wait_for_idle
148
170
  end
149
171
 
150
172
  # A real pointer entering an element fires `mouseover` (bubbling) AND
@@ -253,7 +275,8 @@ module Capybara
253
275
  unless html5
254
276
  raise NotImplementedError,
255
277
  "drag_to needs coordinate mouse dispatch for non-HTML5 (legacy) drags, which Lightpanda " \
256
- "cannot do (no layout). Pass `html5: true` to force HTML5 DragEvent simulation."
278
+ "cannot do (no layout). Run this example with Cuprite (Chrome) for coordinate-based dragging. " \
279
+ "For an HTML5 drop target, pass `html5: true` to simulate drag events."
257
280
  end
258
281
 
259
282
  driver.browser.evaluate_async(HTML5_DRAG_JS, self, other, (delay * 1000).to_i, keys)
@@ -376,6 +399,15 @@ module Capybara
376
399
 
377
400
  private
378
401
 
402
+ def mouse_event_options(keys, button: 0, detail: 1)
403
+ names = Array(keys).map(&:to_s)
404
+ {
405
+ bubbles: true, cancelable: true, button: button, detail: detail,
406
+ shiftKey: names.include?("shift"), ctrlKey: names.intersect?(%w[control ctrl]),
407
+ altKey: names.include?("alt"), metaKey: names.intersect?(%w[meta command]),
408
+ }
409
+ end
410
+
379
411
  def find_hinted(method, selector, hints)
380
412
  driver.browser.find_within_hinted(@remote_object_id, method, selector, self.class.hint_spec(**hints))
381
413
  .map { |oid, cache| self.class.new(driver, oid, cache, frame_scoped: @frame_scoped) }
@@ -595,7 +627,7 @@ module Capybara
595
627
  # 6167 as duplicate `turbo:submit-start` events; the first request
596
628
  # gets aborted by the second and Turbo never renders the response.
597
629
  CLICK_JS = <<~JS
598
- function() {
630
+ function(mouseOptions) {
599
631
  var EventCtor = (typeof MouseEvent !== 'undefined') ? MouseEvent : Event;
600
632
  // Emulate coordinate hit-testing without a layout engine. In a real
601
633
  // browser a pointer click on a container lands on its frontmost
@@ -619,6 +651,10 @@ module Capybara
619
651
  // that element, not inside its first child. A multi select2 holding
620
652
  // a choice is the case: descending into the choice is a click
621
653
  // select2 deliberately ignores, while the choices list opens it.
654
+ // The walk also stops at an element holding text of its own: the
655
+ // centred pointer lands on that text, not on a small child beside
656
+ // it. A select2 v4 with allowClear renders `<span>×</span>Alpha`,
657
+ // and descending pressed the "×", which cleared the selection.
622
658
  // The descent never starts from an interactive element, so a normal
623
659
  // button/link/input click still lands exactly on `this`.
624
660
  var INTERACTIVE = { A: 1, BUTTON: 1, INPUT: 1, SELECT: 1, TEXTAREA: 1,
@@ -635,6 +671,11 @@ module Capybara
635
671
  }
636
672
  }
637
673
  if (!next || (hit !== this && visible > 1)) break;
674
+ var ownText = false;
675
+ for (var n = hit.firstChild; n && !ownText; n = n.nextSibling) {
676
+ ownText = n.nodeType === 3 && n.nodeValue.trim() !== '';
677
+ }
678
+ if (ownText) break;
638
679
  hit = next;
639
680
  }
640
681
  // Real pointer clicks are a mousedown -> mouseup -> click sequence,
@@ -642,7 +683,8 @@ module Capybara
642
683
  // Cancelling mousedown suppresses focus/text-selection in a real
643
684
  // browser but never the click, so the click below is dispatched
644
685
  // unconditionally.
645
- var pressed = hit.dispatchEvent(new EventCtor('mousedown', { bubbles: true, cancelable: true }));
686
+ var held = { ...mouseOptions, buttons: mouseOptions.button === 2 ? 2 : 1 };
687
+ var pressed = hit.dispatchEvent(new EventCtor('mousedown', held));
646
688
  // mousedown's default action moves focus. Ours is untrusted, so the
647
689
  // browser won't do it (and since upstream #3702 its click handling
648
690
  // doesn't either): focus what the press landed on, or blur the
@@ -657,8 +699,13 @@ module Capybara
657
699
  doc.activeElement.blur();
658
700
  }
659
701
  }
660
- hit.dispatchEvent(new EventCtor('mouseup', { bubbles: true, cancelable: true }));
661
- var clickEvt = new EventCtor('click', { bubbles: true, cancelable: true });
702
+ if (mouseOptions.button === 2) {
703
+ hit.dispatchEvent(new EventCtor('contextmenu', { ...held, detail: 0 }));
704
+ hit.dispatchEvent(new EventCtor('mouseup', mouseOptions));
705
+ return;
706
+ }
707
+ hit.dispatchEvent(new EventCtor('mouseup', mouseOptions));
708
+ var clickEvt = new EventCtor('click', mouseOptions);
662
709
  // A link to a scheme the browser can't fetch (mailto:, tel:, sms:…)
663
710
  // goes to an external app in Chrome and the page stays. The link's
664
711
  // own activation is a no-op for it since upstream #3940 (10536, in
@@ -667,6 +714,7 @@ module Capybara
667
714
  var scheme = link && /^\\s*([a-z][a-z0-9+.-]*):/i.exec(link.getAttribute('href'));
668
715
  var external = !!scheme && !/^(https?|about|blob|data|file|javascript)$/i.test(scheme[1]);
669
716
  var notCancelled = hit.dispatchEvent(clickEvt);
717
+ if (mouseOptions.detail === 2) hit.dispatchEvent(new EventCtor('dblclick', mouseOptions));
670
718
  if (external || !notCancelled || clickEvt.defaultPrevented) return;
671
719
  // Native activation has already started the download (upstream
672
720
  // #4124, 11097, in the floor). Navigating again cancels it and
@@ -943,6 +991,38 @@ module Capybara
943
991
 
944
992
  VISIBLE_TEXT_JS = "function() { return _lightpanda.visibleText(this); }"
945
993
 
994
+ # Capybara supplies its own getAttribute atom to the Selenium bridge.
995
+ WEBDRIVER_ATTRIBUTE_JS = <<~JS
996
+ function(name) {
997
+ const key = name.toLowerCase();
998
+ const tag = this.localName;
999
+ const markup = attr => this.getAttributeNode(attr)?.value ?? null;
1000
+ if (key === 'style') return this.style?.cssText ?? null;
1001
+ if ((tag === 'a' && key === 'href') || (tag === 'img' && key === 'src')) {
1002
+ const raw = markup(key);
1003
+ if (!raw) return raw;
1004
+ const url = this[key];
1005
+ if (url && typeof url === 'object') return { baseVal: url.baseVal, animVal: url.animVal };
1006
+ return url;
1007
+ }
1008
+ if (key === 'selected' || key === 'checked') {
1009
+ if (tag === 'option') return this.selected ? 'true' : null;
1010
+ if (tag === 'input' && (this.type === 'checkbox' || this.type === 'radio')) {
1011
+ return this.checked ? 'true' : null;
1012
+ }
1013
+ }
1014
+ if (key === 'spellcheck') {
1015
+ const raw = markup(key);
1016
+ return /^(true|false)$/i.test(raw) ? raw.toLowerCase() : String(this.spellcheck);
1017
+ }
1018
+ const prop = name === 'class' ? 'className' : name === 'readonly' ? 'readOnly' : name;
1019
+ let value;
1020
+ try { value = this[prop]; } catch (_) { return markup(name); }
1021
+ if (value == null || typeof value === 'object' || typeof value === 'function') return markup(name);
1022
+ return String(value);
1023
+ }
1024
+ JS
1025
+
946
1026
  PROPERTY_OR_ATTRIBUTE_JS = <<~JS
947
1027
  function(name) {
948
1028
  var tag = this.tagName.toLowerCase();
@@ -984,12 +1064,26 @@ module Capybara
984
1064
  }
985
1065
  JS
986
1066
 
1067
+ # The value is written in one step, not typed, but the field still
1068
+ # reports a key press around it: Selenium and Cuprite type `fill_in`, so
1069
+ # suites rely on a `keyup` (or `keydown`) listener running: a table
1070
+ # filter, an autocomplete, a character counter. One keydown/keyup pair
1071
+ # naming the last character stands in for the keystrokes; a listener that
1072
+ # needs one event per character wants `send_keys`.
987
1073
  SET_VALUE_JS = <<~JS
988
1074
  function(value) {
989
1075
  if (this.readOnly || this.hasAttribute('readonly')) return;
1076
+ var chars = Array.from(String(value));
1077
+ var key = chars.length ? chars[chars.length - 1] : 'Backspace';
1078
+ var el = this;
1079
+ var press = function(type) {
1080
+ el.dispatchEvent(new KeyboardEvent(type, {key: key, bubbles: true, cancelable: true}));
1081
+ };
990
1082
  this.focus();
1083
+ press('keydown');
991
1084
  this.value = value;
992
1085
  this.dispatchEvent(new Event('input', {bubbles: true}));
1086
+ press('keyup');
993
1087
  this.dispatchEvent(new Event('change', {bubbles: true}));
994
1088
  }
995
1089
  JS
@@ -1034,14 +1128,40 @@ module Capybara
1034
1128
  # after the last non-blank text, inside its <p>, the position Chrome
1035
1129
  # normalizes WebDriver's collapsed end-of-contents range to; a host with
1036
1130
  # no text gets the end of its children.
1131
+ #
1132
+ # Inside an iframe, Lightpanda sends keys down the chain of focused
1133
+ # <iframe> elements (upstream `focusedFrame`), so every owning <iframe>
1134
+ # must be its document's active element. `focus()` on a field does that;
1135
+ # on a <body> that is the editing host (TinyMCE, CKEditor 4) it does not,
1136
+ # and the keys went to whatever the top page had focused. A <body> is
1137
+ # also `activeElement` whenever nothing is focused, so it never proves
1138
+ # it has focus: it keeps its caret only when the selection is already in
1139
+ # it. A node inside an editing host that can't take focus itself (the
1140
+ # <p> of a rich-text editor) focuses its host, as in Chrome.
1037
1141
  SEND_KEYS_FOCUS_JS = <<~JS
1038
1142
  function() {
1039
1143
  var doc = this.ownerDocument;
1040
- if (doc.activeElement === this) return;
1144
+ var frameFocused = true;
1145
+ for (var w = doc.defaultView; w && w.frameElement; w = w.frameElement.ownerDocument.defaultView) {
1146
+ var frame = w.frameElement;
1147
+ if (frame.ownerDocument.activeElement !== frame) {
1148
+ frameFocused = false;
1149
+ frame.focus();
1150
+ }
1151
+ }
1152
+ var selection = doc.defaultView && doc.defaultView.getSelection();
1153
+ var caretInside = this !== doc.body ||
1154
+ !!(selection && selection.rangeCount && this.contains(selection.anchorNode));
1155
+ if (doc.activeElement === this && frameFocused && caretInside) return;
1041
1156
  this.focus();
1042
1157
  if (doc.activeElement !== this) {
1043
- if (doc.activeElement && doc.activeElement !== doc.body && doc.activeElement.blur) doc.activeElement.blur();
1044
- return;
1158
+ var host = this.isContentEditable ? this.parentElement : null;
1159
+ while (host && host.parentElement && host.parentElement.isContentEditable) host = host.parentElement;
1160
+ if (host && host.isContentEditable) host.focus();
1161
+ if (!host || doc.activeElement !== host) {
1162
+ if (doc.activeElement && doc.activeElement !== doc.body && doc.activeElement.blur) doc.activeElement.blur();
1163
+ return;
1164
+ }
1045
1165
  }
1046
1166
  if (typeof this.setSelectionRange === 'function') {
1047
1167
  // Throws on types without a selection (email, number, …) — those
@@ -1184,7 +1304,7 @@ module Capybara
1184
1304
  # of private_constant for its JS snippets.
1185
1305
  private_constant :CLICK_JS, :TRIGGER_JS, :DROP_JS, :CREATE_DROP_INPUT_JS, :SHADOW_ROOT_JS, :VISIBLE_JS,
1186
1306
  :VISIBLE_TEXT_JS,
1187
- :PROPERTY_OR_ATTRIBUTE_JS, :GET_VALUE_JS, :SET_VALUE_JS,
1307
+ :WEBDRIVER_ATTRIBUTE_JS, :PROPERTY_OR_ATTRIBUTE_JS, :GET_VALUE_JS, :SET_VALUE_JS,
1188
1308
  :IMPLICIT_SUBMIT_JS, :SELECT_OPTION_JS, :UNSELECT_OPTION_JS,
1189
1309
  :SET_CHECKBOX_JS, :EDITABLE_HOST_JS, :DISABLED_JS, :GET_STYLE_JS,
1190
1310
  :GET_RECT_JS, :OBSCURED_JS, :GET_PATH_JS
@@ -55,9 +55,15 @@ module Capybara
55
55
  # skipping image fetches entirely. When on, image requests ride the
56
56
  # Network domain like any other — they show in `network.traffic` and
57
57
  # count toward `wait_for_network_idle`.
58
+ # timezone: IANA zone ("America/New_York") the browser reports through
59
+ # Date and Intl. Lightpanda accepts Emulation.setTimezoneOverride but
60
+ # ignores it (verified 2026-11-18 on 1.0.4 and by source at 12238), so the
61
+ # zone is set through the TZ variable of the browser process alone: the
62
+ # test process and the app it boots keep their own. It is per process,
63
+ # not per test, and has no effect with ws_url (the gem spawns nothing).
58
64
  attr_accessor :host, :port, :timeout, :handshake_timeout, :process_timeout,
59
65
  :window_size, :browser_path, :headless, :logger, :save_path,
60
- :raise_on_unhandled_modal, :load_images
66
+ :raise_on_unhandled_modal, :load_images, :timezone
61
67
  attr_writer :ws_url
62
68
 
63
69
  def initialize(options = {})
@@ -72,6 +78,7 @@ module Capybara
72
78
  @save_path = options[:save_path]
73
79
  @raise_on_unhandled_modal = options.fetch(:raise_on_unhandled_modal, false)
74
80
  @load_images = options.fetch(:load_images, false)
81
+ @timezone = validate_timezone(options[:timezone])
75
82
  @ws_url = options[:ws_url]
76
83
  @logger = parse_logger(options[:logger])
77
84
  end
@@ -98,6 +105,7 @@ module Capybara
98
105
  save_path: save_path,
99
106
  raise_on_unhandled_modal: raise_on_unhandled_modal,
100
107
  load_images: load_images,
108
+ timezone: timezone,
101
109
  }
102
110
  h[:ws_url] = @ws_url if @ws_url
103
111
  h
@@ -116,6 +124,13 @@ module Capybara
116
124
  raise ArgumentError, "window_size must be [width, height] of positive Integers, got #{size.inspect}"
117
125
  end
118
126
 
127
+ # Same reason as window_size: fail before a process is spawned.
128
+ def validate_timezone(zone)
129
+ return zone if zone.nil? || (zone.is_a?(String) && !zone.empty?)
130
+
131
+ raise ArgumentError, "timezone must be an IANA zone name such as \"America/New_York\", got #{zone.inspect}"
132
+ end
133
+
119
134
  def parse_logger(logger)
120
135
  return logger if logger.is_a?(Capybara::Lightpanda::Logger)
121
136
  return Capybara::Lightpanda::Logger.new(logger) if logger
@@ -40,8 +40,9 @@ module Capybara
40
40
  # PR #2368 (events: report listener exceptions instead of halting
41
41
  # dispatch — load-bearing for the gem's JS bundle dispatch assumptions),
42
42
  # PR #2289 (Page.getNavigationHistory + Page.navigateToHistoryEntry —
43
- # lets us drop the history.back()/history.forward() JS workaround in
44
- # Browser#back / #forward), PR #2305 (XPath 1.0: Document.evaluate,
43
+ # Browser#back / #forward deliberately keep history.back()/forward() in
44
+ # the page: navigateToHistoryEntry reloaded pushState entries until #3903,
45
+ # and a switch has not been validated), PR #2305 (XPath 1.0: Document.evaluate,
45
46
  # XPathResult, XPathEvaluator, XPathExpression — lets us drop the
46
47
  # ~700 LOC XPath polyfill in javascripts/index.js),
47
48
  # PR #2431 (cdp: remove duplicate Page.frameNavigated emission + reuse
@@ -552,7 +553,7 @@ module Capybara
552
553
  args = build_args
553
554
 
554
555
  ::Process.spawn(
555
- { "LIGHTPANDA_DISABLE_TELEMETRY" => "true" },
556
+ spawn_env,
556
557
  binary_path, *args,
557
558
  out: @stdout_w,
558
559
  err: @stderr_w,
@@ -560,6 +561,15 @@ module Capybara
560
561
  )
561
562
  end
562
563
 
564
+ # TZ reaches the browser only: Process.spawn merges this hash into the
565
+ # child's environment, so Ruby's own zone (and the app server's) is
566
+ # untouched. See Options#timezone.
567
+ def spawn_env
568
+ env = { "LIGHTPANDA_DISABLE_TELEMETRY" => "true" }
569
+ env["TZ"] = @options.timezone if @options.timezone
570
+ env
571
+ end
572
+
563
573
  def build_args
564
574
  base = [
565
575
  "serve",
@@ -2,10 +2,13 @@
2
2
 
3
3
  module Capybara
4
4
  module Lightpanda
5
- # Exposes the gem's rake tasks (lightpanda:binary:*) inside Rails apps.
6
- # Without this, the BinaryError remediation hint ("bundle exec rake
7
- # lightpanda:binary:remove lightpanda:binary:update") pointed at tasks
8
- # that didn't exist in the app's rake namespace.
5
+ # Exposes the gem's rake tasks (lightpanda:binary:version, :update,
6
+ # :remove) inside Rails apps, so `bin/rails lightpanda:binary:update`
7
+ # works without a Rakefile edit. Rails only loads the gem (and so this
8
+ # Railtie) in the Gemfile groups the current environment requires — for
9
+ # the usual :test group that means RAILS_ENV=test — which is why
10
+ # Binary's too-old-binary hint suggests a require-the-gem one-liner
11
+ # instead of these tasks.
9
12
  class Railtie < Rails::Railtie
10
13
  rake_tasks do
11
14
  load File.expand_path("tasks/binary.rake", __dir__)