Skip to main content

script/dom/characterdata/
characterdata.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
5//! DOM bindings for `CharacterData`.
6use std::cell::LazyCell;
7
8use atomic_refcell::{AtomicRef, AtomicRefCell};
9use dom_struct::dom_struct;
10use js::context::JSContext;
11use script_bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId, TextTypeId};
12use servo_base::text::{AssumeUnder4GB, RangeAny, Utf16CodeUnits, Utf32CodeUnits};
13
14use crate::dom::bindings::cell::AtomicSafeBorrowMut;
15use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
16use crate::dom::bindings::codegen::Bindings::NodeBinding::Node_Binding::NodeMethods;
17use crate::dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods;
18use crate::dom::bindings::codegen::UnionTypes::NodeOrString;
19use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
20use crate::dom::bindings::inheritance::Castable;
21use crate::dom::bindings::root::{DomRoot, LayoutDom};
22use crate::dom::bindings::str::DOMString;
23use crate::dom::cdatasection::CDATASection;
24use crate::dom::comment::Comment;
25use crate::dom::document::Document;
26use crate::dom::element::Element;
27use crate::dom::mutationobserver::{Mutation, MutationObserver};
28use crate::dom::node::virtualmethods::vtable_for;
29use crate::dom::node::{ChildrenMutation, Node, NodeDamage};
30use crate::dom::processinginstruction::ProcessingInstruction;
31use crate::dom::text::Text;
32
33// https://dom.spec.whatwg.org/#characterdata
34#[dom_struct]
35pub(crate) struct CharacterData {
36    node: Node,
37    #[no_trace]
38    data: AtomicRefCell<String>,
39}
40
41impl CharacterData {
42    pub(crate) fn new_inherited(data: DOMString, document: &Document) -> CharacterData {
43        CharacterData {
44            node: Node::new_inherited(document),
45            data: AtomicRefCell::new(String::from(data)),
46        }
47    }
48
49    pub(crate) fn clone_with_data(
50        &self,
51        cx: &mut js::context::JSContext,
52        data: DOMString,
53        document: &Document,
54    ) -> DomRoot<Node> {
55        match self.upcast::<Node>().type_id() {
56            NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => {
57                DomRoot::upcast(Comment::new(cx, data, document, None))
58            },
59            NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => {
60                let pi = self.downcast::<ProcessingInstruction>().unwrap();
61                DomRoot::upcast(ProcessingInstruction::new(cx, pi.Target(), data, document))
62            },
63            NodeTypeId::CharacterData(CharacterDataTypeId::Text(TextTypeId::CDATASection)) => {
64                DomRoot::upcast(CDATASection::new(cx, data, document))
65            },
66            NodeTypeId::CharacterData(CharacterDataTypeId::Text(TextTypeId::Text)) => {
67                DomRoot::upcast(Text::new(cx, data, document))
68            },
69            _ => unreachable!(),
70        }
71    }
72
73    #[inline]
74    pub(crate) fn data(&self) -> AtomicRef<'_, String> {
75        self.data.borrow()
76    }
77
78    #[inline]
79    pub(crate) fn append_data(&self, cx: &mut JSContext, data: &str) {
80        self.queue_mutation_record(cx);
81        self.data.safe_borrow_mut(cx.no_gc()).push_str(data);
82        self.content_changed(cx);
83    }
84
85    fn content_changed(&self, cx: &mut JSContext) {
86        let node = self.upcast::<Node>();
87        node.dirty(cx.no_gc(), NodeDamage::Other);
88
89        // If this is a Text node, we might need to re-parse (say, if our parent
90        // is a <style> element.) We don't need to if this is a Comment or
91        // ProcessingInstruction.
92        if self.is::<Text>() &&
93            let Some(parent_node) = node.GetParentNode()
94        {
95            let mutation = ChildrenMutation::ChangeText;
96            vtable_for(&parent_node).children_changed(cx, &mutation);
97        }
98    }
99
100    // Queue a MutationObserver record before changing the content.
101    fn queue_mutation_record(&self, cx: &mut JSContext) {
102        let mutation = LazyCell::new(|| Mutation::CharacterData {
103            old_value: self.data.borrow(),
104        });
105        MutationObserver::queue_a_mutation_record(cx, self.upcast::<Node>(), mutation);
106    }
107
108    /// Returns whether `new_range` was successfully set on an existing text run
109    pub(crate) fn set_text_run_selection(
110        &self,
111        new_range: Option<RangeAny<Utf32CodeUnits>>,
112        new_paints_caret: bool,
113    ) -> bool {
114        self.upcast::<Node>()
115            .layout_data()
116            .borrow()
117            .as_ref()
118            .is_some_and(|layout_data| {
119                layout_data.set_text_run_selection(new_range, new_paints_caret)
120            })
121    }
122
123    /// Returns the rendered text for this [`CharacterData`].
124    pub(crate) fn rendered_text(&self, range: RangeAny<Utf32CodeUnits>) -> Option<String> {
125        self.upcast::<Node>()
126            .layout_data()
127            .borrow()
128            .as_ref()
129            .and_then(|layout_data| layout_data.rendered_text(range))
130    }
131}
132
133impl CharacterDataMethods<crate::DomTypeHolder> for CharacterData {
134    /// <https://dom.spec.whatwg.org/#dom-characterdata-data>
135    fn Data(&self) -> DOMString {
136        DOMString::from(self.data.borrow().clone())
137    }
138
139    /// <https://dom.spec.whatwg.org/#dom-characterdata-data>
140    fn SetData(&self, cx: &mut JSContext, data: DOMString) {
141        self.queue_mutation_record(cx);
142        let old_length = self.Length();
143        *self.data.safe_borrow_mut(cx.no_gc()) = data.into();
144        self.content_changed(cx);
145
146        let mut utf16_length = None;
147        // TODO: ensure that DOMString’s are under 4 GiB?
148        let mut lazy_length = move || {
149            *utf16_length.get_or_insert_with(|| {
150                Utf16CodeUnits::length_of(AssumeUnder4GB, &self.data.borrow()).0
151            })
152        };
153
154        let node: &Node = self.upcast();
155        let document = node.owner_doc_unrooted(cx.no_gc());
156        if let Some(selection) = document.selection() {
157            selection.replace_data_steps(node, 0, old_length, &mut lazy_length);
158        }
159        document.live_range_replace_data_steps(cx.no_gc(), node, 0, old_length, &mut lazy_length);
160    }
161
162    /// <https://dom.spec.whatwg.org/#dom-characterdata-length>
163    fn Length(&self) -> u32 {
164        // TODO: ensure that DOMString’s are under 4 GiB?
165        Utf16CodeUnits::length_of(AssumeUnder4GB, &self.data.borrow()).0
166    }
167
168    /// <https://dom.spec.whatwg.org/#dom-characterdata-substringdata>
169    fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> {
170        let data = self.data.borrow();
171        // Step 1.
172        let mut substring = String::new();
173        let remaining = match split_at_utf16_code_unit_offset(&data, offset) {
174            Ok((_, astral, s)) => {
175                // As if we had split the UTF-16 surrogate pair in half
176                // and then transcoded that to UTF-8 lossily,
177                // since our DOMString is currently strict UTF-8.
178                if astral.is_some() {
179                    substring += "\u{FFFD}";
180                }
181                s
182            },
183            // Step 2.
184            Err(()) => {
185                return Err(Error::IndexSize(Some(
186                    "Offset is greater than the node's length".into(),
187                )));
188            },
189        };
190        match split_at_utf16_code_unit_offset(remaining, count) {
191            // Steps 3.
192            Err(()) => substring += remaining,
193            // Steps 4.
194            Ok((s, astral, _)) => {
195                substring += s;
196                // As if we had split the UTF-16 surrogate pair in half
197                // and then transcoded that to UTF-8 lossily,
198                // since our DOMString is currently strict UTF-8.
199                if astral.is_some() {
200                    substring += "\u{FFFD}";
201                }
202            },
203        };
204        Ok(DOMString::from(substring))
205    }
206
207    /// <https://dom.spec.whatwg.org/#dom-characterdata-appenddata>
208    fn AppendData(&self, cx: &mut JSContext, data: DOMString) {
209        // > The appendData(data) method steps are to replace data of this with this’s length, 0, and data.
210        //
211        // FIXME(ajeffrey): Efficient append on DOMStrings?
212        self.append_data(cx, &data.str());
213    }
214
215    /// <https://dom.spec.whatwg.org/#dom-characterdata-insertdata>
216    fn InsertData(&self, cx: &mut JSContext, offset: u32, arg: DOMString) -> ErrorResult {
217        // > The insertData(offset, data) method steps are to replace data of this with offset, 0, and data.
218        self.ReplaceData(cx, offset, 0, arg)
219    }
220
221    /// <https://dom.spec.whatwg.org/#dom-characterdata-deletedata>
222    fn DeleteData(&self, cx: &mut JSContext, offset: u32, count: u32) -> ErrorResult {
223        // > The deleteData(offset, count) method steps are to replace data of this with offset, count, and the empty string.
224        self.ReplaceData(cx, offset, count, DOMString::new())
225    }
226
227    /// <https://dom.spec.whatwg.org/#dom-characterdata-replacedata>
228    fn ReplaceData(
229        &self,
230        cx: &mut JSContext,
231        offset: u32,
232        count: u32,
233        arg: DOMString,
234    ) -> ErrorResult {
235        let mut new_data;
236        {
237            let data = self.data.borrow();
238
239            let (prefix, replacement_before, remaining) =
240                match split_at_utf16_code_unit_offset(&data, offset) {
241                    Ok((prefix, astral, remaining)) => {
242                        // As if we had split the UTF-16 surrogate pair in half
243                        // and then transcoded that to UTF-8 lossily,
244                        // since our DOMString is currently strict UTF-8.
245                        let replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" };
246                        (prefix, replacement_before, remaining)
247                    },
248                    // Step 2.
249                    Err(()) => {
250                        return Err(Error::IndexSize(Some(
251                            "Offset is greater than the node's length".into(),
252                        )));
253                    },
254                };
255
256            let (replacement_after, suffix) =
257                match split_at_utf16_code_unit_offset(remaining, count) {
258                    // Steps 3.
259                    Err(()) => ("", ""),
260                    Ok((_, astral, suffix)) => {
261                        // As if we had split the UTF-16 surrogate pair in half
262                        // and then transcoded that to UTF-8 lossily,
263                        // since our DOMString is currently strict UTF-8.
264                        let replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" };
265                        (replacement_after, suffix)
266                    },
267                };
268
269            // Step 4: Mutation observers.
270            self.queue_mutation_record(cx);
271
272            // Step 5 to 7.
273            new_data = String::with_capacity(
274                prefix.len() +
275                    replacement_before.len() +
276                    usize::from(arg.len_utf8()) +
277                    replacement_after.len() +
278                    suffix.len(),
279            );
280            new_data.push_str(prefix);
281            new_data.push_str(replacement_before);
282            new_data.push_str(&arg.str());
283            new_data.push_str(replacement_after);
284            new_data.push_str(suffix);
285        }
286        *self.data.safe_borrow_mut(cx.no_gc()) = new_data;
287        self.content_changed(cx);
288
289        let node = self.upcast::<Node>();
290
291        let mut utf16_length = None;
292        // TODO: ensure that DOMString’s are under 4 GiB?
293        let mut lazy_length = move || {
294            *utf16_length
295                .get_or_insert_with(|| Utf16CodeUnits::length_of(AssumeUnder4GB, &arg.str()).0)
296        };
297
298        let document = node.owner_doc_unrooted(cx.no_gc());
299        if let Some(selection) = document.selection() {
300            selection.replace_data_steps(node, offset, count, &mut lazy_length);
301        }
302        document.live_range_replace_data_steps(cx.no_gc(), node, offset, count, &mut lazy_length);
303
304        // Step 12: If node is a ProcessingInstruction node and piAttributesAlreadyUpdated
305        // is false, then update attributes from data given node.
306        // TODO: Implement this.
307
308        // Step 13: If node’s parent is non-null, then run the children changed steps for
309        // node’s parent.
310        // TODO: This is handled above, but it should be handled here.
311
312        Ok(())
313    }
314
315    /// <https://dom.spec.whatwg.org/#dom-childnode-before>
316    fn Before(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
317        self.upcast::<Node>().before(cx, nodes)
318    }
319
320    /// <https://dom.spec.whatwg.org/#dom-childnode-after>
321    fn After(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
322        self.upcast::<Node>().after(cx, nodes)
323    }
324
325    /// <https://dom.spec.whatwg.org/#dom-childnode-replacewith>
326    fn ReplaceWith(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
327        self.upcast::<Node>().replace_with(cx, nodes)
328    }
329
330    /// <https://dom.spec.whatwg.org/#dom-childnode-remove>
331    fn Remove(&self, cx: &mut JSContext) {
332        self.upcast::<Node>().remove_self(cx);
333    }
334
335    /// <https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling>
336    fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> {
337        self.upcast::<Node>()
338            .preceding_siblings()
339            .find_map(DomRoot::downcast)
340    }
341
342    /// <https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling>
343    fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> {
344        self.upcast::<Node>()
345            .following_siblings()
346            .find_map(DomRoot::downcast)
347    }
348}
349
350impl<'dom> LayoutDom<'dom, CharacterData> {
351    #[inline]
352    pub(crate) fn data_for_layout(self) -> AtomicRef<'dom, str> {
353        AtomicRef::map(self.unsafe_get().data.borrow(), |data| &**data)
354    }
355}
356
357/// Split the given string at the given position measured in UTF-16 code units from the start.
358///
359/// * `Err(())` indicates that `offset` if after the end of the string
360/// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points.
361///   The two string slices are such that:
362///   `before == s.to_utf16()[..offset].to_utf8()` and
363///   `after == s.to_utf16()[offset..].to_utf8()`
364/// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle"
365///   of a single Unicode code point that would be represented in UTF-16 by a surrogate pair
366///   of two 16-bit code units.
367///   `ch` is that code point.
368///   The two string slices are such that:
369///   `before == s.to_utf16()[..offset - 1].to_utf8()` and
370///   `after == s.to_utf16()[offset + 1..].to_utf8()`
371fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> {
372    let mut code_units = 0;
373    for (i, c) in s.char_indices() {
374        if code_units == offset {
375            let (a, b) = s.split_at(i);
376            return Ok((a, None, b));
377        }
378        code_units += 1;
379        if c > '\u{FFFF}' {
380            if code_units == offset {
381                debug_assert_eq!(c.len_utf8(), 4);
382                warn!("Splitting a surrogate pair in CharacterData API.");
383                return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..]));
384            }
385            code_units += 1;
386        }
387    }
388    if code_units == offset {
389        Ok((s, None, ""))
390    } else {
391        Err(())
392    }
393}