Skip to main content

script/dom/datatransfer/
datatransferitemlist.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::{Ref, RefCell};
6use std::rc::Rc;
7
8use dom_struct::dom_struct;
9use js::context::JSContext;
10use js::rust::MutableHandleValue;
11use script_bindings::reflector::{Reflector, reflect_dom_object};
12
13use crate::dom::bindings::codegen::Bindings::DataTransferItemListBinding::DataTransferItemListMethods;
14use crate::dom::bindings::codegen::Bindings::FileBinding::FileMethods;
15use crate::dom::bindings::error::{Error, Fallible};
16use crate::dom::bindings::frozenarray::CachedFrozenArray;
17use crate::dom::bindings::inheritance::Castable;
18use crate::dom::bindings::reflector::DomGlobal;
19use crate::dom::bindings::root::{DomRoot, MutNullableDom};
20use crate::dom::bindings::str::{DOMString, USVString};
21use crate::dom::datatransferitem::DataTransferItem;
22use crate::dom::file::File;
23use crate::dom::filesystem::FileSystem;
24use crate::dom::filesystemdirectoryentry::FileSystemDirectoryEntry;
25use crate::dom::filesystementry::FileSystemEntry;
26use crate::dom::filesystemfileentry::FileSystemFileEntry;
27use crate::dom::window::Window;
28use crate::drag::drag_data_store::{DragDataStore, Kind, Mode};
29
30#[dom_struct]
31pub(crate) struct DataTransferItemList {
32    reflector_: Reflector,
33    #[conditional_malloc_size_of]
34    #[no_trace]
35    data_store: Rc<RefCell<Option<DragDataStore>>>,
36    frozen_types: CachedFrozenArray,
37    /// The entries-api file system for the drag data store, built lazily by
38    /// `webkitGetAsEntry()` and shared by all of the store's items.
39    /// Must be cleared whenever the store's File items change.
40    filesystem: MutNullableDom<FileSystem>,
41}
42
43impl DataTransferItemList {
44    fn new_inherited(data_store: Rc<RefCell<Option<DragDataStore>>>) -> DataTransferItemList {
45        DataTransferItemList {
46            reflector_: Reflector::new(),
47            frozen_types: CachedFrozenArray::new(),
48            data_store,
49            filesystem: MutNullableDom::new(None),
50        }
51    }
52
53    pub(crate) fn new(
54        cx: &mut JSContext,
55        window: &Window,
56        data_store: Rc<RefCell<Option<DragDataStore>>>,
57    ) -> DomRoot<DataTransferItemList> {
58        reflect_dom_object(
59            cx,
60            Box::new(DataTransferItemList::new_inherited(data_store)),
61            window,
62        )
63    }
64
65    pub(crate) fn frozen_types(&self, cx: &mut js::context::JSContext, retval: MutableHandleValue) {
66        self.frozen_types.get_or_init(
67            cx,
68            || {
69                self.data_store
70                    .borrow()
71                    .as_ref()
72                    .map_or(Vec::new(), |data_store| data_store.types())
73            },
74            retval,
75        );
76    }
77
78    pub(crate) fn invalidate_frozen_types(&self) {
79        self.frozen_types.clear();
80    }
81
82    /// Return the drag data store backing this list, if it is still associated.
83    pub(crate) fn data_store(&self) -> Option<Ref<'_, DragDataStore>> {
84        Ref::filter_map(self.data_store.borrow(), |data_store| data_store.as_ref()).ok()
85    }
86
87    /// Return the entries-api `FileSystem` for the drag data store, building it
88    /// from the File items on first use.
89    ///
90    /// <https://wicg.github.io/entries-api/#html-data>
91    /// "During a drag-and-drop operation, file and directory items are associated
92    ///  with entries. Each entry is a member of a root directory unique to the
93    ///  drag data store."
94    pub(crate) fn filesystem(&self, cx: &mut JSContext) -> DomRoot<FileSystem> {
95        self.filesystem.or_init(|| self.create_filesystem(cx))
96    }
97
98    fn create_filesystem(&self, cx: &mut JSContext) -> DomRoot<FileSystem> {
99        let global = self.global();
100        let root = FileSystemDirectoryEntry::new(
101            cx,
102            &global,
103            USVString::default(),
104            USVString::from(String::from("/")),
105        );
106        let filesystem = FileSystem::new(
107            cx,
108            &global,
109            USVString::from(String::from("filesystem")),
110            &root,
111        );
112        root.set_filesystem(&filesystem);
113
114        if let Some(store) = self.data_store.borrow().as_ref() {
115            for kind in store.iter_item_list() {
116                // Non-File items are not represented in the entries tree.
117                let Some(file) = kind.as_file(cx, &global) else {
118                    continue;
119                };
120                let name = file.Name().to_string();
121                let full_path = USVString::from(format!("/{}", name));
122                let entry =
123                    FileSystemFileEntry::new(cx, &global, USVString::from(name), full_path, &file);
124                entry.set_filesystem(&filesystem);
125                root.push_child(entry.upcast::<FileSystemEntry>());
126            }
127        }
128
129        filesystem
130    }
131}
132
133impl DataTransferItemListMethods<crate::DomTypeHolder> for DataTransferItemList {
134    /// <https://html.spec.whatwg.org/multipage/#dom-datatransferitemlist-length>
135    fn Length(&self) -> u32 {
136        // Return zero if the object is in the disabled mode;
137        // otherwise it must return the number of items in the drag data store item list.
138        self.data_store
139            .borrow()
140            .as_ref()
141            .map_or(0, |data_store| data_store.list_len() as u32)
142    }
143
144    /// <https://html.spec.whatwg.org/multipage/#dom-datatransferitemlist-item>
145    fn IndexedGetter(
146        &self,
147        cx: &mut js::context::JSContext,
148        index: u32,
149    ) -> Option<DomRoot<DataTransferItem>> {
150        // Step 1 Return null if it isn't associated with a data store
151        let option = self.data_store.borrow();
152        let data_store = match option.as_ref() {
153            Some(value) => value,
154            _ => return None,
155        };
156
157        // Step 2
158        data_store
159            .get_by_index(index as usize)
160            .map(|(id, _)| DataTransferItem::new(cx, &self.global(), self, *id))
161    }
162
163    /// <https://html.spec.whatwg.org/multipage/#dom-datatransferitemlist-add>
164    fn Add(
165        &self,
166        cx: &mut js::context::JSContext,
167        data: DOMString,
168        mut type_: DOMString,
169    ) -> Fallible<Option<DomRoot<DataTransferItem>>> {
170        // Step 1 If the DataTransferItemList object is not in the read/write mode, return null.
171        let index = {
172            let mut option = self.data_store.borrow_mut();
173            let data_store = match option.as_mut() {
174                Some(value) if value.mode() == Mode::ReadWrite => value,
175                _ => return Ok(None),
176            };
177
178            // Add an item to the drag data store item list whose kind is text,
179            // whose type string is equal to the value of the method's second argument, converted to ASCII lowercase,
180            // and whose data is the string given by the method's first argument.
181            type_.make_ascii_lowercase();
182            data_store.add(Kind::Text { data, type_ })
183        };
184
185        index.map(|id| {
186            self.frozen_types.clear();
187
188            // Step 3 Determine the value of the indexed property corresponding to the newly added item,
189            // and return that value (a newly created DataTransferItem object).
190            Some(DataTransferItem::new(cx, &self.global(), self, id))
191        })
192    }
193
194    /// <https://html.spec.whatwg.org/multipage/#dom-datatransferitemlist-add>
195    fn Add_(
196        &self,
197        cx: &mut js::context::JSContext,
198        data: &File,
199    ) -> Fallible<Option<DomRoot<DataTransferItem>>> {
200        let index = {
201            // Step 1 If the DataTransferItemList object is not in the read/write mode, return null.
202            let mut option = self.data_store.borrow_mut();
203            let data_store = match option.as_mut() {
204                Some(value) if value.mode() == Mode::ReadWrite => value,
205                _ => return Ok(None),
206            };
207
208            // Add an item to the drag data store item list whose kind is File,
209            // whose type string is the type of the File, converted to ASCII lowercase,
210            // and whose data is the same as the File's data.
211            let mut type_ = data.file_type();
212            type_.make_ascii_lowercase();
213            let bytes = data.file_bytes().unwrap_or_default();
214            let name = data.name().clone().root();
215            data_store.add(Kind::File { bytes, name, type_ })
216        };
217        index.map(|id| {
218            self.frozen_types.clear();
219            // The entries root no longer matches the drag data store item list.
220            self.filesystem.set(None);
221
222            // Step 3 Determine the value of the indexed property corresponding to the newly added item,
223            // and return that value (a newly created DataTransferItem object).
224            Some(DataTransferItem::new(cx, &self.global(), self, id))
225        })
226    }
227
228    /// <https://html.spec.whatwg.org/multipage/#dom-datatransferitemlist-remove>
229    fn Remove(&self, index: u32) -> Fallible<()> {
230        // Step 1 If the DataTransferItemList object is not in the read/write mode,
231        // throw an "InvalidStateError" DOMException.
232        let mut option = self.data_store.borrow_mut();
233        let data_store = match option.as_mut() {
234            Some(value) if value.mode() == Mode::ReadWrite => value,
235            _ => return Err(Error::InvalidState(None)),
236        };
237
238        let index = index as usize;
239
240        // Step 2 If the drag data store does not contain an indexth item, then return.
241        if index < data_store.list_len() {
242            // Step 3 Remove the indexth item from the drag data store.
243            // The entries root no longer matches the item list if a File was removed.
244            if data_store.remove(index).is_some_and(|item| item.is_file()) {
245                self.filesystem.set(None);
246            }
247            self.frozen_types.clear();
248        }
249
250        Ok(())
251    }
252
253    /// <https://html.spec.whatwg.org/multipage/#dom-datatransferitemlist-clear>
254    fn Clear(&self) {
255        // If the DataTransferItemList object is in the read/write mode, remove all the items from the drag data store.
256        // Otherwise, it must do nothing.
257        let mut option = self.data_store.borrow_mut();
258        let data_store = match option.as_mut() {
259            Some(value) if value.mode() == Mode::ReadWrite => value,
260            _ => return,
261        };
262
263        // If the item list is empty we don't clear it.
264        if data_store.list_len() > 0 {
265            data_store.clear_list();
266            // The entries root no longer matches the drag data store item list.
267            self.filesystem.set(None);
268            self.frozen_types.clear();
269        }
270    }
271}