1use super::generated_json::{
6 export_auto_link_node, export_compact_auto_link_node, export_compact_link_node,
7 export_link_node, update_auto_link_node, update_link_node,
8};
9use crate::caret::{CaretDirection, PointCaret, get_child_caret};
10use crate::caret_utils::{
11 SplitAtPointCaretNextOptions, caret_from_point, insert_node_to_nearest_root_at_caret,
12 normalize_caret, rewind_sibling_caret, set_point_from_caret,
13};
14use crate::editor::LexicalCommand;
15use crate::error::invariant;
16use crate::json::Object;
17use crate::json::Value;
18use crate::lexical_selection::{
19 Point, PointType, SelectionRef, Which, get_selection, set_selection,
20};
21use crate::lexical_utils::{copy_node, set_node_key, with_writable};
22use crate::node::{LexicalNode, NodeBase, NodeRef};
23use crate::nodes::element::ElementData;
24use crate::schema::{
25 NodeSchema, SchemaField, boolean_value, node_schema, nullable, string_value, with_accessors,
26 with_field,
27};
28use crate::selection_insert_nodes::normalize_selection;
29use crate::utils::find_matching_parent;
30use crate::{LexicalError, NodeKey};
31use std::collections::HashSet;
32use std::rc::Rc;
33
34#[derive(Clone, Debug, Default, PartialEq, Eq)]
38pub struct LinkAttributes {
39 pub rel: Option<Option<String>>,
40 pub target: Option<Option<String>>,
41 pub title: Option<Option<String>>,
42}
43
44impl LinkAttributes {
45 pub fn merging(&self, overrides: &LinkAttributes) -> LinkAttributes {
48 LinkAttributes {
49 rel: overrides.rel.clone().or_else(|| self.rel.clone()),
50 target: overrides.target.clone().or_else(|| self.target.clone()),
51 title: overrides.title.clone().or_else(|| self.title.clone()),
52 }
53 }
54}
55
56#[derive(Clone, Debug, Default, PartialEq, Eq)]
59pub struct AutoLinkAttributes {
60 pub rel: Option<Option<String>>,
61 pub target: Option<Option<String>>,
62 pub title: Option<Option<String>>,
63 pub is_unlinked: Option<bool>,
64}
65
66#[derive(Clone, Debug, Default)]
68pub struct LinkNode {
69 base: NodeBase,
70 pub(super) element: ElementData,
71 pub(super) url: String,
72 pub(super) target: Option<String>,
73 pub(super) rel: Option<String>,
74 pub(super) title: Option<String>,
75}
76
77#[derive(Clone, Debug, Default)]
81pub struct AutoLinkNode {
82 pub(super) link: LinkNode,
83 pub(super) is_unlinked: bool,
84}
85
86impl LinkNode {
87 fn new(
90 url: &str,
91 rel: &Option<Option<String>>,
92 target: &Option<Option<String>>,
93 title: &Option<Option<String>>,
94 ) -> Self {
95 LinkNode {
96 url: url.to_owned(),
97 rel: rel.clone().flatten(),
98 target: target.clone().flatten(),
99 title: title.clone().flatten(),
100 ..LinkNode::default()
101 }
102 }
103
104 pub fn url(&self) -> &str {
105 &self.url
106 }
107
108 pub fn target(&self) -> Option<&str> {
109 self.target.as_deref()
110 }
111
112 pub fn rel(&self) -> Option<&str> {
113 self.rel.as_deref()
114 }
115
116 pub fn title(&self) -> Option<&str> {
117 self.title.as_deref()
118 }
119}
120
121impl AutoLinkNode {
122 pub fn link(&self) -> &LinkNode {
124 &self.link
125 }
126
127 pub fn is_unlinked(&self) -> bool {
128 self.is_unlinked
129 }
130}
131
132pub fn create_link_node(url: &str, attributes: &LinkAttributes) -> NodeRef {
134 crate::lexical_utils::replaced(set_node_key(Box::new(LinkNode::new(
135 url,
136 &attributes.rel,
137 &attributes.target,
138 &attributes.title,
139 ))))
140}
141
142pub fn is_link_node(node: &NodeRef) -> bool {
144 link_of(&*node.get_latest()).is_some()
145}
146
147pub fn create_auto_link_node(url: &str, attributes: &AutoLinkAttributes) -> NodeRef {
149 crate::lexical_utils::replaced(set_node_key(Box::new(AutoLinkNode {
150 link: LinkNode::new(url, &attributes.rel, &attributes.target, &attributes.title),
151 is_unlinked: attributes.is_unlinked.unwrap_or(false),
152 })))
153}
154
155pub fn is_auto_link_node(node: &NodeRef) -> bool {
157 node.get_latest().is::<AutoLinkNode>()
158}
159
160fn link_of(node: &dyn LexicalNode) -> Option<&LinkNode> {
162 node.downcast_ref::<LinkNode>()
163 .or_else(|| node.downcast_ref::<AutoLinkNode>().map(|a| &a.link))
164}
165
166fn set_link(node: &NodeRef, f: impl FnOnce(&mut LinkNode)) {
169 if is_link_node(node) {
170 with_writable(node.get_key(), |n| {
171 if n.is::<LinkNode>() {
172 f(n.downcast_mut::<LinkNode>().expect("a link"));
173 } else {
174 f(&mut n.downcast_mut::<AutoLinkNode>().expect("an autolink").link);
175 }
176 });
177 }
178}
179
180impl NodeRef {
181 pub fn get_url(&self) -> Option<String> {
183 link_of(&*self.get_latest()).map(|l| l.url.clone())
184 }
185
186 pub fn set_url(&self, url: &str) {
188 set_link(self, |l| l.url = url.to_owned());
189 }
190
191 pub fn get_target(&self) -> Option<String> {
194 link_of(&*self.get_latest()).and_then(|l| l.target.clone())
195 }
196
197 pub fn set_target(&self, target: Option<&str>) {
199 set_link(self, |l| l.target = target.map(str::to_owned));
200 }
201
202 pub fn get_rel(&self) -> Option<String> {
204 link_of(&*self.get_latest()).and_then(|l| l.rel.clone())
205 }
206
207 pub fn set_rel(&self, rel: Option<&str>) {
209 set_link(self, |l| l.rel = rel.map(str::to_owned));
210 }
211
212 pub fn get_title(&self) -> Option<String> {
215 link_of(&*self.get_latest()).and_then(|l| l.title.clone())
216 }
217
218 pub fn set_title(&self, title: Option<&str>) {
220 set_link(self, |l| l.title = title.map(str::to_owned));
221 }
222
223 pub fn get_is_unlinked(&self) -> Option<bool> {
225 self.get_latest()
226 .downcast_ref::<AutoLinkNode>()
227 .map(|a| a.is_unlinked)
228 }
229
230 pub fn set_is_unlinked(&self, value: bool) {
232 if is_auto_link_node(self) {
233 with_writable(self.get_key(), |n| {
234 n.downcast_mut::<AutoLinkNode>()
235 .expect("an autolink")
236 .is_unlinked = value;
237 });
238 }
239 }
240
241 pub fn is_email_uri(&self) -> bool {
244 self.get_url().is_some_and(|url| url.starts_with("mailto:"))
245 }
246
247 pub fn is_web_site_uri(&self) -> bool {
250 self.get_url()
251 .is_some_and(|url| url.starts_with("https://") || url.starts_with("http://"))
252 }
253
254 pub fn should_merge_adjacent_link(&self, other_link: &NodeRef) -> bool {
258 let this = self.get_latest();
259 let other = other_link.get_latest();
260 if this.is::<AutoLinkNode>() {
261 return false;
262 }
263 match (link_of(&*this), link_of(&*other)) {
264 (Some(a), Some(b)) => {
265 this.get_type() == other.get_type()
266 && a.url == b.url
267 && a.target == b.target
268 && a.rel == b.rel
269 && a.title == b.title
270 }
271 _ => false,
272 }
273 }
274}
275
276fn insert_new_after(
279 this: &NodeRef,
280 restore_selection: bool,
281) -> Result<Option<NodeRef>, LexicalError> {
282 let link_node = copy_node(this);
283 this.insert_after(&link_node, restore_selection)?;
284 Ok(Some(link_node))
285}
286
287fn extract_with_child(
291 this: &NodeRef,
292 selection: Option<&SelectionRef>,
293) -> Result<bool, LexicalError> {
294 let Some(selection) = selection.filter(|s| s.is_range()) else {
295 return Ok(false);
296 };
297 let range = selection.range().expect("a range selection");
298 let anchor_node = range.anchor.get_node()?;
299 let focus_node = range.focus.get_node()?;
300 Ok((this == &anchor_node || this.is_parent_of(&anchor_node))
301 && (this == &focus_node || this.is_parent_of(&focus_node))
302 && !selection.get_text_content()?.is_empty())
303}
304
305fn link_node_config_chain() -> Vec<crate::structure::NodeConfigLink> {
307 use crate::structure::{
308 MergeAdjacentDeclaration, MergeAdjacentEntry, NodeChildrenConfig, NodeConfigLink,
309 StaticNodeConfig,
310 };
311 vec![NodeConfigLink::new(
312 "link",
313 StaticNodeConfig {
314 inline: Some(true),
315 children: Some(NodeChildrenConfig::Inline),
316 merge_adjacent: Some(MergeAdjacentDeclaration::By(vec![
317 MergeAdjacentEntry::Field("url"),
318 MergeAdjacentEntry::Field("target"),
319 MergeAdjacentEntry::Field("rel"),
320 MergeAdjacentEntry::Field("title"),
321 ])),
322 },
323 )]
324}
325
326thread_local! {
327 static LINK_NODE_SCHEMA: NodeSchema = build_link_node_schema().expect("LinkNode's schema");
328 static AUTO_LINK_NODE_SCHEMA: NodeSchema = node_schema(vec![(
329 "isUnlinked",
330 with_field(
331 boolean_value(false),
332 |n: &AutoLinkNode| &n.is_unlinked,
333 |n: &mut AutoLinkNode| &mut n.is_unlinked,
334 )
335 .expect("a field"),
336 )])
337 .expect("AutoLinkNode's schema");
338}
339
340fn schema_link_of(node: &dyn LexicalNode) -> &LinkNode {
342 link_of(node).expect("a link")
343}
344
345fn link_of_mut(node: &mut dyn LexicalNode) -> &mut LinkNode {
346 if node.is::<LinkNode>() {
347 return node.downcast_mut::<LinkNode>().expect("a link");
348 }
349 &mut node.downcast_mut::<AutoLinkNode>().expect("a link").link
350}
351
352pub fn link_node_schema() -> NodeSchema {
355 LINK_NODE_SCHEMA.with(Clone::clone)
356}
357
358pub fn auto_link_node_schema() -> NodeSchema {
360 AUTO_LINK_NODE_SCHEMA.with(Clone::clone)
361}
362
363fn build_link_node_schema() -> Result<NodeSchema, LexicalError> {
364 fn nullable_field(
365 get: fn(&LinkNode) -> &Option<String>,
366 set: fn(&mut LinkNode) -> &mut Option<String>,
367 ) -> Result<SchemaField, LexicalError> {
368 with_accessors(
369 nullable(string_value(""), true)?,
370 Some(Rc::new(move |node| {
371 get(schema_link_of(node))
372 .as_deref()
373 .map_or(Value::Null, Value::from)
374 })),
375 Some(Rc::new(move |node, value| {
376 *set(link_of_mut(node)) = value.as_str().map(str::to_owned);
377 })),
378 )
379 }
380 node_schema(vec![
381 ("rel", nullable_field(|l| &l.rel, |l| &mut l.rel)?),
382 ("target", nullable_field(|l| &l.target, |l| &mut l.target)?),
383 ("title", nullable_field(|l| &l.title, |l| &mut l.title)?),
384 (
385 "url",
386 with_accessors(
387 string_value(""),
388 Some(Rc::new(|node| schema_link_of(node).url.as_str().into())),
389 Some(Rc::new(|node, value| {
390 link_of_mut(node).url = value.as_str().unwrap_or("").to_owned();
391 })),
392 )?,
393 ),
394 ])
395}
396
397impl LexicalNode for LinkNode {
398 fn json_schema_chain(&self) -> Vec<NodeSchema> {
399 vec![
400 link_node_schema(),
401 crate::nodes::element::element_node_schema(),
402 ]
403 }
404 fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
410 link_node_config_chain()
411 }
412
413 fn get_type(&self) -> &'static str {
414 "link"
415 }
416 #[cfg(feature = "html")]
417 fn create_dom(
418 &self,
419 _this: &NodeRef,
420 config: &crate::EditorConfig,
421 _editor: &crate::Editor,
422 ) -> Result<crate::dom::DomNode, LexicalError> {
423 Ok(link_dom::create_dom(self, config))
424 }
425 #[cfg(feature = "html")]
426 fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
427 Some(link_dom::import_dom())
428 }
429 fn base(&self) -> &NodeBase {
430 &self.base
431 }
432 fn base_mut(&mut self) -> &mut NodeBase {
433 &mut self.base
434 }
435 fn element(&self) -> Option<&ElementData> {
436 Some(&self.element)
437 }
438 fn element_mut(&mut self) -> Option<&mut ElementData> {
439 Some(&mut self.element)
440 }
441
442 fn is_inline(&self) -> bool {
444 true
445 }
446
447 fn can_be_empty(&self) -> bool {
449 false
450 }
451
452 fn can_insert_text_before(&self) -> bool {
455 false
456 }
457
458 fn can_insert_text_after(&self) -> bool {
461 false
462 }
463
464 fn insert_new_after(
466 &self,
467 this: &NodeRef,
468 _: &SelectionRef,
469 restore_selection: bool,
470 ) -> Result<Option<NodeRef>, LexicalError> {
471 insert_new_after(this, restore_selection)
472 }
473
474 fn extract_with_child(
476 &self,
477 this: &NodeRef,
478 _: &NodeRef,
479 selection: Option<&SelectionRef>,
480 _: &str,
481 ) -> Result<bool, LexicalError> {
482 extract_with_child(this, selection)
483 }
484
485 fn generated_export_json(&self, compact: bool) -> Option<Object> {
487 Some(if compact {
488 export_compact_link_node(self)
489 } else {
490 export_link_node(self)
491 })
492 }
493
494 fn generated_update_from_json(&mut self, json: &Object) -> bool {
496 update_link_node(self, json);
497 true
498 }
499}
500
501impl LexicalNode for AutoLinkNode {
505 fn json_schema_chain(&self) -> Vec<NodeSchema> {
506 vec![
507 auto_link_node_schema(),
508 link_node_schema(),
509 crate::nodes::element::element_node_schema(),
510 ]
511 }
512 fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
516 use crate::structure::{MergeAdjacentDeclaration, NodeConfigLink, StaticNodeConfig};
517 let mut chain = vec![NodeConfigLink::new(
518 "autolink",
519 StaticNodeConfig {
520 merge_adjacent: Some(MergeAdjacentDeclaration::Off),
521 ..StaticNodeConfig::default()
522 },
523 )];
524 chain.extend(link_node_config_chain());
525 chain
526 }
527
528 fn update_dom(&self, prev_node: &dyn LexicalNode) -> bool {
531 prev_node
532 .downcast_ref::<AutoLinkNode>()
533 .is_some_and(|prev| prev.is_unlinked != self.is_unlinked)
534 }
535 fn get_type(&self) -> &'static str {
536 "autolink"
537 }
538 #[cfg(feature = "html")]
540 fn super_types(&self) -> Vec<&'static str> {
541 vec!["link"]
542 }
543 #[cfg(feature = "html")]
546 fn create_dom(
547 &self,
548 _this: &NodeRef,
549 config: &crate::EditorConfig,
550 _editor: &crate::Editor,
551 ) -> Result<crate::dom::DomNode, LexicalError> {
552 if self.is_unlinked {
553 return Ok(crate::lexical_dom::get_document().create_element("span"));
554 }
555 Ok(link_dom::create_dom(&self.link, config))
556 }
557 fn base(&self) -> &NodeBase {
558 &self.link.base
559 }
560 fn base_mut(&mut self) -> &mut NodeBase {
561 &mut self.link.base
562 }
563 fn element(&self) -> Option<&ElementData> {
564 Some(&self.link.element)
565 }
566 fn element_mut(&mut self) -> Option<&mut ElementData> {
567 Some(&mut self.link.element)
568 }
569
570 fn is_inline(&self) -> bool {
571 true
572 }
573
574 fn can_be_empty(&self) -> bool {
575 false
576 }
577
578 fn can_insert_text_before(&self) -> bool {
579 false
580 }
581
582 fn can_insert_text_after(&self) -> bool {
583 false
584 }
585
586 fn insert_new_after(
589 &self,
590 this: &NodeRef,
591 _: &SelectionRef,
592 restore_selection: bool,
593 ) -> Result<Option<NodeRef>, LexicalError> {
594 insert_new_after(this, restore_selection)
595 }
596
597 fn extract_with_child(
598 &self,
599 this: &NodeRef,
600 _: &NodeRef,
601 selection: Option<&SelectionRef>,
602 _: &str,
603 ) -> Result<bool, LexicalError> {
604 extract_with_child(this, selection)
605 }
606
607 fn generated_export_json(&self, compact: bool) -> Option<Object> {
609 Some(if compact {
610 export_compact_auto_link_node(self)
611 } else {
612 export_auto_link_node(self)
613 })
614 }
615
616 fn generated_update_from_json(&mut self, json: &Object) -> bool {
618 update_auto_link_node(self, json);
619 true
620 }
621}
622
623type CaretPair = [PointCaret; 2];
625
626fn save_caret_pair(point: &Point) -> Result<CaretPair, LexicalError> {
628 let next = caret_from_point(point, CaretDirection::Next)?;
629 let flipped = next.get_flipped()?;
630 Ok([next, flipped])
631}
632
633fn restore_caret_pair(
636 selection: &SelectionRef,
637 which: Which,
638 pair: &CaretPair,
639) -> Result<(), LexicalError> {
640 for caret in pair {
641 if caret.origin().is_attached() {
642 let normalized = normalize_caret(caret);
643 return set_point_from_caret(selection, which, &normalized);
644 }
645 }
646 Ok(())
647}
648
649fn fix_merge_boundary_caret(
654 pair: CaretPair,
655 absorbing_link: &NodeRef,
656 merging_link: &NodeRef,
657) -> Result<CaretPair, LexicalError> {
658 let is_affected =
659 |caret: &PointCaret| caret.is_sibling_caret() && caret.origin() == absorbing_link;
660 if !is_affected(&pair[0]) && !is_affected(&pair[1]) {
661 return Ok(pair);
662 }
663 let fixed = normalize_caret(
666 &get_child_caret(merging_link, CaretDirection::Next).expect("a link is an element"),
667 );
668 let flipped = fixed.get_flipped()?;
669 Ok([fixed, flipped])
670}
671
672pub fn link_node_transform(link: &NodeRef) -> Result<(), LexicalError> {
682 let selection = get_selection().filter(SelectionRef::is_range);
683 let mut pairs = None;
684 if let Some(selection) = &selection {
685 pairs = Some((
686 save_caret_pair(&selection.point(Which::Anchor).expect("a range"))?,
687 save_caret_pair(&selection.point(Which::Focus).expect("a range"))?,
688 ));
689 }
690 let restore_selection = |pairs: &Option<(CaretPair, CaretPair)>| -> Result<(), LexicalError> {
691 if let (Some(selection), Some((anchor_pair, focus_pair))) = (&selection, pairs) {
692 restore_caret_pair(selection, Which::Anchor, anchor_pair)?;
693 restore_caret_pair(selection, Which::Focus, focus_pair)?;
694 normalize_selection(selection)?;
695 }
696 Ok(())
697 };
698
699 let mut transformed = false;
700 let lifts_blocks = !crate::structure::is_structure_enforced_on_active_editor();
701 let children = get_child_caret(link, CaretDirection::Next).expect("a link is an element");
702 for caret in children.iter().filter(|_| lifts_blocks) {
703 let node = caret.origin().clone();
704 if node.is_element() && !node.is_inline() {
705 let block_children = node.get_children();
706 if !block_children.is_empty() {
707 let inner_link = copy_node(link);
708 inner_link.append(&block_children)?;
709 node.append(std::slice::from_ref(&inner_link))?;
710 transformed = true;
711 }
712 insert_node_to_nearest_root_at_caret(
713 &node,
714 &rewind_sibling_caret(&caret)?,
715 &SplitAtPointCaretNextOptions {
716 should_split: |_, _| false,
717 ..SplitAtPointCaretNextOptions::default()
718 },
719 )?;
720 }
721 }
722
723 let fix_pairs = |pairs: Option<(CaretPair, CaretPair)>,
724 absorbing: &NodeRef,
725 merging: &NodeRef|
726 -> Result<Option<(CaretPair, CaretPair)>, LexicalError> {
727 pairs
728 .map(|(anchor, focus)| {
729 Ok((
730 fix_merge_boundary_caret(anchor, absorbing, merging)?,
731 fix_merge_boundary_caret(focus, absorbing, merging)?,
732 ))
733 })
734 .transpose()
735 };
736 if link.is_attached() {
737 if let Some(prev_sibling) = link.get_previous_sibling().filter(|p| {
738 is_link_node(p)
739 && !crate::structure::structure_merges(p, link)
740 && p.should_merge_adjacent_link(link)
741 }) {
742 pairs = fix_pairs(pairs, &prev_sibling, link)?;
743 prev_sibling.append(&link.get_children())?;
744 link.remove(false)?;
745 return restore_selection(&pairs);
746 }
747 if let Some(next_sibling) = link.get_next_sibling().filter(|n| {
748 is_link_node(n)
749 && !crate::structure::structure_merges(link, n)
750 && link.should_merge_adjacent_link(n)
751 }) {
752 pairs = fix_pairs(pairs, link, &next_sibling)?;
753 link.append(&next_sibling.get_children())?;
754 next_sibling.remove(false)?;
755 transformed = true;
756 }
757 }
758 if !transformed {
759 return Ok(());
760 }
761 if !link.can_be_empty() && link.is_empty() {
762 let parent = link.get_parent();
763 link.remove(false)?;
764 if let Some(parent) = parent.filter(NodeRef::is_empty) {
765 parent.remove(false)?;
766 }
767 }
768 restore_selection(&pairs)
769}
770
771#[derive(Clone, Debug, PartialEq, Eq)]
774pub enum ToggleLinkPayload {
775 Url(String),
776 Attributes {
777 url: String,
778 attributes: LinkAttributes,
779 },
780}
781
782pub const TOGGLE_LINK_COMMAND: LexicalCommand<Option<ToggleLinkPayload>> =
788 LexicalCommand::constant(u64::MAX - 25, "TOGGLE_LINK_COMMAND");
789
790fn get_point_node(point: &Point, offset: isize) -> Result<Option<NodeRef>, LexicalError> {
793 if point.point_type != PointType::Element {
794 return Ok(None);
795 }
796 let node = point.get_node()?;
797 invariant!(
798 node.is_element(),
799 "$getPointNode: element point is not an ElementNode"
800 );
801 Ok(point
802 .offset
803 .checked_add_signed(offset)
804 .and_then(|index| node.get_child_at_index(index)))
805}
806
807fn with_selected_nodes<T>(f: impl FnOnce() -> Result<T, LexicalError>) -> Result<T, LexicalError> {
810 let Some(initial_selection) = get_selection().filter(SelectionRef::is_range) else {
811 return f();
812 };
813 normalize_selection(&initial_selection)?;
814 let normalized = &initial_selection;
815 let is_backwards = normalized.is_backward()?;
816 let anchor_node = get_point_node(
817 &normalized.point(Which::Anchor).expect("a range"),
818 if is_backwards { -1 } else { 0 },
819 )?;
820 let focus_node = get_point_node(
821 &normalized.point(Which::Focus).expect("a range"),
822 if is_backwards { 0 } else { -1 },
823 )?;
824 let rval = f()?;
825 if (anchor_node.is_some() || focus_node.is_some())
826 && let Some(updated_selection) = get_selection().filter(SelectionRef::is_range)
827 {
828 let final_selection = updated_selection.clone_selection();
829 for (which, node, after) in [
830 (Which::Anchor, &anchor_node, is_backwards),
831 (Which::Focus, &focus_node, !is_backwards),
832 ] {
833 if let Some(node) = node
834 && let Some(parent) = node.get_parent()
835 {
836 let index = node
837 .get_index_within_parent()
838 .expect("a child of its parent");
839 final_selection.point_set(
840 which,
841 parent.get_key(),
842 index + usize::from(after),
843 PointType::Element,
844 )?;
845 }
846 }
847 normalize_selection(&final_selection)?;
848 set_selection(Some(final_selection));
849 }
850 Ok(rval)
851}
852
853fn split_link_at_selection(
857 parent_link: &NodeRef,
858 extracted_nodes: &[NodeRef],
859) -> Result<(), LexicalError> {
860 let extracted_keys: HashSet<NodeKey> = extracted_nodes
861 .iter()
862 .filter(|n| parent_link.is_parent_of(n))
863 .map(|n| n.get_key().to_owned())
864 .collect();
865
866 let all_children = parent_link.get_children();
867 let is_extracted_child = |child: &NodeRef| {
870 extracted_keys.contains(child.get_key())
871 || (child.is_element()
872 && extracted_nodes
873 .iter()
874 .any(|n| parent_link.is_parent_of(n) && child.is_parent_of(n)))
875 };
876
877 let extracted_children: Vec<NodeRef> = all_children
878 .iter()
879 .filter(|c| is_extracted_child(c))
880 .cloned()
881 .collect();
882
883 if extracted_children.is_empty() && !all_children.is_empty() {
884 return Ok(());
889 }
890
891 if extracted_children.len() == all_children.len() {
892 for child in &all_children {
893 parent_link.insert_before(child, true)?;
894 }
895 return parent_link.remove(false);
896 }
897
898 let first_extracted_index = all_children
899 .iter()
900 .position(&is_extracted_child)
901 .expect("an extracted child");
902 let last_extracted_index = all_children
903 .iter()
904 .rposition(&is_extracted_child)
905 .expect("an extracted child");
906
907 let is_at_start = first_extracted_index == 0;
908 let is_at_end = last_extracted_index == all_children.len() - 1;
909
910 if is_at_start {
911 for child in &extracted_children {
912 parent_link.insert_before(child, true)?;
913 }
914 } else if is_at_end {
915 for child in extracted_children.iter().rev() {
916 parent_link.insert_after(child, true)?;
917 }
918 } else {
919 for child in extracted_children.iter().rev() {
920 parent_link.insert_after(child, true)?;
921 }
922
923 let trailing_children = &all_children[last_extracted_index + 1..];
924 if !trailing_children.is_empty() {
925 let new_link = copy_node(parent_link);
926 extracted_children
927 .last()
928 .expect("an extracted child")
929 .insert_after(&new_link, true)?;
930 for child in trailing_children {
931 new_link.append(std::slice::from_ref(child))?;
932 }
933 }
934 }
935 Ok(())
936}
937
938fn is_non_auto_link(node: &NodeRef) -> bool {
941 !is_auto_link_node(node) && is_link_node(node)
942}
943
944pub fn toggle_link(url: Option<&str>, attributes: &LinkAttributes) -> Result<(), LexicalError> {
954 let target = attributes.target.clone();
955 let title = attributes.title.clone();
956 let rel = match &attributes.rel {
957 None => Some(Some("noreferrer".to_owned())),
958 rel => rel.clone(),
959 };
960 let new_link_attributes = LinkAttributes {
961 rel: rel.clone(),
962 target: target.clone(),
963 title: title.clone(),
964 };
965 let update_attributes = |link_node: &NodeRef| {
966 if let Some(target) = &target {
967 link_node.set_target(target.as_deref());
968 }
969 if let Some(rel) = &rel {
970 link_node.set_rel(rel.as_deref());
971 }
972 if let Some(title) = &title {
973 link_node.set_title(title.as_deref());
974 }
975 };
976 let Some(selection) = get_selection() else {
977 return Ok(());
978 };
979
980 if selection.is_node() {
981 let nodes = selection.get_nodes()?;
982 if nodes.is_empty() {
983 return Ok(());
984 }
985
986 for node in &nodes {
988 match url {
989 None => {
990 if let Some(link_parent) = find_matching_parent(node, is_non_auto_link) {
992 link_parent.insert_before(node, true)?;
993 if link_parent.get_children().is_empty() {
994 link_parent.remove(false)?;
995 }
996 }
997 }
998 Some(url) => {
999 if let Some(existing_link) = find_matching_parent(node, is_non_auto_link) {
1001 existing_link.set_url(url);
1002 update_attributes(&existing_link);
1003 } else {
1004 let link_node = create_link_node(url, &new_link_attributes);
1005 node.insert_before(&link_node, true)?;
1006 link_node.append(std::slice::from_ref(node))?;
1007 }
1008 }
1009 }
1010 }
1011 return Ok(());
1012 }
1013
1014 let is_collapsed = selection.range().is_some_and(|r| r.is_collapsed());
1015 if is_collapsed
1016 && url.is_none()
1017 && let Some(node) = selection.get_nodes()?.first()
1018 {
1019 if let Some(parent_link) = find_matching_parent(node, is_non_auto_link) {
1020 parent_link.get_parent_or_throw()?.splice(
1021 parent_link
1022 .get_index_within_parent()
1023 .expect("a child of its parent"),
1024 0,
1025 &parent_link.get_children(),
1026 )?;
1027 parent_link.remove(false)?;
1028 }
1029 return Ok(());
1030 }
1031
1032 let nodes = selection.extract()?;
1034
1035 let Some(url) = url else {
1036 let mut processed_links = HashSet::new();
1037 for node in &nodes {
1038 if let Some(parent_link) = find_matching_parent(node, is_non_auto_link) {
1039 let link_key = parent_link.get_key().to_owned();
1040 if processed_links.contains(&link_key) {
1041 continue;
1042 }
1043 split_link_at_selection(&parent_link, &nodes)?;
1044 processed_links.insert(link_key);
1045 }
1046 }
1047 return Ok(());
1048 };
1049 let mut updated_nodes = HashSet::new();
1050 let mut update_link_node = |link_node: &NodeRef| {
1051 if !updated_nodes.insert(link_node.get_key().to_owned()) {
1052 return;
1053 }
1054 link_node.set_url(url);
1055 update_attributes(link_node);
1056 };
1057 if nodes.len() == 1 {
1059 if let Some(link_node) = find_matching_parent(&nodes[0], is_link_node) {
1062 update_link_node(&link_node);
1063 return Ok(());
1064 }
1065 }
1066
1067 with_selected_nodes(|| {
1068 let mut link_node: Option<NodeRef> = None;
1069 for node in &nodes {
1070 if !node.is_attached() {
1071 continue;
1072 }
1073 if let Some(parent_link_node) = find_matching_parent(node, is_link_node) {
1074 update_link_node(&parent_link_node);
1075 continue;
1076 }
1077 if node.is_element() {
1078 if !node.is_inline() {
1079 continue;
1082 }
1083 if is_link_node(node) {
1084 let reusable = match &link_node {
1087 None => true,
1088 Some(link_node) => !link_node.get_parent_or_throw()?.is_parent_of(node),
1089 };
1090 if !is_auto_link_node(node) && reusable {
1091 update_link_node(node);
1092 link_node = Some(node.clone());
1093 continue;
1094 }
1095 for child in node.get_children() {
1097 node.insert_before(&child, true)?;
1098 }
1099 node.remove(false)?;
1100 continue;
1101 }
1102 }
1103 if let Some(prev_link_node) = node.get_previous_sibling()
1104 && is_link_node(&prev_link_node)
1105 && link_node.as_ref() == Some(&prev_link_node)
1106 {
1107 prev_link_node.append(std::slice::from_ref(node))?;
1108 continue;
1109 }
1110 let new_link_node = create_link_node(url, &new_link_attributes);
1111 node.insert_after(&new_link_node, true)?;
1112 new_link_node.append(std::slice::from_ref(node))?;
1113 link_node = Some(new_link_node);
1114 }
1115 Ok(())
1116 })
1117}
1118
1119fn is_phone_number(url: &str) -> bool {
1121 let rest = url.strip_prefix('+').unwrap_or(url);
1122 rest.chars().count() >= 5
1123 && rest
1124 .chars()
1125 .all(|c| c.is_ascii_digit() || is_js_whitespace(c) || matches!(c, '(' | ')' | '-'))
1126}
1127
1128fn is_js_whitespace(c: char) -> bool {
1130 matches!(
1131 c,
1132 '\u{9}'..='\u{D}'
1133 | ' '
1134 | '\u{A0}'
1135 | '\u{1680}'
1136 | '\u{2000}'..='\u{200A}'
1137 | '\u{2028}'
1138 | '\u{2029}'
1139 | '\u{202F}'
1140 | '\u{205F}'
1141 | '\u{3000}'
1142 | '\u{FEFF}'
1143 )
1144}
1145
1146fn has_scheme(url: &str) -> bool {
1148 let mut chars = url.chars();
1149 if !chars.next().is_some_and(|c| c.is_ascii_alphabetic()) {
1150 return false;
1151 }
1152 for c in chars {
1153 if c == ':' {
1154 return true;
1155 }
1156 if !(c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-')) {
1157 return false;
1158 }
1159 }
1160 false
1161}
1162
1163pub fn format_url(url: &str) -> String {
1168 if has_scheme(url) {
1170 url.to_owned()
1172 }
1173 else if url.starts_with(['/', '#', '.']) {
1175 url.to_owned()
1177 }
1178 else if url.contains('@') {
1180 format!("mailto:{url}")
1181 }
1182 else if is_phone_number(url) {
1184 format!("tel:{url}")
1185 }
1186 else {
1188 format!("https://{url}")
1189 }
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194 use super::format_url;
1195
1196 #[test]
1203 fn format_url_matches_js() {
1204 for (url, formatted) in [
1205 ("https://lexical.dev", "https://lexical.dev"),
1206 ("mailto:a@b.c", "mailto:a@b.c"),
1207 ("javascript:alert(1)", "javascript:alert(1)"),
1208 ("/path", "/path"),
1209 ("#anchor", "#anchor"),
1210 ("./rel", "./rel"),
1211 ("a@b.c", "mailto:a@b.c"),
1212 ("+1 (555) 123-4567", "tel:+1 (555) 123-4567"),
1213 ("12345", "tel:12345"),
1214 ("1234", "https://1234"),
1215 ("+1234", "https://+1234"),
1216 ("1\u{3000}2\u{A0}3 4", "tel:1\u{3000}2\u{A0}3 4"),
1217 ("123456\n", "tel:123456\n"),
1218 ("lexical.dev", "https://lexical.dev"),
1219 ("1a:b", "https://1a:b"),
1220 ("", "https://"),
1221 ] {
1222 assert_eq!(format_url(url), formatted, "{url:?}");
1223 }
1224 }
1225}
1226
1227pub(crate) mod sanitize {
1232 use super::{format_url, is_js_whitespace};
1233
1234 const SUPPORTED_URL_PROTOCOLS: [&str; 5] = ["http:", "https:", "mailto:", "sms:", "tel:"];
1236
1237 fn leading_scheme(url: &str) -> Option<&str> {
1239 let end = url.find(':')?;
1240 let scheme = &url[..end];
1241 let mut chars = scheme.chars();
1242 (chars.next()?.is_ascii_alphabetic()
1243 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-')))
1244 .then_some(scheme)
1245 }
1246
1247 fn whatwg_url_protocol(url: &str) -> Option<String> {
1252 let trimmed = url.trim_matches(|c: char| c <= ' ');
1253 let input: String = trimmed
1254 .chars()
1255 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
1256 .collect();
1257 let scheme = leading_scheme(&input)?.to_ascii_lowercase();
1258 let is_special = ["http", "https", "ws", "wss", "ftp", "file"].contains(&scheme.as_str());
1259 let mut rest = &input[scheme.len() + 1..];
1260 if is_special {
1261 if scheme == "file" {
1262 return Some("file:".to_owned());
1263 }
1264 rest = rest.trim_start_matches(['/', '\\']);
1265 } else if let Some(r) = rest.strip_prefix("//") {
1266 rest = r;
1267 } else {
1268 return Some(format!("{scheme}:"));
1269 }
1270 let authority_end = rest
1271 .find(|c| matches!(c, '/' | '?' | '#') || (is_special && c == '\\'))
1272 .unwrap_or(rest.len());
1273 let mut authority = &rest[..authority_end];
1274 if let Some(at) = authority.rfind('@') {
1275 authority = &authority[at + 1..];
1276 }
1277 let mut host = authority;
1278 let mut port = None;
1279 if host.starts_with('[') {
1280 let close = host.find(']')?;
1281 let after = &host[close + 1..];
1282 if let Some(p) = after.strip_prefix(':') {
1283 port = Some(p);
1284 } else if !after.is_empty() {
1285 return None;
1286 }
1287 host = &host[..=close];
1288 } else if let Some(colon) = host.find(':') {
1289 port = Some(&host[colon + 1..]);
1290 host = &host[..colon];
1291 }
1292 if let Some(port) = port.filter(|p| !p.is_empty())
1293 && (!port.bytes().all(|b| b.is_ascii_digit())
1294 || port.trim_start_matches('0').len() > 5
1295 || port.trim_start_matches('0').parse::<u32>().unwrap_or(0) > 65535)
1296 {
1297 return None;
1298 }
1299 if host.is_empty() {
1300 return if is_special || port.is_some() {
1301 None
1302 } else {
1303 Some(format!("{scheme}:"))
1304 };
1305 }
1306 if !host.starts_with('[') {
1307 let forbidden = |c: char| {
1308 matches!(
1309 c,
1310 '\0' | '\t'
1311 | '\n'
1312 | '\r'
1313 | ' '
1314 | '#'
1315 | '/'
1316 | ':'
1317 | '<'
1318 | '>'
1319 | '?'
1320 | '@'
1321 | '['
1322 | '\\'
1323 | ']'
1324 | '^'
1325 | '|'
1326 ) || (is_special && (c <= '\u{1f}' || c == '%' || c == '\u{7f}'))
1327 };
1328 if host.chars().any(forbidden) {
1329 return None;
1330 }
1331 }
1332 Some(format!("{scheme}:"))
1333 }
1334
1335 pub fn sanitize_url(url: &str) -> String {
1338 let raw_url = url;
1339 let url = format_url(url);
1340 match whatwg_url_protocol(&format_url(&url)) {
1341 Some(protocol) => {
1342 if !SUPPORTED_URL_PROTOCOLS.contains(&protocol.as_str()) {
1343 return "about:blank".to_owned();
1344 }
1345 }
1346 None => {
1347 let normalized: String = raw_url
1351 .chars()
1352 .filter(|&c| !(c <= '\u{1f}' || c == '\u{7f}' || is_js_whitespace(c)))
1353 .collect();
1354 if let Some(scheme) = leading_scheme(&normalized) {
1355 let protocol = format!("{}:", scheme.to_ascii_lowercase());
1356 if !SUPPORTED_URL_PROTOCOLS.contains(&protocol.as_str()) {
1357 return "about:blank".to_owned();
1358 }
1359 }
1360 }
1361 }
1362 url
1363 }
1364}
1365
1366#[cfg(feature = "html")]
1367pub(super) mod link_dom {
1368 use super::sanitize::sanitize_url;
1369 use super::{LinkNode, create_link_node};
1370 use crate::dom::DomNode;
1371 use crate::lexical_dom::{
1372 DomConversionMap, DomConversionOutput, add_theme_class_names, get_document, importer,
1373 };
1374 use crate::{EditorConfig, LexicalError};
1375
1376 pub(crate) fn create_dom(link: &LinkNode, config: &EditorConfig) -> DomNode {
1380 let element = get_document().create_element("a");
1381 element.set_attribute("href", &sanitize_url(&link.url));
1382 for (attr, value) in [
1383 ("target", &link.target),
1384 ("rel", &link.rel),
1385 ("title", &link.title),
1386 ] {
1387 match value.as_deref().filter(|v| !v.is_empty()) {
1388 Some(value) => element.set_attribute(attr, value),
1389 None => element.remove_attribute(attr),
1390 }
1391 }
1392 add_theme_class_names(&element, &config.theme, "link");
1393 element
1394 }
1395
1396 pub(crate) fn import_dom() -> DomConversionMap {
1398 vec![("a".to_owned(), importer(1, convert_anchor_element))]
1399 }
1400
1401 fn convert_anchor_element(
1403 dom_node: &DomNode,
1404 ) -> Result<Option<DomConversionOutput>, LexicalError> {
1405 let mut node = None;
1406 if dom_node.is_element()
1407 && dom_node.local_name() == "a"
1408 && (!dom_node.text_content().is_empty() || !dom_node.children().is_empty())
1409 {
1410 node = Some(create_link_node(
1411 &dom_node.get_attribute("href").unwrap_or_default(),
1412 &super::LinkAttributes {
1413 rel: Some(dom_node.get_attribute("rel")),
1414 target: Some(dom_node.get_attribute("target")),
1415 title: Some(dom_node.get_attribute("title")),
1416 },
1417 ));
1418 }
1419 Ok(Some(DomConversionOutput::node(node)))
1420 }
1421}