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
//! Page event handler methods.
//!
//! This module contains the `impl Page` block with methods for setting up
//! event handlers (on_dialog, on_console, etc.) and waiting for events.
use std::time::Duration;
use super::super::Page;
use super::super::console::ConsoleMessage;
use super::super::dialog::Dialog;
use super::super::download::Download;
use super::super::file_chooser::FileChooser;
use super::super::frame::Frame;
use super::super::page_error::PageError as PageErrorInfo;
use crate::error::{LocatorError, PageError};
/// Default timeout for navigation and event waiting.
const DEFAULT_NAVIGATION_TIMEOUT: Duration = Duration::from_secs(30);
impl Page {
// =========================================================================
// Dialog Handling Methods
// =========================================================================
/// Set a handler for browser dialogs (alert, confirm, prompt, beforeunload).
///
/// The handler will be called whenever a dialog appears. If no handler is
/// set, dialogs are automatically dismissed.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
/// use viewpoint_core::DialogType;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// // Accept all dialogs
/// page.on_dialog(|dialog| async move {
/// println!("Dialog: {:?} - {}", dialog.type_(), dialog.message());
/// dialog.accept().await
/// }).await;
///
/// // Handle prompt with custom text
/// page.on_dialog(|dialog| async move {
/// if matches!(dialog.type_(), DialogType::Prompt) {
/// dialog.accept_with_text("my answer").await
/// } else {
/// dialog.accept().await
/// }
/// }).await;
/// # Ok(())
/// # }
/// ```
pub async fn on_dialog<F, Fut>(&self, handler: F)
where
F: Fn(Dialog) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<(), PageError>> + Send + 'static,
{
self.event_manager.set_dialog_handler(handler).await;
}
/// Remove the dialog handler.
///
/// After calling this, dialogs will be automatically dismissed.
pub async fn off_dialog(&self) {
self.event_manager.remove_dialog_handler().await;
}
// =========================================================================
// Console Event Methods
// =========================================================================
/// Set a handler for console messages (console.log, console.error, etc.).
///
/// The handler will be called whenever JavaScript code logs to the console.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
/// use viewpoint_core::page::console::ConsoleMessageType;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// page.on_console(|message| async move {
/// println!("[{:?}] {}", message.type_(), message.text());
/// }).await;
///
/// // Filter by message type
/// page.on_console(|message| async move {
/// if matches!(message.type_(), ConsoleMessageType::Error) {
/// eprintln!("Console error: {}", message.text());
/// }
/// }).await;
/// # Ok(())
/// # }
/// ```
pub async fn on_console<F, Fut>(&self, handler: F)
where
F: Fn(ConsoleMessage) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
self.event_manager.set_console_handler(handler).await;
}
/// Remove the console message handler.
pub async fn off_console(&self) {
self.event_manager.remove_console_handler().await;
}
// =========================================================================
// Page Error Event Methods
// =========================================================================
/// Set a handler for page errors (uncaught exceptions).
///
/// The handler will be called whenever an uncaught JavaScript exception occurs.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// page.on_pageerror(|error| async move {
/// eprintln!("Page error: {}", error.message());
/// if let Some(stack) = error.stack() {
/// eprintln!("Stack trace:\n{}", stack);
/// }
/// }).await;
/// # Ok(())
/// # }
/// ```
pub async fn on_pageerror<F, Fut>(&self, handler: F)
where
F: Fn(PageErrorInfo) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
self.event_manager.set_pageerror_handler(handler).await;
}
/// Remove the page error handler.
pub async fn off_pageerror(&self) {
self.event_manager.remove_pageerror_handler().await;
}
// =========================================================================
// Frame Event Methods
// =========================================================================
/// Set a handler for frame attached events.
///
/// The handler will be called whenever a new frame is attached to the page,
/// typically when an `<iframe>` is added to the DOM.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// page.on_frameattached(|frame| async move {
/// println!("Frame attached: {}", frame.url());
/// }).await;
/// # Ok(())
/// # }
/// ```
pub async fn on_frameattached<F, Fut>(&self, handler: F)
where
F: Fn(Frame) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
self.event_manager.set_frameattached_handler(handler).await;
}
/// Remove the frame attached handler.
pub async fn off_frameattached(&self) {
self.event_manager.remove_frameattached_handler().await;
}
/// Set a handler for frame navigated events.
///
/// The handler will be called whenever a frame navigates to a new URL.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// page.on_framenavigated(|frame| async move {
/// println!("Frame navigated to: {}", frame.url());
/// }).await;
/// # Ok(())
/// # }
/// ```
pub async fn on_framenavigated<F, Fut>(&self, handler: F)
where
F: Fn(Frame) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
self.event_manager.set_framenavigated_handler(handler).await;
}
/// Remove the frame navigated handler.
pub async fn off_framenavigated(&self) {
self.event_manager.remove_framenavigated_handler().await;
}
/// Set a handler for frame detached events.
///
/// The handler will be called whenever a frame is detached from the page,
/// typically when an `<iframe>` is removed from the DOM.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// page.on_framedetached(|frame| async move {
/// println!("Frame detached: {}", frame.id());
/// }).await;
/// # Ok(())
/// # }
/// ```
pub async fn on_framedetached<F, Fut>(&self, handler: F)
where
F: Fn(Frame) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
self.event_manager.set_framedetached_handler(handler).await;
}
/// Remove the frame detached handler.
pub async fn off_framedetached(&self) {
self.event_manager.remove_framedetached_handler().await;
}
// =========================================================================
// Expect Methods (Wait for events triggered by actions)
// =========================================================================
/// Wait for a console message triggered by an action.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// let message = page.expect_console(|| async {
/// page.locator("#log-button").click().await?;
/// Ok(())
/// }).await?;
///
/// println!("Console message: {}", message.text());
/// # Ok(())
/// # }
/// ```
pub async fn expect_console<F, Fut>(&self, action: F) -> Result<ConsoleMessage, PageError>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<(), LocatorError>>,
{
let timeout = DEFAULT_NAVIGATION_TIMEOUT;
let console_future = self.event_manager.wait_for_console(timeout);
// Perform the action
action()
.await
.map_err(|e| PageError::EvaluationFailed(e.to_string()))?;
// Wait for the console message
console_future.await
}
/// Wait for a page error triggered by an action.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// let error = page.expect_pageerror(|| async {
/// page.locator("#trigger-error").click().await?;
/// Ok(())
/// }).await?;
///
/// println!("Page error: {}", error.message());
/// # Ok(())
/// # }
/// ```
pub async fn expect_pageerror<F, Fut>(&self, action: F) -> Result<PageErrorInfo, PageError>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<(), LocatorError>>,
{
let timeout = DEFAULT_NAVIGATION_TIMEOUT;
let pageerror_future = self.event_manager.wait_for_pageerror(timeout);
// Perform the action
action()
.await
.map_err(|e| PageError::EvaluationFailed(e.to_string()))?;
// Wait for the page error
pageerror_future.await
}
// =========================================================================
// Download Handling Methods
// =========================================================================
/// Set a handler for file downloads.
///
/// The handler will be called whenever a download starts.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// page.on_download(|mut download| async move {
/// let path = download.path().await.unwrap();
/// println!("Downloaded: {}", path.display());
/// }).await;
/// # Ok(())
/// # }
/// ```
pub async fn on_download<F, Fut>(&self, handler: F)
where
F: Fn(Download) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
// Enable downloads first
let _ = self.event_manager.set_download_behavior(true).await;
self.event_manager.set_download_handler(handler).await;
}
/// Wait for a download triggered by an action.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// let mut download = page.expect_download(|| async {
/// page.locator("a.download").click().await?;
/// Ok(())
/// }).await?;
///
/// download.save_as("./my-file.pdf").await?;
/// # Ok(())
/// # }
/// ```
pub async fn expect_download<F, Fut>(&self, action: F) -> Result<Download, PageError>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<(), LocatorError>>,
{
// Enable downloads first
self.event_manager.set_download_behavior(true).await?;
// Register the download waiter BEFORE performing the action
// This ensures we don't miss the download event due to race conditions
let timeout = DEFAULT_NAVIGATION_TIMEOUT;
let download_rx = self.event_manager.register_download_waiter().await;
// Perform the action that triggers the download
action()
.await
.map_err(|e| PageError::EvaluationFailed(e.to_string()))?;
// Now await the download with timeout
self.event_manager
.await_download_waiter(download_rx, timeout)
.await
}
// =========================================================================
// File Chooser Handling Methods
// =========================================================================
/// Set whether to intercept file chooser dialogs.
///
/// When enabled, file chooser dialogs will be intercepted and the
/// `on_filechooser` handler will be called instead of showing the
/// native file picker.
pub async fn set_intercept_file_chooser(&self, enabled: bool) -> Result<(), PageError> {
self.event_manager.set_intercept_file_chooser(enabled).await
}
/// Set a handler for file chooser dialogs.
///
/// You must call `set_intercept_file_chooser(true)` before using this.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// page.set_intercept_file_chooser(true).await?;
/// page.on_filechooser(|chooser| async move {
/// chooser.set_files(&["./upload.txt"]).await.unwrap();
/// }).await;
/// # Ok(())
/// # }
/// ```
pub async fn on_filechooser<F, Fut>(&self, handler: F)
where
F: Fn(FileChooser) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
self.event_manager.set_file_chooser_handler(handler).await;
}
/// Wait for a file chooser triggered by an action.
///
/// You must call `set_intercept_file_chooser(true)` before using this.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
/// page.set_intercept_file_chooser(true).await?;
/// let chooser = page.expect_file_chooser(|| async {
/// page.locator("input[type=file]").click().await?;
/// Ok(())
/// }).await?;
///
/// chooser.set_files(&["./upload.txt"]).await?;
/// # Ok(())
/// # }
/// ```
pub async fn expect_file_chooser<F, Fut>(&self, action: F) -> Result<FileChooser, PageError>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<(), LocatorError>>,
{
let timeout = DEFAULT_NAVIGATION_TIMEOUT;
let chooser_future = self.event_manager.wait_for_file_chooser(timeout);
// Perform the action
action()
.await
.map_err(|e| PageError::EvaluationFailed(e.to_string()))?;
// Wait for the file chooser
chooser_future.await
}
}