WebKit/Element.pm untested

filter: Statementstmt 0.0% 0 / 84 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 35 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 205 CC 18 SCAR 24.2
CC
18
Cov
0%
check
30.0
_need_name
20.0
find
20.0
CRAP 11.2
1 package EV::WebKit::Element;
2 use v5.10; use strict; use warnings;
3 use Carp ();
4 our $VERSION = '0.03';
5  
6 # $frame is a web-process frame id when this element was found through a frame
7 # the main-frame script cannot reach; undef is the ordinary main-frame case.
8 # Every method routes on it (see _call_js), so a handle stays bound to the
9 # frame it came from.
10 sub _new {
11 my ($class, $browser, $id, $epoch, $frame) = @_;
12 bless { b => $browser, id => $id, epoch => $epoch, frame => $frame }, $class;
13 }
14  
15 sub frame_id { $_[0]{frame} }
16  
17 # attr/prop/type bind positionally (my ($s, $n, $cb) = @_), so a caller who omits
18 # the name leaves the CALLBACK sitting in the name slot -- and since a call with
19 # no callback is legal here, nothing complains: the coderef is quietly shipped to
20 # the JSON encoder, the encode dies inside a deferred timer where $EV::DIED only
21 # warns, and the caller waits forever for a result that is never coming. Croak
22 # instead, as every other method in this API does for a bad argument.
23 sub _need_name {
24 my ($what, $n) = @_;
25 Carp::croak("$what: a name is required") unless defined $n;
26 Carp::croak("$what: the name must be a plain string, not a " . ref($n) . ' reference'
27 . ($n && ref $n eq 'CODE' ? ' (did you omit the name and pass only a callback?)' : ''))
28 if ref $n;
29 return;
30 }
31  
32 sub _call_js {
33 my ($self, $code, $args, $cb) = @_;
34 # Same synchronous croak every async EV::WebKit method makes, and for the
35 # same reason: a non-coderef callback would only blow up later, deep inside
36 # the completion, where the die is swallowed by $EV::DIED -- so the caller's
37 # EV::run just hangs, waiting for a callback that can never be invoked.
38 # Guarding here covers every method that reaches _call_js at once, rather
39 # than once per method. It matters most for find/find_all, which pass their
40 # OWN closure down, so the guard below would otherwise never see the
41 # caller's callback at all. (An omitted callback stays legal -- _defer no-ops.)
42 Carp::croak('callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
43 # 'id' and 'epoch' are reserved for this element's registry id/per-
44 # document epoch stamp and override any caller key -- epoch lets
45 # window.__evwk.get() detect a handle from a page that has since been
46 # navigated away from, even if the new page's registry reused the same
47 # numeric id (see EV::WebKit's $BOOT script).
48 my $a = { %{ $args // {} }, id => $self->{id}, epoch => $self->{epoch} };
49 # An element found inside a frame must be operated on IN that frame: its
50 # registry entry lives in that frame's world, where the main frame cannot
51 # see it -- which is the whole reason the handle carries a frame id.
52 return $self->{b}->_call_js_frame($self->{frame}, $code, $a, $cb) if defined $self->{frame};
53 $self->{b}->_call_js($code, $a, $cb);
54 }
55  
56 sub text { $_[0]->_call_js('return window.__evwk.get(A.id, A.epoch).textContent;', {}, $_[1]) }
57 sub html { $_[0]->_call_js('return window.__evwk.get(A.id, A.epoch).innerHTML;', {}, $_[1]) }
58 sub value { $_[0]->_call_js('return window.__evwk.get(A.id, A.epoch).value;', {}, $_[1]) }
59 sub tag { $_[0]->_call_js('return window.__evwk.get(A.id, A.epoch).tagName.toLowerCase();', {}, $_[1]) }
60 sub attr { my ($s,$n,$cb)=@_; _need_name(attr => $n); $s->_call_js('return window.__evwk.get(A.id, A.epoch).getAttribute(A.name);', {name=>$n}, $cb) }
61 sub prop { my ($s,$n,$cb)=@_; _need_name(prop => $n); $s->_call_js('return window.__evwk.get(A.id, A.epoch)[A.name];', {name=>$n}, $cb) }
62  
63 sub is_visible {
64 $_[0]->_call_js(
65 'const el = window.__evwk.get(A.id, A.epoch); const s = getComputedStyle(el);'
66 . 'return s.display !== "none" && s.visibility !== "hidden" && el.getClientRects().length > 0;',
67 {}, $_[1]);
68 }
69  
70 sub find {
71 my ($s, $sel, $cb) = @_;
72 # These two pass their OWN closure to _call_js, so its callback guard sees a
73 # coderef either way and cannot check the caller's -- guard here too, or a
74 # non-coderef $cb dies inside the completion below, where $EV::DIED eats it
75 # and the caller's EV::run hangs forever.
76 Carp::croak('find: last argument must be a callback') if ref $cb ne 'CODE';
77 # The same guard the browser's own find() has. Without it a JSON null (or an
78 # omitted selector) marshalled through to querySelector, which coerces it to
79 # the TYPE selector "null" -- so find(undef) answered "not found" instead of
80 # complaining, indistinguishable from a selector that simply did not match.
81 # Reachable over the control socket too: el.find with a:[null] is one
82 # argument, so the arity guard passes it.
83 EV::WebKit::_need_selector(find => $sel);
84 # This wrapper closure is captured strongly by the (permanently
85 # GI-retained) _call_js completion closure -- but UNLIKE _call_js/
86 # EV::WebKit::find's own $self (the browser, always independently held
87 # by the caller's own long-lived variable in practice), $s (an Element)
88 # is frequently held ONLY via this closure's own capture -- e.g. several
89 # sibling calls issued off the same $el, where none of the sibling
90 # closures happen to mention $el by name, so nothing else keeps it
91 # reachable during the async gap (confirmed: weakening $s here, mirroring
92 # the find()/wait_for() fix, broke exactly that pattern -- t/41's 9
93 # concurrent $d->... calls). So $s must stay STRONGLY captured while the
94 # call is in flight; instead, break the retention at a single resolution
95 # point, explicitly undef'ing our OWN copy the instant we're done needing
96 # it (same "single resolution point" shape as wait_for's $finish) -- this
97 # releases $s (and transitively $s->{b}, the browser) from THIS closure
98 # without affecting any sibling closure's own (still-strong) copy.
99 $s->_call_js('const el = window.__evwk.get(A.id, A.epoch).querySelector(A.sel); return el ? { evwk_id: window.__evwk.put(el), evwk_epoch: window.__evwk.epoch } : null;',
100 { sel => $sel },
101 sub {
102 my ($r, $err) = @_;
103 # A hostile/buggy page can make ANY JS value come back here (e.g.
104 # Object.prototype.toJSON polluted to return something else
105 # entirely) -- never trust the decoded shape before dereferencing
106 # it: an unvalidated $r->{evwk_id} below would die inside
107 # _defer's bare EV::timer(0,0,...), which EV's default $EV::DIED
108 # swallows to stderr, permanently dropping this callback (a
109 # silent hang, not an error) instead of ever reaching the caller.
110 if (!$err && defined $r && !(ref $r eq 'HASH' && defined $r->{evwk_id})) {
111 $err = 'find: unexpected result from page (registry tampered?)';
112 }
113 my $result = (!$err && defined $r) ? EV::WebKit::Element->_new($s->{b}, $r->{evwk_id}, $r->{evwk_epoch}, $s->{frame}) : undef;
114 undef $s;
115 $cb->($result, $err);
116 });
117 }
118  
119 sub find_all {
120 my ($s, $sel, $cb) = @_;
121 Carp::croak('find_all: last argument must be a callback') if ref $cb ne 'CODE';
122 EV::WebKit::_need_selector(find_all => $sel);
123 # same reasoning as find() above.
124 $s->_call_js('return [...window.__evwk.get(A.id, A.epoch).querySelectorAll(A.sel)].map(e => ({ evwk_id: window.__evwk.put(e), evwk_epoch: window.__evwk.epoch }));',
125 { sel => $sel },
126 sub {
127 my ($r, $err) = @_;
128 # same shape distrust as find() above -- a tampered result (e.g.
129 # the whole array replaced, or containing non-descriptor
130 # elements) must degrade to a clean error, never dereference
131 # blind and die inside _defer's unguarded timer.
132 if (!$err && !(ref $r eq 'ARRAY' && !grep { ref $_ ne 'HASH' || !defined $_->{evwk_id} } @$r)) {
133 $err = 'find_all: unexpected result from page (registry tampered?)';
134 }
135 my $result = $err ? undef : [ map { EV::WebKit::Element->_new($s->{b}, $_->{evwk_id}, $_->{evwk_epoch}, $s->{frame}) } @$r ];
136 undef $s;
137 $cb->($result, $err);
138 });
139 }
140  
141 # A bare el.click() dispatches ONLY a click event, so a control whose handler is
142 # on mousedown/pointerdown -- custom dropdowns, menus, sliders, most
143 # design-system widgets -- did not respond at all, and this still reported
144 # success. Press first, then click, using hover's dictionary so the two agree
145 # about pointerType/isPrimary. Skipped for a disabled control, because no engine
146 # dispatches mouse events to one and firing them here would let a test drive
147 # something a person could not.
148 sub click {
149 $_[0]->_call_js(
150 'const el = window.__evwk.get(A.id, A.epoch);'
151 . 'const r = el.getBoundingClientRect();'
152 . 'const at = { bubbles:true, cancelable:true, composed:true, view:window,'
153 . ' pointerType:"mouse", pointerId:1, isPrimary:true, button:0,'
154 . ' clientX: r.left + r.width/2, clientY: r.top + r.height/2 };'
155 . 'const off = el.disabled === true'
156 . ' || !!(el.closest && el.closest("fieldset[disabled]") && !el.closest("legend"));'
157 . 'if (!off) {'
158 . ' const P = window.PointerEvent || MouseEvent;'
159 . ' el.dispatchEvent(new P("pointerdown", {...at, buttons:1}));'
160 . ' el.dispatchEvent(new MouseEvent("mousedown", {...at, buttons:1}));'
161 . ' el.dispatchEvent(new P("pointerup", {...at, buttons:0}));'
162 . ' el.dispatchEvent(new MouseEvent("mouseup", {...at, buttons:0}));'
163 . '}'
164 # click() last, and unconditionally: it is what activates a link or submits
165 # a form, and on a disabled control the engine makes it the no-op it should be.
166 . 'el.click();'
167 . 'return true;',
168 {}, $_[1]);
169 }
170  
171 sub focus { $_[0]->_call_js('window.__evwk.get(A.id, A.epoch).focus(); return true;', {}, $_[1]) }
172  
173 sub type {
174 my ($s, $text, $cb) = @_;
175 _need_name(type => $text); # same positional-binding trap as attr/prop -- see there
176 $s->_call_js(
177 'const el = window.__evwk.get(A.id, A.epoch); const tag = el.tagName;'
178 . 'if (tag === "INPUT" || tag === "TEXTAREA") {'
179 . ' el.focus(); el.value = (el.value || "") + A.text;'
180 . ' el.dispatchEvent(new Event("input", {bubbles:true}));'
181 . ' el.dispatchEvent(new Event("change", {bubbles:true}));'
182 . '} else if (el.isContentEditable) {'
183 . ' el.focus(); el.textContent = (el.textContent || "") + A.text;'
184 . ' el.dispatchEvent(new InputEvent("input", {bubbles:true}));'
185 . '} else { throw new Error("element is not editable"); }'
186 . 'return true;',
187 { text => $text }, $cb);
188 }
189 *send_keys = \&type;
190  
191 sub clear {
192 $_[0]->_call_js(
193 'const el = window.__evwk.get(A.id, A.epoch); const tag = el.tagName;'
194 . 'if (tag === "INPUT" || tag === "TEXTAREA") {'
195 . ' el.value = "";'
196 . ' el.dispatchEvent(new Event("input", {bubbles:true}));'
197 . '} else if (el.isContentEditable) {'
198 . ' el.textContent = "";'
199 . ' el.dispatchEvent(new InputEvent("input", {bubbles:true}));'
200 . '} else { throw new Error("element is not editable"); }'
201 . 'return true;',
202 {}, $_[1]);
203 }
204  
205 sub submit {
206 $_[0]->_call_js(
207 'const el = window.__evwk.get(A.id, A.epoch); const f = el.form || el;'
208 . 'if (f instanceof HTMLFormElement) HTMLFormElement.prototype.submit.call(f);'
209 . 'return true;',
210 {}, $_[1]);
211 }
212  
213 # Bring the element into the viewport. Not merely a convenience: click() on an
214 # off-screen element works in the DOM but a page that reacts to scroll position
215 # (lazy images, sticky headers, infinite scroll) will not have done its work
216 # yet, so a subsequent read sees the pre-scroll state.
217 #
218 # behavior:"instant" is load-bearing: under a page's own CSS
219 # `scroll-behavior: smooth` the scroll ANIMATES, and this would resolve with the
220 # viewport still travelling -- so the reads it exists to make correct happen at
221 # the wrong offset.
222 sub scroll_into_view {
223 $_[0]->_call_js(
224 'const el = window.__evwk.get(A.id, A.epoch);'
225 . 'el.scrollIntoView({block:"center", inline:"center", behavior:"instant"});'
226 . 'return true;',
227 {}, $_[1]);
228 }
229  
230 # Hover. A real pointer entering an element produces pointerover/mouseover (which
231 # bubble) AND pointerenter/mouseenter (which do NOT), then a move; menus and
232 # tooltips variously listen for any of them, so sending only mouseover leaves a
233 # menu that opens on mouseenter shut. isTrusted is false for all of these -- a
234 # page checking it is not fooled (documented in the Ceiling).
235 sub hover {
236 $_[0]->_call_js(
237 'const el = window.__evwk.get(A.id, A.epoch);'
238 . 'const r = el.getBoundingClientRect();'
239 # A PointerEvent built without these reports pointerType "" and isPrimary
240 # false, so a menu branching on the device takes the wrong branch -- which
241 # is the class of menu this method exists to open. MouseEventInit has no
242 # such members and WebIDL ignores unknown ones, so one dictionary serves
243 # both constructors.
244 . 'const at = { bubbles:true, cancelable:true, view:window,'
245 . ' pointerType:"mouse", pointerId:1, isPrimary:true,'
246 . ' clientX: r.left + r.width/2, clientY: r.top + r.height/2 };'
247 . 'for (const t of ["pointerover","mouseover"]) {'
248 . ' el.dispatchEvent(new (window.PointerEvent && t[0] === "p" ? PointerEvent : MouseEvent)(t, at)); }'
249 . 'for (const t of ["pointerenter","mouseenter"]) {'
250 . ' el.dispatchEvent(new (window.PointerEvent && t[0] === "p" ? PointerEvent : MouseEvent)(t, {...at, bubbles:false})); }'
251 . 'el.dispatchEvent(new MouseEvent("mousemove", at));'
252 . 'return true;',
253 {}, $_[1]);
254 }
255  
256 # Select an <option> by value, or by visible label when no value matches. Setting
257 # el.value alone is not enough: every framework binds to input/change, so a
258 # silent assignment updates the DOM and leaves the application state stale.
259 sub select_option {
260 my ($s, $value, $cb) = @_;
261 _need_name(select_option => $value); # same positional-binding trap as attr/prop
262 # Stringify before the JSON bridge: an option's value is always a string in
263 # the DOM and the match below is ===, so an integer crossed as a JSON number
264 # and select_option(5) failed to find <option value="5">.
265 $value = "$value";
266 $s->_call_js(
267 'const el = window.__evwk.get(A.id, A.epoch);'
268 . 'if (!(el instanceof HTMLSelectElement)) throw new Error("element is not a <select>");'
269 . 'const opts = [...el.options];'
270 . 'let i = opts.findIndex(o => o.value === A.value);'
271 . 'if (i < 0) i = opts.findIndex(o => (o.label || o.textContent || "").trim() === A.value);'
272 . 'if (i < 0) throw new Error("no option with value or label " + JSON.stringify(A.value));'
273 . 'el.selectedIndex = i;'
274 . 'el.dispatchEvent(new Event("input", {bubbles:true}));'
275 . 'el.dispatchEvent(new Event("change", {bubbles:true}));'
276 . 'return opts[i].value;',
277 { value => $value }, $cb);
278 }
279  
280 # Set a checkbox/radio to $on (default true). click() would TOGGLE, so calling it
281 # twice to "make sure" silently undoes itself; this is idempotent by construction
282 # and a no-op (no events) when the box is already in the requested state, which is
283 # also what a real user clicking an already-checked radio produces.
284 sub check {
285 my ($s, @arg) = @_;
286 my $cb = (@arg && ref $arg[-1] eq 'CODE') ? pop @arg : undef;
287 # Two leftover arguments means a mistyped callback in the state position
288 # followed by the real one. A SINGLE leftover is the state, whatever it is:
289 # decoded-JSON booleans are blessed scalar refs, and croaking on those would
290 # reject the most ordinary source of a boolean this API has.
291 Carp::croak('check: takes at most a state and a callback') if @arg > 1;
292 my $on = @arg ? ($arg[0] ? 1 : 0) : 1;
293 $s->_call_js(
294 'const el = window.__evwk.get(A.id, A.epoch);'
295 . 'if (!(el instanceof HTMLInputElement) || !/^(checkbox|radio)$/.test(el.type))'
296 . ' throw new Error("element is not a checkbox or radio");'
297 . 'if (el.checked === !!A.on) return !!A.on;'
298 . 'el.checked = !!A.on;'
299 . 'el.dispatchEvent(new Event("input", {bubbles:true}));'
300 . 'el.dispatchEvent(new Event("change", {bubbles:true}));'
301 . 'return !!A.on;',
302 { on => $on }, $cb);
303 }
304 sub uncheck {
305 my ($s, $cb) = @_;
306 Carp::croak('uncheck: callback must be a code reference') if defined $cb && ref $cb ne 'CODE';
307 $s->check(0, $cb ? ($cb) : ());
308 }
309  
310 # Geometry, as a hashref: x/y/width/height/top/left/bottom/right plus the
311 # page-relative page_x/page_y. Viewport-relative like getBoundingClientRect
312 # itself, which is what a caller comparing against a screenshot wants; page_x/y
313 # add the scroll offset for anyone who needs absolute document coordinates.
314 #
315 # An element that is not rendered at all (display:none, or detached) has a rect
316 # of all zeros in every browser. Reporting that as a box would be a lie a caller
317 # could easily divide by, so it comes back undef instead, with is_visible left as
318 # the way to ask the question directly.
319 sub box {
320 $_[0]->_call_js(
321 'const el = window.__evwk.get(A.id, A.epoch);'
322 . 'const r = el.getBoundingClientRect();'
323 . 'if (!r.width && !r.height && !r.x && !r.y) return null;'
324 . 'return { x: r.x, y: r.y, width: r.width, height: r.height,'
325 . ' top: r.top, left: r.left, bottom: r.bottom, right: r.right,'
326 . ' page_x: r.x + window.scrollX, page_y: r.y + window.scrollY };',
327 {}, $_[1]);
328 }
329  
330 1;
331  
332 =pod
333  
334 =head1 NAME
335  
336 EV::WebKit::Element - a handle to a DOM element found by EV::WebKit
337  
338 =head1 SYNOPSIS
339  
340 $b->find('#login', sub {
341 my ($el, $err) = @_;
342 # A die inside an EV callback only reaches $EV::DIED, which warns and
343 # keeps going -- break instead.
344 if ($err) { warn "find failed: $err\n"; return EV::break }
345 if (!$el) { warn "no #login on this page\n"; return EV::break }
346  
347 $el->type('alice', sub {
348 my (undef, $err) = @_;
349 if ($err) { warn "type failed: $err\n"; return EV::break }
350 $el->submit(sub {
351 my (undef, $err) = @_;
352 warn "submit failed: $err\n" if $err;
353 EV::break;
354 });
355 });
356 });
357  
358 =head1 DESCRIPTION
359  
360 An EV::WebKit::Element is a handle to a single DOM node discovered via
361 L<EV::WebKit>'s C<find>, C<find_all>, C<find_js>, C<find_all_js> or
362 C<wait_for>, or (scoped to that element's descendants) its own C<find>/
363 C<find_all> below. Internally it is just a
364 small page-side registry id, the per-document epoch stamp of the registry
365 it was created from, and a back-reference to the owning L<EV::WebKit>
366 browser -- not a live DOM reference held on the Perl side. Every method
367 runs JavaScript against that node asynchronously, on the same L<EV> loop as
368 the browser, and follows the browser's own callback convention: a trailing
369 C<sub { my ($result, $err) = @_; ... }>, C<$err> undef on success. See
370 L<EV::WebKit/"CALLBACK CONVENTION">.
371  
372 Instances are only ever returned by L<EV::WebKit> methods; there is no
373 public constructor.
374  
375 If the underlying DOM node has since been removed from the document, any
376 method call on that handle fails with a script error whose message
377 mentions "stale element". The same happens if navigation has replaced the
378 page entirely, even though the new page's own registry happens to reuse
379 the same numeric id the old handle had: each navigation re-injects a fresh
380 registry with a new epoch stamp, every handle carries the epoch it was
381 created with, and a mismatch is treated exactly like a removed node.
382 C<id> and C<epoch> are reserved argument names, always set by this class
383 internally, for every JavaScript snippet run through these methods.
384  
385 A handle found through the C<< frame => { url => ... } >> form remembers B<which
386 frame> it came from, and every call on it runs there -- see
387 L<EV::WebKit/"Addressing an iframe">. A handle found through the selector form
388 (C<< frame => '#f' >>) does not: main-frame script walked C<contentDocument> to
389 reach it, and every call is made the same way.
390  
391 Neither outlives its frame, but they say so differently: once the frame is
392 removed or the page navigates away, the first kind fails with C<frame is gone>
393 and the second with the ordinary C<stale element>.
394  
395 =head1 METHODS
396  
397 All methods below take a trailing C<sub { my ($result, $err) = @_; ... }>
398 callback.
399  
400 =head2 text
401  
402 $el->text($cb);
403  
404 C<$result> is the node's C<textContent>.
405  
406 =head2 html
407  
408 $el->html($cb);
409  
410 C<$result> is the node's C<innerHTML>.
411  
412 =head2 value
413  
414 $el->value($cb);
415  
416 C<$result> is the form control's current C<value>.
417  
418 =head2 tag
419  
420 $el->tag($cb);
421  
422 C<$result> is the node's lower-cased tag name, e.g. C<"div">.
423  
424 =head2 attr
425  
426 $el->attr($name, $cb);
427  
428 C<$result> is the HTML attribute C<$name> (via C<getAttribute>), or
429 C<undef> if the attribute is not present.
430  
431 =head2 prop
432  
433 $el->prop($name, $cb);
434  
435 C<$result> is the live JavaScript/DOM property C<$name> (e.g.
436 C<< prop('checked') >>), as opposed to C<attr>'s raw HTML attribute --
437 useful when the two differ (checkbox C<checked> state, current vs default
438 C<value>, and so on).
439  
440 =head2 is_visible
441  
442 $el->is_visible($cb);
443  
444 C<$result> is true if the element's computed C<display> is not C<none>,
445 its computed C<visibility> is not C<hidden>, and it has at least one client
446 rect (roughly: it takes up visible space in the rendered page).
447  
448 =head2 find
449  
450 $el->find($selector, $cb);
451  
452 Scoped C<querySelector> under this element. C<$result> is an
453 L<EV::WebKit::Element> on a match, or C<undef> if nothing matched --
454 not-found is not an error.
455  
456 =head2 find_all
457  
458 $el->find_all($selector, $cb);
459  
460 Scoped C<querySelectorAll> under this element. C<$result> is a (possibly
461 empty) arrayref of L<EV::WebKit::Element>.
462  
463 =head2 click
464  
465 $el->click($cb);
466  
467 Presses the element the way a pointer does: C<pointerdown>, C<mousedown>,
468 C<pointerup>, C<mouseup>, then the node's own C<click()>. The press matters --
469 plenty of controls (custom dropdowns, menus, sliders) act on C<mousedown> and
470 never see a bare C<click()> at all. A B<disabled> control gets the C<click()>
471 only, with no synthetic press, because no engine dispatches mouse events to one
472 and firing them here would drive something a person could not.
473  
474 Visibility is not checked: an off-screen or C<display:none> element is clicked
475 as asked, and reports success. Ask L</is_visible> first if that matters, and
476 L</scroll_into_view> if the page reacts to scroll position.
477  
478 =head2 type
479  
480 $el->type($text, $cb);
481  
482 On an C<< <input> >> or C<< <textarea> >>, appends C<$text> to the
483 element's current C<value> and dispatches C<input> and C<change> events.
484 On a contenteditable element (C<isContentEditable>), appends C<$text> to
485 its C<textContent> instead (there is no native C<value> to set) and
486 dispatches an C<input> event. Either way this sets the content directly and
487 fires the event(s) once -- it does not simulate individual keydown/keyup
488 events per character. On anything else (not a form control, not
489 contenteditable), C<$err> is set to an error mentioning "not editable"
490 rather than silently doing nothing.
491  
492 =head2 send_keys
493  
494 An alias for C<type> above (identical behavior, including the "not really
495 per-key" caveat and the contenteditable/not-editable handling).
496  
497 =head2 clear
498  
499 $el->clear($cb);
500  
501 On an C<< <input> >> or C<< <textarea> >>, empties C<value> and dispatches
502 an C<input> event. On a contenteditable element, empties C<textContent>
503 instead and dispatches an C<input> event. On anything else, C<$err> is set
504 to an error mentioning "not editable".
505  
506 =head2 focus
507  
508 $el->focus($cb);
509  
510 Calls the node's C<focus()>.
511  
512 =head2 submit
513  
514 $el->submit($cb);
515  
516 Calls the native C<submit()> of the element's owning C<< <form> >>, or of
517 the element itself if it has no C<form> (e.g. calling C<submit> directly on
518 a C<< <form> >> element). This bypasses any C<onsubmit> handler and may
519 navigate the page. Resolves successfully even if there was nothing to
520 submit (a silent no-op).
521  
522 =head2 select_option
523  
524 $el->select_option($value, $cb); # $cb->($selected_value, $err)
525  
526 Selects an C<< <option> >> of a C<< <select> >> by its C<value>, falling back
527 to matching the visible label when no value matches -- so an option whose
528 C<value> differs from what the page displays, such as
529 C<< <option value="b">Beta</option> >>, is still reachable by the text the
530 user sees. (An option with no C<value> attribute at all takes its value from
531 its own text, so it already matches on the first pass.) Fires C<input> and C<change> so page code bound to
532 those actually runs; assigning C<el.value> alone updates the DOM and leaves
533 application state stale. Errors if the element is not a C<< <select> >>, or if
534 no option matches.
535  
536 =head2 check / uncheck
537  
538 $el->check($cb); # ensure checked
539 $el->check(0, $cb); # ensure UNchecked
540 $el->uncheck($cb); # the same thing, spelled out
541  
542 Sets a checkbox or radio to a definite state and resolves with that state.
543 Deliberately not C<click>: clicking B<toggles>, so calling it twice "to be
544 sure" silently undoes itself. These are idempotent -- already in the requested
545 state means no change and, like a real browser, B<no> C<change> event. Errors
546 if the element is not a checkbox or radio.
547  
548 The single-argument form is read as a B<callback> if it is a code reference and
549 as the B<state> otherwise -- evaluated for truth, so a decoded-JSON boolean
550 works as well as a plain C<1> or C<0>. C<uncheck> has no state argument, so a
551 non-coderef there is a mistyped callback and croaks.
552  
553 =head2 hover
554  
555 $el->hover($cb);
556  
557 Dispatches the pointer/mouse sequence an entering cursor produces:
558 C<pointerover>/C<mouseover> (which bubble), then C<pointerenter>/C<mouseenter>
559 (which do not), then C<mousemove>, positioned at the element's centre. Menus
560 and tooltips listen for various of these, so dispatching only C<mouseover>
561 leaves a menu that opens on C<mouseenter> shut. These are synthetic events:
562 C<isTrusted> is false, so a page that checks it is not fooled.
563  
564 =head2 box
565  
566 $el->box($cb); # $cb->($box, $err)
567  
568 The element's geometry as a hashref: C<x>, C<y>, C<width>, C<height>, C<top>,
569 C<left>, C<bottom>, C<right> -- viewport-relative, exactly as
570 C<getBoundingClientRect> gives them, which is what you want when comparing
571 against a screenshot -- plus C<page_x> and C<page_y>, the same origin with the
572 scroll offset added, for absolute document coordinates.
573  
574 C<$box> is C<undef> for an element that is not rendered (C<display:none>, or
575 detached from the document). Such an element has an all-zero rect in every
576 browser, and returning that as a box would be a plausible-looking lie a caller
577 could divide by; ask L</is_visible> if that is the question.
578  
579 For an element inside a frame the rect is relative to B<that frame's> viewport,
580 not the top-level one, since that is the only coordinate space the element's
581 own document has. Offsetting it into page coordinates would need the frame's
582 position, which is the parent document's to know.
583  
584 =head2 frame_id
585  
586 my $id = $el->frame_id;
587  
588 The id of the frame this handle is B<bound> to, or C<undef> if it is not bound
589 to one. Synchronous; the id itself is opaque and lives only as long as the frame
590 does.
591  
592 Note what C<undef> does B<not> mean. Only the C<< frame => { url => ... } >>
593 form binds a handle to a frame; a handle reached through the selector form
594 (C<< frame => '#f' >>) is inside an iframe but reports C<undef>, exactly as a
595 main-frame handle does. So this tells you how the handle will be operated on,
596 not where the element lives -- it is not a test for "is this inside an iframe".
597 See L<EV::WebKit/"Addressing an iframe">.
598  
599 =head2 scroll_into_view
600  
601 $el->scroll_into_view($cb);
602  
603 Scrolls the element to the centre of the viewport. Worth doing before reading
604 around it: C<click> works on an off-screen element, but a page that reacts to
605 scroll position (lazy images, infinite scroll, sticky headers) will not have
606 done that work yet.
607  
608 =head1 SEE ALSO
609  
610 L<EV::WebKit>
611  
612 =head1 AUTHOR
613  
614 vividsnow
615  
616 =head1 LICENSE
617  
618 This library is free software; you can redistribute it and/or modify it
619 under the same terms as Perl itself.
620  
621 =cut