playwright-rs 0.11.0

Rust bindings for Microsoft Playwright
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
// Locator - Lazy element selector with auto-waiting
//
// Locators are the central piece of Playwright's auto-waiting and retry-ability.
// They represent a way to find element(s) on the page at any given moment.
//
// Key characteristics:
// - Lazy: Don't execute until an action is performed
// - Retryable: Auto-wait for elements to match actionability checks
// - Chainable: Can create sub-locators via first(), last(), nth(), locator()
//
// Architecture:
// - Locator is NOT a ChannelOwner - it's a lightweight wrapper
// - Stores selector string and reference to Frame
// - Delegates all operations to Frame with strict=true
//
// See: https://playwright.dev/docs/api/class-locator

use crate::error::Result;
use crate::protocol::Frame;
use serde::Deserialize;

/// Trait for action option structs that have an optional timeout field.
/// Used by `Locator::with_timeout` to inject the page's default timeout.
pub(crate) trait HasTimeout {
    fn timeout_ref(&self) -> &Option<f64>;
    fn timeout_ref_mut(&mut self) -> &mut Option<f64>;
}

macro_rules! impl_has_timeout {
    ($($ty:ty),+ $(,)?) => {
        $(impl HasTimeout for $ty {
            fn timeout_ref(&self) -> &Option<f64> { &self.timeout }
            fn timeout_ref_mut(&mut self) -> &mut Option<f64> { &mut self.timeout }
        })+
    };
}

impl_has_timeout!(
    crate::protocol::ClickOptions,
    crate::protocol::FillOptions,
    crate::protocol::PressOptions,
    crate::protocol::CheckOptions,
    crate::protocol::HoverOptions,
    crate::protocol::SelectOptions,
    crate::protocol::ScreenshotOptions,
    crate::protocol::TapOptions,
    crate::protocol::DragToOptions,
    crate::protocol::WaitForOptions,
);
use std::sync::Arc;

/// The bounding box of an element in pixels.
///
/// All values are measured relative to the top-left corner of the page.
///
/// See: <https://playwright.dev/docs/api/class-locator#locator-bounding-box>
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct BoundingBox {
    /// The x coordinate of the top-left corner of the element in pixels.
    pub x: f64,
    /// The y coordinate of the top-left corner of the element in pixels.
    pub y: f64,
    /// The width of the element in pixels.
    pub width: f64,
    /// The height of the element in pixels.
    pub height: f64,
}

/// Escapes text for use in Playwright's internal selector engine.
///
/// JSON-stringifies the text and appends `i` (case-insensitive) or `s` (strict/exact).
/// Matches the `escapeForTextSelector`/`escapeForAttributeSelector` in Playwright TypeScript.
fn escape_for_selector(text: &str, exact: bool) -> String {
    let suffix = if exact { "s" } else { "i" };
    let escaped = serde_json::to_string(text).unwrap_or_else(|_| format!("\"{}\"", text));
    format!("{}{}", escaped, suffix)
}

/// Builds the internal selector string for `get_by_text`.
///
/// - `exact=false` → `internal:text="text"i` (case-insensitive substring)
/// - `exact=true` → `internal:text="text"s` (case-sensitive exact)
pub(crate) fn get_by_text_selector(text: &str, exact: bool) -> String {
    format!("internal:text={}", escape_for_selector(text, exact))
}

/// Builds the internal selector string for `get_by_label`.
///
/// - `exact=false` → `internal:label="text"i`
/// - `exact=true` → `internal:label="text"s`
pub(crate) fn get_by_label_selector(text: &str, exact: bool) -> String {
    format!("internal:label={}", escape_for_selector(text, exact))
}

/// Builds the internal selector string for `get_by_placeholder`.
///
/// - `exact=false` → `internal:attr=[placeholder="text"i]`
/// - `exact=true` → `internal:attr=[placeholder="text"s]`
pub(crate) fn get_by_placeholder_selector(text: &str, exact: bool) -> String {
    format!(
        "internal:attr=[placeholder={}]",
        escape_for_selector(text, exact)
    )
}

/// Builds the internal selector string for `get_by_alt_text`.
///
/// - `exact=false` → `internal:attr=[alt="text"i]`
/// - `exact=true` → `internal:attr=[alt="text"s]`
pub(crate) fn get_by_alt_text_selector(text: &str, exact: bool) -> String {
    format!("internal:attr=[alt={}]", escape_for_selector(text, exact))
}

/// Builds the internal selector string for `get_by_title`.
///
/// - `exact=false` → `internal:attr=[title="text"i]`
/// - `exact=true` → `internal:attr=[title="text"s]`
pub(crate) fn get_by_title_selector(text: &str, exact: bool) -> String {
    format!("internal:attr=[title={}]", escape_for_selector(text, exact))
}

/// Builds the internal selector string for `get_by_test_id`.
///
/// Uses `data-testid` attribute by default (matching Playwright's default).
/// Always uses exact matching (`s` suffix).
pub(crate) fn get_by_test_id_selector(test_id: &str) -> String {
    get_by_test_id_selector_with_attr(test_id, "data-testid")
}

/// Builds the internal selector string for `get_by_test_id` with a custom attribute.
///
/// Used when `playwright.selectors().set_test_id_attribute()` has been called.
pub(crate) fn get_by_test_id_selector_with_attr(test_id: &str, attribute: &str) -> String {
    format!(
        "internal:testid=[{}={}]",
        attribute,
        escape_for_selector(test_id, true)
    )
}

/// Escapes text for use in Playwright's attribute role selector.
///
/// Unlike `escape_for_selector` (which uses JSON encoding), this only escapes
/// backslashes and double quotes, matching Playwright's `escapeForAttributeSelector`.
fn escape_for_attribute_selector(text: &str, exact: bool) -> String {
    let suffix = if exact { "s" } else { "i" };
    let escaped = text.replace('\\', "\\\\").replace('"', "\\\"");
    format!("\"{}\"{}", escaped, suffix)
}

/// Builds the internal selector string for `get_by_role`.
///
/// Format: `internal:role=<role>[prop1=val1][prop2=val2]...`
///
/// Properties are appended in Playwright's required order:
/// checked, disabled, selected, expanded, include-hidden, level, name, pressed.
pub(crate) fn get_by_role_selector(role: AriaRole, options: Option<GetByRoleOptions>) -> String {
    let mut selector = format!("internal:role={}", role.as_str());

    if let Some(opts) = options {
        if let Some(checked) = opts.checked {
            selector.push_str(&format!("[checked={}]", checked));
        }
        if let Some(disabled) = opts.disabled {
            selector.push_str(&format!("[disabled={}]", disabled));
        }
        if let Some(selected) = opts.selected {
            selector.push_str(&format!("[selected={}]", selected));
        }
        if let Some(expanded) = opts.expanded {
            selector.push_str(&format!("[expanded={}]", expanded));
        }
        if let Some(include_hidden) = opts.include_hidden {
            selector.push_str(&format!("[include-hidden={}]", include_hidden));
        }
        if let Some(level) = opts.level {
            selector.push_str(&format!("[level={}]", level));
        }
        if let Some(name) = &opts.name {
            let exact = opts.exact.unwrap_or(false);
            selector.push_str(&format!(
                "[name={}]",
                escape_for_attribute_selector(name, exact)
            ));
        }
        if let Some(pressed) = opts.pressed {
            selector.push_str(&format!("[pressed={}]", pressed));
        }
    }

    selector
}

/// ARIA roles for `get_by_role()` locator.
///
/// Represents WAI-ARIA roles used to locate elements by their accessibility role.
/// Matches Playwright's `AriaRole` enum across all language bindings.
///
/// See: <https://playwright.dev/docs/api/class-page#page-get-by-role>
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AriaRole {
    Alert,
    Alertdialog,
    Application,
    Article,
    Banner,
    Blockquote,
    Button,
    Caption,
    Cell,
    Checkbox,
    Code,
    Columnheader,
    Combobox,
    Complementary,
    Contentinfo,
    Definition,
    Deletion,
    Dialog,
    Directory,
    Document,
    Emphasis,
    Feed,
    Figure,
    Form,
    Generic,
    Grid,
    Gridcell,
    Group,
    Heading,
    Img,
    Insertion,
    Link,
    List,
    Listbox,
    Listitem,
    Log,
    Main,
    Marquee,
    Math,
    Meter,
    Menu,
    Menubar,
    Menuitem,
    Menuitemcheckbox,
    Menuitemradio,
    Navigation,
    None,
    Note,
    Option,
    Paragraph,
    Presentation,
    Progressbar,
    Radio,
    Radiogroup,
    Region,
    Row,
    Rowgroup,
    Rowheader,
    Scrollbar,
    Search,
    Searchbox,
    Separator,
    Slider,
    Spinbutton,
    Status,
    Strong,
    Subscript,
    Superscript,
    Switch,
    Tab,
    Table,
    Tablist,
    Tabpanel,
    Term,
    Textbox,
    Time,
    Timer,
    Toolbar,
    Tooltip,
    Tree,
    Treegrid,
    Treeitem,
}

impl AriaRole {
    /// Returns the lowercase string representation used in selectors.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Alert => "alert",
            Self::Alertdialog => "alertdialog",
            Self::Application => "application",
            Self::Article => "article",
            Self::Banner => "banner",
            Self::Blockquote => "blockquote",
            Self::Button => "button",
            Self::Caption => "caption",
            Self::Cell => "cell",
            Self::Checkbox => "checkbox",
            Self::Code => "code",
            Self::Columnheader => "columnheader",
            Self::Combobox => "combobox",
            Self::Complementary => "complementary",
            Self::Contentinfo => "contentinfo",
            Self::Definition => "definition",
            Self::Deletion => "deletion",
            Self::Dialog => "dialog",
            Self::Directory => "directory",
            Self::Document => "document",
            Self::Emphasis => "emphasis",
            Self::Feed => "feed",
            Self::Figure => "figure",
            Self::Form => "form",
            Self::Generic => "generic",
            Self::Grid => "grid",
            Self::Gridcell => "gridcell",
            Self::Group => "group",
            Self::Heading => "heading",
            Self::Img => "img",
            Self::Insertion => "insertion",
            Self::Link => "link",
            Self::List => "list",
            Self::Listbox => "listbox",
            Self::Listitem => "listitem",
            Self::Log => "log",
            Self::Main => "main",
            Self::Marquee => "marquee",
            Self::Math => "math",
            Self::Meter => "meter",
            Self::Menu => "menu",
            Self::Menubar => "menubar",
            Self::Menuitem => "menuitem",
            Self::Menuitemcheckbox => "menuitemcheckbox",
            Self::Menuitemradio => "menuitemradio",
            Self::Navigation => "navigation",
            Self::None => "none",
            Self::Note => "note",
            Self::Option => "option",
            Self::Paragraph => "paragraph",
            Self::Presentation => "presentation",
            Self::Progressbar => "progressbar",
            Self::Radio => "radio",
            Self::Radiogroup => "radiogroup",
            Self::Region => "region",
            Self::Row => "row",
            Self::Rowgroup => "rowgroup",
            Self::Rowheader => "rowheader",
            Self::Scrollbar => "scrollbar",
            Self::Search => "search",
            Self::Searchbox => "searchbox",
            Self::Separator => "separator",
            Self::Slider => "slider",
            Self::Spinbutton => "spinbutton",
            Self::Status => "status",
            Self::Strong => "strong",
            Self::Subscript => "subscript",
            Self::Superscript => "superscript",
            Self::Switch => "switch",
            Self::Tab => "tab",
            Self::Table => "table",
            Self::Tablist => "tablist",
            Self::Tabpanel => "tabpanel",
            Self::Term => "term",
            Self::Textbox => "textbox",
            Self::Time => "time",
            Self::Timer => "timer",
            Self::Toolbar => "toolbar",
            Self::Tooltip => "tooltip",
            Self::Tree => "tree",
            Self::Treegrid => "treegrid",
            Self::Treeitem => "treeitem",
        }
    }
}

/// Options for `get_by_role()` locator.
///
/// All fields are optional. When not specified, the property is not included
/// in the role selector, meaning it matches any value.
///
/// See: <https://playwright.dev/docs/api/class-page#page-get-by-role>
#[derive(Debug, Clone, Default)]
pub struct GetByRoleOptions {
    /// Whether the element is checked (for checkboxes, radio buttons).
    pub checked: Option<bool>,
    /// Whether the element is disabled.
    pub disabled: Option<bool>,
    /// Whether the element is selected (for options).
    pub selected: Option<bool>,
    /// Whether the element is expanded (for tree items, comboboxes).
    pub expanded: Option<bool>,
    /// Whether to include hidden elements.
    pub include_hidden: Option<bool>,
    /// The heading level (1-6, for heading role).
    pub level: Option<u32>,
    /// The accessible name of the element.
    pub name: Option<String>,
    /// Whether `name` matching is exact (case-sensitive, full-string).
    /// Default is false (case-insensitive substring).
    pub exact: Option<bool>,
    /// Whether the element is pressed (for toggle buttons).
    pub pressed: Option<bool>,
}

/// Options for [`Locator::filter()`].
///
/// Narrows an existing locator according to the specified criteria.
/// All fields are optional; unset fields are ignored.
///
/// See: <https://playwright.dev/docs/api/class-locator#locator-filter>
#[derive(Debug, Clone, Default)]
pub struct FilterOptions {
    /// Matches elements containing the specified text (case-insensitive substring by default).
    pub has_text: Option<String>,
    /// Matches elements that do **not** contain the specified text anywhere inside.
    pub has_not_text: Option<String>,
    /// Narrows to elements that contain a descendant matching this locator.
    ///
    /// The inner locator is queried relative to the outer locator's matched element,
    /// not the document root.
    pub has: Option<Locator>,
    /// Narrows to elements that do **not** contain a descendant matching this locator.
    pub has_not: Option<Locator>,
}

/// Locator represents a way to find element(s) on the page at any given moment.
///
/// Locators are lazy - they don't execute queries until an action is performed.
/// This enables auto-waiting and retry-ability for robust test automation.
///
/// # Examples
///
/// ```ignore
/// use playwright_rs::protocol::{Playwright, SelectOption};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let playwright = Playwright::launch().await?;
///     let browser = playwright.chromium().launch().await?;
///     let page = browser.new_page().await?;
///
///     // Demonstrate set_checked() - checkbox interaction
///     let _ = page.goto(
///         "data:text/html,<input type='checkbox' id='cb'>",
///         None
///     ).await;
///     let checkbox = page.locator("#cb").await;
///     checkbox.set_checked(true, None).await?;
///     assert!(checkbox.is_checked().await?);
///     checkbox.set_checked(false, None).await?;
///     assert!(!checkbox.is_checked().await?);
///
///     // Demonstrate select_option() - select by value, label, and index
///     let _ = page.goto(
///         "data:text/html,<select id='fruits'>\
///             <option value='apple'>Apple</option>\
///             <option value='banana'>Banana</option>\
///             <option value='cherry'>Cherry</option>\
///         </select>",
///         None
///     ).await;
///     let select = page.locator("#fruits").await;
///     select.select_option("banana", None).await?;
///     assert_eq!(select.input_value(None).await?, "banana");
///     select.select_option(SelectOption::Label("Apple".to_string()), None).await?;
///     assert_eq!(select.input_value(None).await?, "apple");
///     select.select_option(SelectOption::Index(2), None).await?;
///     assert_eq!(select.input_value(None).await?, "cherry");
///
///     // Demonstrate select_option_multiple() - multi-select
///     let _ = page.goto(
///         "data:text/html,<select id='colors' multiple>\
///             <option value='red'>Red</option>\
///             <option value='green'>Green</option>\
///             <option value='blue'>Blue</option>\
///             <option value='yellow'>Yellow</option>\
///         </select>",
///         None
///     ).await;
///     let multi = page.locator("#colors").await;
///     let selected = multi.select_option_multiple(&["red", "blue"], None).await?;
///     assert_eq!(selected.len(), 2);
///     assert!(selected.contains(&"red".to_string()));
///     assert!(selected.contains(&"blue".to_string()));
///
///     // Demonstrate get_by_text() - find elements by text content
///     let _ = page.goto(
///         "data:text/html,<button>Submit</button><button>Submit Order</button>",
///         None
///     ).await;
///     let all_submits = page.get_by_text("Submit", false).await;
///     assert_eq!(all_submits.count().await?, 2); // case-insensitive substring
///     let exact_submit = page.get_by_text("Submit", true).await;
///     assert_eq!(exact_submit.count().await?, 1); // exact match only
///
///     // Demonstrate get_by_label, get_by_placeholder, get_by_test_id
///     let _ = page.goto(
///         "data:text/html,<label for='email'>Email</label>\
///             <input id='email' placeholder='you@example.com' data-testid='email-input' />",
///         None
///     ).await;
///     let by_label = page.get_by_label("Email", false).await;
///     assert_eq!(by_label.count().await?, 1);
///     let by_placeholder = page.get_by_placeholder("you@example.com", true).await;
///     assert_eq!(by_placeholder.count().await?, 1);
///     let by_test_id = page.get_by_test_id("email-input").await;
///     assert_eq!(by_test_id.count().await?, 1);
///
///     // Demonstrate screenshot() - element screenshot
///     let _ = page.goto(
///         "data:text/html,<h1 id='title'>Hello World</h1>",
///         None
///     ).await;
///     let heading = page.locator("#title").await;
///     let screenshot = heading.screenshot(None).await?;
///     assert!(!screenshot.is_empty());
///
///     browser.close().await?;
///     Ok(())
/// }
/// ```
///
/// See: <https://playwright.dev/docs/api/class-locator>
#[derive(Clone)]
pub struct Locator {
    frame: Arc<Frame>,
    selector: String,
    page: crate::protocol::Page,
}

impl Locator {
    /// Creates a new Locator (internal use only)
    ///
    /// Use `page.locator()` or `frame.locator()` to create locators in application code.
    pub(crate) fn new(frame: Arc<Frame>, selector: String, page: crate::protocol::Page) -> Self {
        Self {
            frame,
            selector,
            page,
        }
    }

    /// Returns the selector string for this locator
    pub fn selector(&self) -> &str {
        &self.selector
    }

    /// Creates a [`FrameLocator`](crate::protocol::FrameLocator) scoped within this locator's subtree.
    ///
    /// The `selector` identifies an iframe element within the locator's scope.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-frame-locator>
    pub fn frame_locator(&self, selector: &str) -> crate::protocol::FrameLocator {
        crate::protocol::FrameLocator::new(
            Arc::clone(&self.frame),
            format!("{} >> {}", self.selector, selector),
            self.page.clone(),
        )
    }

    /// Returns the Page this locator belongs to.
    ///
    /// Each locator is bound to the page that created it. Chained locators (via
    /// `first()`, `last()`, `nth()`, `locator()`, `filter()`, etc.) all return
    /// the same owning page. This matches the behavior of `locator.page` in
    /// other Playwright language bindings.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use playwright_rs::Playwright;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let playwright = Playwright::launch().await?;
    /// let browser = playwright.chromium().launch().await?;
    /// let page = browser.new_page().await?;
    /// page.goto("https://example.com", None).await?;
    ///
    /// let locator = page.locator("h1").await;
    /// let locator_page = locator.page()?;
    /// assert_eq!(locator_page.url(), page.url());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-page>
    pub fn page(&self) -> Result<crate::protocol::Page> {
        Ok(self.page.clone())
    }

    /// Evaluate a JavaScript expression in the frame context.
    ///
    /// Used internally for injecting CSS (e.g., disabling animations) before screenshot assertions.
    pub(crate) async fn evaluate_js<T: serde::Serialize>(
        &self,
        expression: &str,
        _arg: Option<T>,
    ) -> Result<()> {
        self.frame
            .frame_evaluate_expression(expression)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Creates a locator for the first matching element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-first>
    pub fn first(&self) -> Locator {
        Locator::new(
            Arc::clone(&self.frame),
            format!("{} >> nth=0", self.selector),
            self.page.clone(),
        )
    }

    /// Creates a locator for the last matching element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-last>
    pub fn last(&self) -> Locator {
        Locator::new(
            Arc::clone(&self.frame),
            format!("{} >> nth=-1", self.selector),
            self.page.clone(),
        )
    }

    /// Creates a locator for the nth matching element (0-indexed).
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-nth>
    pub fn nth(&self, index: i32) -> Locator {
        Locator::new(
            Arc::clone(&self.frame),
            format!("{} >> nth={}", self.selector, index),
            self.page.clone(),
        )
    }

    /// Returns a locator that matches elements containing the given text.
    ///
    /// By default, matching is case-insensitive and searches for a substring.
    /// Set `exact` to `true` for case-sensitive exact matching.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-get-by-text>
    pub fn get_by_text(&self, text: &str, exact: bool) -> Locator {
        self.locator(&get_by_text_selector(text, exact))
    }

    /// Returns a locator that matches elements by their associated label text.
    ///
    /// Targets form controls (`input`, `textarea`, `select`) linked via `<label>`,
    /// `aria-label`, or `aria-labelledby`.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-get-by-label>
    pub fn get_by_label(&self, text: &str, exact: bool) -> Locator {
        self.locator(&get_by_label_selector(text, exact))
    }

    /// Returns a locator that matches elements by their placeholder text.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-get-by-placeholder>
    pub fn get_by_placeholder(&self, text: &str, exact: bool) -> Locator {
        self.locator(&get_by_placeholder_selector(text, exact))
    }

    /// Returns a locator that matches elements by their alt text.
    ///
    /// Typically used for `<img>` elements.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-get-by-alt-text>
    pub fn get_by_alt_text(&self, text: &str, exact: bool) -> Locator {
        self.locator(&get_by_alt_text_selector(text, exact))
    }

    /// Returns a locator that matches elements by their title attribute.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-get-by-title>
    pub fn get_by_title(&self, text: &str, exact: bool) -> Locator {
        self.locator(&get_by_title_selector(text, exact))
    }

    /// Returns a locator that matches elements by their test ID attribute.
    ///
    /// By default, uses the `data-testid` attribute. Call
    /// `playwright.selectors().set_test_id_attribute()` to change the attribute name.
    ///
    /// Always uses exact matching (case-sensitive).
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-get-by-test-id>
    pub fn get_by_test_id(&self, test_id: &str) -> Locator {
        use crate::server::channel_owner::ChannelOwner as _;
        let attr = self.frame.connection().selectors().test_id_attribute();
        self.locator(&get_by_test_id_selector_with_attr(test_id, &attr))
    }

    /// Returns a locator that matches elements by their ARIA role.
    ///
    /// This is the recommended way to locate elements, as it matches the way
    /// users and assistive technology perceive the page.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-get-by-role>
    pub fn get_by_role(&self, role: AriaRole, options: Option<GetByRoleOptions>) -> Locator {
        self.locator(&get_by_role_selector(role, options))
    }

    /// Creates a sub-locator within this locator's subtree.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-locator>
    pub fn locator(&self, selector: &str) -> Locator {
        Locator::new(
            Arc::clone(&self.frame),
            format!("{} >> {}", self.selector, selector),
            self.page.clone(),
        )
    }

    /// Narrows this locator according to the filter options.
    ///
    /// Can be chained to apply multiple filters in sequence.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use playwright_rs::{Playwright, FilterOptions};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let playwright = Playwright::launch().await?;
    /// let browser = playwright.chromium().launch().await?;
    /// let page = browser.new_page().await?;
    ///
    /// // Filter rows to those containing "Apple"
    /// let rows = page.locator("tr").await;
    /// let apple_row = rows.filter(FilterOptions {
    ///     has_text: Some("Apple".to_string()),
    ///     ..Default::default()
    /// });
    /// # browser.close().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-filter>
    pub fn filter(&self, options: FilterOptions) -> Locator {
        let mut selector = self.selector.clone();

        if let Some(text) = &options.has_text {
            let escaped = escape_for_selector(text, false);
            selector = format!("{} >> internal:has-text={}", selector, escaped);
        }

        if let Some(text) = &options.has_not_text {
            let escaped = escape_for_selector(text, false);
            selector = format!("{} >> internal:has-not-text={}", selector, escaped);
        }

        if let Some(locator) = &options.has {
            let inner = serde_json::to_string(&locator.selector)
                .unwrap_or_else(|_| format!("\"{}\"", locator.selector));
            selector = format!("{} >> internal:has={}", selector, inner);
        }

        if let Some(locator) = &options.has_not {
            let inner = serde_json::to_string(&locator.selector)
                .unwrap_or_else(|_| format!("\"{}\"", locator.selector));
            selector = format!("{} >> internal:has-not={}", selector, inner);
        }

        Locator::new(Arc::clone(&self.frame), selector, self.page.clone())
    }

    /// Creates a locator matching elements that satisfy **both** this locator and `locator`.
    ///
    /// Note: named `and_` because `and` is a Rust keyword.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use playwright_rs::Playwright;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let playwright = Playwright::launch().await?;
    /// let browser = playwright.chromium().launch().await?;
    /// let page = browser.new_page().await?;
    ///
    /// // Find a button that also has a specific title
    /// let button = page.locator("button").await;
    /// let titled = page.locator("[title='Subscribe']").await;
    /// let subscribe_btn = button.and_(&titled);
    /// # browser.close().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-and>
    pub fn and_(&self, locator: &Locator) -> Locator {
        let inner = serde_json::to_string(&locator.selector)
            .unwrap_or_else(|_| format!("\"{}\"", locator.selector));
        Locator::new(
            Arc::clone(&self.frame),
            format!("{} >> internal:and={}", self.selector, inner),
            self.page.clone(),
        )
    }

    /// Creates a locator matching elements that satisfy **either** this locator or `locator`.
    ///
    /// Note: named `or_` because `or` is a Rust keyword.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use playwright_rs::Playwright;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let playwright = Playwright::launch().await?;
    /// let browser = playwright.chromium().launch().await?;
    /// let page = browser.new_page().await?;
    ///
    /// // Find any element that is either a button or a link
    /// let buttons = page.locator("button").await;
    /// let links = page.locator("a").await;
    /// let interactive = buttons.or_(&links);
    /// # browser.close().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-or>
    pub fn or_(&self, locator: &Locator) -> Locator {
        let inner = serde_json::to_string(&locator.selector)
            .unwrap_or_else(|_| format!("\"{}\"", locator.selector));
        Locator::new(
            Arc::clone(&self.frame),
            format!("{} >> internal:or={}", self.selector, inner),
            self.page.clone(),
        )
    }

    /// Returns the number of elements matching this locator.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-count>
    pub async fn count(&self) -> Result<usize> {
        self.frame
            .locator_count(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns an array of locators, one for each matching element.
    ///
    /// Note: `all()` does not wait for elements to match the locator,
    /// and instead immediately returns whatever is in the DOM.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-all>
    pub async fn all(&self) -> Result<Vec<Locator>> {
        let count = self.count().await?;
        Ok((0..count).map(|i| self.nth(i as i32)).collect())
    }

    /// Returns the text content of the element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-text-content>
    pub async fn text_content(&self) -> Result<Option<String>> {
        self.frame
            .locator_text_content(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns the inner text of the element (visible text).
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-inner-text>
    pub async fn inner_text(&self) -> Result<String> {
        self.frame
            .locator_inner_text(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns the inner HTML of the element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-inner-html>
    pub async fn inner_html(&self) -> Result<String> {
        self.frame
            .locator_inner_html(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns the value of the specified attribute.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-get-attribute>
    pub async fn get_attribute(&self, name: &str) -> Result<Option<String>> {
        self.frame
            .locator_get_attribute(&self.selector, name)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns whether the element is visible.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-is-visible>
    pub async fn is_visible(&self) -> Result<bool> {
        self.frame
            .locator_is_visible(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns whether the element is enabled.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-is-enabled>
    pub async fn is_enabled(&self) -> Result<bool> {
        self.frame
            .locator_is_enabled(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns whether the checkbox or radio button is checked.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-is-checked>
    pub async fn is_checked(&self) -> Result<bool> {
        self.frame
            .locator_is_checked(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns whether the element is editable.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-is-editable>
    pub async fn is_editable(&self) -> Result<bool> {
        self.frame
            .locator_is_editable(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns whether the element is hidden.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-is-hidden>
    pub async fn is_hidden(&self) -> Result<bool> {
        self.frame
            .locator_is_hidden(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns whether the element is disabled.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-is-disabled>
    pub async fn is_disabled(&self) -> Result<bool> {
        self.frame
            .locator_is_disabled(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns whether the element is focused (currently has focus).
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-is-focused>
    pub async fn is_focused(&self) -> Result<bool> {
        self.frame
            .locator_is_focused(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    // Action methods

    /// Clicks the element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-click>
    pub async fn click(&self, options: Option<crate::protocol::ClickOptions>) -> Result<()> {
        self.frame
            .locator_click(&self.selector, Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Ensures an options struct has the page's default timeout when none is explicitly set.
    fn with_timeout<T: HasTimeout + Default>(&self, options: Option<T>) -> T {
        let mut opts = options.unwrap_or_default();
        if opts.timeout_ref().is_none() {
            *opts.timeout_ref_mut() = Some(self.page.default_timeout_ms());
        }
        opts
    }

    /// Wraps an error with selector context for better error messages.
    fn wrap_error_with_selector(&self, error: crate::error::Error) -> crate::error::Error {
        match &error {
            crate::error::Error::ProtocolError(msg) => {
                // Add selector context to protocol errors (timeouts, etc.)
                crate::error::Error::ProtocolError(format!("{} [selector: {}]", msg, self.selector))
            }
            crate::error::Error::Timeout(msg) => {
                crate::error::Error::Timeout(format!("{} [selector: {}]", msg, self.selector))
            }
            _ => error, // Other errors pass through unchanged
        }
    }

    /// Double clicks the element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-dblclick>
    pub async fn dblclick(&self, options: Option<crate::protocol::ClickOptions>) -> Result<()> {
        self.frame
            .locator_dblclick(&self.selector, Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Fills the element with text.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-fill>
    pub async fn fill(
        &self,
        text: &str,
        options: Option<crate::protocol::FillOptions>,
    ) -> Result<()> {
        self.frame
            .locator_fill(&self.selector, text, Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Clears the element's value.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-clear>
    pub async fn clear(&self, options: Option<crate::protocol::FillOptions>) -> Result<()> {
        self.frame
            .locator_clear(&self.selector, Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Presses a key on the element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-press>
    pub async fn press(
        &self,
        key: &str,
        options: Option<crate::protocol::PressOptions>,
    ) -> Result<()> {
        self.frame
            .locator_press(&self.selector, key, Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Sets focus on the element.
    ///
    /// Calls the element's `focus()` method. Used to move keyboard focus to a
    /// specific element for subsequent keyboard interactions.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-focus>
    pub async fn focus(&self) -> Result<()> {
        self.frame
            .locator_focus(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Removes focus from the element.
    ///
    /// Calls the element's `blur()` method. Moves keyboard focus away from the element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-blur>
    pub async fn blur(&self) -> Result<()> {
        self.frame
            .locator_blur(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Types `text` into the element character by character, as though it was typed
    /// on a real keyboard.
    ///
    /// Use this method when you need to simulate keystrokes with individual key events
    /// (e.g., for autocomplete widgets). For simply setting a field value, prefer
    /// [`Locator::fill()`].
    ///
    /// # Arguments
    ///
    /// * `text` - Text to type into the element
    /// * `options` - Optional [`PressSequentiallyOptions`](crate::protocol::PressSequentiallyOptions) (e.g., `delay` between key presses)
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-press-sequentially>
    pub async fn press_sequentially(
        &self,
        text: &str,
        options: Option<crate::protocol::PressSequentiallyOptions>,
    ) -> Result<()> {
        self.frame
            .locator_press_sequentially(&self.selector, text, options)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns the `innerText` values of all elements matching this locator.
    ///
    /// Unlike [`Locator::inner_text()`] (which uses strict mode and requires exactly one match),
    /// `all_inner_texts()` returns text from all matching elements.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-all-inner-texts>
    pub async fn all_inner_texts(&self) -> Result<Vec<String>> {
        self.frame
            .locator_all_inner_texts(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns the `textContent` values of all elements matching this locator.
    ///
    /// Unlike [`Locator::text_content()`] (which uses strict mode and requires exactly one match),
    /// `all_text_contents()` returns text from all matching elements.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-all-text-contents>
    pub async fn all_text_contents(&self) -> Result<Vec<String>> {
        self.frame
            .locator_all_text_contents(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Ensures the checkbox or radio button is checked.
    ///
    /// This method is idempotent - if already checked, does nothing.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-check>
    pub async fn check(&self, options: Option<crate::protocol::CheckOptions>) -> Result<()> {
        self.frame
            .locator_check(&self.selector, Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Ensures the checkbox is unchecked.
    ///
    /// This method is idempotent - if already unchecked, does nothing.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-uncheck>
    pub async fn uncheck(&self, options: Option<crate::protocol::CheckOptions>) -> Result<()> {
        self.frame
            .locator_uncheck(&self.selector, Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Sets the checkbox or radio button to the specified checked state.
    ///
    /// This is a convenience method that calls `check()` if `checked` is true,
    /// or `uncheck()` if `checked` is false.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-set-checked>
    pub async fn set_checked(
        &self,
        checked: bool,
        options: Option<crate::protocol::CheckOptions>,
    ) -> Result<()> {
        if checked {
            self.check(options).await
        } else {
            self.uncheck(options).await
        }
    }

    /// Hovers the mouse over the element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-hover>
    pub async fn hover(&self, options: Option<crate::protocol::HoverOptions>) -> Result<()> {
        self.frame
            .locator_hover(&self.selector, Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns the value of the input, textarea, or select element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-input-value>
    pub async fn input_value(&self, _options: Option<()>) -> Result<String> {
        self.frame
            .locator_input_value(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Selects one or more options in a select element.
    ///
    /// Returns an array of option values that have been successfully selected.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-select-option>
    pub async fn select_option(
        &self,
        value: impl Into<crate::protocol::SelectOption>,
        options: Option<crate::protocol::SelectOptions>,
    ) -> Result<Vec<String>> {
        self.frame
            .locator_select_option(
                &self.selector,
                value.into(),
                Some(self.with_timeout(options)),
            )
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Selects multiple options in a select element.
    ///
    /// Returns an array of option values that have been successfully selected.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-select-option>
    pub async fn select_option_multiple(
        &self,
        values: &[impl Into<crate::protocol::SelectOption> + Clone],
        options: Option<crate::protocol::SelectOptions>,
    ) -> Result<Vec<String>> {
        let select_options: Vec<crate::protocol::SelectOption> =
            values.iter().map(|v| v.clone().into()).collect();
        self.frame
            .locator_select_option_multiple(
                &self.selector,
                select_options,
                Some(self.with_timeout(options)),
            )
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Sets the file path(s) to upload to a file input element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-set-input-files>
    pub async fn set_input_files(
        &self,
        file: &std::path::PathBuf,
        _options: Option<()>,
    ) -> Result<()> {
        self.frame
            .locator_set_input_files(&self.selector, file)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Sets multiple file paths to upload to a file input element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-set-input-files>
    pub async fn set_input_files_multiple(
        &self,
        files: &[&std::path::PathBuf],
        _options: Option<()>,
    ) -> Result<()> {
        self.frame
            .locator_set_input_files_multiple(&self.selector, files)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Sets a file to upload using FilePayload (explicit name, mimeType, buffer).
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-set-input-files>
    pub async fn set_input_files_payload(
        &self,
        file: crate::protocol::FilePayload,
        _options: Option<()>,
    ) -> Result<()> {
        self.frame
            .locator_set_input_files_payload(&self.selector, file)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Sets multiple files to upload using FilePayload.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-set-input-files>
    pub async fn set_input_files_payload_multiple(
        &self,
        files: &[crate::protocol::FilePayload],
        _options: Option<()>,
    ) -> Result<()> {
        self.frame
            .locator_set_input_files_payload_multiple(&self.selector, files)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Dispatches a DOM event on the element.
    ///
    /// Unlike clicking or typing, `dispatch_event` directly sends the event without
    /// performing any actionability checks. It still waits for the element to be present
    /// in the DOM.
    ///
    /// # Arguments
    ///
    /// * `type_` - The event type to dispatch, e.g. `"click"`, `"focus"`, `"myevent"`.
    /// * `event_init` - Optional event initializer properties (e.g. `{"detail": "value"}` for
    ///   `CustomEvent`). Corresponds to the second argument of `new Event(type, init)`.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The element is not found within the timeout
    /// - The protocol call fails
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-dispatch-event>
    pub async fn dispatch_event(
        &self,
        type_: &str,
        event_init: Option<serde_json::Value>,
    ) -> Result<()> {
        self.frame
            .locator_dispatch_event(&self.selector, type_, event_init)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Returns the bounding box of the element, or `None` if the element is not visible.
    ///
    /// The bounding box is in pixels, relative to the top-left corner of the page.
    /// Returns `None` when the element has `display: none` or is otherwise not part of
    /// the layout.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The element is not found within the timeout
    /// - The protocol call fails
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-bounding-box>
    pub async fn bounding_box(&self) -> Result<Option<BoundingBox>> {
        self.frame
            .locator_bounding_box(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Scrolls the element into view if it is not already visible in the viewport.
    ///
    /// This is an alias for calling `element.scrollIntoView()` in the browser.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The element is not found within the timeout
    /// - The protocol call fails
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-scroll-into-view-if-needed>
    pub async fn scroll_into_view_if_needed(&self) -> Result<()> {
        self.frame
            .locator_scroll_into_view_if_needed(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Takes a screenshot of the element and returns the image bytes.
    ///
    /// This method uses strict mode - it will fail if the selector matches multiple elements.
    /// Use `first()`, `last()`, or `nth()` to refine the selector to a single element.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-screenshot>
    pub async fn screenshot(
        &self,
        options: Option<crate::protocol::ScreenshotOptions>,
    ) -> Result<Vec<u8>> {
        // Query for the element using strict mode (should return exactly one)
        let element = self
            .frame
            .query_selector(&self.selector)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))?
            .ok_or_else(|| {
                crate::error::Error::ElementNotFound(format!(
                    "Element not found: {}",
                    self.selector
                ))
            })?;

        // Delegate to ElementHandle.screenshot() with default timeout injected
        element
            .screenshot(Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Performs a touch-tap on the element.
    ///
    /// This method dispatches a `touchstart` and `touchend` event on the element.
    /// For touch support to work, the browser context must be created with
    /// `has_touch: true`.
    ///
    /// # Arguments
    ///
    /// * `options` - Optional [`TapOptions`](crate::protocol::TapOptions) (force, modifiers, position, timeout, trial)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The element is not found within the timeout
    /// - Actionability checks fail (unless `force: true`)
    /// - The browser context was not created with `has_touch: true`
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-tap>
    pub async fn tap(&self, options: Option<crate::protocol::TapOptions>) -> Result<()> {
        self.frame
            .locator_tap(&self.selector, Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Drags this element to the `target` element.
    ///
    /// Both this locator and `target` must resolve to elements in the same frame.
    /// Playwright performs a series of mouse events (move, press, move to target, release)
    /// to simulate the drag.
    ///
    /// # Arguments
    ///
    /// * `target` - The locator of the element to drag onto
    /// * `options` - Optional [`DragToOptions`](crate::protocol::DragToOptions) (force, no_wait_after, timeout, trial,
    ///   source_position, target_position)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Either element is not found within the timeout
    /// - Actionability checks fail (unless `force: true`)
    /// - The protocol call fails
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-drag-to>
    pub async fn drag_to(
        &self,
        target: &Locator,
        options: Option<crate::protocol::DragToOptions>,
    ) -> Result<()> {
        self.frame
            .locator_drag_to(
                &self.selector,
                &target.selector,
                Some(self.with_timeout(options)),
            )
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Waits until the element satisfies the given state condition.
    ///
    /// If no state is specified, waits for the element to be `visible` (the default).
    ///
    /// This method is useful for waiting for lazy-rendered elements or elements that
    /// appear/disappear based on user interaction or async data loading.
    ///
    /// # Arguments
    ///
    /// * `options` - Optional [`WaitForOptions`](crate::protocol::WaitForOptions) specifying the `state` to wait for
    ///   (`Visible`, `Hidden`, `Attached`, or `Detached`) and a `timeout` in milliseconds.
    ///
    /// # Errors
    ///
    /// Returns an error if the element does not satisfy the expected state within the timeout.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-wait-for>
    pub async fn wait_for(&self, options: Option<crate::protocol::WaitForOptions>) -> Result<()> {
        self.frame
            .locator_wait_for(&self.selector, Some(self.with_timeout(options)))
            .await
            .map_err(|e| self.wrap_error_with_selector(e))
    }

    /// Evaluates a JavaScript expression in the scope of the matched element.
    ///
    /// The element is passed as the first argument to the expression. The expression
    /// can be any JavaScript function or expression that returns a JSON-serializable value.
    ///
    /// # Arguments
    ///
    /// * `expression` - JavaScript expression or function, e.g. `"(el) => el.textContent"`
    /// * `arg` - Optional argument passed as the second argument to the function
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The element is not found within the timeout
    /// - The JavaScript expression throws an error
    /// - The return value is not JSON-serializable
    ///
    /// # Example
    ///
    /// ```ignore
    /// use playwright_rs::Playwright;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let playwright = Playwright::launch().await?;
    /// let browser = playwright.chromium().launch().await?;
    /// let page = browser.new_page().await?;
    /// let _ = page.goto("data:text/html,<h1>Hello</h1>", None).await;
    ///
    /// let heading = page.locator("h1").await;
    /// let text: String = heading.evaluate("(el) => el.textContent", None::<()>).await?;
    /// assert_eq!(text, "Hello");
    ///
    /// // With an argument
    /// let result: String = heading
    ///     .evaluate("(el, suffix) => el.textContent + suffix", Some("!"))
    ///     .await?;
    /// assert_eq!(result, "Hello!");
    /// # browser.close().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-evaluate>
    pub async fn evaluate<R, T>(&self, expression: &str, arg: Option<T>) -> Result<R>
    where
        R: serde::de::DeserializeOwned,
        T: serde::Serialize,
    {
        let raw = self
            .frame
            .locator_evaluate(&self.selector, expression, arg)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))?;
        serde_json::from_value(raw).map_err(|e| {
            crate::error::Error::ProtocolError(format!(
                "evaluate result deserialization failed: {}",
                e
            ))
        })
    }

    /// Evaluates a JavaScript expression in the scope of all elements matching this locator.
    ///
    /// The array of all matched elements is passed as the first argument to the expression.
    /// Unlike [`evaluate()`](Self::evaluate), this does not use strict mode — all matching
    /// elements are collected and passed as an array.
    ///
    /// # Arguments
    ///
    /// * `expression` - JavaScript function that receives an array of elements
    /// * `arg` - Optional argument passed as the second argument to the function
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The JavaScript expression throws an error
    /// - The return value is not JSON-serializable
    ///
    /// # Example
    ///
    /// ```ignore
    /// use playwright_rs::Playwright;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let playwright = Playwright::launch().await?;
    /// let browser = playwright.chromium().launch().await?;
    /// let page = browser.new_page().await?;
    /// let _ = page.goto(
    ///     "data:text/html,<li class='item'>A</li><li class='item'>B</li>",
    ///     None
    /// ).await;
    ///
    /// let items = page.locator(".item").await;
    /// let texts: Vec<String> = items
    ///     .evaluate_all("(elements) => elements.map(e => e.textContent)", None::<()>)
    ///     .await?;
    /// assert_eq!(texts, vec!["A", "B"]);
    /// # browser.close().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-evaluate-all>
    pub async fn evaluate_all<R, T>(&self, expression: &str, arg: Option<T>) -> Result<R>
    where
        R: serde::de::DeserializeOwned,
        T: serde::Serialize,
    {
        let raw = self
            .frame
            .locator_evaluate_all(&self.selector, expression, arg)
            .await
            .map_err(|e| self.wrap_error_with_selector(e))?;
        serde_json::from_value(raw).map_err(|e| {
            crate::error::Error::ProtocolError(format!(
                "evaluate_all result deserialization failed: {}",
                e
            ))
        })
    }
}

impl std::fmt::Debug for Locator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Locator")
            .field("selector", &self.selector)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_escape_for_selector_case_insensitive() {
        assert_eq!(escape_for_selector("hello", false), "\"hello\"i");
    }

    #[test]
    fn test_escape_for_selector_exact() {
        assert_eq!(escape_for_selector("hello", true), "\"hello\"s");
    }

    #[test]
    fn test_escape_for_selector_with_quotes() {
        assert_eq!(
            escape_for_selector("say \"hi\"", false),
            "\"say \\\"hi\\\"\"i"
        );
    }

    #[test]
    fn test_get_by_text_selector_case_insensitive() {
        assert_eq!(
            get_by_text_selector("Click me", false),
            "internal:text=\"Click me\"i"
        );
    }

    #[test]
    fn test_get_by_text_selector_exact() {
        assert_eq!(
            get_by_text_selector("Click me", true),
            "internal:text=\"Click me\"s"
        );
    }

    #[test]
    fn test_get_by_label_selector() {
        assert_eq!(
            get_by_label_selector("Email", false),
            "internal:label=\"Email\"i"
        );
    }

    #[test]
    fn test_get_by_placeholder_selector() {
        assert_eq!(
            get_by_placeholder_selector("Enter name", false),
            "internal:attr=[placeholder=\"Enter name\"i]"
        );
    }

    #[test]
    fn test_get_by_alt_text_selector() {
        assert_eq!(
            get_by_alt_text_selector("Logo", true),
            "internal:attr=[alt=\"Logo\"s]"
        );
    }

    #[test]
    fn test_get_by_title_selector() {
        assert_eq!(
            get_by_title_selector("Help", false),
            "internal:attr=[title=\"Help\"i]"
        );
    }

    #[test]
    fn test_get_by_test_id_selector() {
        assert_eq!(
            get_by_test_id_selector("submit-btn"),
            "internal:testid=[data-testid=\"submit-btn\"s]"
        );
    }

    #[test]
    fn test_escape_for_attribute_selector_case_insensitive() {
        assert_eq!(
            escape_for_attribute_selector("Submit", false),
            "\"Submit\"i"
        );
    }

    #[test]
    fn test_escape_for_attribute_selector_exact() {
        assert_eq!(escape_for_attribute_selector("Submit", true), "\"Submit\"s");
    }

    #[test]
    fn test_escape_for_attribute_selector_escapes_quotes() {
        assert_eq!(
            escape_for_attribute_selector("Say \"hello\"", false),
            "\"Say \\\"hello\\\"\"i"
        );
    }

    #[test]
    fn test_escape_for_attribute_selector_escapes_backslashes() {
        assert_eq!(
            escape_for_attribute_selector("path\\to", true),
            "\"path\\\\to\"s"
        );
    }

    #[test]
    fn test_get_by_role_selector_role_only() {
        assert_eq!(
            get_by_role_selector(AriaRole::Button, None),
            "internal:role=button"
        );
    }

    #[test]
    fn test_get_by_role_selector_with_name() {
        let opts = GetByRoleOptions {
            name: Some("Submit".to_string()),
            ..Default::default()
        };
        assert_eq!(
            get_by_role_selector(AriaRole::Button, Some(opts)),
            "internal:role=button[name=\"Submit\"i]"
        );
    }

    #[test]
    fn test_get_by_role_selector_with_name_exact() {
        let opts = GetByRoleOptions {
            name: Some("Submit".to_string()),
            exact: Some(true),
            ..Default::default()
        };
        assert_eq!(
            get_by_role_selector(AriaRole::Button, Some(opts)),
            "internal:role=button[name=\"Submit\"s]"
        );
    }

    #[test]
    fn test_get_by_role_selector_with_checked() {
        let opts = GetByRoleOptions {
            checked: Some(true),
            ..Default::default()
        };
        assert_eq!(
            get_by_role_selector(AriaRole::Checkbox, Some(opts)),
            "internal:role=checkbox[checked=true]"
        );
    }

    #[test]
    fn test_get_by_role_selector_with_level() {
        let opts = GetByRoleOptions {
            level: Some(2),
            ..Default::default()
        };
        assert_eq!(
            get_by_role_selector(AriaRole::Heading, Some(opts)),
            "internal:role=heading[level=2]"
        );
    }

    #[test]
    fn test_get_by_role_selector_with_disabled() {
        let opts = GetByRoleOptions {
            disabled: Some(true),
            ..Default::default()
        };
        assert_eq!(
            get_by_role_selector(AriaRole::Button, Some(opts)),
            "internal:role=button[disabled=true]"
        );
    }

    #[test]
    fn test_get_by_role_selector_include_hidden() {
        let opts = GetByRoleOptions {
            include_hidden: Some(true),
            ..Default::default()
        };
        assert_eq!(
            get_by_role_selector(AriaRole::Button, Some(opts)),
            "internal:role=button[include-hidden=true]"
        );
    }

    #[test]
    fn test_get_by_role_selector_property_order() {
        // All properties: checked, disabled, selected, expanded, include-hidden, level, name, pressed
        let opts = GetByRoleOptions {
            pressed: Some(true),
            name: Some("OK".to_string()),
            checked: Some(false),
            disabled: Some(true),
            ..Default::default()
        };
        assert_eq!(
            get_by_role_selector(AriaRole::Button, Some(opts)),
            "internal:role=button[checked=false][disabled=true][name=\"OK\"i][pressed=true]"
        );
    }

    #[test]
    fn test_get_by_role_selector_name_with_special_chars() {
        let opts = GetByRoleOptions {
            name: Some("Click \"here\" now".to_string()),
            exact: Some(true),
            ..Default::default()
        };
        assert_eq!(
            get_by_role_selector(AriaRole::Link, Some(opts)),
            "internal:role=link[name=\"Click \\\"here\\\" now\"s]"
        );
    }

    #[test]
    fn test_aria_role_as_str() {
        assert_eq!(AriaRole::Button.as_str(), "button");
        assert_eq!(AriaRole::Heading.as_str(), "heading");
        assert_eq!(AriaRole::Link.as_str(), "link");
        assert_eq!(AriaRole::Checkbox.as_str(), "checkbox");
        assert_eq!(AriaRole::Alert.as_str(), "alert");
        assert_eq!(AriaRole::Navigation.as_str(), "navigation");
        assert_eq!(AriaRole::Progressbar.as_str(), "progressbar");
        assert_eq!(AriaRole::Treeitem.as_str(), "treeitem");
    }
}