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
//! File handling methods for locators.
//!
//! Methods for setting files on `<input type="file">` elements.
use tracing::{debug, instrument};
use super::Locator;
use crate::error::LocatorError;
impl Locator<'_> {
/// Set files on an `<input type="file">` element.
///
/// This is the recommended way to upload files. Use an empty slice to clear
/// the file selection.
///
/// # Arguments
///
/// * `files` - Paths to the files to upload. Pass an empty slice to clear.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::Page;
///
/// # async fn example(page: &Page) -> Result<(), viewpoint_core::CoreError> {
/// // Set a single file
/// page.locator("input[type=file]").set_input_files(&["./upload.txt"]).await?;
///
/// // Set multiple files
/// page.locator("input[type=file]").set_input_files(&["file1.txt", "file2.txt"]).await?;
///
/// // Clear the file selection
/// page.locator("input[type=file]").set_input_files::<&str>(&[]).await?;
/// # Ok(())
/// # }
/// ```
#[instrument(level = "debug", skip(self, files), fields(selector = ?self.selector, file_count = files.len()))]
pub async fn set_input_files<P: AsRef<std::path::Path>>(
&self,
files: &[P],
) -> Result<(), LocatorError> {
self.wait_for_actionable().await?;
let file_paths: Vec<String> = files
.iter()
.map(|p| p.as_ref().to_string_lossy().into_owned())
.collect();
debug!("Setting {} files on file input", file_paths.len());
// Get the element's backend node ID via JavaScript
let js = format!(
r"(function() {{
const elements = {selector};
if (elements.length === 0) return {{ found: false, error: 'Element not found' }};
const el = elements[0];
if (el.tagName.toLowerCase() !== 'input' || el.type !== 'file') {{
return {{ found: false, error: 'Element is not a file input' }};
}}
return {{ found: true, isMultiple: el.multiple }};
}})()",
selector = self.selector.to_js_expression()
);
let result = self.evaluate_js(&js).await?;
let found = result
.get("found")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
if !found {
let error = result
.get("error")
.and_then(|v| v.as_str())
.unwrap_or("Unknown error");
return Err(LocatorError::EvaluationError(error.to_string()));
}
let is_multiple = result
.get("isMultiple")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
if !is_multiple && file_paths.len() > 1 {
return Err(LocatorError::EvaluationError(
"Cannot set multiple files on a single file input".to_string(),
));
}
// Use Runtime.evaluate to get the element object ID
let get_object_js = format!(
r"(function() {{
const elements = {selector};
return elements[0];
}})()",
selector = self.selector.to_js_expression()
);
let params = viewpoint_cdp::protocol::runtime::EvaluateParams {
expression: get_object_js,
object_group: Some("viewpoint-file-input".to_string()),
include_command_line_api: None,
silent: Some(true),
context_id: None,
return_by_value: Some(false),
await_promise: Some(false),
};
let result: viewpoint_cdp::protocol::runtime::EvaluateResult = self
.page
.connection()
.send_command(
"Runtime.evaluate",
Some(params),
Some(self.page.session_id()),
)
.await?;
let object_id = result.result.object_id.ok_or_else(|| {
LocatorError::EvaluationError("Failed to get element object ID".to_string())
})?;
// Set the files using DOM.setFileInputFiles
self.page
.connection()
.send_command::<_, serde_json::Value>(
"DOM.setFileInputFiles",
Some(viewpoint_cdp::protocol::dom::SetFileInputFilesParams {
files: file_paths,
node_id: None,
backend_node_id: None,
object_id: Some(object_id),
}),
Some(self.page.session_id()),
)
.await?;
Ok(())
}
/// Set files on a file input element from memory buffers.
///
/// This is useful when you want to upload files without having them on disk,
/// such as dynamically generated content or test data.
///
/// # Example
///
/// ```no_run
/// use viewpoint_core::{Page, FilePayload};
///
/// # async fn example(page: &Page) -> Result<(), viewpoint_core::CoreError> {
/// // Upload a text file from memory
/// let payload = FilePayload::new("test.txt", "text/plain", b"Hello, World!".to_vec());
/// page.locator("input[type=file]").set_input_files_from_buffer(&[payload]).await?;
///
/// // Upload multiple files
/// let file1 = FilePayload::from_text("doc1.txt", "Content 1");
/// let file2 = FilePayload::new("data.json", "application/json", r#"{"key": "value"}"#.as_bytes().to_vec());
/// page.locator("input[type=file]").set_input_files_from_buffer(&[file1, file2]).await?;
///
/// // Clear files
/// page.locator("input[type=file]").set_input_files_from_buffer(&[]).await?;
/// # Ok(())
/// # }
/// ```
#[instrument(level = "debug", skip(self, files), fields(selector = ?self.selector, file_count = files.len()))]
pub async fn set_input_files_from_buffer(
&self,
files: &[crate::page::FilePayload],
) -> Result<(), LocatorError> {
use base64::{Engine, engine::general_purpose::STANDARD};
self.wait_for_actionable().await?;
debug!("Setting {} files from buffer on file input", files.len());
// Get the element's info via JavaScript
let js = format!(
r"(function() {{
const elements = {selector};
if (elements.length === 0) return {{ found: false, error: 'Element not found' }};
const el = elements[0];
if (el.tagName.toLowerCase() !== 'input' || el.type !== 'file') {{
return {{ found: false, error: 'Element is not a file input' }};
}}
return {{ found: true, isMultiple: el.multiple }};
}})()",
selector = self.selector.to_js_expression()
);
let result = self.evaluate_js(&js).await?;
let found = result
.get("found")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
if !found {
let error = result
.get("error")
.and_then(|v| v.as_str())
.unwrap_or("Unknown error");
return Err(LocatorError::EvaluationError(error.to_string()));
}
let is_multiple = result
.get("isMultiple")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
if !is_multiple && files.len() > 1 {
return Err(LocatorError::EvaluationError(
"Cannot set multiple files on a single file input".to_string(),
));
}
// Build the file data array for JavaScript
let file_data: Vec<serde_json::Value> = files
.iter()
.map(|f| {
serde_json::json!({
"name": f.name,
"mimeType": f.mime_type,
"data": STANDARD.encode(&f.buffer),
})
})
.collect();
let file_data_json = serde_json::to_string(&file_data)
.map_err(|e| LocatorError::EvaluationError(e.to_string()))?;
// Use JavaScript to create File objects and set them on the input
let set_files_js = format!(
r"(async function() {{
const elements = {selector};
if (elements.length === 0) return {{ success: false, error: 'Element not found' }};
const input = elements[0];
const fileData = {file_data};
// Create File objects from the data
const files = await Promise.all(fileData.map(async (fd) => {{
// Decode base64 to binary
const binaryString = atob(fd.data);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {{
bytes[i] = binaryString.charCodeAt(i);
}}
return new File([bytes], fd.name, {{ type: fd.mimeType }});
}}));
// Create a DataTransfer to hold the files
const dataTransfer = new DataTransfer();
for (const file of files) {{
dataTransfer.items.add(file);
}}
// Set the files on the input
input.files = dataTransfer.files;
// Dispatch change event
input.dispatchEvent(new Event('change', {{ bubbles: true }}));
input.dispatchEvent(new Event('input', {{ bubbles: true }}));
return {{ success: true }};
}})()",
selector = self.selector.to_js_expression(),
file_data = file_data_json
);
let params = viewpoint_cdp::protocol::runtime::EvaluateParams {
expression: set_files_js,
object_group: Some("viewpoint-file-input".to_string()),
include_command_line_api: None,
silent: Some(false),
context_id: None,
return_by_value: Some(true),
await_promise: Some(true),
};
let result: viewpoint_cdp::protocol::runtime::EvaluateResult = self
.page
.connection()
.send_command(
"Runtime.evaluate",
Some(params),
Some(self.page.session_id()),
)
.await?;
if let Some(exception) = result.exception_details {
return Err(LocatorError::EvaluationError(format!(
"Failed to set files: {}",
exception.text
)));
}
if let Some(value) = result.result.value {
let success = value
.get("success")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
if !success {
let error = value
.get("error")
.and_then(|v| v.as_str())
.unwrap_or("Unknown error");
return Err(LocatorError::EvaluationError(error.to_string()));
}
}
Ok(())
}
}