-
Notifications
You must be signed in to change notification settings - Fork 4
/
core.clj
1341 lines (1177 loc) · 53.6 KB
/
core.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns cuic.core
"Core functions for UI queries and interactions"
(:refer-clojure :exclude [find type name])
(:require [clojure.core :as core]
[clojure.string :as string]
[cuic.chrome :refer [chrome? devtools page]]
[cuic.internal.cdt :refer [invoke]]
[cuic.internal.dom :refer [wrap-element
element?
maybe-element?
stale-as-nil
stale-as-ex
get-node-id
get-element-name
get-custom-name
get-element-cdt
assoc-custom-name]]
[cuic.internal.page :refer [navigate-to
navigate-forward
navigate-back]]
[cuic.internal.runtime :refer [get-window
window?
exec-js-code
scroll-into-view-if-needed]]
[cuic.internal.input :refer [mouse-move
mouse-click
type-text
press-key]]
[cuic.internal.html :refer [parse-document parse-element boolean-attributes]]
[cuic.internal.util :refer [rewrite-exceptions
cuic-ex
timeout-ex
check-arg
quoted
decode-base64
url-str?]])
(:import (java.io File)
(cuic TimeoutException)))
(set! *warn-on-reflection* true)
;;;
;;; config
;;;
(defn- -chars-per-minute [speed]
(check-arg [#(or (contains? #{:slow :normal :fast :very-fast :tycitys} %)
(pos-int? %))
"positive integer or one of #{:slow :normal :fast :tycitys}"]
[speed "typing speed"])
(case speed
:slow 300
:normal 600
:fast 1200
:very-fast 2400
:tycitys 12000
speed))
(def ^:dynamic *browser*
"Default browser that will be used for core queries such as
[[cuic.core/find]], [[cuic.core/document]] or [[cuic.core/window]]
if not explicitly defined during the query invocation time.
Use `binding` to assign default for e.g. single test run:
```clojure
(defn shared-chrome-fixture [t]
(binding [*browser* (get-shared-chrome-instance-somehow)]
(t)))
```"
nil)
(def ^:dynamic *timeout*
"Default implicit timeout (in milliseconds) for queries and interactions
before `cuic.TimeoutException` is thrown
Use `binding` to assign default for e.g. single test run:
```clojure
(defn browser-test-defaults-fixture [t]
(binding [*timeout* 20000
*typing-speed* :tycitys]
(t)))
```"
5000)
(def ^:dynamic *base-url*
"Base url that will be prepended to [[cuic.core/goto]] url if the value does
not contain hostname.
Use `binding` to assign default for e.g. single test run:
```clojure
(defn local-server-test-fixture [t]
(binding [*base-url* (str \"http://localhost:\" (get-local-server-port))]
(t)))
```"
nil)
(def ^:dynamic *typing-speed*
"Default typing speed in **typed characters per minute**. Supports
also the following preset values:
* `:slow` - 300 chars/min
* `:normal` - 600 chars/min
* `:fast` - 1200 chars/min
* `:very-fast` - 2400 chars/min
* `:tycitys` - 12000 chars/min
Use `binding` to assign default for e.g. single test run:
```clojure
(defn browser-test-defaults-fixture [t]
(binding [*timeout* 20000
*typing-speed* :tycitys]
(t)))
```"
:normal)
(def ^:dynamic *query-scope*
"HTML element that acts as a root scope for [[cuic.core/find]] and
[[cuic.core/query]] queries, unless othewise specified at query
invocation time. Setting this value to `nil` indicates that
queries should use document scope by default.
Do not bind this variable directly, instead use [[cuic.core/in]]
to define query scope in your application code."
nil)
(defn set-browser!
"Globally resets the default browser. Useful for example REPL
usage. See [[cuic.core/*browser*]] for more details."
[browser]
(rewrite-exceptions
(check-arg [chrome? "chrome instance"] [browser "value"])
(alter-var-root #'*browser* (constantly browser))))
(defn set-timeout!
"Globally resets the default implicit timeout. Useful for
example REPL usage. See [[cuic.core/*timeout*]] for more details."
[timeout]
(rewrite-exceptions
(check-arg [nat-int? "positive integer or zero"] [timeout "timeout"])
(alter-var-root #'*timeout* (constantly timeout))))
(defn set-base-url!
"Globally resets the default base url. Useful for example REPL
usage. See [[cuic.core/*timeout*]] for more details."
[base-url]
(rewrite-exceptions
(check-arg [url-str? "valid url string"] [base-url "base url"])
(alter-var-root #'*base-url* (constantly base-url))))
(defn set-typing-speed!
"Globally resets the default typing speed. Useful for example
REPL usage. See [[cuic.core/*typing-speed*]] for more details."
[speed]
(rewrite-exceptions
(-chars-per-minute speed)
(alter-var-root #'*typing-speed* (constantly speed))))
;;;
;;; misc
;;;
(defn sleep
"Stops the current thread execution for the given
n milliseconds."
[ms]
{:pre [(nat-int? ms)]}
(Thread/sleep ms))
(defmacro wait
"Macro that waits until the given expression returns a
truthy value or timeouts. Uses [[cuic.core/*timeout*]] by
default but the timeout value can be overrided by providing
it as a second parameter.
**Attention:** the waited expression may be invoked
multiple times so it should **not** mutate anything during
the invocation!"
([expr] `(wait ~expr cuic.core/*timeout*))
([expr timeout]
`(let [timeout# ~timeout
start-t# (System/currentTimeMillis)]
(check-arg [nat-int? "positive integer or zero"] [timeout# "timeout"])
(loop []
(let [val# ~expr]
(or val#
(if (>= (- (System/currentTimeMillis) start-t#) timeout#)
(throw (TimeoutException. (str "Timeout exceeded while waiting for truthy "
"value from expression: " ~(pr-str expr))
val#))
(recur))))))))
(defn timeout-ex?
"Return true if the given exception is caused by timeout while waiting
for certain condition, for example element becoming visible before click
or custom condition from [[cuic.core/wait]]."
[ex]
(instance? TimeoutException ex))
(defmacro in
"Macro that runs its body using the given element as \"root scope\"
for queries: all matching elements must be found under the element.
Scope must be a valid HTML element or otherwise an exception will
be thrown.
```clojure
;; the following codes are equivalent
(c/in (c/find \"#header\")
(let [items (c/query \".navi-item\")]
...))
(let [header (c/find \"#header\")
items (c/query {:in header :by \".navi-item\"})]
...)
```"
[scope & body]
`(rewrite-exceptions
(let [root-elem# ~scope]
(check-arg [element? "html element"] [root-elem# "scope root"])
(binding [*query-scope* root-elem#]
~@body))))
(defn as
"Assigns a new custom name for the give element. The assigned name
will be displayed in REPL and in error messages but it does
not have any effect on other behaviour.
```clojure
(-> (c/find \"#sidebar\")
(c/as \"Sidebar\")
```
Note that usually one should prefer `(find {:as <name> :by <sel>})`
for assigning names instead of `(-> (find <sel>) (as <name>)` because
then the name will be displayed in error message if `find` fails
for some reason. See [[cuic.core/find]] and [[cuic.core/query]] for
more details."
[element name]
(rewrite-exceptions
(check-arg [string? "string"] [name "element name"])
(check-arg [element? "html element"] [element "renamed element"])
(assoc-custom-name element name)))
(defn name
"Returns the custom name of the given element or `nil` if debug name is
not set for the element."
[element]
(rewrite-exceptions
(check-arg [element? "html element"] [element "target element"])
(get-custom-name element)))
;;;
;;; core queries
;;;
(defn- -require-default-browser []
(or *browser* (throw (cuic-ex "Default browser not set"))))
(defn window
"Returns a window object for the current default browser.
Note that window can only be used as `this` in [[cuic.core/eval-js]]
and [[cuic.core/exec-js]] but not as query scope. For query
scopes, use [[cuic.core/document]] instead.
Default browser can be overriden by providing browser
explicitly as a parameter."
([] (rewrite-exceptions (window (-require-default-browser))))
([browser]
(rewrite-exceptions
(check-arg [chrome? "chrome instance"] [browser "given browser"])
(get-window (devtools browser)))))
(defn document
"Returns a document object (HTML element) for the current default
browser. Default browser can be overriden by providing browser
explicitly as a parameter."
([] (rewrite-exceptions (document (-require-default-browser))))
([browser]
(rewrite-exceptions
(check-arg [chrome? "chrome instance"] [browser "given browser"])
(let [cdt (devtools browser)
res (invoke {:cdt cdt
:cmd "DOM.getDocument"
:args {:depth 0}})
doc (wrap-element cdt (:root res) nil "document" nil)]
(when (nil? doc)
(throw (cuic-ex "Cound not get page document")))
(vary-meta doc assoc ::document? true)))))
(defn active-element
"Returns active element (HTML element) for the current default
browser or `nil` if there are no active elements in the
page at the moment. Default browser can be overriden by
providing browser explicitly as a parameter."
([] (rewrite-exceptions (active-element (-require-default-browser))))
([browser]
(rewrite-exceptions
(stale-as-ex (cuic-ex "Couldn't get active element")
(check-arg [chrome? "chrome instance"] [browser "given browser"])
(let [cdt (devtools browser)
res (invoke {:cdt cdt
:cmd "Runtime.evaluate"
:args {:expression "document.activeElement"}})
obj (:result res)]
(when obj
(when-let [node (-> (invoke {:cdt cdt
:cmd "DOM.describeNode"
:args (select-keys obj [:objectId])})
(:node))]
(wrap-element cdt node nil (:description obj) nil))))))))
(defn find
"Tries to find **exactly one** html element by the given css
selector and throws an exception element wasn't found **or**
there are multiple elements matching the selector.
If any element is not found from the DOM, `find` tries to wait
for it until the element appears to the DOM or timeout exceeds.
By default, the wait timeout is [[cuic.core/*timeout*]] but it
can be overriden per invocation.
Basic usage:
```clojure
(def search-input (c/find \".navi input.search\")
```
In addition to plain css selector, `find` can be invoked with
more information by using map form:
```clojure
(find {:by <selector> ; mandatory - CSS selector for the query
:in <scope> ; optional - root scope for query, defaults to document see cuic.core/in
:as <name> ; optional - name of the result element, see cuic.core/as
:timeout <ms> ; optional - wait timeout in ms, defaults to cuic.core/*timeout*
})
;; examples
(c/find {:by \".navi input.search\"
:as \"Quick search input\"})
(c/find {:in (find \"#sidebar\")
:by \".logo\"
:timeout 10000})
```"
[selector]
(rewrite-exceptions
(check-arg [#(or (string? %) (map? %)) "string or map"] [selector "selector"])
(loop [selector selector]
(if (map? selector)
(let [{:keys [in by as timeout]
:or {timeout *timeout*}} selector
ctx (or in *query-scope* (document))
_ (check-arg [element? "html element"] [ctx "context"])
_ (check-arg [string? "string"] [by "selector"])
_ (check-arg [#(or (string? %) (nil? %)) "string"] [as "alias"])
_ (check-arg [nat-int? "positive integer or zero"] [timeout "timeout"])
cdt (devtools (-require-default-browser))
ctx-id (or (stale-as-nil (get-node-id ctx))
(throw (cuic-ex "Could not find element" (quoted (or as by)) "because"
"context element" (quoted (get-element-name ctx)) "does not"
"exist anymore")))
start-t (System/currentTimeMillis)]
(loop []
(let [result (invoke {:cdt cdt
:cmd "DOM.querySelectorAll"
:args {:nodeId ctx-id :selector by}})
node-ids (:nodeIds result)
n-nodes (count node-ids)
elapsed (- (System/currentTimeMillis) start-t)]
(case n-nodes
0 (if (< elapsed timeout)
(do (sleep (min 100 (- *timeout* elapsed)))
(recur))
(throw (timeout-ex "Could not find element" (quoted as) "from"
(quoted (get-element-name ctx)) "with selector"
(quoted by) "in" timeout "milliseconds")))
1 (or (stale-as-nil (wrap-element cdt {:nodeId (first node-ids)} ctx as by))
(recur))
(throw (cuic-ex "Found too many" (str "(" n-nodes ")") (quoted as)
"html elements from" (quoted (get-element-name ctx))
"with selector" (quoted by)))))))
(recur {:by selector})))))
(defn query
"Works like [[cuic.core/find]] but returns 0..n elements matching
the given css selector. In case of no results, `nil` will be
returned, otherwise the return value is a vector of matching
HTML elements.
Basic usage:
```clojure
(def navi-items
(c/query \".navi .item\")
```
In addition to plain css selector, `query` can be invoked with
more information by using map form:
```clojure
(query {:by <selector> ; mandatory - CSS selector for the query
:in <scope> ; optional - root scope for query, defaults to document see cuic.core/in
:as <name> ; optional - name for the result elements
})
;; examples
(c/query {:by \".navi .item\"
:as \"Navigation item\"})
(c/find {:in (find \"#sidebar\")
:by \".item\"
:as \"Sidebar item\"})
```
Note that unlike [[cuic.core/find]], [[cuic.core/query]] **does not
wait** for the results: if there are zero elements matching the given
selector at the query time, the result set will be `nil`. If some
results are expected, use [[cuic.core/query]] in conjunction with
[[cuic.core/wait]] e.g.
```clojure
(c/wait (c/query \".navi .item\"))
```"
[selector]
(rewrite-exceptions
(check-arg [#(or (string? %) (map? %)) "string or map"] [selector "selector"])
(loop [selector selector]
(if (map? selector)
(let [{:keys [in by as]} selector
ctx (or in *query-scope* (document))
_ (check-arg [element? "html element"] [ctx "context"])
_ (check-arg [string? "string"] [by "selector"])
_ (check-arg [#(or (string? %) (nil? %)) "string"] [as "alias"])
cdt (devtools (-require-default-browser))
ctx-id (or (stale-as-nil (get-node-id ctx))
(throw (cuic-ex "Could not query" (quoted as) "elements with selector"
(quoted by) "because context element" (quoted (get-element-name ctx))
"does not exist anymore")))]
(->> (invoke {:cdt cdt
:cmd "DOM.querySelectorAll"
:args {:nodeId ctx-id :selector by}})
(:nodeIds)
(keep #(stale-as-nil (wrap-element cdt {:nodeId %} ctx as by)))
(vec)
(doall)
(not-empty)))
(recur {:by selector})))))
;;;
;;; js code execution
;;;
(defn- -exec-js [code args this]
(let [result (exec-js-code {:code code
:args args
:this this})]
(if-let [error (:error result)]
(throw (cuic-ex (str "JavaScript error occurred:\n\n" error)))
(:return result))))
(defn eval-js
"Evaluates the given JavaScript expression in the given `this` object
context and returns the expression's result value. Expression may
take arguments from Clojure code.
By default `this` refers to the [[cuic.core/window]] of the current
default browser but it may be rebound to any html element or window
object.
Arguments serializable JSON values:
* `nil` (will be converted to `null`
* booleans
* numbers
* maps (will be converted to objects)
* collections (will be converted to arrays)
Likewise the return value of the expression is limited to JSON
values:
* `null`, `undefined` (will be converted to `nil`)
* booleans
* numbers
* object (will be converted to maps)
* arrays (will be converted to vectors)
```clojure
;; Return title of the current browser window
(c/eval-js \"document.title\")
;; Return async value
(c/eval-js \"await new Promise(resolve => setTimeout(() => resolve('tsers'), 500))\")
;; Increment list values in JS side
(c/eval-js \"xs.map(x => x + 1)\" {:xs [1 2 3]})
;; Perform some arithmetics in JS side
(c/eval-js \"a + b.num\" {:a 1000 :b {:num 337}})
;; Get placeholder value from the query input
(let [q (c/find \"#query\")]
(c/eval-js \"this.placeholder\" {} q))
```
See also [[cuic.core/exec-js]] if you want to execute statements
in JavaScript side."
([expr]
(rewrite-exceptions (eval-js expr {} (window))))
([expr args]
(rewrite-exceptions (eval-js expr args (window))))
([expr args this]
(rewrite-exceptions
(check-arg [string? "string"] [expr "expression"])
(check-arg [map? "map"] [args "call arguments"])
(check-arg [#(or (element? %) (window? %)) "html element or window object"] [this "this binding"])
(stale-as-ex (cuic-ex "Can't evaluate JavaScript expression on" (quoted this)
"because it does not exist anymore")
(-exec-js (str "return " expr ";") args this)))))
(defn exec-js
"Executes the given JavaScript function body in the given `this`
object context. The executed body may also be parametrized by
arguments from Clojure code, and it can return value by using
JavaScript's `return` statement in the end. Function body may
`await` async values/effects.
By default `this` refers to the [[cuic.core/window]] of the current
default browser but it may be rebound to any html element or window
object.
Arguments serializable JSON values:
* `nil` (will be converted to `null`
* booleans
* numbers
* maps (will be converted to objects)
* collections (will be converted to arrays)
Likewise the return value of the expression is limited to JSON
values:
* `null`, `undefined` (will be converted to `nil`)
* booleans
* numbers
* object (will be converted to maps)
* arrays (will be converted to vectors)
```clojure
;; Reset document title
(c/exec-js \"document.title = 'tsers'\")
;; Reset input's placeholder value
(let [input (c/find \"#my-input\")]
(c/exec-js \"this.setAttribute('placeholder', text)\" {:text \"tsers\"} input))
;; Reset document's title and return the prior value
(c/exec-js \"const prev = document.title;
document.title = 'tsers';
return prev;\")
```
See also [[cuic.core/eval-js]] if you only want to query data
from JavaScript side without performing any side-effects.
"
([body]
(rewrite-exceptions (exec-js body {} (window))))
([body args]
(rewrite-exceptions (exec-js body args (window))))
([body args this]
(rewrite-exceptions
(check-arg [string? "string"] [body "function body"])
(check-arg [map? "map"] [args "call arguments"])
(check-arg [#(or (element? %) (window? %)) "html element or window"] [this "this binding"])
(stale-as-ex (cuic-ex "Can't execute JavaScript code on" (quoted this)
"because it does not exist anymore")
(-exec-js body args this)))))
;;;
;;; properties
;;;
(defn- -js-prop
([element js-expr] (-js-prop element js-expr {}))
([element js-expr args]
(let [code (str "return " (string/replace js-expr #"\n\s+" " ") ";")]
(-exec-js code args element))))
(defn- -bb [element]
(-exec-js "let r = this.getBoundingClientRect();
return {
top: r.top,
left: r.left,
width: r.width,
height: r.height
};" {} element))
(defn client-rect
"Returns the bounding client rect for the given element as a map of:
```clojure
{:top <number>
:left <number>
:width <number>
:height <number>}
```
See https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
for more info."
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't get client rect from element" (quoted (get-element-name element))
"because it does not exist anymore")
(-bb element))))
(defn visible?
"Returns boolean whether the given element is visible in DOM or not"
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't check visibility of element" (quoted (get-element-name element))
"because it does not exist anymore")
(-js-prop element "!!this.offsetParent"))))
(defn in-viewport?
"Returns boolean whether the given element currently visible and
in the viewport"
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "node"])
(stale-as-ex (cuic-ex "Can't check visibility of element" (quoted (get-element-name element))
"because it does not exist anymore")
(-js-prop element "!!this.offsetParent && __CUIC__.isInViewport(this)"))))
(defn inner-text
"Returns the inner text of the given html element. See
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
for more info."
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't get inner text from element" (quoted (get-element-name element))
"because it does not exist anymore")
(-js-prop element "this.innerText"))))
(defn text-content
"Returns the text content of the given html element. See
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
for more info."
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't get text content from element" (quoted (get-element-name element))
"because it does not exist anymore")
(-js-prop element "this.textContent"))))
(defn outer-html
"Returns the outer HTML of the given element as [hiccup](https://github.com/weavejester/hiccup).
Comments will be returned using `:-#comment` tag and CDATA nodes
will be returned using `:-#data` tag."
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't get outer html from element" (quoted (get-element-name element))
"because it does not exist anymore")
(let [cdt (get-element-cdt element)
node-id (get-node-id element)
html (-> (invoke {:cdt cdt
:cmd "DOM.getOuterHTML"
:args {:nodeId node-id}})
(:outerHTML))]
(if (::document? (meta element))
(parse-document html)
(parse-element html))))))
(defn value
"Returns the current string value of the given input/select/textarea
element. Throws an exception if the target element is not a valid
input element"
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't get value from element" (quoted (get-element-name element))
"because it does not exist anymore")
(when-not (-js-prop element "'value' in this")
(throw (cuic-ex (quoted (get-element-name element)) "is not a valid input element")))
(-js-prop element "this.value"))))
(defn options
"Returns a list of options `{:keys [value text selected]}` for the
given element. Throws an exception if element is not a select element."
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't get options from element" (quoted (get-element-name element))
"because it does not exist anymore")
(when (not= "SELECT" (-js-prop element "this.tagName"))
(throw (cuic-ex (quoted (get-element-name element)) "is not a valid select element")))
(-js-prop element "Array.prototype.slice
.call(this.options || [])
.map(({value, text, selected}) => ({ value, text, selected }))"))))
(defn attributes
"Returns element's HTML attributes as a map of keyword keys and
string values. Boolean attribute values will be converted to
`true` if they are present
```clojure
;; html element <div id='foo' data-val='1' class='foo bar'></div>
(c/attributes (c/find \"#foo\"))
; =>
{:id \"foo\"
:data-val \"1\"
:class \"foo bar\"}
```"
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't get attributes from element" (quoted (get-element-name element))
"because it does not exist anymore")
(let [cdt (get-element-cdt element)]
(->> (invoke {:cdt cdt
:cmd "DOM.getAttributes"
:args {:nodeId (get-node-id element)}})
(:attributes)
(partition-all 2 2)
(map (fn [[k v]] [(keyword k) (if (contains? boolean-attributes k) true v)]))
(into {}))))))
(defn classes
"Returns a set of css classes (as strings) for the given element. Returns
an empty set if element does not have any classes.
```clojure
;; <div id='foo' class='foo bar'></div>
(c/classes (c/find \"#foo\"))
; =>
#{\"foo\" \"bar\"}
;; <div id='foo'></div>
(c/classes (c/find \"#foo\"))
; =>
#{}
```"
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(as-> (attributes element) $
(get $ :class "")
(string/split $ #"\s+")
(map string/trim $)
(remove string/blank? $)
(set $))))
(defn has-class?
"Returns boolean whether the given element has the tested
css class or not"
[element class]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(check-arg [string? "string"] [class "tested class name"])
(contains? (classes element) class)))
(defn matches?
"Returns boolean whether the given element matches the tested css
selector or not. Throws an exception if selector is not valid."
[element selector]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(check-arg [string? "string"] [selector "tested css selector"])
(stale-as-ex (cuic-ex "Can't match css selector to element" (quoted (get-element-name element))
"because it does not exist anumore")
(let [match (-js-prop element "(function(n){try{return n.matches(s)}catch(_){}})(this)" {:s selector})]
(when (nil? match)
(throw (cuic-ex "The tested css selector" (quoted selector) "is not valid")))
match))))
(defn has-focus?
"Returns boolean whether the given element has focus or not"
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't resolve focus from element" (quoted (get-element-name element))
"because it does not exist anymore")
(-js-prop element "document.activeElement === this"))))
(defn checked?
"Returns boolean whether the given element is checked or not. Throws
an exception if the target element is not a valid input element."
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't resolve checked status from element" (quoted (get-element-name element))
"because it does not exist anymore")
(when-not (-js-prop element "'checked' in this")
(throw (cuic-ex (quoted (get-element-name element)) "is not a valid input element")))
(-js-prop element "!!this.checked"))))
(defn disabled?
"Returns boolean whether the given element is disabled or not."
[element]
(rewrite-exceptions
(check-arg [maybe-element? "html element"] [element "element"])
(stale-as-ex (cuic-ex "Can't resolve disabled status from element" (quoted (get-element-name element))
"because it does not exist anymore")
(-js-prop element "!!this.disabled"))))
;;;
;;; actions
;;;
(defn- -wait-visible [element]
(try
(wait (-js-prop element "!!this.offsetParent"))
(catch TimeoutException _
false)))
(defn- -wait-enabled [element]
(try
(wait (-js-prop element "!this.disabled"))
(catch TimeoutException _
false)))
(defn goto
"Navigates browser to the given url, equivalent to user typing
url to the browser address bar and pressing enter. Url **must**
contain the protocol. Reloads the page, even if navigating to
the current page, and waits until the page is loaded or timeout
exceeds. Uses [[cuic.core/*timeout*]] by default but it can be
overrided by giving the timeout as an option to the invodation.
If [[cuic.core/*base-url*]] is set, it'll be prepended to the
given url if the given url does not contain hostname.
Uses the current browser by default but it can be overrided
by providing browser as an option to the invocation.
```clojure
;; Use default browser and timeout
(c/goto \"https://clojuredocs.org\")
;; Use non-default browser
(c/goto \"https://clojuredocs.org\" {:browser another-chrome})
;; Use non-default timeout
(c/goto \"https://clojuredocs.org\" {:timeout 300000})
;; Go to https://clojuredocs.org/clojure.core/map using base url
(binding [c/*base-url* \"https://clojuredocs.org\"]
(c/goto \"/clojure.core/map\"))
```"
([url] (goto url {}))
([url opts]
(rewrite-exceptions
(let [{:keys [timeout browser]
:or {timeout *timeout*}} opts
browser (or browser (-require-default-browser))
full-url (if (and (string? url)
(not (url-str? url))
*base-url*)
(str *base-url* url)
url)]
(check-arg [url-str? "valid url string"] [full-url "url"])
(check-arg [nat-int? "positive integer or zero"] [timeout "timeout"])
(navigate-to (page browser) full-url timeout))
nil)))
(defn go-back
"Simulates browser back button click. Returns boolean whether the
back button was pressed or not. Back button pressing is disabled
if there is no browser history to go back anymore.
```clojure
;; Use default browser and timeout
(c/go-back)
;; Use non-default browser
(c/go-back {:browser another-chrome})
;; Use non-default timeout
(c/go-back {:timeout 1000})
```"
([] (go-back {}))
([opts]
(rewrite-exceptions
(let [{:keys [timeout browser]
:or {timeout *timeout*}} opts
browser (or browser (-require-default-browser))]
(check-arg [nat-int? "positive integer or zero"] [timeout "timeout"])
(boolean (navigate-back (page browser) timeout))))))
(defn go-forward
"Simulates browser forward button click. Returns boolean whether the
forward button was pressed or not. Forward button pressing is disabled
if browser is already at the latest navigated page.
```clojure
;; Use default browser and timeout
(c/go-forward)
;; Use non-default browser
(c/go-forward {:browser another-chrome})
;; Use non-default timeout
(c/go-forward {:timeout 1000})
```"
([] (go-forward {}))
([opts]
(rewrite-exceptions
(let [{:keys [timeout browser]
:or {timeout *timeout*}} opts
browser (or browser (-require-default-browser))]
(check-arg [nat-int? "positive integer or zero"] [timeout "timeout"])
(boolean (navigate-forward (page browser) timeout))))))
(defn type
"Simulates keyboard typing. Characters are pressed and released one by one
using the provided typing speed. Typing speed uses [[cuic.core/*typing-speed*]]
by default but it can be overrided by giving it as `:speed` option
to the invocation.
Note that this function is pretty low level and it **does not** focus
the typed text to any element. See [[cuic.core/fill]] for a more high-level
alternative.
Uses the current browser by default but it can be overrided
by providing `:browser` option to the invocation.
```clojure
;; Type some text
(c/type \"Tsers!\")
;; Type some text very fast
(c/type \"Tsers!\" {:speed :tycitys})
;; Type some text to non-default browser
(c/type \"Tsers!\" {:browser another-chrome})
```"
([text] (type text {}))
([text opts]
(rewrite-exceptions
(let [{:keys [browser speed]
:or {speed *typing-speed*}} opts
browser (or browser (-require-default-browser))]
(check-arg [string? "string"] [text "typed text"])
(check-arg [chrome? "chrome instance"] [browser "browser"])
(type-text (devtools browser) text (-chars-per-minute speed))
nil))))
(defn press
"Simulates key press of single key. The pressed key must be a symbol
of a valid keycode with optional modifiers separated by '+' (see
examples below). You can use e.g. https://keycode.info to get desired
key code (`event.code`) for the pressed key. The complete list of
available key codes can be found from
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
Uses the current browser by default but it can be overrided
by providing browser as a second parameter.
```clojure
;; Focus on next tab index element
(c/press 'Tab)
;; Focus on previous tab index element
(c/press 'Shift+Tab)
;; Focus on next tab index element in custom browser
(c/press 'Tab another-chrome)
```"
([key] (rewrite-exceptions (press key (-require-default-browser))))
([key browser]
(rewrite-exceptions
(check-arg [simple-symbol? "symbol"] [key "pressed key"])
(check-arg [chrome? "chrome instance"] [browser "browser"])
(let [cdt (devtools browser)]
(press-key cdt key)
nil))))
(defn scroll-into-view
"Scrolls the given element into view if it is not in the view already.
Waits [[cuic.core/*timeout*]] until the element becomes visible or
throws an exception if timeout exceeds.
Returns the target element for threading."
[element]
(rewrite-exceptions
(check-arg [element? "html element"] [element "target element"])
(stale-as-ex (cuic-ex "Can't scroll element" (quoted (get-element-name element))
"into view because it does not exist anymore")
(when-not (-wait-visible element)
(throw (timeout-ex "Can't scroll element" (quoted (get-element-name element))
"into view because it is not visible")))
(scroll-into-view-if-needed element)
element)))
(defn hover
"First scrolls the given element into view (if needed) and then moves the
mouse over the element. Waits [[cuic.core/*timeout*]] until the element
becomes visible or throws an exception if timeout exceeds.
Throws an exception if element is not hoverable: it has either zero
width or zero height.