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