1use crate::LexicalError;
7use crate::caret::TextPointCaretSlice;
8use crate::caret_utils::{caret_range_from_selection, get_text_point_caret_slice_for_node};
9use crate::constants::{TEXT_TYPE_TO_FORMAT, lookup};
10use crate::lexical_selection::{
11 PointType, SelectionRef, Which, get_selection, selection_touches_element,
12 update_element_selection_on_create_delete_node,
13};
14use crate::node::NodeRef;
15use crate::nodes::tab::TabNode;
16use crate::nodes::text::{to_int32, toggle_text_format_type};
17use crate::utf16;
18
19impl SelectionRef {
20 pub fn format_text(
31 &self,
32 format_type: &str,
33 align_with_format: Option<f64>,
34 ) -> Result<(), LexicalError> {
35 let effective_align = match (align_with_format, self.range()) {
36 (None, Some(range)) => Some(f64::from(toggle_text_format_type(
37 to_int32(range.format),
38 format_type,
39 None,
40 ))),
41 (align, _) => align,
42 };
43 update_text_format(self, |format| {
44 toggle_format_number(format, format_type, effective_align)
45 })
46 }
47
48 pub fn set_text_format(&self, formats: &[(&str, bool)]) -> Result<(), LexicalError> {
53 if formats.is_empty() {
54 return Ok(());
55 }
56 update_text_format(self, |mut format| {
57 for &(format_type, value) in formats {
58 let align = if value {
59 lookup(TEXT_TYPE_TO_FORMAT, format_type).unwrap_or(0)
60 } else {
61 0
62 };
63 format = toggle_format_number(format, format_type, Some(f64::from(align)));
64 }
65 format
66 })
67 }
68
69 pub fn get_character_offsets(&self) -> Result<(usize, usize), LexicalError> {
74 let Some(range) = self.range() else {
75 return Ok((0, 0));
76 };
77 let (anchor, focus) = (&range.anchor, &range.focus);
78 if anchor.point_type == PointType::Element
79 && focus.point_type == PointType::Element
80 && anchor.key == focus.key
81 && anchor.offset == focus.offset
82 {
83 return Ok((0, 0));
84 }
85 let character_offset = |point: &crate::lexical_selection::Point| {
87 if point.point_type == PointType::Text {
88 return Ok(point.offset);
89 }
90 let parent = point.get_node()?;
91 Ok(if point.offset == parent.get_children_size() {
92 utf16::len(&parent.get_text_content())
93 } else {
94 0
95 })
96 };
97 Ok((character_offset(anchor)?, character_offset(focus)?))
98 }
99}
100
101fn toggle_format_number(format: f64, format_type: &str, align_with_format: Option<f64>) -> f64 {
105 let align = align_with_format.map(to_int32);
106 let active = lookup(TEXT_TYPE_TO_FORMAT, format_type).unwrap_or(0);
107 if let Some(align) = align
108 && to_int32(format) & active == align & active
109 {
110 return format;
111 }
112 f64::from(toggle_text_format_type(
113 to_int32(format),
114 format_type,
115 align,
116 ))
117}
118
119fn is_token_or_segmented(node: &NodeRef) -> bool {
122 node.get_latest().is::<TabNode>() || node.is_token() || node.is_segmented()
123}
124
125fn update_text_format(
130 selection: &SelectionRef,
131 apply_format: impl Fn(f64) -> f64,
132) -> Result<(), LexicalError> {
133 let Some(range) = selection.range() else {
134 for node in selection.get_nodes()? {
136 let latest = node.get_latest();
137 if latest.is_inline_formattable() {
138 latest.set_inline_format(&node, apply_format(latest.get_inline_format()))?;
139 }
140 }
141 return Ok(());
142 };
143
144 let nodes = if range.is_collapsed() {
145 Vec::new()
146 } else {
147 selection.get_nodes()?
148 };
149 let slices = if nodes.is_empty() {
150 Vec::new()
151 } else {
152 caret_range_from_selection(&range)?
153 .get_text_slices()
154 .to_vec()
155 };
156 let mut has_text = false;
157 let mut skipped_start: Option<Which> = None;
158 let mut first_text: Option<NodeRef> = None;
159 let mut first_format: Option<f64> = None;
160 let mut last_format = 0.0;
161 for node in &nodes {
162 if node.is_text() {
163 if let (Some(which), Some(first)) = (skipped_start, &first_text) {
167 selection.point_set(which, first.get_key(), 0, PointType::Text)?;
168 skipped_start = None;
169 }
170 let slice = get_text_point_caret_slice_for_node(&slices, node);
171 let empty_slice = slice.is_some_and(|s| s.distance == 0);
172 if !has_text && empty_slice {
173 let start = if selection.is_backward()? {
174 Which::Focus
175 } else {
176 Which::Anchor
177 };
178 let point = selection.point(start).expect("a range selection");
179 if point.point_type == PointType::Text && point.key == node.get_key() {
180 skipped_start = Some(start);
181 }
182 }
183 has_text = true;
184 if empty_slice {
185 continue;
186 }
187 let next_format = apply_format(node.text_data().get_format());
188 let original_size = if skipped_start.is_some() {
189 node.get_text_content_size()
190 } else {
191 0
192 };
193 let replacement = match slice {
194 Some(slice) if !is_token_or_segmented(node) => {
195 split_text_point_caret_slice(slice, Some(selection))?
196 }
197 _ => Some(node.clone()),
198 };
199 if let Some(replacement) = replacement {
200 replacement.set_format(next_format);
201 if first_format.is_none() {
202 first_format = Some(next_format);
203 first_text = Some(replacement.clone());
204 if let Some(which) = skipped_start
208 && replacement.get_text_content_size() != original_size
209 {
210 selection.point_set(which, replacement.get_key(), 0, PointType::Text)?;
211 skipped_start = None;
212 }
213 }
214 last_format = next_format;
215 }
216 } else if node.is_element() {
217 node.set_text_format(apply_format(node.element_data().get_text_format()));
218 } else {
219 let latest = node.get_latest();
220 if latest.is_inline_formattable() {
221 latest.set_inline_format(node, apply_format(latest.get_inline_format()))?;
222 }
223 }
224 }
225 if !has_text {
226 let format = apply_format(range.format);
227 selection.set_format(format);
228 crate::lexical_utils::set_composition_key(None);
229 } else if let Some(first_format) = first_format {
230 let format = f64::from(to_int32(first_format) | to_int32(last_format));
231 selection.with_range(|r| r.format = format);
232 }
233 Ok(())
234}
235
236pub(crate) fn split_text_point_caret_slice(
242 slice: &TextPointCaretSlice,
243 selection: Option<&SelectionRef>,
244) -> Result<Option<NodeRef>, LexicalError> {
245 let origin = slice.caret.origin().clone();
246 let (start, end) = slice.get_slice_indices();
247 if start == end {
248 return Ok(None);
249 }
250 if start == 0 && end == origin.get_text_content_size() {
251 return Ok(Some(origin));
252 }
253 let parent = origin.get_parent();
254 let index = match (selection, &parent) {
257 (Some(selection), Some(parent)) if selection_touches_element(selection, parent) => {
258 origin.get_index_within_parent()
259 }
260 _ => None,
261 };
262 let mut points = Vec::new();
265 if let Some(selection) = selection {
266 for which in [Which::Anchor, Which::Focus] {
267 let point = selection.point(which).expect("a range selection");
268 let offset = if point.key == origin.get_key() && point.point_type == PointType::Text {
269 Some(point.offset.saturating_sub(start))
270 } else if parent.as_ref().is_some_and(|p| point.key == p.get_key())
271 && Some(point.offset) == index
272 {
273 Some(0)
274 } else {
275 None
276 };
277 points.push((which, offset));
278 }
279 }
280 let split_nodes = origin.split_text(&[start as i64, end as i64])?;
281 let node = split_nodes[if start == 0 { 0 } else { 1 }].clone();
282 if let (Some(parent), Some(selection), Some(index)) = (&parent, selection, index)
283 && !get_selection().is_some_and(|s| s.ptr_eq(selection))
284 {
285 update_element_selection_on_create_delete_node(
286 selection,
287 parent,
288 index,
289 split_nodes.len() as isize - 1,
290 )?;
291 }
292 if let Some(selection) = selection {
293 for (which, offset) in points {
294 if let Some(offset) = offset {
295 selection.point_set(which, node.get_key(), offset, PointType::Text)?;
296 }
297 }
298 }
299 Ok(Some(node))
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305 use crate::lexical_selection::{create_range_selection, set_selection};
306 use crate::{
307 CreateEditorArgs, Editor, UpdateOptions, create_editor, get_root, json,
308 parse_serialized_node, reset_random_key,
309 };
310
311 fn discrete() -> UpdateOptions {
312 UpdateOptions {
313 discrete: true,
314 ..UpdateOptions::default()
315 }
316 }
317
318 type Spec = (&'static str, usize, PointType);
319
320 fn select(anchor: Spec, focus: Spec) -> Result<SelectionRef, LexicalError> {
321 let selection = create_range_selection();
322 selection.point_set(Which::Anchor, anchor.0, anchor.1, anchor.2)?;
323 selection.point_set(Which::Focus, focus.0, focus.1, focus.2)?;
324 set_selection(Some(selection.clone()));
325 Ok(selection)
326 }
327
328 fn snapshot(editor: &Editor) -> (String, (Spec, Spec, f64)) {
330 let state = editor.get_editor_state();
331 let text = json::stringify(&state.to_json(true)).unwrap();
332 let range = state
333 .read(|| get_selection().and_then(|s| s.range()))
334 .unwrap();
335 let spec = |p: &crate::lexical_selection::Point| -> Spec {
336 (p.key.clone().leak(), p.offset, p.point_type)
337 };
338 (
339 text,
340 (spec(&range.anchor), spec(&range.focus), range.format),
341 )
342 }
343
344 #[test]
350 fn format_text_matches_js() {
351 use PointType::{Element as E, Text as T};
352 reset_random_key();
353 let editor = create_editor(CreateEditorArgs::default());
354 editor
355 .update(
356 || {
357 let nodes = json::parse(
358 r#"[{"type":"paragraph","children":[{"type":"text","text":"abc","format":1},{"type":"text","text":"de","mode":"token"},{"type":"text","text":"fgh","format":2},{"type":"tab","text":"\t"}]},{"type":"paragraph","textFormat":4,"children":[{"type":"text","text":"ij"}]},{"type":"paragraph","children":[]}]"#,
359 )
360 .unwrap();
361 let nodes: Vec<NodeRef> = nodes
362 .as_array()
363 .unwrap()
364 .iter()
365 .map(|n| parse_serialized_node(n).unwrap())
366 .collect();
367 get_root().append(&nodes)
368 },
369 discrete(),
370 )
371 .unwrap();
372 let after_align = r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","format":1,"text":"abc"},{"type":"text","format":3,"mode":"token","text":"de"},{"type":"text","format":3,"text":"fgh"},{"type":"tab","format":1}],"textFormat":1},{"type":"paragraph","children":[{"type":"text","format":1,"text":"ij"}],"textFormat":1},{"type":"paragraph","children":[],"textFormat":1}]}}"#;
373 let after_set = r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","format":1,"text":"a"},{"type":"text","format":64,"text":"bc"},{"type":"text","format":66,"mode":"token","text":"de"},{"type":"text","format":66,"text":"fgh"},{"type":"tab","format":64}],"textFormat":1},{"type":"paragraph","children":[{"type":"text","format":64,"text":"i"},{"type":"text","format":1,"text":"j"}],"textFormat":64},{"type":"paragraph","children":[],"textFormat":1}]}}"#;
374 type Step = fn() -> Result<(), LexicalError>;
375 let steps: [(Step, &str, (Spec, Spec, f64)); 4] = [
376 (
377 || select(("4", 1, T), ("2", 3, T))?.format_text("italic", None),
380 r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","format":1,"text":"abc"},{"type":"text","format":2,"mode":"token","text":"de"},{"type":"text","format":2,"text":"fgh"},{"type":"tab"}],"textFormat":1},{"type":"paragraph","children":[{"type":"text","text":"ij"}]},{"type":"paragraph","children":[]}]}}"#,
381 (("4", 1, T), ("3", 0, T), 2.0),
382 ),
383 (
384 || select(("1", 1, E), ("8", 0, E))?.format_text("bold", Some(1.0)),
385 after_align,
386 (("1", 1, E), ("8", 0, E), 3.0),
387 ),
388 (
389 || select(("7", 1, T), ("7", 1, T))?.format_text("underline", Some(8.0)),
390 after_align,
391 (("7", 1, T), ("7", 1, T), 8.0),
392 ),
393 (
394 || {
395 select(("2", 1, T), ("7", 1, T))?.set_text_format(&[
396 ("bold", false),
397 ("subscript", true),
398 ("superscript", true),
399 ])
400 },
401 after_set,
402 (("10", 0, T), ("7", 1, T), 64.0),
403 ),
404 ];
405 for (i, (step, state, selection)) in steps.into_iter().enumerate() {
406 editor.update(step, discrete()).unwrap();
407 assert_eq!(snapshot(&editor), (state.to_owned(), selection), "step {i}");
408 }
409 editor
410 .update(
411 || {
412 let offsets = select(("1", 5, E), ("7", 1, T))?.get_character_offsets()?;
413 assert_eq!(offsets, (9, 1));
414 let offsets = select(("1", 2, E), ("1", 2, E))?.get_character_offsets()?;
415 assert_eq!(offsets, (0, 0));
416 Ok(())
417 },
418 discrete(),
419 )
420 .unwrap();
421 }
422}