Skip to content

Truly independent web browser

LibWeb: Implement FormData in Rust

Shannon Boothc39522d220eb
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index 59f3600a6ae..ebeaa33e56a 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -28,7 +28,8 @@ use crate::bindings::services::web_bindings_object_implements_interface;
use crate::bindings::{CallContext, WebIdlResult};
/// A USVString, a string without lone surrogates. Its UTF-16 code units are always well-formed.
-#[derive(Clone, Eq, PartialEq)]
+#[derive(Clone, Eq, PartialEq, Trace)]
+#[gc(crate = libjs_rust)]
pub(crate) struct UsvString(Utf16String);
impl UsvString {
@@ -102,6 +103,15 @@ impl UsvString {
self.0
}
+ pub(crate) fn as_utf16_string(&self) -> &Utf16String {
+ &self.0
+ }
+
+ /// https://infra.spec.whatwg.org/#javascript-string-convert
+ pub(crate) fn from_utf16_string(string: &Utf16String) -> Self {
+ Self(to_well_formed(string))
+ }
+
pub(crate) fn from_utf8(string: &str) -> Self {
Self(Utf16String::from_utf8(string))
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rs
index 841ea6ee3de..715e602148b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rs
@@ -13,7 +13,7 @@ use core::ffi::c_void;
use ak::Utf16String;
use libjs_rust::api::Vm;
-use super::blob::{Blob, BlobPropertyBag, EndingType, ForeignBytesAbi};
+use super::blob::{AnyBlob, Blob, BlobPropertyBag, EndingType, ForeignBytesAbi};
use super::file::{File, FilePropertyBag};
use super::file_list::FileList;
use crate::bindings::interface::{Inherits, Interface, Ref, allocate, cell_from_abi, cell_if_abi, cell_into_abi};
@@ -54,6 +54,20 @@ unsafe fn blob_from_abi<'a>(cell: *mut c_void) -> &'a Blob {
unsafe { object_from_abi::<File>(cell) }.parent()
}
+/// The Blob or File whose cell C++ lends.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a Blob or a File.
+pub(crate) unsafe fn any_blob_from_abi(cell: *mut c_void) -> AnyBlob {
+ // SAFETY: The caller passes a live cell.
+ if let Some(blob) = unsafe { cell_if_abi::<Blob>(cell) } {
+ return AnyBlob::Blob(blob);
+ }
+ // SAFETY: The caller passes the cell of a File.
+ AnyBlob::File(unsafe { cell_from_abi(cell) })
+}
+
/// A new Blob that refers to the bytes that C++ hands over, with the type, a raw AK::Utf16String that C++ hands over.
///
/// # Safety
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index d57aba4c099..57b4ea3aaf9 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -155,6 +155,15 @@ pub(crate) mod web_gl;
pub(crate) mod webidl;
#[cfg(not(test))]
pub(crate) mod webrtc;
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every attribute and operation as one that can throw"
+)]
+pub(crate) mod xhr;
// The generators of the build script, whose tests run with those of the crate.
#[cfg(test)]
diff --git a/Libraries/LibWeb/Bindings/Rust/src/xhr/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/xhr/exports.rs
new file mode 100644
index 00000000000..601b2835051
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/xhr/exports.rs
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The C ABI through which LibWeb's C++ creates FormData objects, reads their entry lists and creates entries.
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{JSVM, vm_from_abi};
+
+use super::form_data::{Entry, FormData, FormDataEntryValue, StringOrBlob, create_an_entry};
+use crate::bindings::conversions::UsvString;
+use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_into_abi};
+use crate::file_api::exports::any_blob_from_abi;
+
+#[repr(C)]
+pub(crate) struct EntryValueAbi {
+ file: *mut c_void,
+ string: usize,
+}
+
+#[repr(C)]
+pub(crate) struct EntryAbi {
+ name: usize,
+ value: EntryValueAbi,
+}
+
+impl EntryValueAbi {
+ fn from_value(value: &FormDataEntryValue) -> Self {
+ match value {
+ FormDataEntryValue::File(file) => Self {
+ file: cell_into_abi(*file),
+ string: 0,
+ },
+ FormDataEntryValue::USVString(string) => Self {
+ file: core::ptr::null_mut(),
+ string: string.as_utf16_string().clone().into_raw(),
+ },
+ }
+ }
+}
+
+impl EntryAbi {
+ fn from_entry((name, value): &Entry) -> Self {
+ Self {
+ name: name.as_utf16_string().clone().into_raw(),
+ value: EntryValueAbi::from_value(value),
+ }
+ }
+
+ /// The entry that C++ hands over.
+ ///
+ /// # Safety
+ ///
+ /// The entry must be one that C++ hands over: its strings are raw strings that it owns a reference to, and its file
+ /// is the live cell of a File.
+ unsafe fn into_entry(self) -> Entry {
+ // SAFETY: The caller hands over the name.
+ let name = unsafe { Utf16String::from_raw_owned(self.name) };
+ let value = if self.value.file.is_null() {
+ // SAFETY: The caller hands over the string.
+ let string = unsafe { Utf16String::from_raw_owned(self.value.string) };
+ FormDataEntryValue::USVString(UsvString::from_utf16_string(&string))
+ } else {
+ // SAFETY: The caller passes a live cell of a File.
+ FormDataEntryValue::File(unsafe { cell_from_abi(self.value.file) })
+ };
+ (UsvString::from_utf16_string(&name), value)
+ }
+}
+
+/// A new FormData whose entry list is the entries that C++ hands over.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `entries` entries that C++ hands over, whose files it keeps alive for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_form_data_create(vm: *mut JSVM, entries: ak::Span<'_, EntryAbi>) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ cell_into_abi(allocate(vm, |defer_gc| {
+ let entry_list = entries
+ .as_slice()
+ .iter()
+ .map(|entry| {
+ // SAFETY: The caller hands over the entries, each of which is read once.
+ unsafe { core::ptr::read(entry).into_entry() }
+ })
+ .collect();
+ FormData::new(defer_gc, entry_list)
+ }))
+}
+
+/// The size of the entry list of the FormData.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a FormData.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_form_data_entry_count(cell: *mut c_void) -> usize {
+ // SAFETY: The caller passes a live cell of a FormData.
+ let form_data: Ref<FormData> = unsafe { cell_from_abi(cell) };
+ form_data.entry_list().len()
+}
+
+/// The entry at the index in the entry list of the FormData. C++ owns its strings.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a FormData, and `index` less than the size of its entry list.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_form_data_entry(cell: *mut c_void, index: usize) -> EntryAbi {
+ // SAFETY: The caller passes a live cell of a FormData.
+ let form_data: Ref<FormData> = unsafe { cell_from_abi(cell) };
+ EntryAbi::from_entry(&form_data.entry_list()[index])
+}
+
+/// The value of the first entry named `name`, a raw AK::Utf16String that C++ hands over. C++ owns the string of the
+/// value.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a FormData, and `name` a raw string that C++ owns a reference to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_form_data_value_named(
+ cell: *mut c_void,
+ name: usize,
+ out_value: &mut EntryValueAbi,
+) -> bool {
+ // SAFETY: The caller passes a live cell of a FormData and hands over the name.
+ let (form_data, name): (Ref<FormData>, _) = unsafe { (cell_from_abi(cell), Utf16String::from_raw_owned(name)) };
+ let Some(value) = form_data.value_named(&UsvString::from_utf16_string(&name)) else {
+ return false;
+ };
+ *out_value = EntryValueAbi::from_value(&value);
+ true
+}
+
+/// Creates an entry with the name and the Blob or File `blob`, or the string if `blob` is null. C++ hands over the raw
+/// AK::Utf16Strings and owns those of the entry,
+/// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `name` and `string` raw strings that C++ owns a reference to, and `blob` null or the live
+/// cell of a Blob or a File.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_html_create_an_entry(
+ vm: *mut JSVM,
+ name: usize,
+ blob: *mut c_void,
+ string: usize,
+) -> EntryAbi {
+ // SAFETY: The caller passes the live VM and hands over the strings.
+ let (vm, name, string) = unsafe {
+ (
+ vm_from_abi(vm),
+ Utf16String::from_raw_owned(name),
+ Utf16String::from_raw_owned(string),
+ )
+ };
+ let value = if blob.is_null() {
+ StringOrBlob::String(string)
+ } else {
+ // SAFETY: The caller passes a live cell of a Blob or a File.
+ StringOrBlob::Blob(unsafe { any_blob_from_abi(blob) })
+ };
+ EntryAbi::from_entry(&create_an_entry(vm, &name, value, None))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/xhr/form_data.rs b/Libraries/LibWeb/Bindings/Rust/src/xhr/form_data.rs
new file mode 100644
index 00000000000..6dd4d3270ba
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/xhr/form_data.rs
@@ -0,0 +1,299 @@
+/*
+ * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! FormData, https://xhr.spec.whatwg.org/#interface-formdata
+
+use core::cell;
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{DeferGc, GcRefCell, MarkedVec, RawNativeFunctionResult, Trace, Vm};
+
+use crate::bindings::conversions::{CppInterface, UsvString};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_from_abi};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::file_api::blob::{AnyBlob, BlobPropertyBag, EndingType};
+use crate::file_api::file::{File, FilePropertyBag};
+
+unsafe extern "C" {
+ fn web_form_data_create_from_form(
+ realm: *mut c_void,
+ form: *mut c_void,
+ submitter: *mut c_void,
+ out_form_data: &mut *mut c_void,
+ ) -> RawNativeFunctionResult;
+}
+
+/// https://xhr.spec.whatwg.org/#formdataentryvalue
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum FormDataEntryValue {
+ File(Ref<File>),
+ USVString(UsvString),
+}
+
+/// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-entry
+pub(crate) type Entry = (UsvString, FormDataEntryValue);
+
+pub(crate) enum StringOrBlob {
+ String(Utf16String),
+ Blob(AnyBlob),
+}
+
+// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
+pub(crate) fn create_an_entry(vm: &Vm, name: &Utf16String, value: StringOrBlob, filename: Option<UsvString>) -> Entry {
+ // 1. Set name to the result of converting name into a scalar value string.
+ let name = UsvString::from_utf16_string(name);
+
+ let value = match value {
+ // 2. If value is a string, then set value to the result of converting value into a scalar value string.
+ StringOrBlob::String(string) => FormDataEntryValue::USVString(UsvString::from_utf16_string(&string)),
+ // 3. Otherwise:
+ StringOrBlob::Blob(blob) => {
+ // 1. If value is not a File object, then set value to a new File object, representing the same bytes, whose
+ // name attribute value is "blob".
+ let file = match blob {
+ AnyBlob::File(file) => file,
+ AnyBlob::Blob(blob) => {
+ let options = file_property_bag(blob.type_string().clone(), None);
+ let file = File::create(blob.raw_bytes().to_vec(), Utf16String::from_ascii(b"blob"), &options);
+ allocate(vm, |_| file)
+ }
+ };
+
+ // 2. If filename is given, then set value to a new File object, representing the same bytes, whose name
+ // attribute is filename.
+ let file = match filename {
+ Some(filename) => {
+ let blob = file.parent();
+ let options = file_property_bag(blob.type_string().clone(), Some(file.last_modified_value()));
+ let file = File::create(blob.raw_bytes().to_vec(), filename.into_utf16_string(), &options);
+ allocate(vm, |_| file)
+ }
+ None => file,
+ };
+
+ FormDataEntryValue::File(file)
+ }
+ };
+
+ // 4. Return an entry whose name is name and whose value is value.
+ (name, value)
+}
+
+fn file_property_bag(r#type: Utf16String, last_modified: Option<i64>) -> FilePropertyBag {
+ FilePropertyBag {
+ parent: BlobPropertyBag {
+ endings: EndingType::Transparent,
+ r#type,
+ },
+ last_modified,
+ }
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct FormData {
+ // https://xhr.spec.whatwg.org/#concept-formdata-entry-list
+ entry_list: GcRefCell<Vec<Entry>>,
+}
+
+impl Wrappable for FormData {}
+
+impl FormData {
+ pub(crate) fn new(_: &DeferGc<'_>, entry_list: Vec<Entry>) -> Self {
+ Self {
+ entry_list: GcRefCell::new(entry_list),
+ }
+ }
+
+ pub(crate) fn entry_list(&self) -> cell::Ref<'_, Vec<Entry>> {
+ self.entry_list.borrow()
+ }
+
+ // https://xhr.spec.whatwg.org/#dom-formdata
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ form: Option<CppInterface>,
+ submitter: Option<CppInterface>,
+ ) -> WebIdlResult<Ref<Self>> {
+ // 1. If form is given, then:
+ // NB: C++ runs the substeps and creates the object.
+ let Some(form) = form else {
+ return Ok(allocate(cx.vm(), |defer_gc| Self::new(defer_gc, Vec::new())));
+ };
+ let submitter = submitter.map_or(core::ptr::null_mut(), |submitter| submitter.wrapper().as_ptr().cast());
+ let mut form_data = core::ptr::null_mut();
+ // SAFETY: The realm and the wrappers are live.
+ unsafe {
+ web_form_data_create_from_form(
+ cx.realm().as_ptr().cast(),
+ form.wrapper().as_ptr().cast(),
+ submitter,
+ &mut form_data,
+ )
+ }
+ .into_completion()?;
+ // SAFETY: C++ creates a FormData when it does not throw.
+ Ok(unsafe { cell_from_abi(form_data) })
+ }
+
+ // https://xhr.spec.whatwg.org/#dom-formdata-append
+ pub(crate) fn append(&self, cx: &mut CallContext, name: UsvString, value: UsvString) -> WebIdlResult<()> {
+ // 1. Let value be value if given; otherwise blobValue.
+ // 2. Let entry be the result of creating an entry with name, value, and filename if given.
+ let entry = create_an_entry(
+ cx.vm(),
+ name.as_utf16_string(),
+ StringOrBlob::String(value.into_utf16_string()),
+ None,
+ );
+
+ // 3. Append entry to this’s entry list.
+ self.entry_list.borrow_mut(cx.vm()).push(entry);
+ Ok(())
+ }
+
+ // https://xhr.spec.whatwg.org/#dom-formdata-append-blob
+ pub(crate) fn append_blob(
+ &self,
+ cx: &mut CallContext,
+ name: UsvString,
+ blob_value: AnyBlob,
+ filename: Option<UsvString>,
+ ) -> WebIdlResult<()> {
+ // 1. Let value be value if given; otherwise blobValue.
+ // 2. Let entry be the result of creating an entry with name, value, and filename if given.
+ let entry = create_an_entry(
+ cx.vm(),
+ name.as_utf16_string(),
+ StringOrBlob::Blob(blob_value),
+ filename,
+ );
+
+ // 3. Append entry to this’s entry list.
+ self.entry_list.borrow_mut(cx.vm()).push(entry);
+ Ok(())
+ }
+
+ // https://xhr.spec.whatwg.org/#dom-formdata-delete
+ pub(crate) fn delete(&self, cx: &mut CallContext, name: UsvString) -> WebIdlResult<()> {
+ // The delete(name) method steps are to remove all entries whose name is name from this’s entry list.
+ self.entry_list
+ .borrow_mut(cx.vm())
+ .retain(|(entry_name, _)| *entry_name != name);
+ Ok(())
+ }
+
+ // https://xhr.spec.whatwg.org/#dom-formdata-get
+ pub(crate) fn get(&self, _: &mut CallContext, name: UsvString) -> WebIdlResult<Option<FormDataEntryValue>> {
+ // 1. If there is no entry whose name is name in this’s entry list, then return null.
+ // 2. Return the value of the first entry whose name is name from this’s entry list.
+ Ok(self.value_named(&name))
+ }
+
+ pub(crate) fn value_named(&self, name: &UsvString) -> Option<FormDataEntryValue> {
+ self.entry_list
+ .borrow()
+ .iter()
+ .find(|(entry_name, _)| entry_name == name)
+ .map(|(_, value)| value.clone())
+ }
+
+ // https://xhr.spec.whatwg.org/#dom-formdata-getall
+ pub(crate) fn get_all<'vm>(
+ &self,
+ cx: &mut CallContext<'vm>,
+ name: UsvString,
+ ) -> WebIdlResult<MarkedVec<'vm, FormDataEntryValue>> {
+ // 1. If there is no entry whose name is name in this’s entry list, then return the empty list.
+ // 2. Return the values of all entries whose name is name, in order, from this’s entry list.
+ let values = MarkedVec::new(cx.vm());
+ for (_, value) in self
+ .entry_list
+ .borrow()
+ .iter()
+ .filter(|(entry_name, _)| *entry_name == name)
+ {
+ values.push(value.clone());
+ }
+ Ok(values)
+ }
+
+ // https://xhr.spec.whatwg.org/#dom-formdata-has
+ pub(crate) fn has(&self, _: &mut CallContext, name: UsvString) -> WebIdlResult<bool> {
+ // The has(name) method steps are to return true if there is an entry whose name is name in this’s entry list; otherwise false.
+ Ok(self.value_named(&name).is_some())
+ }
+
+ // https://xhr.spec.whatwg.org/#dom-formdata-set
+ pub(crate) fn set(&self, cx: &mut CallContext, name: UsvString, value: UsvString) -> WebIdlResult<()> {
+ // 1. Let value be value if given; otherwise blobValue.
+ // 2. Let entry be the result of creating an entry with name, value, and filename if given.
+ let entry = create_an_entry(
+ cx.vm(),
+ name.as_utf16_string(),
+ StringOrBlob::String(value.into_utf16_string()),
+ None,
+ );
+ self.set_entry(cx.vm(), entry);
+ Ok(())
+ }
+
+ // https://xhr.spec.whatwg.org/#dom-formdata-set-blob
+ pub(crate) fn set_blob(
+ &self,
+ cx: &mut CallContext,
+ name: UsvString,
+ blob_value: AnyBlob,
+ filename: Option<UsvString>,
+ ) -> WebIdlResult<()> {
+ // 1. Let value be value if given; otherwise blobValue.
+ // 2. Let entry be the result of creating an entry with name, value, and filename if given.
+ let entry = create_an_entry(
+ cx.vm(),
+ name.as_utf16_string(),
+ StringOrBlob::Blob(blob_value),
+ filename,
+ );
+ self.set_entry(cx.vm(), entry);
+ Ok(())
+ }
+
+ fn set_entry(&self, vm: &Vm, entry: Entry) {
+ let mut entry_list = self.entry_list.borrow_mut(vm);
+
+ // 3. If there are entries in this’s entry list whose name is name, then replace the first such entry with entry
+ // and remove the others.
+ if let Some(first) = entry_list.iter().position(|(entry_name, _)| *entry_name == entry.0) {
+ let mut index = 0;
+ entry_list.retain(|(entry_name, _)| {
+ let keep = index <= first || *entry_name != entry.0;
+ index += 1;
+ keep
+ });
+ entry_list[first] = entry;
+ }
+ // 4. Otherwise, append entry to this’s entry list.
+ else {
+ entry_list.push(entry);
+ }
+ }
+}
+
+// NB: The conversion of a FormDataEntryValue to a JS value is in the generated bindings.
+#[cfg(web_idl_bindings)]
+impl crate::bindings::iterable::PairIterable for FormData {
+ type Key = UsvString;
+ type Value = FormDataEntryValue;
+
+ fn value_pairs_to_iterate_over(&self) -> impl core::ops::Deref<Target = [(UsvString, FormDataEntryValue)]> + '_ {
+ // The value pairs to iterate over are this’s entry list’s entries with the key being the name and the value
+ // being the value.
+ cell::Ref::map(self.entry_list.borrow(), Vec::as_slice)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/xhr/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/xhr/mod.rs
new file mode 100644
index 00000000000..a32f847ec59
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/xhr/mod.rs
@@ -0,0 +1,12 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The FormData interface of the XMLHttpRequest Standard, https://xhr.spec.whatwg.org/#interface-formdata
+
+#[cfg(not(test))]
+pub(crate) mod exports;
+#[cfg(not(test))]
+pub(crate) mod form_data;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index ed89ffe5963..d92d26e4a92 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1112,7 +1112,6 @@ set(SOURCES
WebXR/XRWebGLLayer.cpp
XHR/EventNames.cpp
XHR/FormData.cpp
- XHR/FormDataIterator.cpp
XHR/ProgressEvent.cpp
XHR/XMLHttpRequest.cpp
XHR/XMLHttpRequestEventTarget.cpp
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 1f7dcaf68e6..b949b669341 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -1331,7 +1331,6 @@ class XRWebGLLayer;
namespace Web::XHR {
class FormData;
-class FormDataIterator;
class ProgressEvent;
class XMLHttpRequest;
class XMLHttpRequestEventTarget;
diff --git a/Libraries/LibWeb/HTML/FormControlInfrastructure.cpp b/Libraries/LibWeb/HTML/FormControlInfrastructure.cpp
index f847d5ede8d..de8be2ef16a 100644
--- a/Libraries/LibWeb/HTML/FormControlInfrastructure.cpp
+++ b/Libraries/LibWeb/HTML/FormControlInfrastructure.cpp
@@ -8,60 +8,38 @@
#include <AK/StringBuilder.h>
#include <AK/Utf16StringBuilder.h>
#include <AK/Utf8View.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibTextCodec/Encoder.h>
#include <LibWeb/FileAPI/File.h>
#include <LibWeb/HTML/FormControlInfrastructure.h>
#include <LibWeb/HTML/FormDataEvent.h>
#include <LibWeb/HTML/HTMLButtonElement.h>
#include <LibWeb/HTML/HTMLDataListElement.h>
+#include <LibWeb/HTML/HTMLFormElement.h>
#include <LibWeb/HTML/HTMLInputElement.h>
#include <LibWeb/HTML/HTMLOptionElement.h>
#include <LibWeb/HTML/HTMLSelectElement.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWebCommon/Infra/Strings.h>
namespace Web::HTML {
-static WebIDL::ExceptionOr<XHR::FormDataEntry> create_entry_with_scalar_name(JS::Realm& realm, Utf16String entry_name, Variant<GC::Ref<FileAPI::Blob>, Utf16String> const& value, Optional<Utf16String> const& filename)
-{
- auto entry_value = TRY(value.visit(
- // 2. If value is a string, then set value to the result of converting value into a scalar value string.
- [&](Utf16String const& string) -> WebIDL::ExceptionOr<XHR::FormDataEntry::Value> {
- return TRY_OR_THROW_OOM(realm.vm(), Infra::convert_to_scalar_value_string(string.utf16_view()));
- },
- // 3. Otherwise:
- [&](GC::Ref<FileAPI::Blob> blob) -> WebIDL::ExceptionOr<XHR::FormDataEntry::Value> {
- // 1. If value is not a File object, then set value to a new File object, representing the same bytes, whose
- // name attribute value is "blob".
- if (!is<FileAPI::File>(*blob))
- blob = FileAPI::File::create(blob->raw_bytes(), "blob"_utf16, blob->type());
-
- // 2. If filename is given, then set value to a new File object, representing the same bytes, whose name
- // attribute is filename.
- if (filename.has_value())
- blob = FileAPI::File::create(blob->raw_bytes(), filename.value(), blob->type(), as<FileAPI::File>(*blob).last_modified());
-
- return GC::Ref { as<FileAPI::File>(*blob) };
- }));
-
- // 4. Return an entry whose name is name and whose value is value.
- return XHR::FormDataEntry {
- .name = move(entry_name),
- .value = move(entry_value),
- };
+extern "C" {
+
+// Defined in Bindings/Rust/src/xhr/exports.rs.
+XHR::FormDataEntryABI web_html_create_an_entry(JSVM*, FlatPtr name, FileAPI::Blob* blob, FlatPtr string);
}
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
-WebIDL::ExceptionOr<XHR::FormDataEntry> create_entry(JS::Realm& realm, Utf16View name, Variant<GC::Ref<FileAPI::Blob>, Utf16String> const& value, Optional<Utf16String> const& filename)
+XHR::FormDataEntry create_entry(Utf16View name, Variant<GC::Ref<FileAPI::Blob>, Utf16String> const& value)
{
- // 1. Set name to the result of converting name into a scalar value string.
- auto entry_name = TRY_OR_THROW_OOM(realm.vm(), Infra::convert_to_scalar_value_string(name));
- return create_entry_with_scalar_name(realm, move(entry_name), value, filename);
+ auto* blob = value.visit([](GC::Ref<FileAPI::Blob> blob) { return blob.ptr(); }, [](Utf16String const&) -> FileAPI::Blob* { return nullptr; });
+ auto string = value.visit([](GC::Ref<FileAPI::Blob>) { return Utf16String {}; }, [](Utf16String const& string) { return string; });
+ return XHR::form_data_entry_from_abi(web_html_create_an_entry(JS::HostABI::vm_to_abi(JS::VM::the()), Utf16String::from_utf16(name).into_raw(), blob, move(string).into_raw()));
}
// https://html.spec.whatwg.org/multipage/custom-elements.html#face-entry-construction
-static WebIDL::ExceptionOr<void> construct_face_entry(JS::Realm& realm, GC::Ref<HTMLElement const> form_associated_custom_element, GC::ConservativeVector<XHR::FormDataEntry>& entry_list)
+static void construct_face_entry(GC::Ref<HTMLElement const> form_associated_custom_element, GC::ConservativeVector<XHR::FormDataEntry>& entry_list)
{
// 1. If element's submission value is a list of entries, then append each item of element's submission value to
// entry list, and return.
@@ -72,16 +50,16 @@ static WebIDL::ExceptionOr<void> construct_face_entry(JS::Realm& realm, GC::Ref<
auto const& submission_value = form_associated_custom_element->face_submission_value();
if (auto const* form_data_entries = submission_value.get_pointer<GC::ConservativeVector<XHR::FormDataEntry>>()) {
entry_list.extend(*form_data_entries);
- return {};
+ return;
}
// 2. If the element does not have a name attribute specified, or its name attribute's value is the empty string, then return.
if (!form_associated_custom_element->name().has_value() || form_associated_custom_element->name()->is_empty())
- return {};
+ return;
// 3. If the element's submission value is not null, create an entry with the name attribute value and the submission value, and append it to entry list.
if (submission_value.has<Empty>())
- return {};
+ return;
auto name = form_associated_custom_element->name().value();
auto entry_submission_value = submission_value.visit(
@@ -96,13 +74,12 @@ static WebIDL::ExceptionOr<void> construct_face_entry(JS::Realm& realm, GC::Ref<
VERIFY_NOT_REACHED();
});
- auto entry = TRY(create_entry(realm, name.view(), entry_submission_value));
+ auto entry = create_entry(name.view(), entry_submission_value);
entry_list.append(entry);
- return {};
}
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set
-WebIDL::ExceptionOr<Optional<GC::ConservativeVector<XHR::FormDataEntry>>> construct_entry_list(JS::Realm& realm, HTMLFormElement& form, GC::Ptr<HTMLElement> submitter, Optional<Utf16String> encoding)
+Optional<GC::ConservativeVector<XHR::FormDataEntry>> construct_entry_list(HTMLFormElement& form, GC::Ptr<HTMLElement> submitter, Optional<Utf16String> encoding)
{
// 1. If form's constructing entry list is true, then return null.
if (form.constructing_entry_list())
@@ -160,10 +137,10 @@ WebIDL::ExceptionOr<Optional<GC::ConservativeVector<XHR::FormDataEntry>>> constr
auto [x, y] = input_element->selected_coordinate();
// 6. Create an entry with namex and x, and append it to entry list.
- entry_list.append(TRY(create_entry(realm, name_x.utf16_view(), Utf16String::number(x))));
+ entry_list.append(create_entry(name_x.utf16_view(), Utf16String::number(x)));
// 7. Create an entry with namey and y, and append it to entry list.
- entry_list.append(TRY(create_entry(realm, name_y.utf16_view(), Utf16String::number(y))));
+ entry_list.append(create_entry(name_y.utf16_view(), Utf16String::number(y)));
// 8. Continue.
continue;
@@ -171,7 +148,7 @@ WebIDL::ExceptionOr<Optional<GC::ConservativeVector<XHR::FormDataEntry>>> constr
// 3. If the field is a form-associated custom element, then perform the entry construction algorithm given field and entry list, then continue.
if (control_as_form_associated_element.form_associated_element_to_html_element().is_form_associated_custom_element()) {
- TRY(construct_face_entry(realm, control_as_form_associated_element.form_associated_element_to_html_element(), entry_list));
+ construct_face_entry(control_as_form_associated_element.form_associated_element_to_html_element(), entry_list);
continue;
}
@@ -186,7 +163,7 @@ WebIDL::ExceptionOr<Optional<GC::ConservativeVector<XHR::FormDataEntry>>> constr
if (auto* select_element = as_if<HTMLSelectElement>(*control)) {
for (auto const& option_element : select_element->list_of_options()) {
if (option_element->selected() && !option_element->disabled()) {
- entry_list.append(TRY(create_entry(realm, name.view(), option_element->value())));
+ entry_list.append(create_entry(name.view(), option_element->value()));
}
}
}
@@ -199,20 +176,20 @@ WebIDL::ExceptionOr<Optional<GC::ConservativeVector<XHR::FormDataEntry>>> constr
// 2. Create an entry with name and value, and append it to entry list.
auto checkbox_or_radio_element_name = checkbox_or_radio_element->name();
- entry_list.append(TRY(create_entry(realm, checkbox_or_radio_element_name->view(), value)));
+ entry_list.append(create_entry(checkbox_or_radio_element_name->view(), value));
}
// 8. Otherwise, if the field element is an input element whose type attribute is in the File Upload state, then:
else if (auto* file_element = as_if<HTMLInputElement>(*control); file_element && file_element->type_state() == HTMLInputElement::TypeAttributeState::FileUpload) {
// 1. If there are no selected files, then create an entry with name and a new File object with an empty name, application/octet-stream as type, and an empty body, and append it to entry list.
if (file_element->files()->length() == 0) {
auto file = FileAPI::File::create({}, {}, "application/octet-stream"_utf16);
- entry_list.append(TRY(create_entry(realm, name.view(), Variant<GC::Ref<FileAPI::Blob>, Utf16String> { GC::Ref<FileAPI::Blob> { file } })));
+ entry_list.append(create_entry(name.view(), Variant<GC::Ref<FileAPI::Blob>, Utf16String> { GC::Ref<FileAPI::Blob> { file } }));
}
// 2. Otherwise, for each file in selected files, create an entry with name and a File object representing the file, and append it to entry list.
else {
for (size_t i = 0; i < file_element->files()->length(); i++) {
auto file = GC::Ref { *file_element->files()->item(i) };
- entry_list.append(TRY(create_entry(realm, name.view(), Variant<GC::Ref<FileAPI::Blob>, Utf16String> { GC::Ref<FileAPI::Blob> { file } })));
+ entry_list.append(create_entry(name.view(), Variant<GC::Ref<FileAPI::Blob>, Utf16String> { GC::Ref<FileAPI::Blob> { file } }));
}
}
}
@@ -222,11 +199,11 @@ WebIDL::ExceptionOr<Optional<GC::ConservativeVector<XHR::FormDataEntry>>> constr
auto charset = encoding.value_or("UTF-8"_utf16);
// 2. Create an entry with name and charset, and append it to entry list.
- entry_list.append(TRY(create_entry(realm, name.view(), charset)));
+ entry_list.append(create_entry(name.view(), charset));
}
// 10. Otherwise, create an entry with name and the value of the field element, and append it to entry list.
else {
- entry_list.append(TRY(create_entry(realm, name.view(), control_as_form_associated_element.form_value())));
+ entry_list.append(create_entry(name.view(), control_as_form_associated_element.form_value()));
}
// 11. If the element has a dirname attribute, that attribute's value is not the empty string, and the element is an auto-directionality form-associated element:
@@ -238,7 +215,7 @@ WebIDL::ExceptionOr<Optional<GC::ConservativeVector<XHR::FormDataEntry>>> constr
Utf16String dir = control->directionality() == DOM::Element::Directionality::Ltr ? "ltr"_utf16 : "rtl"_utf16;
// 3. Create an entry with dirname and dir, and append it to entry list.
- entry_list.append(TRY(create_entry(realm, dirname.utf16_view(), dir)));
+ entry_list.append(create_entry(dirname.utf16_view(), dir));
}
}
// 6. Let form data be a new FormData object associated with entry list.
diff --git a/Libraries/LibWeb/HTML/FormControlInfrastructure.h b/Libraries/LibWeb/HTML/FormControlInfrastructure.h
index 1c0d4594399..4c95726ec2d 100644
--- a/Libraries/LibWeb/HTML/FormControlInfrastructure.h
+++ b/Libraries/LibWeb/HTML/FormControlInfrastructure.h
@@ -17,8 +17,8 @@ struct SerializedFormData {
ByteBuffer serialized_data;
};
-WebIDL::ExceptionOr<XHR::FormDataEntry> create_entry(JS::Realm& realm, Utf16View name, Variant<GC::Ref<FileAPI::Blob>, Utf16String> const& value, Optional<Utf16String> const& filename = {});
-WebIDL::ExceptionOr<Optional<GC::ConservativeVector<XHR::FormDataEntry>>> construct_entry_list(JS::Realm&, HTMLFormElement&, GC::Ptr<HTMLElement> submitter = nullptr, Optional<Utf16String> encoding = {});
+XHR::FormDataEntry create_entry(Utf16View name, Variant<GC::Ref<FileAPI::Blob>, Utf16String> const& value);
+Optional<GC::ConservativeVector<XHR::FormDataEntry>> construct_entry_list(HTMLFormElement&, GC::Ptr<HTMLElement> submitter = nullptr, Optional<Utf16String> encoding = {});
ErrorOr<Utf16String> normalize_line_breaks(Utf16View value);
ErrorOr<ByteBuffer> encode(Utf16View input, StringView encoding);
ErrorOr<SerializedFormData> serialize_to_multipart_form_data(GC::ConservativeVector<XHR::FormDataEntry> const& entry_list, StringView encoding = "UTF-8"sv);
diff --git a/Libraries/LibWeb/HTML/FormDataEvent.idl b/Libraries/LibWeb/HTML/FormDataEvent.idl
index 2f885296629..d6d44cc1fa9 100644
--- a/Libraries/LibWeb/HTML/FormDataEvent.idl
+++ b/Libraries/LibWeb/HTML/FormDataEvent.idl
@@ -3,7 +3,7 @@
interface FormDataEvent : Event {
constructor(DOMString type, FormDataEventInit eventInitDict);
- [DirectGetter] readonly attribute FormData formData;
+ readonly attribute FormData formData;
};
dictionary FormDataEventInit : EventInit {
diff --git a/Libraries/LibWeb/HTML/HTMLFormElement.cpp b/Libraries/LibWeb/HTML/HTMLFormElement.cpp
index 39d695b80bf..e8747f2a18d 100644
--- a/Libraries/LibWeb/HTML/HTMLFormElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLFormElement.cpp
@@ -203,7 +203,7 @@ WebIDL::ExceptionOr<void> HTMLFormElement::submit_form(GC::Ref<HTMLElement> subm
auto encoding = TRY_OR_THROW_OOM(vm, pick_an_encoding());
// 7. Let entry list be the result of constructing the entry list with form, submitter, and encoding.
- auto entry_list_or_null = TRY(construct_entry_list(relevant_realm(*this), *this, submitter, encoding));
+ auto entry_list_or_null = construct_entry_list(*this, submitter, encoding);
// 8. Assert: entry list is not null.
VERIFY(entry_list_or_null.has_value());
diff --git a/Libraries/LibWeb/HTML/NavigateEvent.idl b/Libraries/LibWeb/HTML/NavigateEvent.idl
index d013945d804..f771e1c7031 100644
--- a/Libraries/LibWeb/HTML/NavigateEvent.idl
+++ b/Libraries/LibWeb/HTML/NavigateEvent.idl
@@ -9,7 +9,7 @@ interface NavigateEvent : Event {
readonly attribute boolean userInitiated;
readonly attribute boolean hashChange;
[DirectGetter] readonly attribute AbortSignal signal;
- [DirectGetter] readonly attribute FormData? formData;
+ readonly attribute FormData? formData;
readonly attribute DOMString? downloadRequest;
readonly attribute any info;
readonly attribute boolean hasUAVisualTransition;
diff --git a/Libraries/LibWeb/XHR/FormData.cpp b/Libraries/LibWeb/XHR/FormData.cpp
index 6758f8629bd..870b1a9218d 100644
--- a/Libraries/LibWeb/XHR/FormData.cpp
+++ b/Libraries/LibWeb/XHR/FormData.cpp
@@ -5,11 +5,11 @@
*/
#include <AK/TypeCasts.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/Completion.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/RustSerialization.h>
+#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/DOM/Document.h>
-#include <LibWeb/FileAPI/Blob.h>
#include <LibWeb/FileAPI/File.h>
#include <LibWeb/HTML/FormAssociatedElement.h>
#include <LibWeb/HTML/FormControlInfrastructure.h>
@@ -19,211 +19,129 @@
namespace Web::XHR {
-GC_DEFINE_ALLOCATOR(FormData);
+extern "C" {
-static FormDataEntryValue form_data_entry_value_for_bindings(FormDataEntry::Value const& value)
-{
- return value.visit(
- [](GC::Ref<FileAPI::File> file) -> FormDataEntryValue { return file; },
- [](Utf16String const& string) -> FormDataEntryValue { return string; });
-}
-
-WebIDL::ExceptionOr<GC::Ref<FormData>> FormData::construct_impl(GC::Ptr<HTML::HTMLFormElement> form, GC::Ptr<HTML::HTMLElement> submitter)
-{
- if (!form)
- return create(GC::ConservativeVector<FormDataEntry> {});
- return create_from_form(form, submitter);
-}
-
-// https://xhr.spec.whatwg.org/#dom-formdata
-WebIDL::ExceptionOr<GC::Ref<FormData>> FormData::create_from_form(GC::Ptr<HTML::HTMLFormElement> form, GC::Ptr<HTML::HTMLElement> submitter)
-{
- GC::ConservativeVector<FormDataEntry> list;
- // 1. If form is given, then:
- if (form) {
- // 1. If submitter is non-null, then:
- if (submitter) {
- // 1. If submitter is not a submit button, then throw a TypeError.
- auto form_associated_element = as_if<HTML::FormAssociatedElement>(*submitter);
- if (!form_associated_element) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Submitter is not associated with a form."_utf16 };
- }
-
- if (!form_associated_element->is_submit_button()) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Submitter is not a valid submit button."_utf16 };
- }
- // 2. If submitter’s form owner is not form, then throw a "NotFoundError" DOMException.
- GC::Ptr form_owner = form_associated_element->form();
- if (form_owner && form_owner != form) {
- return WebIDL::NotFoundError::create("Submitter does not belong to the provided form."_utf16);
- }
- }
+// Defined in Bindings/Rust/src/xhr/exports.rs.
+void* web_form_data_create(JSVM*, ReadonlySpan<FormDataEntryABI> entries);
+size_t web_form_data_entry_count(void* form_data);
+FormDataEntryABI web_form_data_entry(void* form_data, size_t index);
+bool web_form_data_value_named(void* form_data, FlatPtr name, FormDataEntryValueABI* out_value);
- // 2. Let list be the result of constructing the entry list for form and submitter.
- auto& realm = form->document().relevant_settings_object().realm();
- auto entry_list = TRY(construct_entry_list(realm, *form, submitter));
- // 3. If list is null, then throw an "InvalidStateError" DOMException.
- if (!entry_list.has_value())
- return WebIDL::InvalidStateError::create("Form element does not contain any entries."_utf16);
- // 4. Set this’s entry list to list.
- list = move(entry_list.release_value());
- }
-
- return create(move(list));
+// Called by Bindings/Rust/src/xhr/form_data.rs.
+JSCompletion web_form_data_create_from_form(void* realm, JSObject* form, JSObject* submitter, void** out_form_data);
}
-GC::Ref<FormData> FormData::create(Vector<DOMURL::QueryParam> entry_list)
+FormDataEntryABI form_data_entry_to_abi(FormDataEntry const& entry)
{
- GC::ConservativeVector<FormDataEntry> list;
- list.ensure_capacity(entry_list.size());
- for (auto& entry : entry_list)
- list.unchecked_append({ .name = move(entry.name), .value = move(entry.value) });
-
- return create(move(list));
+ FormDataEntryABI abi { .name = Utf16String { entry.name }.into_raw(), .value = { .file = nullptr, .string = 0 } };
+ entry.value.visit(
+ [&](GC::Ref<FileAPI::File> file) { abi.value.file = file.ptr(); },
+ [&](Utf16String const& string) { abi.value.string = Utf16String { string }.into_raw(); });
+ return abi;
}
-GC::Ref<FormData> FormData::create(GC::ConservativeVector<FormDataEntry> entry_list)
+FormDataEntry::Value form_data_entry_value_from_abi(FormDataEntryValueABI value)
{
- return GC::Heap::the().allocate<FormData>(move(entry_list));
+ if (value.file)
+ return GC::Ref { *static_cast<FileAPI::File*>(value.file) };
+ return Utf16String::adopt_raw(value.string);
}
-FormData::FormData(GC::ConservativeVector<FormDataEntry> entry_list)
- : m_entry_list(entry_list)
+FormDataEntry form_data_entry_from_abi(FormDataEntryABI entry)
{
+ return { .name = Utf16String::adopt_raw(entry.name), .value = form_data_entry_value_from_abi(entry.value) };
}
-FormData::~FormData() = default;
-
-void FormData::visit_edges(GC::Cell::Visitor& visitor)
+GC::Ref<FormData> FormData::create(GC::ConservativeVector<FormDataEntry> const& entry_list)
{
- Base::visit_edges(visitor);
- for (auto const& entry : m_entry_list)
- visitor.visit(entry.value);
+ Vector<FormDataEntryABI> entries;
+ entries.ensure_capacity(entry_list.size());
+ for (auto const& entry : entry_list)
+ entries.unchecked_append(form_data_entry_to_abi(entry));
+ return GC::Ref { *static_cast<FormData*>(web_form_data_create(JS::HostABI::vm_to_abi(JS::VM::the()), entries)) };
}
-// https://xhr.spec.whatwg.org/#dom-formdata-append
-WebIDL::ExceptionOr<void> FormData::append(Utf16String const& name, Utf16String const& value)
+GC::Ref<FormData> FormData::create(Vector<DOMURL::QueryParam> const& entry_list)
{
- return append_impl(name, value);
+ GC::ConservativeVector<FormDataEntry> list;
+ list.ensure_capacity(entry_list.size());
+ for (auto const& entry : entry_list)
+ list.unchecked_append({ .name = entry.name, .value = entry.value });
+ return create(list);
}
-// https://xhr.spec.whatwg.org/#dom-formdata-append-blob
-WebIDL::ExceptionOr<void> FormData::append(Utf16String const& name, GC::Ref<FileAPI::Blob> const& blob_value, Optional<Utf16String> const& filename)
+// https://xhr.spec.whatwg.org/#dom-formdata
+static WebIDL::ExceptionOr<GC::ConservativeVector<FormDataEntry>> entry_list_for_form(GC::Ref<HTML::HTMLFormElement> form, GC::Ptr<HTML::HTMLElement> submitter)
{
- return append_impl(name, blob_value, filename);
-}
+ // 1. If form is given, then:
+ // 1. If submitter is non-null, then:
+ if (submitter) {
+ // 1. If submitter is not a submit button, then throw a TypeError.
+ auto form_associated_element = as_if<HTML::FormAssociatedElement>(*submitter);
+ if (!form_associated_element) {
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Submitter is not associated with a form."_utf16 };
+ }
-// https://xhr.spec.whatwg.org/#dom-formdata-append
-// https://xhr.spec.whatwg.org/#dom-formdata-append-blob
-WebIDL::ExceptionOr<void> FormData::append_impl(Utf16String const& name, Variant<GC::Ref<FileAPI::Blob>, Utf16String> const& value, Optional<Utf16String> const& filename)
-{
- // 1. Let value be value if given; otherwise blobValue.
- // 2. Let entry be the result of creating an entry with name, value, and filename if given.
- auto& realm = JS::VM::the().realm();
- auto entry = TRY(HTML::create_entry(realm, name.utf16_view(), value, filename));
-
- // 3. Append entry to this’s entry list.
- TRY_OR_THROW_OOM(JS::VM::the(), m_entry_list.try_append(move(entry)));
- return {};
-}
+ if (!form_associated_element->is_submit_button()) {
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Submitter is not a valid submit button."_utf16 };
+ }
+ // 2. If submitter’s form owner is not form, then throw a "NotFoundError" DOMException.
+ GC::Ptr form_owner = form_associated_element->form();
+ if (form_owner && form_owner != form) {
+ return WebIDL::NotFoundError::create("Submitter does not belong to the provided form."_utf16);
+ }
+ }
-// https://xhr.spec.whatwg.org/#dom-formdata-delete
-void FormData::delete_(Utf16String const& name)
-{
- // The delete(name) method steps are to remove all entries whose name is name from this’s entry list.
- m_entry_list.remove_all_matching([&name](FormDataEntry const& entry) {
- return entry.name == name;
- });
+ // 2. Let list be the result of constructing the entry list for form and submitter.
+ auto entry_list = HTML::construct_entry_list(*form, submitter);
+ // 3. If list is null, then throw an "InvalidStateError" DOMException.
+ if (!entry_list.has_value())
+ return WebIDL::InvalidStateError::create("Form element does not contain any entries."_utf16);
+ // 4. Set this’s entry list to list.
+ return entry_list.release_value();
}
-// https://xhr.spec.whatwg.org/#dom-formdata-get
-Variant<GC::Ref<FileAPI::File>, Utf16String, Empty> FormData::get(Utf16String const& name)
+WebIDL::ExceptionOr<GC::Ref<FormData>> FormData::create_from_form(GC::Ref<HTML::HTMLFormElement> form, GC::Ptr<HTML::HTMLElement> submitter)
{
- // 1. If there is no entry whose name is name in this’s entry list, then return null.
- auto entry_iterator = m_entry_list.find_if([&name](FormDataEntry const& entry) {
- return entry.name == name;
- });
- if (entry_iterator.is_end())
- return Empty {};
- // 2. Return the value of the first entry whose name is name from this’s entry list.
- return form_data_entry_value_for_bindings(entry_iterator->value);
+ return create(TRY(entry_list_for_form(form, submitter)));
}
-// https://xhr.spec.whatwg.org/#dom-formdata-getall
-WebIDL::ExceptionOr<GC::ConservativeVector<FormDataEntryValue>> FormData::get_all(Utf16String const& name)
+JSCompletion web_form_data_create_from_form(void* realm, JSObject* form, JSObject* submitter, void** out_form_data)
{
- // 1. If there is no entry whose name is name in this’s entry list, then return the empty list.
- // 2. Return the values of all entries whose name is name, in order, from this’s entry list.
- GC::ConservativeVector<FormDataEntryValue> values;
- for (auto const& entry : m_entry_list) {
- if (entry.name == name)
- TRY_OR_THROW_OOM(JS::VM::the(), values.try_append(form_data_entry_value_for_bindings(entry.value)));
- }
- return values;
-}
+ auto& js_realm = *static_cast<JS::Realm*>(realm);
+ auto& form_element = as<HTML::HTMLFormElement>(*Bindings::wrappable_impl_from(JS::HostABI::object_from_abi(form)));
+ GC::Ptr<HTML::HTMLElement> submitter_element;
+ if (submitter)
+ submitter_element = as<HTML::HTMLElement>(*Bindings::wrappable_impl_from(JS::HostABI::object_from_abi(submitter)));
-// https://xhr.spec.whatwg.org/#dom-formdata-has
-bool FormData::has(Utf16String const& name)
-{
- // The has(name) method steps are to return true if there is an entry whose name is name in this’s entry list; otherwise false.
- return !m_entry_list.find_if([&name](auto& entry) {
- return entry.name == name;
- })
- .is_end();
+ auto form_data_or_error = FormData::create_from_form(form_element, submitter_element);
+ if (form_data_or_error.is_exception())
+ return Bindings::completion_to_abi(js_realm, form_data_or_error.release_error());
+ *out_form_data = form_data_or_error.release_value().ptr();
+ return Bindings::completion_to_abi(js_realm, JS::js_undefined());
}
-// https://xhr.spec.whatwg.org/#dom-formdata-set
-WebIDL::ExceptionOr<void> FormData::set(Utf16String const& name, Utf16String const& value)
+Variant<GC::Ref<FileAPI::File>, Utf16String, Empty> FormData::get(Utf16String const& name) const
{
- return set_impl(name, value);
+ FormDataEntryValueABI value {};
+ if (!web_form_data_value_named(const_cast<FormData*>(this), Utf16String { name }.into_raw(), &value))
+ return Empty {};
+ return form_data_entry_value_from_abi(value).visit([](auto value) -> Variant<GC::Ref<FileAPI::File>, Utf16String, Empty> { return value; });
}
-// https://xhr.spec.whatwg.org/#dom-formdata-set-blob
-WebIDL::ExceptionOr<void> FormData::set(Utf16String const& name, GC::Ref<FileAPI::Blob> const& blob_value, Optional<Utf16String> const& filename)
+bool FormData::has(Utf16String const& name) const
{
- return set_impl(name, blob_value, filename);
+ return !get(name).has<Empty>();
}
GC::ConservativeVector<FormDataEntry> FormData::entry_list() const
{
- return GC::ConservativeVector<FormDataEntry> { m_entry_list };
-}
-
-// https://xhr.spec.whatwg.org/#dom-formdata-set
-// https://xhr.spec.whatwg.org/#dom-formdata-set-blob
-WebIDL::ExceptionOr<void> FormData::set_impl(Utf16String const& name, Variant<GC::Ref<FileAPI::Blob>, Utf16String> const& value, Optional<Utf16String> const& filename)
-{
- // 1. Let value be value if given; otherwise blobValue.
- // 2. Let entry be the result of creating an entry with name, value, and filename if given.
- auto& realm = JS::VM::the().realm();
- auto entry = TRY(HTML::create_entry(realm, name.utf16_view(), value, filename));
-
- auto existing = m_entry_list.find_if([&name](auto& entry) {
- return entry.name == name;
- });
-
- // 3. If there are entries in this’s entry list whose name is name, then replace the first such entry with entry and remove the others.
- if (!existing.is_end()) {
- existing->value = entry.value;
- m_entry_list.remove_all_matching([&name, &existing](auto& entry) {
- return &entry != &*existing && entry.name == name;
- });
- }
- // 4. Otherwise, append entry to this’s entry list.
- else {
- TRY_OR_THROW_OOM(JS::VM::the(), m_entry_list.try_append(move(entry)));
- }
-
- return {};
-}
-
-void FormData::for_each(ForEachCallback callback)
-{
- for (auto i = 0u; i < m_entry_list.size(); ++i) {
- auto& entry = m_entry_list[i];
- if (callback(entry.name, entry.value) == IterationDecision::Break)
- break;
- }
+ auto count = web_form_data_entry_count(const_cast<FormData*>(this));
+ GC::ConservativeVector<FormDataEntry> entry_list;
+ entry_list.ensure_capacity(count);
+ for (size_t index = 0; index < count; ++index)
+ entry_list.unchecked_append(form_data_entry_from_abi(web_form_data_entry(const_cast<FormData*>(this), index)));
+ return entry_list;
}
}
diff --git a/Libraries/LibWeb/XHR/FormData.h b/Libraries/LibWeb/XHR/FormData.h
index 268a4717faf..a781e6fba81 100644
--- a/Libraries/LibWeb/XHR/FormData.h
+++ b/Libraries/LibWeb/XHR/FormData.h
@@ -6,56 +6,34 @@
#pragma once
-#include <AK/IterationDecision.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <LibGC/ConservativeVector.h>
+#include <LibWeb/Bindings/FormData.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/DOMURL/URLSearchParams.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
-#include <LibWeb/HTML/HTMLFormElement.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
#include <LibWeb/XHR/FormDataEntry.h>
namespace Web::XHR {
// https://xhr.spec.whatwg.org/#interface-formdata
-class FormData : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(FormData, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(FormData);
+// The C++ side of a FormData, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/xhr): what C++ creates
+// and reads.
+class WEB_API FormData final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(FormData, form_data)
public:
- virtual ~FormData() override;
+ static GC::Ref<FormData> create(GC::ConservativeVector<FormDataEntry> const& entry_list);
+ static GC::Ref<FormData> create(Vector<DOMURL::QueryParam> const& entry_list);
+ static WebIDL::ExceptionOr<GC::Ref<FormData>> create_from_form(GC::Ref<HTML::HTMLFormElement> form, GC::Ptr<HTML::HTMLElement> submitter = nullptr);
- static GC::Ref<FormData> create(GC::ConservativeVector<FormDataEntry> entry_list);
- static GC::Ref<FormData> create(Vector<DOMURL::QueryParam> entry_list);
-
- static WebIDL::ExceptionOr<GC::Ref<FormData>> construct_impl(GC::Ptr<HTML::HTMLFormElement> form, GC::Ptr<HTML::HTMLElement> submitter = nullptr);
- static WebIDL::ExceptionOr<GC::Ref<FormData>> create_from_form(GC::Ptr<HTML::HTMLFormElement> form, GC::Ptr<HTML::HTMLElement> submitter = nullptr);
-
- WebIDL::ExceptionOr<void> append(Utf16String const& name, Utf16String const& value);
- WebIDL::ExceptionOr<void> append(Utf16String const& name, GC::Ref<FileAPI::Blob> const& blob_value, Optional<Utf16String> const& filename = {});
- void delete_(Utf16String const& name);
- Variant<GC::Ref<FileAPI::File>, Utf16String, Empty> get(Utf16String const& name);
- WebIDL::ExceptionOr<GC::ConservativeVector<FormDataEntryValue>> get_all(Utf16String const& name);
- bool has(Utf16String const& name);
- WebIDL::ExceptionOr<void> set(Utf16String const& name, Utf16String const& value);
- WebIDL::ExceptionOr<void> set(Utf16String const& name, GC::Ref<FileAPI::Blob> const& blob_value, Optional<Utf16String> const& filename = {});
+ // https://xhr.spec.whatwg.org/#dom-formdata-get
+ Variant<GC::Ref<FileAPI::File>, Utf16String, Empty> get(Utf16String const& name) const;
+ // https://xhr.spec.whatwg.org/#dom-formdata-has
+ bool has(Utf16String const& name) const;
GC::ConservativeVector<FormDataEntry> entry_list() const;
-
- using ForEachCallback = Function<IterationDecision(Utf16String const&, FormDataEntryValue const&)>;
- void for_each(ForEachCallback);
-
-private:
- friend class FormDataIterator;
-
- explicit FormData(GC::ConservativeVector<FormDataEntry> entry_list);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- WebIDL::ExceptionOr<void> append_impl(Utf16String const& name, Variant<GC::Ref<FileAPI::Blob>, Utf16String> const& value, Optional<Utf16String> const& filename = {});
- WebIDL::ExceptionOr<void> set_impl(Utf16String const& name, Variant<GC::Ref<FileAPI::Blob>, Utf16String> const& value, Optional<Utf16String> const& filename = {});
-
- Vector<FormDataEntry> m_entry_list;
};
}
diff --git a/Libraries/LibWeb/XHR/FormData.idl b/Libraries/LibWeb/XHR/FormData.idl
index 5ecf4015b67..597420889f2 100644
--- a/Libraries/LibWeb/XHR/FormData.idl
+++ b/Libraries/LibWeb/XHR/FormData.idl
@@ -1,17 +1,17 @@
typedef (File or USVString) FormDataEntryValue;
// https://xhr.spec.whatwg.org/#interface-formdata
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface FormData {
constructor(optional HTMLFormElement form, optional HTMLElement? submitter = null);
- undefined append(USVString name, USVString value);
- undefined append(USVString name, Blob blobValue, optional USVString filename);
+ [ImplementedAs=append] undefined append(USVString name, USVString value);
+ [ImplementedAs=append_blob] undefined append(USVString name, Blob blobValue, optional USVString filename);
undefined delete(USVString name);
FormDataEntryValue? get(USVString name);
sequence<FormDataEntryValue> getAll(USVString name);
boolean has(USVString name);
- undefined set(USVString name, USVString value);
- undefined set(USVString name, Blob blobValue, optional USVString filename);
+ [ImplementedAs=set] undefined set(USVString name, USVString value);
+ [ImplementedAs=set_blob] undefined set(USVString name, Blob blobValue, optional USVString filename);
iterable<USVString, FormDataEntryValue>;
};
diff --git a/Libraries/LibWeb/XHR/FormDataEntry.h b/Libraries/LibWeb/XHR/FormDataEntry.h
index db1263dd13c..2f23880b6be 100644
--- a/Libraries/LibWeb/XHR/FormDataEntry.h
+++ b/Libraries/LibWeb/XHR/FormDataEntry.h
@@ -10,6 +10,7 @@
#include <AK/Utf16String.h>
#include <AK/Variant.h>
#include <LibGC/Root.h>
+#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
namespace Web::XHR {
@@ -24,4 +25,18 @@ struct FormDataEntry {
Value value;
};
+struct FormDataEntryValueABI {
+ void* file;
+ FlatPtr string;
+};
+
+struct FormDataEntryABI {
+ FlatPtr name;
+ FormDataEntryValueABI value;
+};
+
+WEB_API FormDataEntryABI form_data_entry_to_abi(FormDataEntry const&);
+WEB_API FormDataEntry::Value form_data_entry_value_from_abi(FormDataEntryValueABI);
+WEB_API FormDataEntry form_data_entry_from_abi(FormDataEntryABI);
+
}
diff --git a/Libraries/LibWeb/XHR/FormDataIterator.cpp b/Libraries/LibWeb/XHR/FormDataIterator.cpp
deleted file mode 100644
index d297a3ac056..00000000000
--- a/Libraries/LibWeb/XHR/FormDataIterator.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2023, Kenneth Myhra <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/Array.h>
-#include <LibJS/Runtime/Iterator.h>
-#include <LibJS/Runtime/PrimitiveString.h>
-#include <LibWeb/Bindings/File.h>
-#include <LibWeb/Bindings/FormData.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/FileAPI/File.h>
-#include <LibWeb/XHR/FormDataIterator.h>
-
-namespace Web::XHR {
-
-GC_DEFINE_ALLOCATOR(FormDataIterator);
-
-static constexpr JSHostClass form_data_iterator_host_class = JS::make_host_class(JS_HOST_CLASS_OBJECT, "FormDataIterator"sv, nullptr, nullptr, nullptr, 0);
-
-FormDataIterator::FormDataIterator(Web::XHR::FormData const& form_data, JS::Object::PropertyKind iterator_kind)
- : m_form_data(form_data)
- , m_iterator_kind(iterator_kind)
-{
-}
-
-FormDataIterator::~FormDataIterator() = default;
-
-static JS::Value form_data_entry_value(JS::Realm& realm, FormDataEntryValue const& value)
-{
- return value.visit(
- [&](GC::Ref<FileAPI::File> const& file) -> JS::Value {
- return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, file);
- },
- [&](Utf16String const& string) -> JS::Value {
- return JS::PrimitiveString::create(realm.vm(), string);
- });
-}
-
-GC::Ref<JS::Object> FormDataIterator::next(JS::Realm& realm)
-{
- auto& vm = this->vm();
-
- if (m_index >= m_form_data->m_entry_list.size())
- return JS::create_iterator_result_object(realm, JS::js_undefined(), true);
-
- auto entry = m_form_data->m_entry_list[m_index++];
- if (m_iterator_kind == JS::Object::PropertyKind::Key)
- return JS::create_iterator_result_object(realm, JS::PrimitiveString::create(vm, entry.name), false);
-
- auto entry_value = form_data_entry_value(realm, entry.value);
-
- if (m_iterator_kind == JS::Object::PropertyKind::Value)
- return JS::create_iterator_result_object(realm, entry_value, false);
-
- return JS::create_iterator_result_object(realm, JS::Array::create_from(realm, { JS::PrimitiveString::create(vm, entry.name), entry_value }), false);
-}
-
-GC::Ref<JS::HostObject> FormDataIterator::create(JS::Realm& realm, FormData const& form_data, JS::Object::PropertyKind iterator_kind)
-{
- static auto const& prototype_name = "FormDataIterator"_utf16_fly_string;
- auto iterator = realm.create<FormDataIterator>(form_data, iterator_kind);
- auto& prototype = Bindings::ensure_web_prototype<Bindings::FormDataIteratorPrototype>(realm, prototype_name);
- return JS::HostObject::create(realm, form_data_iterator_host_class, prototype, {}, iterator);
-}
-
-void FormDataIterator::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_form_data);
-}
-
-}
diff --git a/Libraries/LibWeb/XHR/FormDataIterator.h b/Libraries/LibWeb/XHR/FormDataIterator.h
deleted file mode 100644
index 09661ae3616..00000000000
--- a/Libraries/LibWeb/XHR/FormDataIterator.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2023, Kenneth Myhra <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibJS/Heap/Cell.h>
-#include <LibJS/Runtime/HostObject.h>
-#include <LibJS/Runtime/Object.h>
-#include <LibWeb/XHR/FormData.h>
-
-namespace Web::XHR {
-
-// The state of a FormData iterator. The iterator's JS object is a host object that carries this cell as its host data.
-class FormDataIterator final : public JS::Cell {
- GC_CELL(FormDataIterator, JS::Cell);
- GC_DECLARE_ALLOCATOR(FormDataIterator);
-
-public:
- using JSValueConversionIsForbidden = void;
-
- [[nodiscard]] static GC::Ref<JS::HostObject> create(JS::Realm&, FormData const&, JS::Object::PropertyKind iterator_kind);
-
- virtual ~FormDataIterator() override;
-
- GC::Ref<JS::Object> next(JS::Realm&);
-
-private:
- FormDataIterator(FormData const&, JS::Object::PropertyKind iterator_kind);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<FormData const> m_form_data;
- JS::Object::PropertyKind m_iterator_kind;
- size_t m_index { 0 };
-};
-
-}
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 386435a28e9..b7bf776aee9 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -56,8 +56,8 @@ ALLOWED_REALM_MENTIONS = {
),
"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),
"HTML": (
- 63,
- 185,
+ 61,
+ 179,
"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage; "
"the C++ glue of the Rust structured serialization creates platform objects and SharedArrayBuffers in a given realm",
),
@@ -97,7 +97,7 @@ ALLOWED_REALM_MENTIONS = {
"peer connections, data channels and senders resolve promises and fire events in their relevant realm, encoded "
"frames are constructed and deserialized in the worker's realm, and the stats report's maplike glue",
),
- "XHR": (4, 7, "XHR/FormData/FileReader-style paths still materialize JS values and events"),
+ "XHR": (3, 3, "XHR/FormData/FileReader-style paths still materialize JS values and events"),
}