Skip to content

Truly independent web browser

LibWeb: Implement DataTransferItem and DataTransferItemList in Rust

Shannon Boothc272aa6d98e7
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer.rs b/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer.rs
index 8eb13400916..dac69e4e1b5 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer.rs
@@ -7,15 +7,16 @@
//! DataTransfer, https://html.spec.whatwg.org/multipage/dnd.html#the-datatransfer-interface
-use core::cell::RefCell;
+use core::cell::{self, Cell, RefCell};
use core::ffi::c_void;
-use core::ptr::{NonNull, null_mut};
+use core::ptr::NonNull;
use ak::{Utf16FlyString, Utf16String};
-use libjs_rust::api::{Gc, GcRefCell, Must, Object, Trace, Utf16View, Value, Vm};
+use libjs_rust::api::{Gc, GcRefCell, Must, Object, Realm, Trace, Utf16View, Value, Vm};
+use super::data_transfer_item::DataTransferItem;
+use super::data_transfer_item_list::DataTransferItemList;
use crate::bindings::conversions::{CppInterface, ToJs, frozen_array_to_js, sequence_to_js};
-use crate::bindings::cpp_cell::CppCell;
use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi};
use crate::bindings::setlike::WorldEntries;
use crate::bindings::{CallContext, WebIdlResult};
@@ -30,18 +31,16 @@ unsafe extern "C" {
fn web_data_transfer_store_item(store: *mut c_void, index: usize) -> DragDataStoreItemView;
fn web_data_transfer_store_add_text(store: *mut c_void, type_: usize, data: usize);
fn web_data_transfer_store_remove_item(store: *mut c_void, index: usize);
- fn web_data_transfer_create_item(transfer: *mut c_void, index: usize) -> *mut c_void;
- fn web_data_transfer_set_item_index(item: *mut c_void, index: usize, has_index: bool);
- fn web_data_transfer_create_item_list(transfer: *mut c_void) -> *mut c_void;
- fn web_data_transfer_wrap_item_list(realm: *mut c_void, items: *mut c_void) -> *mut c_void;
+ fn web_data_transfer_store_add_file(store: *mut c_void, file: *mut c_void);
fn web_data_transfer_create_file(store: *mut c_void, index: usize) -> *mut c_void;
+ fn web_data_transfer_create_file_entry(store: *mut c_void, index: usize, realm: *mut c_void) -> *mut c_void;
}
-const READ_WRITE: u8 = 0;
-const PROTECTED: u8 = 2;
+pub(super) const READ_WRITE: u8 = 0;
+pub(super) const PROTECTED: u8 = 2;
// The store is shared with the native drag, drop and clipboard handlers. This holds one reference to it.
-struct DragDataStore(NonNull<c_void>);
+pub(super) struct DragDataStore(NonNull<c_void>);
impl Drop for DragDataStore {
fn drop(&mut self) {
@@ -58,17 +57,17 @@ struct DragDataStoreItemView {
}
impl DragDataStore {
- fn mode(&self) -> u8 {
+ pub(super) fn mode(&self) -> u8 {
// SAFETY: This holds the store alive.
unsafe { web_data_transfer_store_mode(self.0.as_ptr()) }
}
- fn len(&self) -> usize {
+ pub(super) fn len(&self) -> usize {
// SAFETY: This holds the store alive.
unsafe { web_data_transfer_store_size(self.0.as_ptr()) }
}
- fn item(&self, index: usize) -> (bool, Utf16FlyString, Utf16String) {
+ pub(super) fn item(&self, index: usize) -> (bool, Utf16FlyString, Utf16String) {
// SAFETY: All callers pass an index within the live store. The strings are lent by that item.
unsafe {
let item = web_data_transfer_store_item(self.0.as_ptr(), index);
@@ -80,11 +79,29 @@ impl DragDataStore {
}
}
- fn add_text(&self, type_string: &Utf16FlyString, data: &Utf16String) {
+ pub(super) fn add_text(&self, type_string: &Utf16FlyString, data: &Utf16String) {
// SAFETY: This holds the store alive and the strings are lent for the call.
unsafe { web_data_transfer_store_add_text(self.0.as_ptr(), type_string.raw_identity(), data.raw_identity()) };
}
+ pub(super) fn add_file(&self, file: Ref<File>) {
+ // SAFETY: This holds the store alive and the file is live.
+ unsafe { web_data_transfer_store_add_file(self.0.as_ptr(), cell_into_abi(file)) };
+ }
+
+ pub(super) fn create_file(&self, index: usize) -> Ref<File> {
+ // SAFETY: This holds the store alive, and the index refers to a file item. LibWeb returns the new File cell.
+ unsafe { cell_from_abi(web_data_transfer_create_file(self.0.as_ptr(), index)) }
+ }
+
+ pub(super) fn create_file_entry(&self, index: usize, realm: Gc<Realm>) -> CppInterface {
+ // SAFETY: The store and realm are live, and the index refers to a file item.
+ let wrapper = unsafe { web_data_transfer_create_file_entry(self.0.as_ptr(), index, realm.as_ptr().cast()) };
+ let wrapper = NonNull::new(wrapper.cast()).expect("LibWeb wraps the file entry");
+ // SAFETY: LibWeb returns a live FileSystemEntry wrapper.
+ unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }
+ }
+
fn remove_item(&self, index: usize) {
// SAFETY: The transfer's item list and the store have matching indices.
unsafe { web_data_transfer_store_remove_item(self.0.as_ptr(), index) };
@@ -100,8 +117,8 @@ pub(crate) struct DataTransfer {
drop_effect: RefCell<Utf16FlyString>,
#[gc(untraced)]
effect_allowed: RefCell<Utf16FlyString>,
- items: GcRefCell<Option<CppCell>>,
- item_list: GcRefCell<Vec<CppCell>>,
+ items: Cell<Option<Ref<DataTransferItemList>>>,
+ item_list: GcRefCell<Vec<Ref<DataTransferItem>>>,
#[gc(untraced)]
types: RefCell<Vec<Utf16String>>,
types_arrays: WorldEntries<Object>,
@@ -116,7 +133,7 @@ impl DataTransfer {
store: RefCell::new(Some(store)),
drop_effect: RefCell::new(Utf16FlyString::from_utf8("none")),
effect_allowed: RefCell::new(Utf16FlyString::from_utf8("none")),
- items: GcRefCell::default(),
+ items: Cell::default(),
item_list: GcRefCell::new(Vec::with_capacity(count)),
types: RefCell::default(),
types_arrays: WorldEntries::default(),
@@ -204,21 +221,21 @@ impl DataTransfer {
}
// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-items
- pub(crate) fn items(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ pub(crate) fn items(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<Ref<DataTransferItemList>> {
// The items attribute must return a DataTransferItemList object associated with the DataTransfer object.
- let items = this.items.borrow().as_ref().map(CppCell::as_ptr);
- let items = items.unwrap_or_else(|| {
- // SAFETY: The transfer is live. LibWeb returns its new item list.
- let items = unsafe { web_data_transfer_create_item_list(cell_into_abi(*this)) };
- // SAFETY: LibWeb returns a live DataTransferItemList.
- *this.items.borrow_mut(cx.vm()) = Some(unsafe { CppCell::from_raw(items) });
+ Ok(this.items.get().unwrap_or_else(|| {
+ let items = DataTransferItemList::create(cx.vm(), *this);
+ this.items.set(Some(items));
items
- });
- // SAFETY: The realm and list are live. LibWeb returns the wrapper for that list in the wrapper world.
- let wrapper = unsafe { web_data_transfer_wrap_item_list(cx.realm().as_ptr().cast(), items) };
- let wrapper = NonNull::new(wrapper.cast()).expect("LibWeb wraps the item list");
- // SAFETY: LibWeb returns the live wrapper of a DataTransferItemList.
- Ok(unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) })
+ }))
+ }
+
+ pub(super) fn store(&self) -> Option<cell::Ref<'_, DragDataStore>> {
+ cell::Ref::filter_map(self.store.borrow(), Option::as_ref).ok()
+ }
+
+ pub(super) fn item(&self, index: usize) -> Ref<DataTransferItem> {
+ self.item_list.borrow()[index]
}
// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-types
@@ -369,9 +386,7 @@ impl DataTransfer {
for index in 0..store.len() {
let (is_file, _, _) = store.item(index);
if is_file {
- // SAFETY: The store is live and the index is within it. LibWeb returns the new File cell.
- let file = unsafe { cell_from_abi::<File>(web_data_transfer_create_file(store.0.as_ptr(), index)) };
- files.add_file(vm, file);
+ files.add_file(vm, store.create_file(index));
}
}
@@ -379,33 +394,26 @@ impl DataTransfer {
Ok(files)
}
- fn append_item(this: &Ref<Self>, vm: &Vm, index: usize) -> *mut c_void {
- // SAFETY: The transfer is live and the index exists in its store.
- let item = unsafe { web_data_transfer_create_item(cell_into_abi(*this), index) };
- // SAFETY: LibWeb returns a live DataTransferItem.
- this.item_list.borrow_mut(vm).push(unsafe { CppCell::from_raw(item) });
+ fn append_item(this: &Ref<Self>, vm: &Vm, index: usize) -> Ref<DataTransferItem> {
+ let item = DataTransferItem::create(vm, *this, index);
+ this.item_list.borrow_mut(vm).push(item);
item
}
- fn did_add_item(this: &Ref<Self>, vm: &Vm) -> *mut c_void {
+ pub(super) fn did_add_item(this: &Ref<Self>, vm: &Vm) -> Ref<DataTransferItem> {
let index = this.item_list.borrow().len();
let item = Self::append_item(this, vm, index);
this.update_types();
item
}
- fn remove_item(&self, vm: &Vm, index: usize) {
+ pub(super) fn remove_item(&self, vm: &Vm, index: usize) {
let mut items = self.item_list.borrow_mut(vm);
- let store = self.store.borrow();
- let store = store.as_ref().expect("removing an item requires a drag data store");
+ let store = self.store().expect("removing an item requires a drag data store");
store.remove_item(index);
- let removed = items.remove(index);
- // SAFETY: These cells are live. The removed item becomes disabled and the remaining indices shift.
- unsafe {
- web_data_transfer_set_item_index(removed.as_ptr(), 0, false);
- for (index, item) in items.iter().enumerate().skip(index) {
- web_data_transfer_set_item_index(item.as_ptr(), index, true);
- }
+ items.remove(index).set_index(None);
+ for (index, item) in items.iter().enumerate().skip(index) {
+ item.set_index(Some(index));
}
drop(items);
self.update_types();
@@ -473,16 +481,6 @@ pub unsafe extern "C" fn web_rust_data_transfer_create(vm: &Vm, store: NonNull<c
cell_into_abi(DataTransfer::create(vm, DragDataStore(store)))
}
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_data_transfer_drag_data_store(transfer: *mut c_void) -> *mut c_void {
- // SAFETY: LibWeb passes a live DataTransfer. It keeps the returned store alive until disassociation.
- unsafe { cell_from_abi::<DataTransfer>(transfer) }
- .store
- .borrow()
- .as_ref()
- .map_or(null_mut(), |store| store.0.as_ptr())
-}
-
#[unsafe(no_mangle)]
pub unsafe extern "C" fn web_rust_data_transfer_disassociate(transfer: *mut c_void) {
// SAFETY: LibWeb passes a live DataTransfer.
@@ -526,22 +524,3 @@ pub unsafe extern "C" fn web_rust_data_transfer_set_effect_allowed_internal(tran
cell_from_abi::<DataTransfer>(transfer).set_effect_allowed_internal(Utf16FlyString::from_raw_borrowed(effect));
}
}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_data_transfer_did_add_item(vm: &Vm, transfer: *mut c_void) -> *mut c_void {
- // SAFETY: LibWeb passes a live DataTransfer whose store has just gained an item.
- let transfer = unsafe { cell_from_abi::<DataTransfer>(transfer) };
- DataTransfer::did_add_item(&transfer, vm)
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_data_transfer_remove_item(vm: &Vm, transfer: *mut c_void, index: usize) {
- // SAFETY: LibWeb passes a live DataTransfer and an index within its store.
- unsafe { cell_from_abi::<DataTransfer>(transfer) }.remove_item(vm, index);
-}
-
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_data_transfer_item(transfer: *mut c_void, index: usize) -> *mut c_void {
- // SAFETY: LibWeb passes a live DataTransfer and an index within its store.
- unsafe { cell_from_abi::<DataTransfer>(transfer) }.item_list.borrow()[index].as_ptr()
-}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer_item.rs b/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer_item.rs
new file mode 100644
index 00000000000..f396629628a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer_item.rs
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! DataTransferItem, https://html.spec.whatwg.org/multipage/dnd.html#the-datatransferitem-interface
+
+use core::cell::{self, Cell};
+
+use ak::Utf16String;
+use libjs_rust::api::{PrimitiveString, Trace, Value, Vm};
+
+use super::data_transfer::{DataTransfer, DragDataStore, PROTECTED};
+use crate::bindings::callback::CallbackFunction;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::promise::{TaskSource, queue_a_task};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::file_api::file::File;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct DataTransferItem {
+ data_transfer: Ref<DataTransfer>,
+ index: Cell<Option<usize>>,
+}
+
+impl Wrappable for DataTransferItem {}
+
+impl DataTransferItem {
+ pub(super) fn create(vm: &Vm, data_transfer: Ref<DataTransfer>, index: usize) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ data_transfer,
+ index: Cell::new(Some(index)),
+ })
+ }
+
+ pub(super) fn set_index(&self, index: Option<usize>) {
+ self.index.set(index);
+ }
+
+ fn store_and_index(&self) -> Option<(cell::Ref<'_, DragDataStore>, usize)> {
+ let index = self.index.get()?;
+ Some((self.data_transfer.store()?, index))
+ }
+
+ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitem-kind
+ pub(crate) fn kind(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The kind attribute must return the empty string if the DataTransferItem object is in the disabled mode; otherwise
+ // it must return the string given in the cell from the second column of the following table from the row whose cell
+ // in the first column contains the drag data item kind of the item represented by the DataTransferItem object:
+ //
+ // Kind | String
+ // ---------------
+ // Text | "string"
+ // File | "file"
+ let Some((store, index)) = self.store_and_index() else {
+ return Ok(Utf16String::default());
+ };
+ let (is_file, _, _) = store.item(index);
+ Ok(Utf16String::from_ascii(if is_file { b"file" } else { b"string" }))
+ }
+
+ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitem-type
+ pub(crate) fn r#type(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The type attribute must return the empty string if the DataTransferItem object is in the disabled mode; otherwise
+ // it must return the drag data item type string of the item represented by the DataTransferItem object.
+ let Some((store, index)) = self.store_and_index() else {
+ return Ok(Utf16String::default());
+ };
+ let (_, type_string, _) = store.item(index);
+ Ok(Utf16String::from(type_string))
+ }
+
+ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitem-getasstring
+ pub(crate) fn get_as_string(&self, cx: &mut CallContext, callback: Option<CallbackFunction>) -> WebIdlResult<()> {
+ // 1. If the callback is null, return.
+ let Some(callback) = callback else {
+ return Ok(());
+ };
+
+ // 2. If the DataTransferItem object is not in the read/write mode or the read-only mode, return. The callback is
+ // never invoked.
+ let Some((store, index)) = self.store_and_index().filter(|(store, _)| store.mode() != PROTECTED) else {
+ return Ok(());
+ };
+
+ // 3. If the drag data item kind is not text, then return. The callback is never invoked.
+ let (is_file, _, data) = store.item(index);
+ if is_file {
+ return Ok(());
+ }
+
+ // 4. Otherwise, queue a task to invoke callback, passing the actual data of the item represented by the
+ // DataTransferItem object as the argument.
+ queue_a_task(
+ cx.vm(),
+ TaskSource::Unspecified,
+ (callback, data),
+ |vm, (callback, data)| {
+ let data = Value::from_string(PrimitiveString::create(vm, data));
+ let _ = callback.invoke(None, &[data]);
+ },
+ );
+ Ok(())
+ }
+
+ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitem-getasfile
+ pub(crate) fn get_as_file(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<File>>> {
+ // 1. If the DataTransferItem object is not in the read/write mode or the read-only mode, then return null.
+ let Some((store, index)) = self.store_and_index().filter(|(store, _)| store.mode() != PROTECTED) else {
+ return Ok(None);
+ };
+
+ // 2. If the drag data item kind is not File, then return null.
+ let (is_file, _, _) = store.item(index);
+ if !is_file {
+ return Ok(None);
+ }
+
+ // 3. Return a new File object representing the actual data of the item represented by the DataTransferItem object.
+ Ok(Some(store.create_file(index)))
+ }
+
+ // https://wicg.github.io/entries-api/#dom-datatransferitem-webkitgetasentry
+ pub(crate) fn webkit_get_as_entry(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {
+ // 1. Let store be this's DataTransfer object’s drag data store.
+
+ // 2. If store’s drag data store mode is not read/write mode or read-only mode, return null and abort these steps
+ let Some((store, index)) = self.store_and_index().filter(|(store, _)| store.mode() != PROTECTED) else {
+ return Ok(None);
+ };
+
+ // 3. Let item be the item in store’s drag data store item list that this represents.
+ let (is_file, _, _) = store.item(index);
+
+ // 4. If item’s kind is not File, then return null and abort these steps.
+ if !is_file {
+ return Ok(None);
+ }
+
+ // 5. Return a new FileSystemEntry object representing the entry.
+ Ok(Some(store.create_file_entry(index, cx.realm())))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer_item_list.rs b/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer_item_list.rs
new file mode 100644
index 00000000000..d4443d6bc86
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer_item_list.rs
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! DataTransferItemList, https://html.spec.whatwg.org/multipage/dnd.html#the-datatransferitemlist-interface
+
+use ak::{Utf16FlyString, Utf16String};
+use libjs_rust::api::{Trace, Utf16StringBuilder, Utf16View, Vm};
+
+use super::data_transfer::{DataTransfer, READ_WRITE};
+use super::data_transfer_item::DataTransferItem;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::file_api::file::File;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct DataTransferItemList {
+ data_transfer: Ref<DataTransfer>,
+}
+
+impl Wrappable for DataTransferItemList {}
+
+impl DataTransferItemList {
+ pub(super) fn create(vm: &Vm, data_transfer: Ref<DataTransfer>) -> Ref<Self> {
+ allocate(vm, |_| Self { data_transfer })
+ }
+
+ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitemlist-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // The length attribute must return zero if the object is in the disabled mode; otherwise it must return the number
+ // of items in the drag data store item list.
+ let length = self.data_transfer.store().map_or(0, |store| store.len());
+ Ok(u32::try_from(length).expect("a transfer has fewer than 2^32 items"))
+ }
+
+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<Ref<DataTransferItem>> {
+ // The generated indexed property getter checks the index against length.
+ Ok(self.data_transfer.item(index as usize))
+ }
+
+ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitemlist-add
+ pub(crate) fn add_string(
+ &self,
+ cx: &mut CallContext,
+ data: Utf16String,
+ type_string: Utf16String,
+ ) -> WebIdlResult<Option<Ref<DataTransferItem>>> {
+ // 1. If the DataTransferItemList object is not in the read/write mode, return null.
+ let Some(store) = self.data_transfer.store().filter(|store| store.mode() == READ_WRITE) else {
+ return Ok(None);
+ };
+
+ // 2. Jump to the appropriate set of steps from the following list:
+ // -> If the first argument to the method is a string
+
+ // If there is already an item in the drag data store item list whose kind is text and whose type string is equal
+ // to the value of the method's second argument, converted to ASCII lowercase, then throw a "NotSupportedError"
+ // DOMException.
+ let format = Utf16View::of_string(&type_string);
+ if (0..store.len()).any(|index| {
+ let (is_file, item_type, _) = store.item(index);
+ !is_file && Utf16View::of_fly_string(&item_type).equals_ignoring_ascii_case(format)
+ }) {
+ let mut message = Utf16StringBuilder::new();
+ message.append_ascii("There is already a DataTransferItem with type ");
+ message.append(format);
+ return Err(Exception::Dom("NotSupportedError", message.to_utf16_string()));
+ }
+
+ // Otherwise, add an item to the drag data store item list whose kind is text, whose type string is equal to the
+ // value of the method's second argument, converted to ASCII lowercase, and whose data is the string given by the
+ // method's first argument.
+ let lowercase_type = Utf16FlyString::from_utf16_string(&type_string.to_ascii_lowercase());
+ store.add_text(&lowercase_type, &data);
+
+ // 3. Determine the value of the indexed property corresponding to the newly added item, and return that value (a
+ // newly created DataTransferItem object).
+ Ok(Some(DataTransfer::did_add_item(&self.data_transfer, cx.vm())))
+ }
+
+ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitemlist-add
+ pub(crate) fn add_file(
+ &self,
+ cx: &mut CallContext,
+ file: Ref<File>,
+ ) -> WebIdlResult<Option<Ref<DataTransferItem>>> {
+ // 1. If the DataTransferItemList object is not in the read/write mode, return null.
+ let Some(store) = self.data_transfer.store().filter(|store| store.mode() == READ_WRITE) else {
+ return Ok(None);
+ };
+
+ // 2. Jump to the appropriate set of steps from the following list:
+ // -> If the first argument to the method is a File
+
+ // Add an item to the drag data store item list whose kind is File, whose type string is the type of the File,
+ // converted to ASCII lowercase, and whose data is the same as the File's data.
+ store.add_file(file);
+
+ // 3. Determine the value of the indexed property corresponding to the newly added item, and return that value (a
+ // newly created DataTransferItem object).
+ Ok(Some(DataTransfer::did_add_item(&self.data_transfer, cx.vm())))
+ }
+
+ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitemlist-remove
+ pub(crate) fn remove(&self, cx: &mut CallContext, index: u32) -> WebIdlResult<()> {
+ // 1. If the DataTransferItemList object is not in the read/write mode, throw an "InvalidStateError" DOMException.
+ let Some(store) = self.data_transfer.store().filter(|store| store.mode() == READ_WRITE) else {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"DataTransferItemList is not in read/write mode"),
+ ));
+ };
+
+ // 2. If the drag data store does not contain an indexth item, then return.
+ let index = index as usize;
+ if index >= store.len() {
+ return Ok(());
+ }
+
+ // 3. Remove the indexth item from the drag data store.
+ self.data_transfer.remove_item(cx.vm(), index);
+ Ok(())
+ }
+
+ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitemlist-clear
+ pub(crate) fn clear(&self, cx: &mut CallContext) -> WebIdlResult<()> {
+ // The clear() method, if the DataTransferItemList object is in the read/write mode, must remove all the items from
+ // the drag data store. Otherwise, it must do nothing.
+ let Some(store) = self.data_transfer.store().filter(|store| store.mode() == READ_WRITE) else {
+ return Ok(());
+ };
+
+ for index in (0..store.len()).rev() {
+ self.data_transfer.remove_item(cx.vm(), index);
+ }
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index 1332e3c457f..3343e0a89b5 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -58,6 +58,10 @@ pub(crate) mod canvas_transform;
#[cfg(not(test))]
pub(crate) mod data_transfer;
#[cfg(not(test))]
+pub(crate) mod data_transfer_item;
+#[cfg(not(test))]
+pub(crate) mod data_transfer_item_list;
+#[cfg(not(test))]
pub(crate) mod dom_string_list;
#[cfg(not(test))]
pub(crate) mod dom_string_map;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 2f374fc42ff..74ba511664d 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -368,8 +368,6 @@ set(SOURCES
HTML/CustomElements/CustomElementRegistry.cpp
HTML/CustomElements/CustomStateSet.cpp
HTML/DataTransfer.cpp
- HTML/DataTransferItem.cpp
- HTML/DataTransferItemList.cpp
HTML/Dates.cpp
HTML/DecodedImageData.cpp
HTML/DedicatedWorkerGlobalScope.cpp
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 61fa73b47d2..ce521ab4410 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -663,8 +663,6 @@ class CustomElementDefinition;
class CustomElementRegistry;
class CustomStateSet;
class DataTransfer;
-class DataTransferItem;
-class DataTransferItemList;
class DecodedImageData;
class DedicatedWorkerThreadLink;
class DocumentState;
diff --git a/Libraries/LibWeb/HTML/DataTransfer.cpp b/Libraries/LibWeb/HTML/DataTransfer.cpp
index b8337bd2b45..53f87cc16d3 100644
--- a/Libraries/LibWeb/HTML/DataTransfer.cpp
+++ b/Libraries/LibWeb/HTML/DataTransfer.cpp
@@ -8,10 +8,9 @@
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/EntriesAPI/FileSystemEntry.h>
#include <LibWeb/FileAPI/File.h>
#include <LibWeb/HTML/DataTransfer.h>
-#include <LibWeb/HTML/DataTransferItem.h>
-#include <LibWeb/HTML/DataTransferItemList.h>
namespace Web::HTML {
@@ -25,15 +24,11 @@ extern "C" {
// Defined in Bindings/Rust/src/html/data_transfer.rs.
DataTransfer* web_rust_data_transfer_create(JSVM*, DragDataStore*);
-DragDataStore* web_rust_data_transfer_drag_data_store(DataTransfer const*);
void web_rust_data_transfer_disassociate(DataTransfer*);
FlatPtr web_rust_data_transfer_drop_effect(DataTransfer const*);
FlatPtr web_rust_data_transfer_effect_allowed(DataTransfer const*);
void web_rust_data_transfer_set_drop_effect(DataTransfer*, FlatPtr);
void web_rust_data_transfer_set_effect_allowed_internal(DataTransfer*, FlatPtr);
-DataTransferItem* web_rust_data_transfer_did_add_item(JSVM*, DataTransfer*);
-void web_rust_data_transfer_remove_item(JSVM*, DataTransfer*, size_t index);
-DataTransferItem* web_rust_data_transfer_item(DataTransfer const*, size_t index);
DragDataStore* web_data_transfer_create_writable_store();
void web_data_transfer_store_unref(DragDataStore*);
@@ -42,11 +37,9 @@ size_t web_data_transfer_store_size(DragDataStore const*);
DragDataStoreItemView web_data_transfer_store_item(DragDataStore const*, size_t index);
void web_data_transfer_store_add_text(DragDataStore*, FlatPtr type, FlatPtr data);
void web_data_transfer_store_remove_item(DragDataStore*, size_t index);
-DataTransferItem* web_data_transfer_create_item(DataTransfer*, size_t index);
-void web_data_transfer_set_item_index(DataTransferItem*, size_t index, bool has_index);
-DataTransferItemList* web_data_transfer_create_item_list(DataTransfer*);
-JS::Object* web_data_transfer_wrap_item_list(JS::Realm*, DataTransferItemList*);
+void web_data_transfer_store_add_file(DragDataStore*, FileAPI::File const*);
FileAPI::File* web_data_transfer_create_file(DragDataStore const*, size_t index);
+JS::Object* web_data_transfer_create_file_entry(DragDataStore const*, size_t index, JS::Realm*);
}
namespace DataTransferEffect {
@@ -62,11 +55,6 @@ GC::Ref<DataTransfer> DataTransfer::create(NonnullRefPtr<DragDataStore> store)
return *web_rust_data_transfer_create(JS::HostABI::vm_to_abi(JS::VM::the()), &store.leak_ref());
}
-DragDataStore* DataTransfer::drag_data_store() const
-{
- return web_rust_data_transfer_drag_data_store(this);
-}
-
Utf16FlyString DataTransfer::drop_effect() const
{
return Utf16FlyString::adopt_raw(web_rust_data_transfer_drop_effect(this));
@@ -87,65 +75,11 @@ void DataTransfer::set_effect_allowed_internal(Utf16FlyString const& effect)
web_rust_data_transfer_set_effect_allowed_internal(this, effect.raw_identity());
}
-Optional<DragDataStore::Mode> DataTransfer::mode() const
-{
- if (auto* store = drag_data_store())
- return store->mode();
- return {};
-}
-
void DataTransfer::disassociate_with_drag_data_store()
{
web_rust_data_transfer_disassociate(this);
}
-GC::Ref<DataTransferItem> DataTransfer::add_item(DragDataStoreItem item)
-{
- auto* store = drag_data_store();
- VERIFY(store);
- store->add_item(move(item));
- return *web_rust_data_transfer_did_add_item(JS::HostABI::vm_to_abi(JS::VM::the()), this);
-}
-
-void DataTransfer::remove_item(size_t index)
-{
- web_rust_data_transfer_remove_item(JS::HostABI::vm_to_abi(JS::VM::the()), this, index);
-}
-
-void DataTransfer::set_item_index(DataTransferItem& item, Optional<size_t> index)
-{
- item.set_item_index({}, index);
-}
-
-bool DataTransfer::contains_item_with_type(DragDataStoreItem::Kind kind, Utf16View type) const
-{
- auto* store = drag_data_store();
- VERIFY(store);
- for (auto const& item : store->item_list()) {
- if (item.kind == kind && item.type_string.equals_ignoring_ascii_case(type))
- return true;
- }
- return false;
-}
-
-GC::Ref<DataTransferItem> DataTransfer::item(size_t index) const
-{
- return *web_rust_data_transfer_item(this, index);
-}
-
-DragDataStoreItem const& DataTransfer::drag_data(size_t index) const
-{
- auto* store = drag_data_store();
- VERIFY(store);
- return store->item_list()[index];
-}
-
-size_t DataTransfer::length() const
-{
- auto* store = drag_data_store();
- return store ? store->size() : 0;
-}
-
DragDataStore* web_data_transfer_create_writable_store()
{
auto store = DragDataStore::create();
@@ -194,24 +128,15 @@ void web_data_transfer_store_remove_item(DragDataStore* store, size_t index)
store->remove_item_at(index);
}
-DataTransferItem* web_data_transfer_create_item(DataTransfer* transfer, size_t index)
-{
- return DataTransferItem::create(*transfer, index).ptr();
-}
-
-void web_data_transfer_set_item_index(DataTransferItem* item, size_t index, bool has_index)
-{
- DataTransfer::set_item_index(*item, has_index ? Optional<size_t> { index } : Optional<size_t> {});
-}
-
-DataTransferItemList* web_data_transfer_create_item_list(DataTransfer* transfer)
+void web_data_transfer_store_add_file(DragDataStore* store, FileAPI::File const* file)
{
- return DataTransferItemList::create(*transfer).ptr();
-}
-
-JS::Object* web_data_transfer_wrap_item_list(JS::Realm* realm, DataTransferItemList* items)
-{
- return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, GC::Ref { *items }).ptr();
+ store->add_item({
+ .kind = DragDataStoreItem::Kind::File,
+ .type_string = file->type().to_ascii_lowercase(),
+ .data = {},
+ .file_data = MUST(ByteBuffer::copy(file->raw_bytes())),
+ .file_name = file->name(),
+ });
}
FileAPI::File* web_data_transfer_create_file(DragDataStore const* store, size_t index)
@@ -222,4 +147,12 @@ FileAPI::File* web_data_transfer_create_file(DragDataStore const* store, size_t
return FileAPI::File::create(item.file_data, item.file_name, item.type_string.to_utf16_string()).ptr();
}
+JS::Object* web_data_transfer_create_file_entry(DragDataStore const* store, size_t index, JS::Realm* realm)
+{
+ auto const& item = store->item_list()[index];
+ VERIFY(item.kind == DragDataStoreItem::Kind::File);
+ auto entry = EntriesAPI::FileSystemEntry::create(EntriesAPI::EntryType::File, item.file_name.to_utf8().to_byte_string());
+ return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, entry).ptr();
+}
+
}
diff --git a/Libraries/LibWeb/HTML/DataTransfer.h b/Libraries/LibWeb/HTML/DataTransfer.h
index b2c981d6d98..4732280d531 100644
--- a/Libraries/LibWeb/HTML/DataTransfer.h
+++ b/Libraries/LibWeb/HTML/DataTransfer.h
@@ -42,19 +42,7 @@ public:
Utf16FlyString effect_allowed() const;
void set_effect_allowed_internal(Utf16FlyString const&);
- Optional<DragDataStore::Mode> mode() const;
void disassociate_with_drag_data_store();
-
- GC::Ref<DataTransferItem> add_item(DragDataStoreItem);
- void remove_item(size_t index);
- static void set_item_index(DataTransferItem&, Optional<size_t>);
- bool contains_item_with_type(DragDataStoreItem::Kind, Utf16View type) const;
- GC::Ref<DataTransferItem> item(size_t index) const;
- DragDataStoreItem const& drag_data(size_t index) const;
- size_t length() const;
-
-private:
- DragDataStore* drag_data_store() const;
};
}
diff --git a/Libraries/LibWeb/HTML/DataTransferItem.cpp b/Libraries/LibWeb/HTML/DataTransferItem.cpp
deleted file mode 100644
index 0e0d64d7419..00000000000
--- a/Libraries/LibWeb/HTML/DataTransferItem.cpp
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (c) 2024, Tim Flynn <[email protected]>
- * Copyright (c) 2024, Jamie Mansfield <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/ByteBuffer.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/PrimitiveString.h>
-#include <LibWeb/FileAPI/File.h>
-#include <LibWeb/HTML/DataTransfer.h>
-#include <LibWeb/HTML/DataTransferItem.h>
-#include <LibWeb/HTML/EventLoop/EventLoop.h>
-#include <LibWeb/WebIDL/AbstractOperations.h>
-#include <LibWeb/WebIDL/CallbackType.h>
-
-namespace Web::HTML {
-
-GC_DEFINE_ALLOCATOR(DataTransferItem);
-
-GC::Ref<DataTransferItem> DataTransferItem::create(GC::Ref<DataTransfer> data_transfer, size_t item_index)
-{
- return GC::Heap::the().allocate<DataTransferItem>(data_transfer, item_index);
-}
-
-DataTransferItem::DataTransferItem(GC::Ref<DataTransfer> data_transfer, size_t item_index)
- : m_data_transfer(data_transfer)
- , m_item_index(item_index)
-{
-}
-
-DataTransferItem::~DataTransferItem() = default;
-
-void DataTransferItem::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_data_transfer);
-}
-
-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitem-kind
-Utf16FlyString DataTransferItem::kind() const
-{
- // The kind attribute must return the empty string if the DataTransferItem object is in the disabled mode; otherwise
- // it must return the string given in the cell from the second column of the following table from the row whose cell
- // in the first column contains the drag data item kind of the item represented by the DataTransferItem object:
- //
- // Kind | String
- // ---------------
- // Text | "string"
- // File | "file"
- if (!mode().has_value())
- return ""_utf16_fly_string;
-
- auto const& item = m_data_transfer->drag_data(*m_item_index);
-
- switch (item.kind) {
- case DragDataStoreItem::Kind::Text:
- return "string"_utf16_fly_string;
- case DragDataStoreItem::Kind::File:
- return "file"_utf16_fly_string;
- }
-
- VERIFY_NOT_REACHED();
-}
-
-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitem-type
-Utf16String DataTransferItem::type() const
-{
- // The type attribute must return the empty string if the DataTransferItem object is in the disabled mode; otherwise
- // it must return the drag data item type string of the item represented by the DataTransferItem object.
- if (!mode().has_value())
- return {};
-
- auto const& item = m_data_transfer->drag_data(*m_item_index);
- return item.type_string.to_utf16_string();
-}
-
-Optional<DragDataStore::Mode> DataTransferItem::mode() const
-{
- if (!m_item_index.has_value())
- return {};
- return m_data_transfer->mode();
-}
-
-Optional<Utf16String> DataTransferItem::string_data() const
-{
- if (mode() != DragDataStore::Mode::ReadWrite && mode() != DragDataStore::Mode::ReadOnly)
- return {};
-
- auto const& item = m_data_transfer->drag_data(*m_item_index);
-
- if (item.kind != DragDataStoreItem::Kind::Text)
- return {};
-
- return item.data;
-}
-
-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitem-getasstring
-void DataTransferItem::get_as_string(GC::Ptr<WebIDL::CallbackType> callback) const
-{
- // 1. If the callback is null, return.
- if (!callback)
- return;
-
- // 2. If the DataTransferItem object is not in the read/write mode or the read-only mode, return. The callback is
- // never invoked.
- // 3. If the drag data item kind is not text, then return. The callback is never invoked.
- auto data = string_data();
- if (!data.has_value())
- return;
-
- // 4. Otherwise, queue a task to invoke callback, passing the actual data of the item represented by the
- // DataTransferItem object as the argument.
- HTML::queue_a_task(HTML::Task::Source::Unspecified, nullptr, nullptr,
- GC::create_function(GC::Heap::the(), GC::captures(callback, data.release_value()), [](auto& callback, auto& data) {
- auto& vm = callback->callback->vm();
- auto wrapped_data = JS::PrimitiveString::create(vm, move(data));
- (void)WebIDL::invoke_callback(*callback, {}, { { wrapped_data } });
- }));
-}
-
-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitem-getasfile
-GC::Ptr<FileAPI::File> DataTransferItem::get_as_file() const
-{
- // 1. If the DataTransferItem object is not in the read/write mode or the read-only mode, then return null
- if (mode() != DragDataStore::Mode::ReadWrite && mode() != DragDataStore::Mode::ReadOnly)
- return nullptr;
-
- auto const& item = m_data_transfer->drag_data(*m_item_index);
-
- // 2. If the drag data item kind is not File, then return null.
- if (item.kind != DragDataStoreItem::Kind::File)
- return nullptr;
-
- // 3. Return a new File object representing the actual data of the item represented by the DataTransferItem object.
- // FIXME: Fill in other fields (e.g. last_modified).
- return FileAPI::File::create(item.file_data, item.file_name, item.type_string.to_utf16_string());
-}
-
-// https://wicg.github.io/entries-api/#dom-datatransferitem-webkitgetasentry
-GC::Ptr<EntriesAPI::FileSystemEntry> DataTransferItem::webkit_get_as_entry() const
-{
- // 1. Let store be this's DataTransfer object’s drag data store.
-
- // 2. If store’s drag data store mode is not read/write mode or read-only mode, return null and abort these steps
- if (mode() != DragDataStore::Mode::ReadWrite && mode() != DragDataStore::Mode::ReadOnly)
- return nullptr;
-
- // 3. Let item be the item in store’s drag data store item list that this represents.
- auto const& item = m_data_transfer->drag_data(*m_item_index);
-
- // 4. If item’s kind is not File, then return null and abort these steps.
- if (item.kind != DragDataStoreItem::Kind::File)
- return nullptr;
-
- // 5. Return a new FileSystemEntry object representing the entry.
- return EntriesAPI::FileSystemEntry::create(EntriesAPI::EntryType::File, item.file_name.to_utf8().to_byte_string());
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/DataTransferItem.h b/Libraries/LibWeb/HTML/DataTransferItem.h
deleted file mode 100644
index 6676c414e47..00000000000
--- a/Libraries/LibWeb/HTML/DataTransferItem.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2024, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/EntriesAPI/FileSystemEntry.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/HTML/DragDataStore.h>
-
-namespace Web::WebIDL {
-
-class CallbackType;
-
-}
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/dnd.html#the-datatransferitem-interface
-class DataTransferItem : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(DataTransferItem, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(DataTransferItem);
-
-public:
- static GC::Ref<DataTransferItem> create(GC::Ref<DataTransfer>, size_t item_index);
- virtual ~DataTransferItem() override;
-
- Utf16FlyString kind() const;
- Utf16String type() const;
- void set_item_index(Badge<DataTransfer>, Optional<size_t> index) { m_item_index = move(index); }
-
- Optional<Utf16String> string_data() const;
- void get_as_string(GC::Ptr<WebIDL::CallbackType>) const;
- GC::Ptr<FileAPI::File> get_as_file() const;
-
- GC::Ptr<EntriesAPI::FileSystemEntry> webkit_get_as_entry() const;
-
-private:
- DataTransferItem(GC::Ref<DataTransfer>, size_t item_index);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- Optional<DragDataStore::Mode> mode() const;
-
- GC::Ref<DataTransfer> m_data_transfer;
- Optional<size_t> m_item_index;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/DataTransferItem.idl b/Libraries/LibWeb/HTML/DataTransferItem.idl
index 87e4cadf117..aac15559727 100644
--- a/Libraries/LibWeb/HTML/DataTransferItem.idl
+++ b/Libraries/LibWeb/HTML/DataTransferItem.idl
@@ -1,7 +1,7 @@
callback FunctionStringCallback = undefined (DOMString data);
// https://html.spec.whatwg.org/multipage/dnd.html#datatransferitem
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface DataTransferItem {
readonly attribute DOMString kind;
readonly attribute DOMString type;
diff --git a/Libraries/LibWeb/HTML/DataTransferItemList.cpp b/Libraries/LibWeb/HTML/DataTransferItemList.cpp
deleted file mode 100644
index 485918561ee..00000000000
--- a/Libraries/LibWeb/HTML/DataTransferItemList.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (c) 2024, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/FileAPI/File.h>
-#include <LibWeb/HTML/DataTransfer.h>
-#include <LibWeb/HTML/DataTransferItem.h>
-#include <LibWeb/HTML/DataTransferItemList.h>
-#include <LibWebCommon/Infra/Strings.h>
-
-namespace Web::HTML {
-
-GC_DEFINE_ALLOCATOR(DataTransferItemList);
-
-GC::Ref<DataTransferItemList> DataTransferItemList::create(GC::Ref<DataTransfer> data_transfer)
-{
- return GC::Heap::the().allocate<DataTransferItemList>(data_transfer);
-}
-
-DataTransferItemList::DataTransferItemList(GC::Ref<DataTransfer> data_transfer)
- : m_data_transfer(data_transfer)
-{
-}
-
-DataTransferItemList::~DataTransferItemList() = default;
-
-void DataTransferItemList::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_data_transfer);
-}
-
-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitemlist-length
-WebIDL::UnsignedLong DataTransferItemList::length() const
-{
- // The length attribute must return zero if the object is in the disabled mode; otherwise it must return the number
- // of items in the drag data store item list.
- return m_data_transfer->length();
-}
-
-GC::Ptr<DataTransferItem> DataTransferItemList::item(size_t index) const
-{
- if (index >= m_data_transfer->length())
- return nullptr;
- return m_data_transfer->item(index);
-}
-
-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitemlist-add
-WebIDL::ExceptionOr<GC::Ptr<DataTransferItem>> DataTransferItemList::add(Utf16String const& data, Utf16String const& type)
-{
- // 1. If the DataTransferItemList object is not in the read/write mode, return null.
- if (m_data_transfer->mode() != DragDataStore::Mode::ReadWrite)
- return nullptr;
-
- // 2. Jump to the appropriate set of steps from the following list:
- // -> If the first argument to the method is a string
-
- // If there is already an item in the drag data store item list whose kind is text and whose type string is equal
- // to the value of the method's second argument, converted to ASCII lowercase, then throw a "NotSupportedError"
- // DOMException.
- if (m_data_transfer->contains_item_with_type(DragDataStoreItem::Kind::Text, type.utf16_view()))
- return WebIDL::NotSupportedError::create(Utf16String::formatted("There is already a DataTransferItem with type {}", type));
-
- // Otherwise, add an item to the drag data store item list whose kind is text, whose type string is equal to the
- // value of the method's second argument, converted to ASCII lowercase, and whose data is the string given by the
- // method's first argument.
- auto lowercase_type = type.to_ascii_lowercase();
- auto item = m_data_transfer->add_item({
- .kind = HTML::DragDataStoreItem::Kind::Text,
- .type_string = Utf16FlyString::from_utf16(lowercase_type.utf16_view()),
- .data = data,
- .file_data = {},
- .file_name = {},
- });
-
- // 3. Determine the value of the indexed property corresponding to the newly added item, and return that value (a
- // newly created DataTransferItem object).
- return item;
-}
-
-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitemlist-add
-GC::Ptr<DataTransferItem> DataTransferItemList::add(GC::Ref<FileAPI::File> file)
-{
- // 1. If the DataTransferItemList object is not in the read/write mode, return null.
- if (m_data_transfer->mode() != DragDataStore::Mode::ReadWrite)
- return nullptr;
-
- // 2. Jump to the appropriate set of steps from the following list:
- // -> If the first argument to the method is a File
-
- // Add an item to the drag data store item list whose kind is File, whose type string is the type of the File,
- // converted to ASCII lowercase, and whose data is the same as the File's data.
- auto item = m_data_transfer->add_item({
- .kind = HTML::DragDataStoreItem::Kind::File,
- .type_string = file->type().to_ascii_lowercase(),
- .data = {},
- .file_data = MUST(ByteBuffer::copy(file->raw_bytes())),
- .file_name = file->name(),
- });
-
- // 3. Determine the value of the indexed property corresponding to the newly added item, and return that value (a
- // newly created DataTransferItem object).
- return item;
-}
-
-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitemlist-remove
-WebIDL::ExceptionOr<void> DataTransferItemList::remove(WebIDL::UnsignedLong index)
-{
- // 1. If the DataTransferItemList object is not in the read/write mode, throw an "InvalidStateError" DOMException.
- if (m_data_transfer->mode() != DragDataStore::Mode::ReadWrite)
- return WebIDL::InvalidStateError::create("DataTransferItemList is not in read/write mode"_utf16);
-
- // 2. If the drag data store does not contain an indexth item, then return.
- if (index >= m_data_transfer->length())
- return {};
-
- // 3. Remove the indexth item from the drag data store
- m_data_transfer->remove_item(index);
-
- return {};
-}
-
-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitemlist-clear
-void DataTransferItemList::clear()
-{
- // The clear() method, if the DataTransferItemList object is in the read/write mode, must remove all the items from
- // the drag data store. Otherwise, it must do nothing.
- if (m_data_transfer->mode() != DragDataStore::Mode::ReadWrite)
- return;
-
- while (m_data_transfer->length() > 0)
- m_data_transfer->remove_item(m_data_transfer->length() - 1);
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/DataTransferItemList.h b/Libraries/LibWeb/HTML/DataTransferItemList.h
deleted file mode 100644
index 0124749a927..00000000000
--- a/Libraries/LibWeb/HTML/DataTransferItemList.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2024, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/dnd.html#the-datatransferitemlist-interface
-class DataTransferItemList : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(DataTransferItemList, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(DataTransferItemList);
-
-public:
- static GC::Ref<DataTransferItemList> create(GC::Ref<DataTransfer>);
- virtual ~DataTransferItemList() override;
-
- WebIDL::UnsignedLong length() const;
- GC::Ptr<DataTransferItem> item(size_t index) const;
-
- WebIDL::ExceptionOr<GC::Ptr<DataTransferItem>> add(Utf16String const& data, Utf16String const& type);
- GC::Ptr<DataTransferItem> add(GC::Ref<FileAPI::File>);
- WebIDL::ExceptionOr<void> remove(WebIDL::UnsignedLong index);
- void clear();
-
-private:
- explicit DataTransferItemList(GC::Ref<DataTransfer>);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<DataTransfer> m_data_transfer;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/DataTransferItemList.idl b/Libraries/LibWeb/HTML/DataTransferItemList.idl
index b1b0343aa68..ccf3c181869 100644
--- a/Libraries/LibWeb/HTML/DataTransferItemList.idl
+++ b/Libraries/LibWeb/HTML/DataTransferItemList.idl
@@ -1,10 +1,10 @@
// https://html.spec.whatwg.org/multipage/dnd.html#datatransferitemlist
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface DataTransferItemList {
readonly attribute unsigned long length;
getter DataTransferItem (unsigned long index);
- DataTransferItem? add(DOMString data, DOMString type);
- DataTransferItem? add(File data);
+ [ImplementedAs=add_string] DataTransferItem? add(DOMString data, DOMString type);
+ [ImplementedAs=add_file] DataTransferItem? add(File data);
undefined remove(unsigned long index);
undefined clear();
};
diff --git a/Tests/LibWeb/Text/expected/HTML/data-transfer.txt b/Tests/LibWeb/Text/expected/HTML/data-transfer.txt
index 6b6e34a93fe..97fb06d08f5 100644
--- a/Tests/LibWeb/Text/expected/HTML/data-transfer.txt
+++ b/Tests/LibWeb/Text/expected/HTML/data-transfer.txt
@@ -9,3 +9,8 @@ fileItem: kind=file, type=text/plain
length=3, types=custom-type,text/plain,Files
fileItemAsFile: name=file.txt, type=text/plain
fileItemAsEntry: name=file.txt, file=true, directory=false
+item indices after removal: 0,1
+surviving file item keeps its identity: true
+removed item kind: ""
+callback ran before yielding: false
+queued string after removal: well hello friends
diff --git a/Tests/LibWeb/Text/input/HTML/data-transfer.html b/Tests/LibWeb/Text/input/HTML/data-transfer.html
index 92aeacb5ec8..574326cd87b 100644
--- a/Tests/LibWeb/Text/input/HTML/data-transfer.html
+++ b/Tests/LibWeb/Text/input/HTML/data-transfer.html
@@ -53,5 +53,19 @@
if (dataTransferItemList[3] !== undefined) {
println("FAILED");
}
+
+ let callbackRan = false;
+ const queuedData = new Promise(resolve => {
+ stringItem.getAsString(data => {
+ callbackRan = true;
+ resolve(data);
+ });
+ });
+ dataTransferItemList.remove(0);
+ println(`item indices after removal: ${Object.keys(dataTransferItemList).join(",")}`);
+ println(`surviving file item keeps its identity: ${dataTransferItemList[1] === fileItem}`);
+ println(`removed item kind: ${JSON.stringify(stringItem.kind)}`);
+ println(`callback ran before yielding: ${callbackRan}`);
+ println(`queued string after removal: ${await queuedData}`);
});
</script>