script/dom/characterdata/
characterdata.rs1use 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#[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 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 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 fn Data(&self) -> DOMString {
109 DOMString::from(self.data.borrow().clone())
110 }
111
112 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 fn Length(&self) -> u32 {
128 self.data.borrow().encode_utf16().count() as u32
129 }
130
131 fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> {
133 let data = self.data.borrow();
134 let mut substring = String::new();
136 let remaining = match split_at_utf16_code_unit_offset(&data, offset) {
137 Ok((_, astral, s)) => {
138 if astral.is_some() {
142 substring += "\u{FFFD}";
143 }
144 s
145 },
146 Err(()) => return Err(Error::IndexSize(None)),
148 };
149 match split_at_utf16_code_unit_offset(remaining, count) {
150 Err(()) => substring += remaining,
152 Ok((s, astral, _)) => {
154 substring += s;
155 if astral.is_some() {
159 substring += "\u{FFFD}";
160 }
161 },
162 };
163 Ok(DOMString::from(substring))
164 }
165
166 fn AppendData(&self, cx: &mut JSContext, data: DOMString) {
168 self.append_data(cx, &data.str());
172 }
173
174 fn InsertData(&self, cx: &mut JSContext, offset: u32, arg: DOMString) -> ErrorResult {
176 self.ReplaceData(cx, offset, 0, arg)
178 }
179
180 fn DeleteData(&self, cx: &mut JSContext, offset: u32, count: u32) -> ErrorResult {
182 self.ReplaceData(cx, offset, count, DOMString::new())
184 }
185
186 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 replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" };
207 remaining = r;
208 },
209 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 Err(()) => {
217 replacement_after = "";
218 suffix = "";
219 },
220 Ok((_, astral, s)) => {
221 replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" };
225 suffix = s;
226 },
227 };
228 self.queue_mutation_record(cx);
230
231 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 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 Ok(())
282 }
283
284 fn Before(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
286 self.upcast::<Node>().before(cx, nodes)
287 }
288
289 fn After(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
291 self.upcast::<Node>().after(cx, nodes)
292 }
293
294 fn ReplaceWith(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
296 self.upcast::<Node>().replace_with(cx, nodes)
297 }
298
299 fn Remove(&self, cx: &mut JSContext) {
301 self.upcast::<Node>().remove_self(cx);
302 }
303
304 fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> {
306 self.upcast::<Node>()
307 .preceding_siblings()
308 .find_map(DomRoot::downcast)
309 }
310
311 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
327fn 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}