rpage 1.0.0

A Rust browser automation library inspired by DrissionPage
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
//! Locator parsing and matching
//!
//! Supported locator syntax (text/attribute operators follow DrissionPage:
//! `=` exact, `:` contains, `^` starts-with, `$` ends-with):
//! - `#id` → Css("#id")
//! - `.class` → Css(".class")
//! - `tag` → Css("tag")
//! - `css:xxx` → Css("xxx")
//! - `xpath:xxx` → XPath("xxx")
//! - `text=xxx` → Text exact
//! - `text:xxx` / `text*=xxx` → TextContains
//! - `text^xxx` → TextStartsWith, `text$xxx` → TextEndsWith
//! - `@attr=val` → AttrEquals
//! - `@attr:val` / `@attr*=val` → AttrContains
//! - `@attr^val` → AttrStartsWith, `@attr$val` → AttrEndsWith
//! - `tag:div@@class=x@@text:y` → And (same-element, all conditions required)
//! - `@|class=a@|class=b` → Or (same-element, any condition)
//! - `a@@@b@@@c` → Chain (descendant narrowing, rpage extension)

use crate::error::{Error, Result};

/// Locator strategy for finding elements
#[derive(Debug, Clone, PartialEq)]
pub enum Locator {
    /// CSS selector
    Css(String),
    /// XPath expression
    XPath(String),
    /// Exact text match
    Text(String),
    /// Text contains match
    TextContains(String),
    /// Text starts-with match
    TextStartsWith(String),
    /// Text ends-with match
    TextEndsWith(String),
    /// Attribute equals value
    AttrEquals { attr: String, value: String },
    /// Attribute contains value
    AttrContains { attr: String, value: String },
    /// Attribute starts-with value
    AttrStartsWith { attr: String, value: String },
    /// Attribute ends-with value
    AttrEndsWith { attr: String, value: String },
    /// Multiple conditions on the SAME element, all required — DrissionPage `@@`
    /// (e.g. `tag:div@@class=x@@text:y`). The first element may be a bare tag.
    And(Vec<Locator>),
    /// Multiple conditions on the SAME element, any one — DrissionPage `@|`.
    Or(Vec<Locator>),
    /// Chained locators (narrow down step by step) — rpage `@@@` descendant chain
    Chain(Vec<Locator>),
}

impl Locator {
    /// Render this locator as an XPath *predicate* fragment (no leading `//*`),
    /// for composing same-element AND/OR conditions. Returns `None` for things
    /// that can't be a predicate (a tag/element name, xpath, nested groups).
    fn to_xpath_predicate(&self) -> Option<String> {
        let esc = |s: &str| s.replace('\'', "\\'");
        match self {
            Locator::Text(t) => Some(format!("text()='{}'", esc(t))),
            Locator::TextContains(t) => Some(format!("contains(text(),'{}')", esc(t))),
            Locator::TextStartsWith(t) => Some(format!("starts-with(text(),'{}')", esc(t))),
            Locator::TextEndsWith(t) => {
                let t = esc(t);
                Some(format!(
                    "substring(text(),string-length(text())-string-length('{t}')+1)='{t}'"
                ))
            }
            Locator::AttrEquals { attr, value } => Some(format!("@{}='{}'", attr, esc(value))),
            Locator::AttrContains { attr, value } => {
                Some(format!("contains(@{},'{}')", attr, esc(value)))
            }
            Locator::AttrStartsWith { attr, value } => {
                Some(format!("starts-with(@{},'{}')", attr, esc(value)))
            }
            Locator::AttrEndsWith { attr, value } => {
                let value = esc(value);
                Some(format!(
                    "substring(@{attr},string-length(@{attr})-string-length('{value}')+1)='{value}'"
                ))
            }
            // A `#id` / `.class` CSS condition can also be a predicate.
            Locator::Css(s) => {
                if let Some(id) = s.strip_prefix('#') {
                    Some(format!("@id='{}'", esc(id)))
                } else if let Some(cls) = s.strip_prefix('.') {
                    Some(format!(
                        "contains(concat(' ',normalize-space(@class),' '),' {} ')",
                        esc(cls)
                    ))
                } else {
                    None // a bare tag name is the element, not a predicate
                }
            }
            _ => None,
        }
    }

    /// Build the combined XPath for a same-element AND/OR group.
    fn multi_cond_xpath(parts: &[Locator], join: &str) -> Option<String> {
        let mut tag = "*".to_string();
        let mut preds = Vec::new();
        for (i, p) in parts.iter().enumerate() {
            // A leading bare tag (`Css("div")` with no #/.) becomes the element.
            if i == 0 {
                if let Locator::Css(s) = p {
                    if !s.starts_with('#') && !s.starts_with('.') && !s.contains(['>', ' ', '[']) {
                        tag = s.clone();
                        continue;
                    }
                }
            }
            preds.push(p.to_xpath_predicate()?);
        }
        if preds.is_empty() {
            return None;
        }
        Some(format!("//{}[{}]", tag, preds.join(join)))
    }
}

impl Locator {
    /// Convert this locator to a CSS selector if possible
    pub fn to_css(&self) -> Option<String> {
        match self {
            Locator::Css(s) => Some(s.clone()),
            // Text / attribute fuzzy matches have no direct CSS equivalent —
            // they all go through the XPath fallback.
            Locator::Text(_)
            | Locator::TextContains(_)
            | Locator::TextStartsWith(_)
            | Locator::TextEndsWith(_)
            | Locator::XPath(_)
            | Locator::AttrEquals { .. }
            | Locator::AttrContains { .. }
            | Locator::AttrStartsWith { .. }
            | Locator::AttrEndsWith { .. }
            | Locator::And(_)
            | Locator::Or(_)
            | Locator::Chain(_) => None,
        }
    }

    /// Convert to an XPath expression
    pub fn to_xpath(&self) -> Option<String> {
        match self {
            Locator::XPath(x) => Some(x.clone()),
            Locator::Css(sel) => {
                // Basic CSS to XPath: prepend //
                let mut xpath = String::from("//");
                // Simple conversion for common cases
                if let Some(id) = sel.strip_prefix('#') {
                    xpath.push_str(&format!("*[@id='{id}']"));
                } else if let Some(cls) = sel.strip_prefix('.') {
                    xpath.push_str(&format!(
                        "*[contains(concat(' ',normalize-space(@class),' '),' {cls} ')]"
                    ));
                } else {
                    xpath.push_str(sel);
                }
                Some(xpath)
            }
            Locator::Text(t) => Some(format!("//*[text()='{}']", t.replace('\'', "\\'"))),
            Locator::TextContains(t) => Some(format!(
                "//*[contains(text(),'{}')]",
                t.replace('\'', "\\'")
            )),
            Locator::TextStartsWith(t) => Some(format!(
                "//*[starts-with(text(),'{}')]",
                t.replace('\'', "\\'")
            )),
            // XPath 1.0 has no ends-with(); emulate it with substring().
            Locator::TextEndsWith(t) => {
                let t = t.replace('\'', "\\'");
                Some(format!(
                    "//*[substring(text(),string-length(text())-string-length('{t}')+1)='{t}']"
                ))
            }
            Locator::AttrEquals { attr, value } => {
                Some(format!("//*[@{}='{}']", attr, value.replace('\'', "\\'")))
            }
            Locator::AttrContains { attr, value } => Some(format!(
                "//*[contains(@{},'{}')]",
                attr,
                value.replace('\'', "\\'")
            )),
            Locator::AttrStartsWith { attr, value } => Some(format!(
                "//*[starts-with(@{},'{}')]",
                attr,
                value.replace('\'', "\\'")
            )),
            Locator::AttrEndsWith { attr, value } => {
                let value = value.replace('\'', "\\'");
                Some(format!(
                    "//*[substring(@{attr},string-length(@{attr})-string-length('{value}')+1)='{value}']"
                ))
            }
            Locator::And(parts) => Self::multi_cond_xpath(parts, " and "),
            Locator::Or(parts) => Self::multi_cond_xpath(parts, " or "),
            Locator::Chain(locators) => {
                // Build a combined XPath from chain
                let mut parts = Vec::new();
                for loc in locators {
                    if let Some(xp) = loc.to_xpath() {
                        parts.push(xp);
                    } else {
                        return None;
                    }
                }
                Some(parts.join(" | "))
            }
        }
    }

    /// Check if this is a pure CSS locator
    pub fn is_css(&self) -> bool {
        matches!(self, Locator::Css(_))
    }

    /// Check if this requires XPath
    pub fn is_xpath(&self) -> bool {
        matches!(
            self,
            Locator::XPath(_)
                | Locator::Text(_)
                | Locator::TextContains(_)
                | Locator::TextStartsWith(_)
                | Locator::TextEndsWith(_)
                | Locator::AttrEquals { .. }
                | Locator::AttrContains { .. }
                | Locator::AttrStartsWith { .. }
                | Locator::AttrEndsWith { .. }
                | Locator::And(_)
                | Locator::Or(_)
        )
    }
}

/// Parse a locator string into a Locator enum
pub fn parse_locator(input: &str) -> Result<Locator> {
    let input = input.trim();
    if input.is_empty() {
        return Err(Error::InvalidLocator("empty locator string".into()));
    }

    // Same-element OR conditions (DrissionPage `@|`): base@|c1@|c2
    if input.contains("@|") {
        return parse_multi_cond(input, "@|", false);
    }

    // Descendant chain (rpage-specific `@@@`): narrow down step by step.
    if input.contains("@@@") {
        let parts: Vec<&str> = input.split("@@@").collect();
        if parts.len() < 2 {
            return Err(Error::InvalidLocator(format!(
                "invalid chain locator: {input}"
            )));
        }
        let locators: Vec<Locator> = parts
            .iter()
            .map(|p| parse_single_locator(p.trim()))
            .collect::<Result<Vec<_>>>()?;
        return Ok(Locator::Chain(locators));
    }

    // Same-element AND conditions (DrissionPage `@@`): tag:div@@class=x@@text:y
    if input.contains("@@") && !input.starts_with('@') {
        return parse_multi_cond(input, "@@", true);
    }

    parse_single_locator(input)
}

/// Parse a DrissionPage same-element multi-condition (`@@` AND / `@|` OR). The
/// first segment may be a bare tag (becomes the element); the rest are
/// attribute/text conditions, all applied to the *same* element.
fn parse_multi_cond(input: &str, sep: &str, and: bool) -> Result<Locator> {
    let parts: Vec<&str> = input
        .split(sep)
        .map(|p| p.trim())
        .filter(|p| !p.is_empty())
        .collect();
    if parts.len() < 2 {
        return Err(Error::InvalidLocator(format!(
            "invalid multi-condition locator: {input}"
        )));
    }
    let locs: Vec<Locator> = parts
        .iter()
        .map(|p| parse_condition(p))
        .collect::<Result<Vec<_>>>()?;
    Ok(if and {
        Locator::And(locs)
    } else {
        Locator::Or(locs)
    })
}

/// Parse one condition of a multi-condition locator. DrissionPage allows a bare
/// `attr=val` (no `@`) as an attribute condition; a leading tag / `text:` /
/// `#id` / `.class` / `@attr` is parsed as-is.
fn parse_condition(s: &str) -> Result<Locator> {
    let prefixed = s.starts_with('@')
        || s.starts_with("text")
        || s.starts_with("tag:")
        || s.starts_with("css:")
        || s.starts_with("xpath:")
        || s.starts_with('#')
        || s.starts_with('.');
    if !prefixed && s.contains(['=', ':', '^', '$']) {
        return parse_single_locator(&format!("@{s}"));
    }
    parse_single_locator(s)
}

/// A text/attribute match operator, following DrissionPage conventions:
/// `=` exact, `:` contains, `^` starts-with, `$` ends-with. `*=` is kept as a
/// legacy alias for contains, and `^=`/`$=` as aliases for `^`/`$`.
#[derive(Clone, Copy)]
enum MatchOp {
    Exact,
    Contains,
    StartsWith,
    EndsWith,
}

/// Given the part of a locator that follows the field name (e.g. the `:btn`
/// in `@class:btn`, or the `^=Log` in `text^=Log`), detect the operator and
/// return it together with the value. Order matters: the two-char operators
/// must be tried before the single `=`/`^`/`$` they contain.
fn split_match_op(s: &str) -> Option<(MatchOp, &str)> {
    if let Some(v) = s.strip_prefix("*=") {
        return Some((MatchOp::Contains, v));
    }
    if let Some(v) = s.strip_prefix(':') {
        return Some((MatchOp::Contains, v));
    }
    if let Some(v) = s.strip_prefix("^=").or_else(|| s.strip_prefix('^')) {
        return Some((MatchOp::StartsWith, v));
    }
    if let Some(v) = s.strip_prefix("$=").or_else(|| s.strip_prefix('$')) {
        return Some((MatchOp::EndsWith, v));
    }
    if let Some(v) = s.strip_prefix('=') {
        return Some((MatchOp::Exact, v));
    }
    None
}

/// Parse a single (non-chained) locator
fn parse_single_locator(input: &str) -> Result<Locator> {
    let input = input.trim();
    if input.is_empty() {
        return Err(Error::InvalidLocator("empty locator segment".into()));
    }

    // xpath:xxx
    if let Some(rest) = input.strip_prefix("xpath:") {
        if rest.is_empty() {
            return Err(Error::InvalidLocator(
                "xpath: requires an expression".into(),
            ));
        }
        return Ok(Locator::XPath(rest.to_string()));
    }

    // css:xxx
    if let Some(rest) = input.strip_prefix("css:") {
        if rest.is_empty() {
            return Err(Error::InvalidLocator("css: requires a selector".into()));
        }
        return Ok(Locator::Css(rest.to_string()));
    }

    // text=xxx / text:xxx / text^xxx / text$xxx (and text*=xxx legacy).
    // Guard against bare tag names that merely start with "text" (e.g.
    // "textarea"): only treat as a text locator when an operator follows.
    if let Some(rest) = input.strip_prefix("text") {
        if let Some((op, value)) = split_match_op(rest) {
            if value.is_empty() {
                return Err(Error::InvalidLocator(
                    "text matcher requires a value".into(),
                ));
            }
            let value = value.to_string();
            return Ok(match op {
                MatchOp::Exact => Locator::Text(value),
                MatchOp::Contains => Locator::TextContains(value),
                MatchOp::StartsWith => Locator::TextStartsWith(value),
                MatchOp::EndsWith => Locator::TextEndsWith(value),
            });
        }
    }

    // @attr=val / @attr:val / @attr^val / @attr$val (and @attr*=val legacy).
    if let Some(rest) = input.strip_prefix('@') {
        // The attribute name is the leading run of name characters; whatever
        // follows is the operator + value.
        let name_len = rest
            .find(|c: char| !(c.is_alphanumeric() || c == '-' || c == '_'))
            .unwrap_or(rest.len());
        let attr = &rest[..name_len];
        if !attr.is_empty() {
            if let Some((op, value)) = split_match_op(&rest[name_len..]) {
                let attr = attr.to_string();
                let value = value.to_string();
                return Ok(match op {
                    MatchOp::Exact => Locator::AttrEquals { attr, value },
                    MatchOp::Contains => Locator::AttrContains { attr, value },
                    MatchOp::StartsWith => Locator::AttrStartsWith { attr, value },
                    MatchOp::EndsWith => Locator::AttrEndsWith { attr, value },
                });
            }
        }
    }

    // tag:xxx → treat "xxx" as CSS tag selector
    if let Some(rest) = input.strip_prefix("tag:") {
        if rest.is_empty() {
            return Err(Error::InvalidLocator("tag: requires a tag name".into()));
        }
        return Ok(Locator::Css(rest.to_string()));
    }

    // #id → CSS selector
    if input.starts_with('#') {
        return Ok(Locator::Css(input.to_string()));
    }

    // .class → CSS selector
    if input.starts_with('.') {
        return Ok(Locator::Css(input.to_string()));
    }

    // [attr=val] → CSS selector
    if input.starts_with('[') {
        return Ok(Locator::Css(input.to_string()));
    }

    // Plain tag name (letters only, no special chars)
    if input
        .chars()
        .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
    {
        return Ok(Locator::Css(input.to_string()));
    }

    // Fallback: treat as CSS selector
    Ok(Locator::Css(input.to_string()))
}

/// Convert a Locator to a CSS/XPath selector string for CDP queries.
pub fn locator_to_selector(locator: &Locator) -> Result<String> {
    match locator {
        Locator::Css(sel) => Ok(sel.clone()),
        Locator::XPath(xp) => Ok(format!("xpath:{xp}")),
        Locator::Text(t) => Ok(format!("xpath://*[text()='{}']", t.replace('\'', "\\'"))),
        Locator::TextContains(t) => Ok(format!(
            "xpath://*[contains(text(),'{}')]",
            t.replace('\'', "\\'")
        )),
        Locator::AttrEquals { attr, value } => Ok(format!(
            "xpath://*[@{}='{}']",
            attr,
            value.replace('\'', "\\'")
        )),
        Locator::AttrContains { attr, value } => Ok(format!(
            "xpath://*[contains(@{},'{}')]",
            attr,
            value.replace('\'', "\\'")
        )),
        // Starts-with / ends-with reuse the XPath built in `to_xpath`.
        Locator::TextStartsWith(_)
        | Locator::TextEndsWith(_)
        | Locator::AttrStartsWith { .. }
        | Locator::AttrEndsWith { .. }
        | Locator::And(_)
        | Locator::Or(_) => locator
            .to_xpath()
            .map(|xp| format!("xpath:{xp}"))
            .ok_or_else(|| Error::InvalidLocator("cannot build xpath".into())),
        Locator::Chain(locators) => locators
            .last()
            .ok_or_else(|| Error::InvalidLocator("empty chain".into()))
            .and_then(locator_to_selector),
    }
}

/// Trait for converting types into Locator
pub trait IntoLocator {
    fn to_locator(&self) -> Result<Locator>;
}

impl IntoLocator for &str {
    fn to_locator(&self) -> Result<Locator> {
        parse_locator(self)
    }
}

impl IntoLocator for String {
    fn to_locator(&self) -> Result<Locator> {
        parse_locator(self)
    }
}

impl IntoLocator for Locator {
    fn to_locator(&self) -> Result<Locator> {
        Ok(self.clone())
    }
}

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

    #[test]
    fn test_css_id() {
        let loc = parse_locator("#myid").unwrap();
        assert_eq!(loc, Locator::Css("#myid".to_string()));
    }

    #[test]
    fn test_css_class() {
        let loc = parse_locator(".myclass").unwrap();
        assert_eq!(loc, Locator::Css(".myclass".to_string()));
    }

    #[test]
    fn test_tag() {
        let loc = parse_locator("div").unwrap();
        assert_eq!(loc, Locator::Css("div".to_string()));
    }

    #[test]
    fn test_css_prefix() {
        let loc = parse_locator("css:div.container > p").unwrap();
        assert_eq!(loc, Locator::Css("div.container > p".to_string()));
    }

    #[test]
    fn test_xpath_prefix() {
        let loc = parse_locator("xpath://div[@id='foo']").unwrap();
        assert_eq!(loc, Locator::XPath("//div[@id='foo']".to_string()));
    }

    #[test]
    fn test_text_exact() {
        let loc = parse_locator("text=Login").unwrap();
        assert_eq!(loc, Locator::Text("Login".to_string()));
    }

    #[test]
    fn test_text_contains() {
        let loc = parse_locator("text*=Log").unwrap();
        assert_eq!(loc, Locator::TextContains("Log".to_string()));
    }

    #[test]
    fn test_text_contains_colon() {
        // DrissionPage `:` = contains
        let loc = parse_locator("text:登录").unwrap();
        assert_eq!(loc, Locator::TextContains("登录".to_string()));
    }

    #[test]
    fn test_text_starts_ends_with() {
        assert_eq!(
            parse_locator("text^Hello").unwrap(),
            Locator::TextStartsWith("Hello".to_string())
        );
        assert_eq!(
            parse_locator("text$world").unwrap(),
            Locator::TextEndsWith("world".to_string())
        );
    }

    #[test]
    fn test_textarea_is_css_not_text_locator() {
        // A tag name that merely starts with "text" must stay CSS.
        assert_eq!(
            parse_locator("textarea").unwrap(),
            Locator::Css("textarea".to_string())
        );
    }

    #[test]
    fn test_attr_contains_colon() {
        let loc = parse_locator("@class:btn").unwrap();
        assert_eq!(
            loc,
            Locator::AttrContains {
                attr: "class".to_string(),
                value: "btn".to_string(),
            }
        );
    }

    #[test]
    fn test_attr_starts_ends_with() {
        assert_eq!(
            parse_locator("@href^https").unwrap(),
            Locator::AttrStartsWith {
                attr: "href".to_string(),
                value: "https".to_string()
            }
        );
        assert_eq!(
            parse_locator("@src$.png").unwrap(),
            Locator::AttrEndsWith {
                attr: "src".to_string(),
                value: ".png".to_string()
            }
        );
    }

    #[test]
    fn test_text_ends_with_xpath_uses_substring() {
        let xp = Locator::TextEndsWith("bar".to_string()).to_xpath().unwrap();
        assert!(xp.contains("substring") && xp.contains("string-length"));
    }

    #[test]
    fn test_attr_equals() {
        let loc = parse_locator("@name=login").unwrap();
        assert_eq!(
            loc,
            Locator::AttrEquals {
                attr: "name".to_string(),
                value: "login".to_string()
            }
        );
    }

    #[test]
    fn test_attr_contains() {
        let loc = parse_locator("@name*=log").unwrap();
        assert_eq!(
            loc,
            Locator::AttrContains {
                attr: "name".to_string(),
                value: "log".to_string()
            }
        );
    }

    #[test]
    fn test_chain_double_at() {
        // `@@` is now DrissionPage same-element AND (was descendant chain).
        let loc = parse_locator("tag:form@@text=Login").unwrap();
        match loc {
            Locator::And(parts) => {
                assert_eq!(parts.len(), 2);
                assert_eq!(parts[0], Locator::Css("form".to_string()));
                assert_eq!(parts[1], Locator::Text("Login".to_string()));
            }
            _ => panic!("expected And"),
        }
    }

    #[test]
    fn test_chain_triple_at() {
        let loc = parse_locator("tag:form@@@name=login").unwrap();
        match loc {
            Locator::Chain(parts) => {
                assert_eq!(parts.len(), 2);
            }
            _ => panic!("expected Chain"),
        }
    }

    // ── Additional comprehensive tests ──────────────────────//

    #[test]
    fn test_css_div_child_p() {
        let loc = parse_locator("css:div>p").unwrap();
        assert_eq!(loc, Locator::Css("div>p".to_string()));
        assert!(loc.is_css());
    }

    #[test]
    fn test_css_combined_selector() {
        let loc = parse_locator("css:#main .content > p:first-child").unwrap();
        assert_eq!(
            loc,
            Locator::Css("#main .content > p:first-child".to_string())
        );
    }

    #[test]
    fn test_css_bracket_selector() {
        let loc = parse_locator("[data-testid='submit']").unwrap();
        assert_eq!(loc, Locator::Css("[data-testid='submit']".to_string()));
    }

    #[test]
    fn test_xpath_div() {
        let loc = parse_locator("xpath://div").unwrap();
        assert_eq!(loc, Locator::XPath("//div".to_string()));
        assert!(loc.is_xpath());
        assert!(!loc.is_css());
    }

    #[test]
    fn test_text_equals_chinese() {
        let loc = parse_locator("text=登录").unwrap();
        assert_eq!(loc, Locator::Text("登录".to_string()));
        assert!(loc.is_xpath());
    }

    #[test]
    fn test_text_contains_chinese() {
        let loc = parse_locator("text*=登录").unwrap();
        assert_eq!(loc, Locator::TextContains("登录".to_string()));
    }

    #[test]
    fn test_attr_equals_class_btn() {
        let loc = parse_locator("@class=btn").unwrap();
        assert_eq!(
            loc,
            Locator::AttrEquals {
                attr: "class".to_string(),
                value: "btn".to_string(),
            }
        );
    }

    #[test]
    fn test_attr_contains_class_btn() {
        let loc = parse_locator("@class*=btn").unwrap();
        assert_eq!(
            loc,
            Locator::AttrContains {
                attr: "class".to_string(),
                value: "btn".to_string(),
            }
        );
    }

    #[test]
    fn test_tag_prefix() {
        let loc = parse_locator("tag:form").unwrap();
        assert_eq!(loc, Locator::Css("form".to_string()));
    }

    #[test]
    fn test_chain_tag_text_chinese() {
        let loc = parse_locator("tag:form@@text=登录").unwrap();
        match loc {
            Locator::And(parts) => {
                assert_eq!(parts.len(), 2);
                assert_eq!(parts[0], Locator::Css("form".to_string()));
                assert_eq!(parts[1], Locator::Text("登录".to_string()));
            }
            _ => panic!("expected And"),
        }
    }

    #[test]
    fn test_chain_with_attr() {
        let loc = parse_locator("tag:input@@@name=login").unwrap();
        match loc {
            Locator::Chain(parts) => {
                assert_eq!(parts.len(), 2);
                assert_eq!(parts[0], Locator::Css("input".to_string()));
                // The second part "name=login" has no @ prefix, so it's treated as CSS
                assert_eq!(parts[1], Locator::Css("name=login".to_string()));
            }
            _ => panic!("expected Chain"),
        }
    }

    #[test]
    fn test_chain_with_at_attr() {
        // Use @@ (not @@@) so that the @ prefix is preserved
        let loc = parse_locator("tag:div@@@name=user").unwrap();
        match loc {
            Locator::Chain(parts) => {
                assert_eq!(parts.len(), 2);
                // "name=user" without @ is parsed as CSS
                assert_eq!(parts[1], Locator::Css("name=user".to_string()));
            }
            _ => panic!("expected Chain"),
        }
    }

    #[test]
    fn test_chain_double_at_with_attr() {
        let loc = parse_locator("tag:div@@name=user").unwrap();
        // bare `name=user` (no @) is now an attribute condition, AND with the tag.
        match loc {
            Locator::And(parts) => {
                assert_eq!(parts.len(), 2);
                assert_eq!(parts[0], Locator::Css("div".to_string()));
                assert_eq!(
                    parts[1],
                    Locator::AttrEquals {
                        attr: "name".to_string(),
                        value: "user".to_string()
                    }
                );
            }
            _ => panic!("expected And"),
        }
    }

    #[test]
    fn test_and_xpath_same_element() {
        let loc = parse_locator("tag:div@@class=test@@text:hi").unwrap();
        assert_eq!(
            loc.to_xpath().unwrap(),
            "//div[@class='test' and contains(text(),'hi')]"
        );
        assert!(loc.is_xpath() && !loc.is_css());
    }

    #[test]
    fn test_or_xpath() {
        let loc = parse_locator("@|class=a@|class=b").unwrap();
        assert!(matches!(loc, Locator::Or(_)));
        assert_eq!(loc.to_xpath().unwrap(), "//*[@class='a' or @class='b']");
    }

    #[test]
    fn test_and_startswith_and_text_contains() {
        let loc = parse_locator("tag:a@@href^http@@text:more").unwrap();
        assert_eq!(
            loc.to_xpath().unwrap(),
            "//a[starts-with(@href,'http') and contains(text(),'more')]"
        );
    }

    #[test]
    fn test_empty_locator_error() {
        let result = parse_locator("");
        assert!(result.is_err());
    }

    #[test]
    fn test_whitespace_only_locator_error() {
        let result = parse_locator("   ");
        assert!(result.is_err());
    }

    #[test]
    fn test_xpath_empty_error() {
        let result = parse_locator("xpath:");
        assert!(result.is_err());
    }

    #[test]
    fn test_css_empty_error() {
        let result = parse_locator("css:");
        assert!(result.is_err());
    }

    #[test]
    fn test_text_empty_error() {
        let result = parse_locator("text=");
        assert!(result.is_err());
    }

    #[test]
    fn test_to_css_returns_some_for_css() {
        let loc = Locator::Css("#id".to_string());
        assert_eq!(loc.to_css(), Some("#id".to_string()));
    }

    #[test]
    fn test_to_css_returns_none_for_xpath() {
        let loc = Locator::XPath("//div".to_string());
        assert!(loc.to_css().is_none());
    }

    #[test]
    fn test_to_css_returns_none_for_text() {
        let loc = Locator::Text("hello".to_string());
        assert!(loc.to_css().is_none());
    }

    #[test]
    fn test_to_xpath_css_id() {
        let loc = Locator::Css("#myid".to_string());
        assert_eq!(loc.to_xpath(), Some("//*[@id='myid']".to_string()));
    }

    #[test]
    fn test_to_xpath_css_class() {
        let loc = Locator::Css(".myclass".to_string());
        let xp = loc.to_xpath().unwrap();
        assert!(xp.contains("contains") && xp.contains("@class"));
    }

    #[test]
    fn test_to_xpath_text() {
        let loc = Locator::Text("hello".to_string());
        assert_eq!(loc.to_xpath(), Some("//*[text()='hello']".to_string()));
    }

    #[test]
    fn test_to_xpath_text_contains() {
        let loc = Locator::TextContains("hello".to_string());
        assert_eq!(
            loc.to_xpath(),
            Some("//*[contains(text(),'hello')]".to_string())
        );
    }

    #[test]
    fn test_to_xpath_attr_equals() {
        let loc = Locator::AttrEquals {
            attr: "class".to_string(),
            value: "btn".to_string(),
        };
        assert_eq!(loc.to_xpath(), Some("//*[@class='btn']".to_string()));
    }

    #[test]
    fn test_to_xpath_attr_contains() {
        let loc = Locator::AttrContains {
            attr: "class".to_string(),
            value: "btn".to_string(),
        };
        assert_eq!(
            loc.to_xpath(),
            Some("//*[contains(@class,'btn')]".to_string())
        );
    }

    #[test]
    fn test_locator_to_selector_css() {
        let loc = Locator::Css("div > p".to_string());
        assert_eq!(locator_to_selector(&loc).unwrap(), "div > p");
    }

    #[test]
    fn test_locator_to_selector_xpath() {
        let loc = Locator::XPath("//div".to_string());
        assert_eq!(locator_to_selector(&loc).unwrap(), "xpath://div");
    }

    #[test]
    fn test_locator_to_selector_text() {
        let loc = Locator::Text("Login".to_string());
        assert_eq!(
            locator_to_selector(&loc).unwrap(),
            "xpath://*[text()='Login']"
        );
    }

    #[test]
    fn test_into_locator_str() {
        use super::IntoLocator;
        let loc = "#test".to_locator().unwrap();
        assert_eq!(loc, Locator::Css("#test".to_string()));
    }

    #[test]
    fn test_into_locator_string() {
        use super::IntoLocator;
        let s = String::from(".cls");
        let loc = s.to_locator().unwrap();
        assert_eq!(loc, Locator::Css(".cls".to_string()));
    }

    #[test]
    fn test_into_locator_locator() {
        use super::IntoLocator;
        let original = Locator::XPath("//div".to_string());
        let cloned = original.to_locator().unwrap();
        assert_eq!(original, cloned);
    }
}