Skip to main content

script/dom/mutationobserver/
mutationobserver.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::LazyCell;
6
7use dom_struct::dom_struct;
8use html5ever::{LocalName, Namespace, ns};
9use js::context::JSContext;
10use js::rust::HandleObject;
11use rustc_hash::FxHashMap;
12use script_bindings::callback::{OwnerWindow, RootedCallback, TracedCallback};
13use script_bindings::cell::DomRefCell;
14use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto};
15use style::attr::AttrValue;
16
17use crate::dom::bindings::codegen::Bindings::MutationObserverBinding::MutationObserver_Binding::MutationObserverMethods;
18use crate::dom::bindings::codegen::Bindings::MutationObserverBinding::{
19    MutationCallback, MutationObserverInit,
20};
21use crate::dom::bindings::error::{Error, Fallible};
22use crate::dom::bindings::reflector::DomGlobal;
23use crate::dom::bindings::root::{Dom, DomRoot};
24use crate::dom::bindings::str::DOMString;
25use crate::dom::iterators::ShadowIncluding;
26use crate::dom::mutationrecord::MutationRecord;
27use crate::dom::node::Node;
28use crate::dom::window::Window;
29use crate::event_loop::script_thread::ScriptThread;
30
31#[dom_struct]
32pub(crate) struct MutationObserver {
33    reflector_: Reflector,
34    callback: TracedCallback<MutationCallback>,
35    record_queue: DomRefCell<Vec<Dom<MutationRecord>>>,
36    node_list: DomRefCell<Vec<Dom<Node>>>,
37}
38
39pub(crate) enum Mutation<'a> {
40    Attribute {
41        name: LocalName,
42        namespace: Namespace,
43        old_value: Option<&'a AttrValue>,
44    },
45    CharacterData {
46        old_value: atomic_refcell::AtomicRef<'a, String>,
47    },
48    ChildList {
49        added: Option<&'a [&'a Node]>,
50        removed: Option<&'a [&'a Node]>,
51        prev: Option<&'a Node>,
52        next: Option<&'a Node>,
53    },
54}
55
56#[derive(JSTraceable, MallocSizeOf)]
57#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
58pub(crate) struct RegisteredObserver {
59    pub(crate) observer: Dom<MutationObserver>,
60    options: ObserverOptions,
61}
62
63#[derive(JSTraceable, MallocSizeOf)]
64pub(crate) struct ObserverOptions {
65    attribute_old_value: bool,
66    attributes: bool,
67    character_data: bool,
68    character_data_old_value: bool,
69    child_list: bool,
70    subtree: bool,
71    attribute_filter: Vec<DOMString>,
72}
73
74impl MutationObserver {
75    fn new_with_proto(
76        cx: &mut JSContext,
77        global: &Window,
78        proto: Option<HandleObject>,
79        callback: RootedCallback<MutationCallback>,
80    ) -> DomRoot<MutationObserver> {
81        let boxed_observer = Box::new(MutationObserver::new_inherited(callback));
82        reflect_dom_object_with_proto(cx, boxed_observer, global, proto)
83    }
84
85    fn new_inherited(callback: RootedCallback<MutationCallback>) -> MutationObserver {
86        MutationObserver {
87            reflector_: Reflector::new(),
88            callback: callback.to_traced(),
89            record_queue: DomRefCell::new(vec![]),
90            node_list: DomRefCell::new(vec![]),
91        }
92    }
93
94    pub(crate) fn record_queue(&self) -> &DomRefCell<Vec<Dom<MutationRecord>>> {
95        &self.record_queue
96    }
97
98    pub(crate) fn callback(&self) -> &TracedCallback<MutationCallback> {
99        &self.callback
100    }
101
102    /// <https://dom.spec.whatwg.org/#queueing-a-mutation-record>
103    pub(crate) fn queue_a_mutation_record<'a, F>(
104        cx: &mut JSContext,
105        target: &Node,
106        attr_type: LazyCell<Mutation<'a>, F>,
107    ) where
108        F: FnOnce() -> Mutation<'a>,
109    {
110        if !target.global().as_window().get_exists_mut_observer() {
111            return;
112        }
113        // Step 1 Let interestedObservers be an empty map.
114        let mut interested_observers: FxHashMap<DomRoot<MutationObserver>, Option<DOMString>> =
115            FxHashMap::default();
116
117        // Step 2 Let nodes be the inclusive ancestors of target.
118        // Step 3 For each node in nodes ...
119        for node in target.inclusive_ancestors_unrooted(cx.no_gc(), ShadowIncluding::No) {
120            let registered = node.registered_mutation_observers();
121            if registered.is_none() {
122                continue;
123            }
124
125            // Step 3 ... and then for each registered of node’s registered observer list:
126            for registered in &*registered.unwrap() {
127                // 3.2 "1": node is not target and options["subtree"] is false
128                if *node != target && !registered.options.subtree {
129                    continue;
130                }
131
132                match *attr_type {
133                    // 3.2 "2", "3"
134                    Mutation::Attribute {
135                        ref name,
136                        ref namespace,
137                        ref old_value,
138                    } => {
139                        // 3.1.2 "2": type is "attributes" and options["attributes"] either does not exist or is false
140                        if !registered.options.attributes {
141                            continue;
142                        }
143                        // 3.1.2 "3": type is "attributes", options["attributeFilter"] exists,
144                        // and options["attributeFilter"] does not contain name or namespace is non-null
145                        if !registered.options.attribute_filter.is_empty() {
146                            if *namespace != ns!() {
147                                continue;
148                            }
149                            if !registered
150                                .options
151                                .attribute_filter
152                                .iter()
153                                .any(|s| *s == **name)
154                            {
155                                continue;
156                            }
157                        }
158                        // 3.2.1 Let mo be registered’s observer.
159                        let mo = registered.observer.as_rooted();
160                        // 3.2.2 If interestedObservers[mo] does not exist, then set interestedObservers[mo] to null.
161                        if registered.options.attribute_old_value {
162                            // 3.2.3 ... type is "attributes" and options["attributeOldValue"] is true ...
163                            interested_observers.insert(
164                                mo,
165                                old_value.map(|attr_value| DOMString::from(&**attr_value)),
166                            );
167                        } else {
168                            // 3.2.2 If interestedObservers[mo] does not exist, then set interestedObservers[mo] to null.
169                            interested_observers.entry(mo).or_insert(None);
170                        }
171                    },
172                    // 3.2 "4"
173                    Mutation::CharacterData { ref old_value } => {
174                        // 3.2 "4": type is "characterData" and options["characterData"] either does not exist or is false
175                        if !registered.options.character_data {
176                            continue;
177                        }
178                        // 3.2.1 Let mo be registered’s observer.
179                        let mo = registered.observer.as_rooted();
180                        if registered.options.character_data_old_value {
181                            // 3.2.3 ... type is "characterData" and options["characterDataOldValue"] is true
182                            interested_observers
183                                .insert(mo, Some(DOMString::from(old_value.as_str())));
184                        } else {
185                            // 3.2.2 If interestedObservers[mo] does not exist, then set interestedObservers[mo] to null.
186                            interested_observers.entry(mo).or_insert(None);
187                        }
188                    },
189                    // 3.2 "5"
190                    Mutation::ChildList { .. } => {
191                        // 3.2 "5": type is "childList" and options["childList"] is false
192                        if !registered.options.child_list {
193                            continue;
194                        }
195                        // 3.2.1 Let mo be registered’s observer.
196                        let mo = registered.observer.as_rooted();
197                        // 3.2.2 If interestedObservers[mo] does not exist, then set interestedObservers[mo] to null.
198                        interested_observers.entry(mo).or_insert(None);
199                    },
200                }
201            }
202        }
203
204        // Step 4 For each observer → mappedOldValue of interestedObservers:
205        for (observer, mapped_old_value) in interested_observers {
206            // Step 4.1 Let record be a new MutationRecord object ...
207            let record = match *attr_type {
208                Mutation::Attribute {
209                    ref name,
210                    ref namespace,
211                    ..
212                } => {
213                    let namespace = if *namespace != ns!() {
214                        Some(namespace)
215                    } else {
216                        None
217                    };
218                    MutationRecord::attribute_mutated(cx, target, name, namespace, mapped_old_value)
219                },
220                Mutation::CharacterData { .. } => {
221                    MutationRecord::character_data_mutated(cx, target, mapped_old_value)
222                },
223                Mutation::ChildList {
224                    ref added,
225                    ref removed,
226                    ref next,
227                    ref prev,
228                } => MutationRecord::child_list_mutated(cx, target, *added, *removed, *next, *prev),
229            };
230            // Step 4.2 Enqueue record to observer’s record queue.
231            observer
232                .record_queue
233                .borrow_mut()
234                .push(Dom::from_ref(&*record));
235            // Step 4.3 Append observer to the surrounding agent’s pending mutation observers.
236            ScriptThread::mutation_observers().add_mutation_observer(&observer);
237        }
238
239        // Step 5 Queue a mutation observer microtask.
240        let mutation_observers = ScriptThread::mutation_observers();
241        mutation_observers.queue_mutation_observer_microtask(cx);
242    }
243}
244
245impl MutationObserverMethods<crate::DomTypeHolder> for MutationObserver {
246    /// <https://dom.spec.whatwg.org/#dom-mutationobserver-mutationobserver>
247    fn Constructor(
248        cx: &mut JSContext,
249        global: &Window,
250        proto: Option<HandleObject>,
251        callback: RootedCallback<MutationCallback>,
252    ) -> Fallible<DomRoot<MutationObserver>> {
253        global.set_exists_mut_observer();
254        let observer = MutationObserver::new_with_proto(cx, global, proto, callback);
255        ScriptThread::mutation_observers().add_mutation_observer(&observer);
256        Ok(observer)
257    }
258
259    /// <https://dom.spec.whatwg.org/#dom-mutationobserver-observe>
260    fn Observe(&self, target: &Node, options: &MutationObserverInit) -> Fallible<()> {
261        let attribute_filter = options.attributeFilter.clone().unwrap_or_default();
262        let attribute_old_value = options.attributeOldValue.unwrap_or(false);
263        let mut attributes = options.attributes.unwrap_or(false);
264        let mut character_data = options.characterData.unwrap_or(false);
265        let character_data_old_value = options.characterDataOldValue.unwrap_or(false);
266        let child_list = options.childList;
267        let subtree = options.subtree;
268
269        // Step 1
270        if (options.attributeOldValue.is_some() || options.attributeFilter.is_some()) &&
271            options.attributes.is_none()
272        {
273            attributes = true;
274        }
275
276        // Step 2
277        if options.characterDataOldValue.is_some() && options.characterData.is_none() {
278            character_data = true;
279        }
280
281        // Step 3
282        if !child_list && !attributes && !character_data {
283            return Err(Error::Type(
284                c"One of childList, attributes, or characterData must be true".into(),
285            ));
286        }
287
288        // Step 4
289        if attribute_old_value && !attributes {
290            return Err(Error::Type(
291                c"attributeOldValue is true but attributes is false".into(),
292            ));
293        }
294
295        // Step 5
296        if options.attributeFilter.is_some() && !attributes {
297            return Err(Error::Type(
298                c"attributeFilter is present but attributes is false".into(),
299            ));
300        }
301
302        // Step 6
303        if character_data_old_value && !character_data {
304            return Err(Error::Type(
305                c"characterDataOldValue is true but characterData is false".into(),
306            ));
307        }
308
309        // Step 7
310        let add_new_observer = {
311            let mut replaced = false;
312            for registered in &mut *target.registered_mutation_observers_mut() {
313                if registered.observer != self {
314                    continue;
315                }
316                // TODO: remove matching transient registered observers
317                registered.options.attribute_old_value = attribute_old_value;
318                registered.options.attributes = attributes;
319                registered.options.character_data = character_data;
320                registered.options.character_data_old_value = character_data_old_value;
321                registered.options.child_list = child_list;
322                registered.options.subtree = subtree;
323                registered
324                    .options
325                    .attribute_filter
326                    .clone_from(&attribute_filter);
327                replaced = true;
328            }
329            !replaced
330        };
331
332        // Step 8
333        if add_new_observer {
334            target.add_mutation_observer(RegisteredObserver {
335                observer: Dom::from_ref(self),
336                options: ObserverOptions {
337                    attributes,
338                    attribute_old_value,
339                    character_data,
340                    character_data_old_value,
341                    subtree,
342                    attribute_filter,
343                    child_list,
344                },
345            });
346
347            self.node_list.borrow_mut().push(Dom::from_ref(target));
348        }
349
350        Ok(())
351    }
352
353    /// <https://dom.spec.whatwg.org/#dom-mutationobserver-takerecords>
354    fn TakeRecords(&self) -> Vec<DomRoot<MutationRecord>> {
355        let records: Vec<DomRoot<MutationRecord>> = self
356            .record_queue
357            .borrow()
358            .iter()
359            .map(|record| record.as_rooted())
360            .collect();
361        self.record_queue.borrow_mut().clear();
362        records
363    }
364
365    /// <https://dom.spec.whatwg.org/#dom-mutationobserver-disconnect>
366    fn Disconnect(&self) {
367        // Step 1
368        let nodes = self
369            .node_list
370            .borrow()
371            .iter()
372            .map(|node| node.as_rooted())
373            .collect::<Vec<_>>();
374        self.node_list.borrow_mut().clear();
375
376        for node in nodes {
377            node.remove_mutation_observer(self);
378        }
379
380        // Step 2
381        self.record_queue.borrow_mut().clear();
382    }
383}
384
385impl OwnerWindow<crate::DomTypeHolder> for MutationObserver {}