ferrum 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.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +60 -0
  3. data/lib/ferrum/browser/binary.rb +1 -2
  4. data/lib/ferrum/browser/options.rb +33 -12
  5. data/lib/ferrum/browser/process/output.rb +143 -0
  6. data/lib/ferrum/browser/process.rb +42 -69
  7. data/lib/ferrum/browser.rb +9 -23
  8. data/lib/ferrum/client/web_socket.rb +93 -73
  9. data/lib/ferrum/client.rb +9 -5
  10. data/lib/ferrum/console/location.rb +42 -0
  11. data/lib/ferrum/console/message.rb +230 -0
  12. data/lib/ferrum/console.rb +157 -0
  13. data/lib/ferrum/context.rb +23 -15
  14. data/lib/ferrum/contexts.rb +41 -18
  15. data/lib/ferrum/errors.rb +7 -5
  16. data/lib/ferrum/frame/dom.rb +50 -44
  17. data/lib/ferrum/frame/runtime/legacy.rb +336 -0
  18. data/lib/ferrum/frame/runtime.rb +416 -186
  19. data/lib/ferrum/frame/script.rb +289 -0
  20. data/lib/ferrum/frame.rb +33 -4
  21. data/lib/ferrum/interceptable.rb +19 -9
  22. data/lib/ferrum/isolated_world.rb +94 -0
  23. data/lib/ferrum/keyboard.rb +95 -8
  24. data/lib/ferrum/log/annotated.rb +77 -0
  25. data/lib/ferrum/log/default.rb +55 -0
  26. data/lib/ferrum/log/json.rb +32 -0
  27. data/lib/ferrum/log/paint.rb +28 -0
  28. data/lib/ferrum/log.rb +247 -0
  29. data/lib/ferrum/mouse.rb +16 -8
  30. data/lib/ferrum/node.rb +127 -52
  31. data/lib/ferrum/page/frames.rb +10 -3
  32. data/lib/ferrum/page/screenshot.rb +8 -7
  33. data/lib/ferrum/page.rb +106 -53
  34. data/lib/ferrum/proxy.rb +8 -7
  35. data/lib/ferrum/remote_object.rb +75 -0
  36. data/lib/ferrum/target.rb +7 -0
  37. data/lib/ferrum/utils/deprecate.rb +77 -0
  38. data/lib/ferrum/version.rb +1 -1
  39. data/lib/ferrum/worker.rb +8 -0
  40. data/lib/ferrum.rb +3 -0
  41. metadata +16 -2
@@ -0,0 +1,289 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strscan"
4
+
5
+ module Ferrum
6
+ class Frame
7
+ #
8
+ # @api private
9
+ #
10
+ # A script passed to {Runtime#evaluate} and friends. Reads just enough
11
+ # JavaScript to tell a function declaration from an expression and to
12
+ # find where the code and its statements end, skipping strings, template
13
+ # literals, regular expressions and comments so that a `//` inside
14
+ # `"http://…"` isn't mistaken for one.
15
+ #
16
+ # The source is scanned once, in {#initialize}, keeping a stack of open
17
+ # brackets and template literals. On the way it records where the code
18
+ # starts and ends, where the first top-level `(…)` opens and closes,
19
+ # where the first top-level `{…}` closes, where the last statement
20
+ # starts, and whether `await` appears. Every question below is answered
21
+ # from those positions.
22
+ #
23
+ # @example
24
+ # script = Script.new("// sum\nasync function(a, b = 1) { return a + b };")
25
+ # script.code # => "async function(a, b = 1) { return a + b }"
26
+ # script.declaration? # => true
27
+ # script.awaits? # => false
28
+ #
29
+ class Script
30
+ # A JavaScript identifier, Unicode letters included.
31
+ IDENTIFIER = /[\p{L}\p{Nl}_$][\p{L}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}$]*/
32
+
33
+ FUNCTION_DECLARATION = /\A(?:async\s+)?function[\s*(]/
34
+ SINGLE_PARAMETER_ARROW = /\A(?:async\s+)?#{IDENTIFIER}\s*=>/
35
+ ASYNC_PREFIX = /\A(?:async\s*)?\z/
36
+ ARROW = /\A\s*=>/
37
+
38
+ COMMENT = %r{//[^\n]*|/\*.*?(?:\*/|\z)}m
39
+ NOISE = /\s+|#{COMMENT}/
40
+ STRING = /"(?:\\.|[^"\\\n])*"?|'(?:\\.|[^'\\\n])*'?/m
41
+ TEMPLATE_CHUNK = /(?:\\.|[^`\\$]|\$(?!\{))*/m
42
+ REGEXP = %r{/(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\\n\[])+/[A-Za-z]*}
43
+ WORD = /[\p{Alnum}_$]+/
44
+
45
+ # Characters ending a value, after which a `/` is a division.
46
+ VALUE_END = %r{[\p{Alnum}_$)\]\}"'`/]}
47
+
48
+ # Words after which a `/` starts a regular expression, not a division.
49
+ REGEXP_KEYWORDS = %w[return typeof instanceof in of new delete void throw case do else yield await].freeze
50
+
51
+ # Words that continue the statement on the line before them.
52
+ CONTINUING_WORDS = %w[in instanceof of else catch finally].freeze
53
+
54
+ # `x++` ends a value, and `++x` starts one.
55
+ INCREMENTS = %w[++ --].freeze
56
+
57
+ # Words whose condition in parentheses is followed by the statement they
58
+ # control, which may start on the next line.
59
+ CONTROL_WORDS = %w[if for while with].freeze
60
+
61
+ # Words after which a `{` opens an object, not a block.
62
+ OBJECT_KEYWORDS = (REGEXP_KEYWORDS - %w[do else]).freeze
63
+
64
+ # A statement that isn't an expression, so it has no value to return.
65
+ STATEMENT = /\A(?:const|let|var|if|for|while|do|switch|try|return|throw|break|continue)\b/
66
+
67
+ # @return [String] the script as given.
68
+ attr_reader :source
69
+
70
+ # @return [String] the script without surrounding whitespace, comments
71
+ # and trailing semicolons.
72
+ attr_reader :code
73
+
74
+ #
75
+ # @param [String] source
76
+ #
77
+ def initialize(source)
78
+ @source = source.to_s
79
+ @code_start = @code_end = 0
80
+ @words = Set.new
81
+ @scanned = @source.valid_encoding? && (@source.encoding == Encoding::UTF_8 || @source.ascii_only?)
82
+ @scanned ? scan : @code_end = @source.bytesize
83
+ @code = @source.byteslice(@code_start...@code_end)
84
+ @wrapped = Script.new(@code[1...-1]) if parenthesized?
85
+ end
86
+
87
+ #
88
+ # Whether the script is a complete function or arrow declaration,
89
+ # rather than an expression that happens to begin with one, such as the
90
+ # immediately invoked `function() { … }()`.
91
+ #
92
+ # @return [Boolean]
93
+ #
94
+ def declaration?
95
+ return false unless @scanned
96
+ return @wrapped.declaration? if @wrapped
97
+
98
+ arrow? || (@code.match?(FUNCTION_DECLARATION) && @body_end == @code_end)
99
+ end
100
+
101
+ #
102
+ # Whether the script uses `await`, and so has to run in an `async`
103
+ # function.
104
+ #
105
+ # @return [Boolean]
106
+ #
107
+ def awaits?
108
+ uses?("await")
109
+ end
110
+
111
+ #
112
+ # Whether the script mentions the given word as code, rather than as a
113
+ # property name or inside a string or comment.
114
+ #
115
+ # @param [String] word
116
+ #
117
+ # @return [Boolean]
118
+ #
119
+ def uses?(word)
120
+ @words.include?(word)
121
+ end
122
+
123
+ #
124
+ # Whether the code is several statements, separated by a top-level
125
+ # semicolon, as in `"a(); b"`, or by a line break that can only end a
126
+ # statement, as in `"a()\nb"`, unlike `"a\n.b()"`.
127
+ #
128
+ # @return [Boolean]
129
+ #
130
+ def several_statements?
131
+ !@last_statement_start.nil?
132
+ end
133
+
134
+ #
135
+ # The code split before its last statement, so that the value of that
136
+ # one can be returned: `"a = 1\nb"` gives `["a = 1\n", "b"]`.
137
+ #
138
+ # @return [Array(String, String)]
139
+ #
140
+ def split_last_statement
141
+ return ["", @code] unless several_statements?
142
+
143
+ [@source.byteslice(@code_start...@last_statement_start), @source.byteslice(@last_statement_start...@code_end)]
144
+ end
145
+
146
+ #
147
+ # Whether a line break comes before the code, which right after a
148
+ # `return` ends that statement.
149
+ #
150
+ # @return [Boolean]
151
+ #
152
+ def leading_line_break?
153
+ @scanned && !@code.empty? && @source.byteslice(0...@code_start).include?("\n")
154
+ end
155
+
156
+ private
157
+
158
+ # Whether the code is one parenthesized group, as in `(function() {})`.
159
+ def parenthesized?
160
+ @paren_open == @code_start && @paren_close == @code_end - 1
161
+ end
162
+
163
+ def arrow?
164
+ return true if @code.match?(SINGLE_PARAMETER_ARROW)
165
+ return false unless @paren_close
166
+
167
+ @source.byteslice(@code_start...@paren_open).match?(ASYNC_PREFIX) &&
168
+ @source.byteslice((@paren_close + 1)..).match?(ARROW)
169
+ end
170
+
171
+ def scan
172
+ scanner = StringScanner.new(@source)
173
+ stack = []
174
+ previous = nil
175
+ ended = line_break = false
176
+
177
+ until scanner.eos?
178
+ if (length = scanner.skip(NOISE))
179
+ line_break ||= @source.byteslice(scanner.pos - length, length).include?("\n")
180
+ next
181
+ end
182
+
183
+ start = scanner.pos
184
+ top = stack.empty?
185
+ token = scan_token(scanner, stack, previous)
186
+ new_line = line_break && top && new_line_statement?(previous, token, scanner.peek(1))
187
+ @last_statement_start = start if token != ";" && (ended || new_line)
188
+ track_block(token, previous, stack)
189
+ track_condition(token, previous, stack)
190
+ ended = token == ";" && (ended || stack.empty?)
191
+ previous = token
192
+ line_break = false
193
+ @code_start = start if @code_end.zero?
194
+ @code_end = scanner.pos unless previous == ";"
195
+ end
196
+ end
197
+
198
+ # A value, or `x++`, followed on the next line by a word, a string, `!`,
199
+ # `~`, `++` or `--` can't continue it, so the line break ends the statement.
200
+ def new_line_statement?(previous, token, following)
201
+ return true if @block_end && ["(", "["].include?(token)
202
+ return false if @condition_end
203
+ return false if previous.nil? || REGEXP_KEYWORDS.include?(previous) || CONTINUING_WORDS.include?(token)
204
+
205
+ ends = previous[-1].match?(VALUE_END) || INCREMENTS.include?(previous)
206
+ ends && (token.match?(/\A[\p{Alnum}_$"'~]/) || INCREMENTS.include?(token) || (token == "!" && following != "="))
207
+ end
208
+
209
+ # Remembers whether the last top-level `}` closed a block, whose end
210
+ # ends the statement even before a `(` or `[` on the next line.
211
+ def track_block(token, previous, stack)
212
+ @block = block_start?(previous) if token == "{" && stack == ["{"]
213
+ @block_end = token == "}" && stack.empty? && @block
214
+ end
215
+
216
+ # Remembers whether the last top-level `)` closed the condition of an
217
+ # `if`, `for` or `while`, whose statement goes on even after a line break.
218
+ def track_condition(token, previous, stack)
219
+ @condition = CONTROL_WORDS.include?(previous) if token == "(" && stack == ["("]
220
+ @condition_end = token == ")" && stack.empty? && @condition
221
+ end
222
+
223
+ # A `{` after `)`, `=>`, a statement or a name opens a block, as in
224
+ # `function f() {`, `class A {` or `if (a) {`.
225
+ def block_start?(previous)
226
+ return true if previous.nil? || %w[) > ; }].include?(previous)
227
+
228
+ previous.match?(/\A#{WORD}\z/) && !OBJECT_KEYWORDS.include?(previous)
229
+ end
230
+
231
+ def scan_token(scanner, stack, previous)
232
+ if scanner.scan(WORD)
233
+ @words << scanner.matched unless previous == "."
234
+ scanner.matched
235
+ elsif scanner.scan(STRING) || (regexp_allowed?(previous) && scanner.scan(REGEXP))
236
+ scanner.matched
237
+ elsif scanner.skip(/`/)
238
+ scan_template(scanner, stack)
239
+ else
240
+ scan_punctuator(scanner, stack)
241
+ end
242
+ end
243
+
244
+ def scan_punctuator(scanner, stack)
245
+ char = scanner.getch
246
+ return char + scanner.getch if %w[+ -].include?(char) && scanner.peek(1) == char
247
+
248
+ track_parens(char, scanner.pos - 1, stack)
249
+ case char
250
+ when "{", "(", "[" then stack.push(char)
251
+ when ")", "]" then stack.pop
252
+ when "}"
253
+ opened = stack.pop
254
+ return scan_template(scanner, stack) if opened == :template
255
+
256
+ @body_end ||= scanner.pos if opened == "{" && stack.empty?
257
+ end
258
+ char
259
+ end
260
+
261
+ # Remembers where the first top-level parenthesized group, the
262
+ # parameter list of a declaration, opens and closes.
263
+ def track_parens(char, position, stack)
264
+ return if @paren_close
265
+
266
+ case char
267
+ when "(" then @paren_open ||= position if stack.empty?
268
+ when ")" then @paren_close = position if @paren_open && stack == ["("]
269
+ end
270
+ end
271
+
272
+ def scan_template(scanner, stack)
273
+ scanner.skip(TEMPLATE_CHUNK)
274
+ if scanner.skip(/\$\{/)
275
+ stack.push(:template)
276
+ else
277
+ scanner.skip(/`/)
278
+ end
279
+ "`"
280
+ end
281
+
282
+ def regexp_allowed?(previous)
283
+ return true if previous.nil? || REGEXP_KEYWORDS.include?(previous)
284
+
285
+ previous.length == 1 && !previous.match?(VALUE_END)
286
+ end
287
+ end
288
+ end
289
+ end
data/lib/ferrum/frame.rb CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "ferrum/frame/dom"
4
4
  require "ferrum/frame/runtime"
5
+ require "ferrum/isolated_world"
5
6
 
6
7
  module Ferrum
7
8
  #
@@ -62,6 +63,7 @@ module Ferrum
62
63
  @parent_id = parent_id
63
64
  @lifecycle_events = []
64
65
  @execution_id = Concurrent::MVar.new
66
+ @isolated_worlds = Concurrent::Map.new
65
67
  end
66
68
 
67
69
  # Sets the frame's state, validating it's one of {STATE_VALUES}.
@@ -165,12 +167,11 @@ module Ferrum
165
167
  # frame.body # => <html><head></head><body><p>lol</p></body></html>
166
168
  #
167
169
  def content=(html)
168
- evaluate_async(%(
170
+ execute(<<~JS, html: html)
169
171
  document.open();
170
- document.write(arguments[0]);
172
+ document.write(html);
171
173
  document.close();
172
- arguments[1](true);
173
- ), @page.timeout, html)
174
+ JS
174
175
  @page.document_node_id
175
176
  end
176
177
  alias set_content content=
@@ -222,6 +223,34 @@ module Ferrum
222
223
  end
223
224
  end
224
225
 
226
+ #
227
+ # Returns the frame's isolated world with the given name: its own
228
+ # JavaScript globals over the frame's DOM. Created on first use.
229
+ #
230
+ # @param [String] name
231
+ #
232
+ # @return [IsolatedWorld]
233
+ #
234
+ # @example
235
+ # world = page.main_frame.isolated_world("ferrum")
236
+ # world.execute("window.secret = 'top'")
237
+ # world.evaluate("window.secret") # => "top"
238
+ # page.evaluate("window.secret") # => nil
239
+ #
240
+ def isolated_world(name)
241
+ @isolated_worlds.compute_if_absent(name) { IsolatedWorld.new(self, name) }
242
+ end
243
+
244
+ #
245
+ # The frame's isolated worlds used so far, by {#isolated_world},
246
+ # {Page#evaluate_on_new_document} with `world_name:` or extensions.
247
+ #
248
+ # @return [Array<IsolatedWorld>]
249
+ #
250
+ def isolated_worlds
251
+ @isolated_worlds.values
252
+ end
253
+
225
254
  #
226
255
  # Debug representation of the frame, including its internal state.
227
256
  #
@@ -3,31 +3,39 @@
3
3
  module Ferrum
4
4
  # Shared by {Page} and {Worker}: subscribes to the CDP events behind the
5
5
  # `:request` (Fetch-domain request interception), `:response` (a request's
6
- # response has fully loaded) and `:auth` (proxy/basic auth challenges)
7
- # pseudo-events, on top of the includer's own `client` and `network`.
8
- # Anything else is passed straight through to `client`.
6
+ # response has fully loaded), `:auth` (proxy/basic auth challenges) and
7
+ # `:console` (a new console message) pseudo-events, on top of the
8
+ # includer's own `client`, `network` and `console`. Anything else is passed
9
+ # straight through to `client`.
9
10
  module Interceptable
10
- # Subscribes to a CDP event, or to `:request`/`:response`/`:auth`.
11
+ # Subscribes to a CDP event, or to `:request`/`:response`/`:auth`/`:console`.
11
12
  #
12
13
  # @param [Symbol, String] name
13
14
  #
14
- # @yieldparam [Network::InterceptedRequest, Network::Exchange, Network::AuthRequest, Hash] arg
15
+ # @yieldparam [Network::InterceptedRequest, Network::Exchange, Network::AuthRequest, Console::Message, Hash] arg
15
16
  # For `:request`, the intercepted {Network::InterceptedRequest}. For
16
17
  # `:response`, the finished {Network::Exchange}. For `:auth`, the
17
- # {Network::AuthRequest} challenge. For any other (raw CDP) event name,
18
- # the event's params `Hash`.
18
+ # {Network::AuthRequest} challenge. For `:console`, the new
19
+ # {Console::Message}. For any other (raw CDP) event name, the event's
20
+ # params `Hash`.
19
21
  #
20
22
  # @yieldparam [Integer] index
21
23
  # This callback's position among all callbacks currently registered for
22
- # the event.
24
+ # the event. Not passed for `:console`.
23
25
  #
24
26
  # @yieldparam [Integer] total
25
- # Total number of callbacks currently registered for the event.
27
+ # Total number of callbacks currently registered for the event. Not
28
+ # passed for `:console`.
26
29
  #
27
30
  # @return [Integer]
28
31
  # The subscription id, used to unsubscribe via {#off}.
32
+ #
33
+ # @example
34
+ # page.on(:console) { |message| warn(message) if message.error? }
29
35
  def on(name, &block)
30
36
  case name
37
+ when :console
38
+ console.on(&block)
31
39
  when :request
32
40
  client.on("Fetch.requestPaused") do |params, index, total|
33
41
  request = Network::InterceptedRequest.new(client, params)
@@ -60,6 +68,8 @@ module Ferrum
60
68
  # @return [void]
61
69
  def off(name, id)
62
70
  case name
71
+ when :console
72
+ console.off(id)
63
73
  when :request
64
74
  client.off("Fetch.requestPaused", id)
65
75
  when :response
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ferrum
4
+ #
5
+ # A named JavaScript world in a {Frame}: it shares the frame's DOM but has
6
+ # its own globals, so the page's scripts can't see or tamper with what runs
7
+ # in it. Chrome creates the world on first use and again in every new
8
+ # document, and it's the same world that
9
+ # {Page#evaluate_on_new_document} with `world_name:` runs scripts in.
10
+ # Evaluation methods are the same as {Frame}'s, see {Frame::Runtime}.
11
+ #
12
+ class IsolatedWorld
13
+ include Frame::Runtime
14
+
15
+ # The world's name.
16
+ #
17
+ # @return [String]
18
+ attr_reader :name
19
+
20
+ # The frame the world belongs to.
21
+ #
22
+ # @return [Frame]
23
+ attr_reader :frame
24
+
25
+ # The page the world belongs to.
26
+ #
27
+ # @return [Page]
28
+ attr_reader :page
29
+
30
+ def initialize(frame, name)
31
+ @frame = frame
32
+ @page = frame.page
33
+ @name = name
34
+ @execution_id = Concurrent::MVar.new
35
+ end
36
+
37
+ #
38
+ # Execution context id of the world in the frame's current document,
39
+ # creating the world there if it doesn't exist yet.
40
+ #
41
+ # @return [Integer]
42
+ #
43
+ def execution_id!
44
+ execution_id || begin
45
+ id = @page.command("Page.createIsolatedWorld", frameId: @frame.id, worldName: @name)["executionContextId"]
46
+ self.execution_id = id
47
+ execution_id || id
48
+ end
49
+ end
50
+
51
+ #
52
+ # Execution context id of the world in the frame's current document.
53
+ #
54
+ # @return [Integer, nil]
55
+ #
56
+ def execution_id
57
+ value = @execution_id.value
58
+ return if value.instance_of?(Object)
59
+
60
+ value
61
+ end
62
+
63
+ #
64
+ # Sets the execution context id, or clears it if +nil+ is given, e.g.
65
+ # when the document the world was created in is gone.
66
+ #
67
+ # @param [Integer, nil] value
68
+ #
69
+ # @return [Integer, nil]
70
+ #
71
+ def execution_id=(value)
72
+ if value.nil?
73
+ @execution_id.try_take!
74
+ else
75
+ @execution_id.try_put!(value)
76
+ end
77
+ end
78
+
79
+ #
80
+ # Debug representation of the world.
81
+ #
82
+ # @return [String]
83
+ #
84
+ def inspect
85
+ "#<#{self.class} @name=#{@name.inspect} @frame_id=#{@frame.id.inspect} @execution_id=#{execution_id.inspect}>"
86
+ end
87
+
88
+ private
89
+
90
+ def resolve_node_options
91
+ { executionContextId: execution_id! }
92
+ end
93
+ end
94
+ end
@@ -32,8 +32,15 @@ module Ferrum
32
32
  f10: "F10", f11: "F11", f12: "F12", meta: "Meta", command: "Meta"
33
33
  }.freeze
34
34
 
35
+ # Modifier keys currently pressed by {#hold}, in the same format as
36
+ # {#modifiers} returns. It's 0 outside a {#hold} block.
37
+ #
38
+ # @return [Integer]
39
+ attr_reader :held_modifiers
40
+
35
41
  def initialize(page)
36
42
  @page = page
43
+ @held_modifiers = 0
37
44
  end
38
45
 
39
46
  #
@@ -44,7 +51,10 @@ module Ferrum
44
51
  #
45
52
  # @return [self]
46
53
  #
54
+ # @raise [ArgumentError] If the key is a modifier, use {#hold} instead.
55
+ #
47
56
  def down(key)
57
+ reject_modifier(key)
48
58
  key = normalize_keys(Array(key)).first
49
59
  type = key[:text] ? "keyDown" : "rawKeyDown"
50
60
  @page.command("Input.dispatchKeyEvent", slowmoable: true, type: type, **key)
@@ -59,7 +69,10 @@ module Ferrum
59
69
  #
60
70
  # @return [self]
61
71
  #
72
+ # @raise [ArgumentError] If the key is a modifier, use {#hold} instead.
73
+ #
62
74
  def up(key)
75
+ reject_modifier(key)
63
76
  key = normalize_keys(Array(key)).first
64
77
  @page.command("Input.dispatchKeyEvent", slowmoable: true, type: "keyUp", **key)
65
78
  self
@@ -86,6 +99,44 @@ module Ferrum
86
99
  self
87
100
  end
88
101
 
102
+ #
103
+ # Holds modifier keys down while the block runs: every keyboard and mouse
104
+ # event dispatched inside it carries them, and they are released when the
105
+ # block returns or raises.
106
+ #
107
+ # @param [Array<:alt, :ctrl, :control, :meta, :command, :shift>] keys
108
+ #
109
+ # @yield The input to dispatch with the modifiers held.
110
+ #
111
+ # @return [Object] The block's value.
112
+ #
113
+ # @raise [ArgumentError] If no block is given or a key isn't a modifier.
114
+ #
115
+ # @example
116
+ # page.keyboard.hold(:shift) do
117
+ # page.mouse.move(x: 10, y: 10).down.move(x: 200, y: 200, steps: 10).up
118
+ # end
119
+ #
120
+ def hold(*keys)
121
+ raise ArgumentError, "block is required" unless block_given?
122
+
123
+ keys = keys.map { |key| modifier_name(key) || raise(ArgumentError, "not a modifier key: #{key.inspect}") }
124
+ previous = @held_modifiers
125
+ pressed = []
126
+
127
+ begin
128
+ keys.each { |key| press_modifier(key, pressed) }
129
+ result = yield
130
+ release_modifiers(pressed)
131
+ result
132
+ rescue StandardError
133
+ release_modifiers(pressed, quietly: true)
134
+ raise
135
+ ensure
136
+ @held_modifiers = previous
137
+ end
138
+ end
139
+
89
140
  #
90
141
  # Returns bitfield for a given keys.
91
142
  #
@@ -99,6 +150,42 @@ module Ferrum
99
150
 
100
151
  private
101
152
 
153
+ def modifier_name(key)
154
+ name = key.to_s.downcase
155
+ name if MODIFIERS.key?(name)
156
+ end
157
+
158
+ def reject_modifier(key)
159
+ return unless key.is_a?(Symbol) && modifier_name(key)
160
+
161
+ raise ArgumentError, "#{key.inspect} is a modifier, use keyboard.hold(#{key.inspect}) { ... } instead"
162
+ end
163
+
164
+ def press_modifier(name, pressed)
165
+ bit = MODIFIERS[name]
166
+ return if @held_modifiers.anybits?(bit)
167
+
168
+ @held_modifiers |= bit
169
+ dispatch_modifier("rawKeyDown", name)
170
+ pressed.push(name)
171
+ end
172
+
173
+ def release_modifiers(pressed, quietly: false)
174
+ while (name = pressed.pop)
175
+ @held_modifiers &= ~MODIFIERS[name]
176
+ begin
177
+ dispatch_modifier("keyUp", name)
178
+ rescue Error
179
+ raise unless quietly
180
+ end
181
+ end
182
+ end
183
+
184
+ def dispatch_modifier(type, name)
185
+ key = to_options(KEYS.fetch(KEYS_MAPPING[name.to_sym]))
186
+ @page.command("Input.dispatchKeyEvent", slowmoable: true, type: type, modifiers: @held_modifiers, **key)
187
+ end
188
+
102
189
  # rubocop:disable Metrics/PerceivedComplexity
103
190
  # rubocop:disable Metrics/CyclomaticComplexity
104
191
  def normalize_keys(keys, pressed_keys = [], memo = [])
@@ -120,33 +207,34 @@ module Ferrum
120
207
  nil
121
208
  else
122
209
  key = KEYS.fetch(KEYS_MAPPING[key.to_sym] || key.to_sym)
123
- key[:modifiers] = pressed_keys.flatten.map { |k| MODIFIERS[k] }.reduce(0, :|)
210
+ key[:modifiers] = pressed_keys.flatten.map { |k| MODIFIERS[k] }.reduce(@held_modifiers, :|)
124
211
  to_options(key)
125
212
  end
126
213
  when String
127
214
  raise ArgumentError, "empty keys passed" if keys.empty?
128
215
 
129
216
  pressed = pressed_keys.flatten
217
+ mask = pressed.map { |k| MODIFIERS[k] }.reduce(@held_modifiers, :|)
130
218
  keys.each_char.map do |char|
131
219
  key = KEYS[char] || {}
132
220
 
133
- if pressed.empty?
221
+ if mask.zero?
134
222
  key = key.merge(text: char, unmodifiedText: char)
135
223
  [to_options(key)]
136
224
  else
137
- text = pressed == ["shift"] ? char.upcase : char
225
+ text = mask == MODIFIERS["shift"] ? char.upcase : char
138
226
  key = key.merge(
139
227
  text: text,
140
228
  unmodifiedText: text,
141
229
  isKeypad: key["location"] == 3,
142
- modifiers: pressed.map { |k| MODIFIERS[k] }.reduce(0, :|)
230
+ modifiers: mask
143
231
  )
144
232
 
145
233
  # Synthetic key events alone do not trigger the browser's editing
146
234
  # shortcuts (e.g. select-all). When the chord matches a platform
147
235
  # accelerator, name the editing command explicitly so Chrome
148
236
  # executes it via the CDP `commands` field.
149
- command = editing_command(pressed, char)
237
+ command = editing_command(mask, char)
150
238
  key = key.merge(commands: [command]) if command
151
239
 
152
240
  modifiers = pressed.map { |k| to_options(KEYS.fetch(KEYS_MAPPING[k.to_sym])) }
@@ -175,12 +263,11 @@ module Ferrum
175
263
  # is not an editing accelerator. The accelerator modifier is Cmd on macOS
176
264
  # and Ctrl elsewhere, matching Chrome's own key bindings. Currently only
177
265
  # select-all is mapped; extend the guard for further commands as needed.
178
- def editing_command(pressed, char)
266
+ def editing_command(mask, char)
179
267
  return unless char.casecmp?("a")
180
- return if pressed.include?("shift")
181
268
 
182
269
  accelerator = Utils::Platform.mac? ? MODIFIERS["meta"] : MODIFIERS["ctrl"]
183
- "selectAll" if pressed.map { |k| MODIFIERS[k] }.compact.uniq == [accelerator]
270
+ "selectAll" if mask == accelerator
184
271
  end
185
272
  end
186
273
  end