Skip to main content

script/dom/datatransfer/
datatransferitem.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::{Cell, Ref};
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use script_bindings::cell::DomRefCell;
10use script_bindings::reflector::{Reflector, reflect_dom_object};
11
12use crate::dom::bindings::callback::{ExceptionHandling, RootedCallback, TracedCallback};
13use crate::dom::bindings::codegen::Bindings::DataTransferItemBinding::{
14    DataTransferItemMethods, FunctionStringCallback,
15};
16use crate::dom::bindings::codegen::Bindings::FileBinding::FileMethods;
17use crate::dom::bindings::refcounted::Trusted;
18use crate::dom::bindings::reflector::DomGlobal;
19use crate::dom::bindings::root::{Dom, DomRoot};
20use crate::dom::bindings::str::{DOMString, USVString};
21use crate::dom::datatransferitemlist::DataTransferItemList;
22use crate::dom::file::File;
23use crate::dom::filesystementry::FileSystemEntry;
24use crate::dom::filesystemfileentry::FileSystemFileEntry;
25use crate::dom::globalscope::GlobalScope;
26use crate::drag::drag_data_store::{Kind, Mode};
27
28#[dom_struct]
29pub(crate) struct DataTransferItem {
30    reflector_: Reflector,
31    /// The `DataTransferItemList` that created this item. It owns the drag data
32    /// store and the entries-api `FileSystem` shared by all of its items.
33    list: Dom<DataTransferItemList>,
34    id: u16,
35    pending_callbacks: DomRefCell<Vec<PendingStringCallback>>,
36    next_callback: Cell<usize>,
37}
38
39#[derive(JSTraceable, MallocSizeOf)]
40#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
41struct PendingStringCallback {
42    id: usize,
43    callback: TracedCallback<FunctionStringCallback>,
44}
45
46impl DataTransferItem {
47    fn new_inherited(list: &DataTransferItemList, id: u16) -> DataTransferItem {
48        DataTransferItem {
49            reflector_: Reflector::new(),
50            list: Dom::from_ref(list),
51            id,
52            pending_callbacks: Default::default(),
53            next_callback: Cell::new(0),
54        }
55    }
56
57    pub(crate) fn new(
58        cx: &mut JSContext,
59        global: &GlobalScope,
60        list: &DataTransferItemList,
61        id: u16,
62    ) -> DomRoot<DataTransferItem> {
63        reflect_dom_object(
64            cx,
65            Box::new(DataTransferItem::new_inherited(list, id)),
66            global,
67        )
68    }
69
70    fn item_kind(&self) -> Option<Ref<'_, Kind>> {
71        let data_store = self.list.data_store()?;
72        Ref::filter_map(data_store, |data_store| data_store.get_by_id(&self.id)).ok()
73    }
74
75    fn can_read(&self) -> bool {
76        self.list
77            .data_store()
78            .is_some_and(|data_store| data_store.mode() != Mode::Protected)
79    }
80}
81
82impl DataTransferItemMethods<crate::DomTypeHolder> for DataTransferItem {
83    /// <https://html.spec.whatwg.org/multipage/#dom-datatransferitem-kind>
84    fn Kind(&self) -> DOMString {
85        self.item_kind()
86            .map_or(DOMString::new(), |item| match *item {
87                Kind::Text { .. } => DOMString::from_static("string"),
88                Kind::File { .. } => DOMString::from_static("file"),
89            })
90    }
91
92    /// <https://html.spec.whatwg.org/multipage/#dom-datatransferitem-type>
93    fn Type(&self) -> DOMString {
94        self.item_kind()
95            .map_or(DOMString::new(), |item| item.type_())
96    }
97
98    /// <https://html.spec.whatwg.org/multipage/#dom-datatransferitem-getasstring>
99    fn GetAsString(&self, callback: Option<RootedCallback<FunctionStringCallback>>) {
100        // Step 1 If the callback is null, return.
101        let Some(callback) = callback else {
102            return;
103        };
104
105        // Step 2 If the DataTransferItem object is not in the read/write mode or the read-only mode, return.
106        if !self.can_read() {
107            return;
108        }
109
110        // Step 3 If the drag data item kind is not text, then return.
111        if let Some(string) = self.item_kind().and_then(|item| item.as_string()) {
112            let id = self.next_callback.get();
113            self.pending_callbacks
114                .borrow_mut()
115                .push(PendingStringCallback {
116                    id,
117                    callback: callback.to_traced(),
118                });
119
120            self.next_callback.set(id + 1);
121            let this = Trusted::new(self);
122
123            // Step 4 Otherwise, queue a task to invoke callback,
124            // passing the actual data of the item represented by the DataTransferItem object as the argument.
125            self.global()
126                .task_manager()
127                .dom_manipulation_task_source()
128                .queue(task!(invoke_callback: move |cx| {
129                    let this = this.root();
130                    let maybe_index = this.pending_callbacks.borrow().iter().position(|val| val.id == id);
131                    if let Some(index) = maybe_index {
132                        rooted!(&in(cx) let callback = this
133                            .pending_callbacks
134                            .safe_borrow_mut(cx.no_gc())
135                            .swap_remove(index)
136                            .callback);
137                        let _ = callback.Call__(cx, DOMString::from(string), ExceptionHandling::Report);
138                    }
139                }));
140        }
141    }
142
143    /// <https://html.spec.whatwg.org/multipage/#dom-datatransferitem-getasfile>
144    fn GetAsFile(&self, cx: &mut JSContext) -> Option<DomRoot<File>> {
145        // Step 1 If the DataTransferItem object is not in the read/write mode or the read-only mode, then return null.
146        if !self.can_read() {
147            return None;
148        }
149
150        // Step 2 If the drag data item kind is not File, then return null.
151        // Step 3 Return a new File object representing the actual data
152        // of the item represented by the DataTransferItem object.
153        self.item_kind()?.as_file(cx, &self.global())
154    }
155
156    /// <https://wicg.github.io/entries-api/#dom-datatransferitem-webkitgetasentry>
157    fn WebkitGetAsEntry(&self, cx: &mut JSContext) -> Option<DomRoot<FileSystemEntry>> {
158        // Step 1. Let store be this’s DataTransfer object’s drag data store.
159        // Step 2. If store’s drag data store mode is not read/write mode or read-only mode,
160        // return null and abort these steps.
161        if !self.can_read() {
162            return None;
163        }
164
165        // Step 3. Let item be the item in store’s drag data store item list that this represents.
166        // Step 4. If item’s kind is not `File`, then return null and abort these steps.
167        if !self.item_kind().is_some_and(|item| item.is_file()) {
168            return None;
169        }
170        let global = self.global();
171
172        // <https://wicg.github.io/entries-api/#html-data>
173        //
174        // "During a drag-and-drop operation, file and directory items are associated
175        //  with entries. Each entry is a member of a root directory unique to the
176        //  drag data store."
177        let filesystem = self.list.filesystem(cx);
178
179        // Step 5. Return a new FileSystemEntry object representing the entry.
180        let file = self.item_kind()?.as_file(cx, &global)?;
181        let name = file.Name().to_string();
182        let full_path = USVString::from(format!("/{}", name));
183        let entry = FileSystemFileEntry::new(cx, &global, USVString::from(name), full_path, &file);
184        entry.set_filesystem(&filesystem);
185
186        Some(DomRoot::upcast::<FileSystemEntry>(entry))
187    }
188}