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
// Test Server - Local HTTP server for integration tests
//
// Provides a local HTTP server serving test HTML pages.
// This enables deterministic, offline integration testing.

// Note: Functions appear "unused" because each test binary compiles separately,
// but they ARE used across multiple test files. Suppress false-positive warnings.
#![allow(dead_code)]

use axum::{
    Router,
    body::Body,
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    http::{HeaderMap, Response, StatusCode},
    routing::get,
};
use std::net::SocketAddr;
use tokio::task::JoinHandle;

/// Test server handle
pub struct TestServer {
    addr: SocketAddr,
    handle: JoinHandle<()>,
}

impl TestServer {
    /// Start the test server on a random available port
    pub async fn start() -> Self {
        let app = Router::new()
            .route("/", get(index_page))
            .route("/button.html", get(button_page))
            .route("/form.html", get(form_page))
            .route("/input.html", get(input_page))
            .route("/dblclick.html", get(dblclick_page))
            .route("/keyboard.html", get(keyboard_page))
            .route("/locator.html", get(locator_page))
            .route("/locators.html", get(locators_page))
            .route("/checkbox.html", get(checkbox_page))
            .route("/hover.html", get(hover_page))
            .route("/select.html", get(select_page))
            .route("/upload.html", get(upload_page))
            .route("/keyboard_mouse.html", get(keyboard_mouse_page))
            .route("/click_options.html", get(click_options_page))
            .route("/text.html", get(text_page))
            .route("/websocket.html", get(websocket_page))
            .route("/anchors.html", get(anchors_page))
            .route("/filter.html", get(filter_page))
            .route("/ws", get(ws_handler))
            .route("/frame.html", get(frame_handler))
            .route("/focus_blur.html", get(focus_blur_page))
            .route("/all_texts.html", get(all_texts_page))
            .route("/echo-headers", get(echo_headers_page))
            .route("/drag_drop.html", get(drag_drop_page))
            .route("/wait_for.html", get(wait_for_page))
            .route("/api/data.json", get(json_data_endpoint))
            .route("/redirect", get(redirect_handler))
            .route("/iframe-test.html", get(iframe_test_page))
            .route("/iframe-content.html", get(iframe_content_page))
            .route("/iframe-content2.html", get(iframe_content2_page))
            .route("/nested-iframe.html", get(nested_iframe_page))
            .route("/inner-iframe.html", get(inner_iframe_page));

        // Bind to port 0 to get any available port
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("Failed to bind test server");

        let addr = listener.local_addr().expect("Failed to get local address");

        let handle = tokio::spawn(async move {
            axum::serve(listener, app)
                .await
                .expect("Test server failed");
        });

        TestServer { addr, handle }
    }

    /// Get the base URL of the test server
    pub fn url(&self) -> String {
        format!("http://{}", self.addr)
    }

    /// Shutdown the test server
    pub fn shutdown(self) {
        self.handle.abort();
    }
}

// Test HTML pages

async fn index_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Test Index</title></head>
<body>
  <h1>Test Page</h1>
  <p>This is a test paragraph.</p>
  <a href="/button.html">Go to button page</a>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn button_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Button Test</title></head>
<body>
  <button id="btn" onclick="this.textContent='clicked'">Click me</button>
  <button id="btn2" onclick="this.textContent='clicked 2'">Click me 2</button>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn form_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Form Test</title></head>
<body>
  <form>
    <input type="text" id="name" name="name" />
    <textarea id="bio" name="bio"></textarea>
    <input type="submit" value="Submit" />
  </form>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn input_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Input Test</title></head>
<body>
  <input type="text" id="input" value="initial" />
  <input type="text" id="empty" value="" />
</body>
</html>"#,
        ))
        .unwrap()
}

async fn dblclick_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Double Click Test</title></head>
<body>
  <div id="target" ondblclick="this.textContent='double clicked'">Double click me</div>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn keyboard_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Keyboard Test</title></head>
<body>
  <input type="text" id="input" onkeydown="if(event.key==='Enter') this.value='submitted'" />
</body>
</html>"#,
        ))
        .unwrap()
}

async fn locator_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Locator Test</title></head>
<body>
  <h1>Test Page</h1>
  <p id="p1">First paragraph</p>
  <p id="p2">Second paragraph</p>
  <p id="p3">Third paragraph</p>
  <div class="container">
    <span id="nested">Nested element</span>
  </div>
  <div id="hidden" style="display: none;">Hidden element</div>
  <button>Submit</button>
  <button>Submit Order</button>
  <span>Hello World</span>
  <span>hello world</span>
  <div class="text-container">
    <span>Inner Text</span>
  </div>
  <label for="email">Email Address</label>
  <input id="email" type="text" placeholder="Enter your email" />
  <label for="name">Full Name</label>
  <input id="name" type="text" placeholder="Enter your name" />
  <img src="logo.png" alt="Company Logo" />
  <img src="banner.png" alt="Welcome Banner" />
  <span title="More Info">Details</span>
  <span title="More Info Expanded">Extended Details</span>
  <button data-testid="submit-btn">Submit Form</button>
  <button data-testid="cancel-btn">Cancel</button>
  <!-- get_by_role test elements -->
  <nav aria-label="Main">
    <a href="/home">Home</a>
    <a href="/about">About</a>
  </nav>
  <h2>Section Title</h2>
  <h3>Subsection</h3>
  <input type="checkbox" aria-label="I agree" checked />
  <input type="checkbox" aria-label="Subscribe" />
  <button disabled>Disabled Button</button>
  <div role="alert">Important message</div>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn locators_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Locators Test</title></head>
<body>
  <h1>Test Page</h1>
  <p id="p1">First paragraph</p>
  <p id="p2">Second paragraph</p>
  <p id="p3">Third paragraph</p>
  <p id="p4">Fourth paragraph</p>
  <div class="container">
    <span id="nested">Nested element</span>
  </div>
  <div id="hidden" style="display: none;">Hidden element</div>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn checkbox_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Checkbox Test</title></head>
<body>
  <input type="checkbox" id="checkbox" />
  <label for="checkbox">Unchecked checkbox</label>
  <br />
  <input type="checkbox" id="checked-checkbox" checked />
  <label for="checked-checkbox">Checked checkbox</label>
  <br />
  <input type="radio" id="radio1" name="radio-group" />
  <label for="radio1">Radio 1</label>
  <br />
  <input type="radio" id="radio2" name="radio-group" />
  <label for="radio2">Radio 2</label>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn hover_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head>
  <title>Hover Test</title>
  <style>
    #hover-button {
      padding: 10px;
      background-color: #ccc;
    }
    #tooltip {
      display: none;
      margin-top: 10px;
      padding: 5px;
      background-color: yellow;
    }
    #hover-button:hover + #tooltip {
      display: block;
    }
  </style>
</head>
<body>
  <button id="hover-button">Hover over me</button>
  <div id="tooltip">This is a tooltip</div>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn select_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Select Test</title></head>
<body>
  <select id="single-select">
    <option value="">--Please choose an option--</option>
    <option value="apple">Apple</option>
    <option value="banana">Banana</option>
    <option value="cherry">Cherry</option>
  </select>
  <br /><br />
  <select id="multi-select" multiple>
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
    <option value="yellow">Yellow</option>
  </select>
  <br /><br />
  <select id="select-by-index">
    <option>First</option>
    <option>Second</option>
    <option>Third</option>
  </select>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn upload_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>File Upload Test</title></head>
<body>
  <input type="file" id="single-file" />
  <br /><br />
  <input type="file" id="multi-file" multiple />
  <br /><br />
  <div id="file-info"></div>
  <script>
    document.getElementById('single-file').addEventListener('change', (e) => {
      const files = Array.from(e.target.files).map(f => f.name).join(', ');
      document.getElementById('file-info').textContent = 'Single: ' + files;
    });
    document.getElementById('multi-file').addEventListener('change', (e) => {
      const files = Array.from(e.target.files).map(f => f.name).join(', ');
      document.getElementById('file-info').textContent = 'Multiple: ' + files;
    });
  </script>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn keyboard_mouse_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Keyboard and Mouse Test</title></head>
<body>
  <h1>Keyboard and Mouse Testing</h1>

  <input type="text" id="keyboard-input" placeholder="Type here" />
  <div id="keyboard-result"></div>

  <div id="clickable" style="width: 300px; height: 300px; background-color: lightblue; margin-top: 20px;">
    Click or double-click me
  </div>
  <div id="mouse-result"></div>
  <div id="mouse-coords"></div>

  <script>
    // Keyboard event handlers
    document.getElementById('keyboard-input').addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        document.getElementById('keyboard-result').textContent = 'Enter pressed';
      }
    });

    // Mouse event handlers
    document.getElementById('clickable').addEventListener('click', (e) => {
      document.getElementById('mouse-result').textContent = 'Clicked';
    });

    document.getElementById('clickable').addEventListener('dblclick', (e) => {
      document.getElementById('mouse-result').textContent = 'Double-clicked';
    });

    document.addEventListener('mousemove', (e) => {
      document.getElementById('mouse-coords').textContent = `Mouse: (${e.clientX}, ${e.clientY})`;
    });
  </script>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn click_options_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Click Options Test</title></head>
<body>
  <button id="button">Click Me</button>
  <button id="hidden-button" style="display: none;">Hidden Button</button>
  <div id="result"></div>
  <script>
    const button = document.getElementById('button');
    const hiddenButton = document.getElementById('hidden-button');
    const result = document.getElementById('result');

    // Track all mouse events
    button.addEventListener('mousedown', (e) => {
      const buttonName = e.button === 0 ? 'left' : e.button === 1 ? 'middle' : 'right';
      result.textContent = `mousedown button:${buttonName} shiftKey:${e.shiftKey} ctrlKey:${e.ctrlKey}`;
    });

    button.addEventListener('click', (e) => {
      const buttonName = e.button === 0 ? 'left' : e.button === 1 ? 'middle' : 'right';
      result.textContent = `click button:${buttonName} shiftKey:${e.shiftKey} ctrlKey:${e.ctrlKey}`;
    });

    button.addEventListener('contextmenu', (e) => {
      e.preventDefault(); // Prevent context menu
      result.textContent = `contextmenu (right) shiftKey:${e.shiftKey} ctrlKey:${e.ctrlKey}`;
    });

    button.addEventListener('auxclick', (e) => {
      const buttonName = e.button === 1 ? 'middle' : e.button === 2 ? 'right' : 'other';
      result.textContent = `auxclick button:${buttonName} shiftKey:${e.shiftKey} ctrlKey:${e.ctrlKey}`;
    });

    button.addEventListener('dblclick', (e) => {
      result.textContent = 'dblclick';
    });

    hiddenButton.addEventListener('click', (e) => {
      result.textContent = 'hidden-button-clicked';
    });
  </script>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn text_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Text Assertions Test</title></head>
<body>
  <h1>Welcome to Playwright</h1>
  <p id="whitespace">
    Text with whitespace
  </p>
  <p id="long-text">This is the beginning and middle of the text and the end.</p>
  <input type="text" id="name-input" value="John Doe" />
  <input type="text" id="empty-input" value="" />
</body>
</html>"#,
        ))
        .unwrap()
}

async fn websocket_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>WebSocket Test</title></head>
<body>
  <h1>WebSocket Test</h1>
  <div id="log"></div>
  <script>
    const log = document.getElementById('log');
    const ws = new WebSocket('ws://' + location.host + '/ws');

    ws.onopen = () => {
        log.textContent += 'open\n';
        ws.send('Hello Server');
    };

    ws.onmessage = (event) => {
        log.textContent += 'received: ' + event.data + '\n';
    };

    ws.onclose = () => {
        log.textContent += 'closed\n';
    };
  </script>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn anchors_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            "<!DOCTYPE html>
<html>
<head><title>Anchor Navigation Test</title></head>
<body>
  <h1>Anchor Navigation Test Page</h1>

  <nav>
    <a id=\"link-to-section1\" href=\"#section1\">Go to Section 1</a> |
    <a id=\"link-to-section2\" href=\"#section2\">Go to Section 2</a> |
    <a id=\"link-to-section3\" href=\"#section3\">Go to Section 3</a>
  </nav>

  <section id=\"section1\" style=\"margin-top: 50px; padding: 20px; background: #f0f0f0;\">
    <h2>Section 1</h2>
    <p>This is section 1. The URL should include #section1 when you navigate here.</p>
  </section>

  <section id=\"section2\" style=\"margin-top: 50px; padding: 20px; background: #e0e0e0;\">
    <h2>Section 2</h2>
    <p>This is section 2. The URL should include #section2 when you navigate here.</p>
  </section>

  <section id=\"section3\" style=\"margin-top: 50px; padding: 20px; background: #d0d0d0;\">
    <h2>Section 3</h2>
    <p>This is section 3. The URL should include #section3 when you navigate here.</p>
  </section>
</body>
</html>",
        ))
        .unwrap()
}

async fn filter_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Filter Test</title></head>
<body>
  <nav>
    <a class="nav-link" href="/home">Home</a>
    <a class="nav-link" href="/about">About</a>
  </nav>
  <table>
    <thead>
      <tr><th>Fruit</th><th>Price</th><th>Action</th></tr>
    </thead>
    <tbody>
      <!-- Row 1: Apple with action button -->
      <tr class="data-row">
        <td>Apple</td>
        <td>$1.00</td>
        <td><button class="action-btn">Buy</button></td>
      </tr>
      <!-- Row 2: Banana with action button -->
      <tr class="data-row">
        <td>Banana</td>
        <td>$0.50</td>
        <td><button class="action-btn">Buy</button></td>
      </tr>
      <!-- Row 3: Cherry without action button (out of stock) -->
      <tr class="data-row">
        <td>Cherry</td>
        <td>$2.00</td>
        <td><span class="out-of-stock">Out of stock</span></td>
      </tr>
    </tbody>
  </table>
  <button class="delete-btn">Delete All</button>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn focus_blur_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Focus Blur Test</title></head>
<body>
  <input type="text" id="input1" />
  <input type="text" id="input2" />
  <button id="btn">Button</button>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn all_texts_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>All Texts Test</title></head>
<body>
  <li class="item">Alpha</li>
  <li class="item">Beta</li>
  <li class="item">Gamma</li>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn drag_drop_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head>
  <title>Drag and Drop Test</title>
  <style>
    #source {
      width: 80px; height: 80px;
      background: steelblue;
      position: absolute; top: 50px; left: 50px;
      cursor: grab;
    }
    #target {
      width: 120px; height: 120px;
      background: lightgreen;
      position: absolute; top: 50px; left: 250px;
      border: 2px dashed #666;
    }
    #target.dropped { background: gold; }
    #result { position: absolute; top: 220px; left: 50px; }
  </style>
</head>
<body>
  <div id="source" draggable="true">Drag me</div>
  <div id="target">Drop here</div>
  <div id="result">no drop</div>
  <script>
    var source = document.getElementById('source');
    var target = document.getElementById('target');
    var result = document.getElementById('result');

    source.addEventListener('dragstart', function(e) {
      e.dataTransfer.setData('text/plain', 'dragged');
    });
    target.addEventListener('dragover', function(e) {
      e.preventDefault();
    });
    target.addEventListener('drop', function(e) {
      e.preventDefault();
      target.classList.add('dropped');
      result.textContent = 'dropped';
    });
  </script>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn wait_for_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>Wait For Test</title></head>
<body>
  <div id="visible-element" style="display: block;">I am visible</div>
  <div id="hidden-element" style="display: none;">I am hidden</div>
  <div id="container"></div>
  <script>
    // showElement: makes #hidden-element visible after a delay
    window.showElement = function(delayMs) {
      setTimeout(function() {
        document.getElementById('hidden-element').style.display = 'block';
      }, delayMs);
    };
    // hideElement: hides #visible-element after a delay
    window.hideElement = function(delayMs) {
      setTimeout(function() {
        document.getElementById('visible-element').style.display = 'none';
      }, delayMs);
    };
    // appendElement: appends a new div#dynamic-element after a delay
    window.appendElement = function(delayMs) {
      setTimeout(function() {
        var el = document.createElement('div');
        el.id = 'dynamic-element';
        el.textContent = 'I was appended';
        document.getElementById('container').appendChild(el);
      }, delayMs);
    };
    // removeElement: removes #visible-element after a delay
    window.removeElement = function(delayMs) {
      setTimeout(function() {
        var el = document.getElementById('visible-element');
        if (el) el.parentNode.removeChild(el);
      }, delayMs);
    };
  </script>
</body>
</html>"#,
        ))
        .unwrap()
}

async fn ws_handler(ws: WebSocketUpgrade) -> impl axum::response::IntoResponse {
    ws.on_upgrade(handle_socket)
}

async fn frame_handler() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(r#"<iframe src="/button.html"></iframe>"#))
        .unwrap()
}

async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        if let Ok(msg) = msg {
            if let Message::Text(text) = msg {
                // Echo back
                let _ = socket.send(Message::Text(text)).await;
            }
        } else {
            // Client likely disconnected
            return;
        }
    }
}

/// Returns all request headers as a JSON object so tests can inspect them.
async fn echo_headers_page(headers: HeaderMap) -> Response<Body> {
    let mut map = serde_json::Map::new();
    for (name, value) in &headers {
        if let Ok(v) = value.to_str() {
            map.insert(
                name.as_str().to_lowercase(),
                serde_json::Value::String(v.to_string()),
            );
        }
    }
    let json = serde_json::to_string(&map).unwrap_or_else(|_| "{}".to_string());
    let html = format!(
        r#"<!DOCTYPE html>
<html>
<head><title>Echo Headers</title></head>
<body>
<pre id="headers">{}</pre>
</body>
</html>"#,
        html_escape(&json)
    );
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(html))
        .unwrap()
}

/// Returns a simple JSON response for testing response.json()
async fn json_data_endpoint() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "application/json")
        .body(Body::from(
            r#"{"status":"ok","message":"hello from test server"}"#,
        ))
        .unwrap()
}

/// Page with two named iframes for FrameLocator testing
async fn iframe_test_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r##"<!DOCTYPE html>
<html>
<head><title>IFrame Test</title></head>
<body>
  <h1>Main Page</h1>
  <iframe name="content" src="/iframe-content.html" id="frame1" width="400" height="300"></iframe>
  <iframe name="secondary" src="/iframe-content2.html" id="frame2" width="400" height="300"></iframe>
</body>
</html>"##,
        ))
        .unwrap()
}

/// Content page loaded inside iframes — has elements for all get_by_* methods
async fn iframe_content_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r##"<!DOCTYPE html>
<html>
<head><title>IFrame Content</title></head>
<body>
  <h1>Inside Frame</h1>
  <button id="frame-btn" onclick="this.textContent='clicked'">Click Me</button>
  <label for="frame-input">Email</label>
  <input id="frame-input" type="text" placeholder="Enter email" />
  <img src="logo.png" alt="Frame Logo" />
  <span title="Frame Tooltip">Info</span>
  <button data-testid="frame-submit">Submit</button>
  <nav>
    <a href="#" role="link">Frame Link</a>
  </nav>
</body>
</html>"##,
        ))
        .unwrap()
}

/// Second iframe content — distinct from first for multi-iframe tests
async fn iframe_content2_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r#"<!DOCTYPE html>
<html>
<head><title>IFrame Content 2</title></head>
<body>
  <h1>Second Frame</h1>
  <button id="btn2" onclick="this.textContent='clicked2'">Other Button</button>
</body>
</html>"#,
        ))
        .unwrap()
}

/// Page with a nested iframe (iframe within iframe)
async fn nested_iframe_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r##"<!DOCTYPE html>
<html>
<head><title>Nested IFrame</title></head>
<body>
  <h1>Outer Page</h1>
  <iframe id="outer" src="/inner-iframe.html" width="500" height="400"></iframe>
</body>
</html>"##,
        ))
        .unwrap()
}

/// Inner iframe page that itself contains an iframe
async fn inner_iframe_page() -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/html")
        .body(Body::from(
            r##"<!DOCTYPE html>
<html>
<head><title>Inner IFrame</title></head>
<body>
  <h1>Inner Frame</h1>
  <iframe id="innermost" src="/iframe-content.html" width="300" height="200"></iframe>
</body>
</html>"##,
        ))
        .unwrap()
}

/// Redirect handler: 302 redirect to /
async fn redirect_handler() -> Response<Body> {
    Response::builder()
        .status(StatusCode::FOUND)
        .header("Location", "/")
        .body(Body::empty())
        .unwrap()
}

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}