Skip to main content

lexical_ui/link/
link_node.rs

1//! `LexicalLinkNode.ts`: `LinkNode` and `AutoLinkNode`, their `$create*`
2//! and `$is*` functions, `$linkNodeTransform`, `TOGGLE_LINK_COMMAND`,
3//! `$toggleLink` and `formatUrl`.
4
5use 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/// `LinkAttributes`: a link's `rel`, `target` and `title`. Each is `None`
35/// where JS's is `undefined` (left as it is, or `null` on a new link),
36/// `Some(None)` where it is `null`, and otherwise the string.
37#[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    /// `{...self, ...overrides}`: each attribute `overrides` carries
46    /// replaces this one's.
47    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/// `AutoLinkAttributes`: [`LinkAttributes`] and `isUnlinked` (`None` for
57/// `undefined` or `null`, which mean `false`).
58#[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/// `LinkNode`: an inline element linking its children to a URL.
67#[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/// `AutoLinkNode`: a [`LinkNode`] made while typing (by `registerAutoLink`,
78/// the `autolink` feature) that records whether it was ever unlinked. A
79/// `LinkNode` in every other respect: [`is_link_node`] holds for it.
80#[derive(Clone, Debug, Default)]
81pub struct AutoLinkNode {
82    pub(super) link: LinkNode,
83    pub(super) is_unlinked: bool,
84}
85
86impl LinkNode {
87    /// `new LinkNode(url, attributes)`: an attribute that is `undefined`
88    /// is `null`.
89    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    /// The fields `AutoLinkNode` inherits from `LinkNode`.
123    pub fn link(&self) -> &LinkNode {
124        &self.link
125    }
126
127    pub fn is_unlinked(&self) -> bool {
128        self.is_unlinked
129    }
130}
131
132/// `$createLinkNode(url, attributes)`.
133pub 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
142/// `$isLinkNode(node)`: a `LinkNode` or an `AutoLinkNode`.
143pub fn is_link_node(node: &NodeRef) -> bool {
144    link_of(&*node.get_latest()).is_some()
145}
146
147/// `$createAutoLinkNode(url, attributes)`.
148pub 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
155/// `$isAutoLinkNode(node)`.
156pub fn is_auto_link_node(node: &NodeRef) -> bool {
157    node.get_latest().is::<AutoLinkNode>()
158}
159
160/// The `LinkNode` fields of a `LinkNode` or an `AutoLinkNode`.
161fn 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
166/// Changes the `LinkNode` fields of a link (`getWritable()`); does nothing
167/// to any other node.
168fn 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    /// `LinkNode.getURL()`; `None` for any other node.
182    pub fn get_url(&self) -> Option<String> {
183        link_of(&*self.get_latest()).map(|l| l.url.clone())
184    }
185
186    /// `LinkNode.setURL(url)`. Does nothing to any other node.
187    pub fn set_url(&self, url: &str) {
188        set_link(self, |l| l.url = url.to_owned());
189    }
190
191    /// `LinkNode.getTarget()`; `None` when it is `null`, or for any other
192    /// node.
193    pub fn get_target(&self) -> Option<String> {
194        link_of(&*self.get_latest()).and_then(|l| l.target.clone())
195    }
196
197    /// `LinkNode.setTarget(target)`. Does nothing to any other node.
198    pub fn set_target(&self, target: Option<&str>) {
199        set_link(self, |l| l.target = target.map(str::to_owned));
200    }
201
202    /// `LinkNode.getRel()`; `None` when it is `null`, or for any other node.
203    pub fn get_rel(&self) -> Option<String> {
204        link_of(&*self.get_latest()).and_then(|l| l.rel.clone())
205    }
206
207    /// `LinkNode.setRel(rel)`. Does nothing to any other node.
208    pub fn set_rel(&self, rel: Option<&str>) {
209        set_link(self, |l| l.rel = rel.map(str::to_owned));
210    }
211
212    /// `LinkNode.getTitle()`; `None` when it is `null`, or for any other
213    /// node.
214    pub fn get_title(&self) -> Option<String> {
215        link_of(&*self.get_latest()).and_then(|l| l.title.clone())
216    }
217
218    /// `LinkNode.setTitle(title)`. Does nothing to any other node.
219    pub fn set_title(&self, title: Option<&str>) {
220        set_link(self, |l| l.title = title.map(str::to_owned));
221    }
222
223    /// `AutoLinkNode.getIsUnlinked()`; `None` for any other node.
224    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    /// `AutoLinkNode.setIsUnlinked(value)`. Does nothing to any other node.
231    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    /// `LinkNode.isEmailURI()`: whether the URL starts with `mailto:`;
242    /// false for any other node.
243    pub fn is_email_uri(&self) -> bool {
244        self.get_url().is_some_and(|url| url.starts_with("mailto:"))
245    }
246
247    /// `LinkNode.isWebSiteURI()`: whether the URL starts with `https://` or
248    /// `http://`; false for any other node.
249    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    /// `LinkNode.shouldMergeAdjacentLink(otherLink)`: whether two links of
255    /// the same type have the same URL and attributes. `AutoLinkNode`'s is
256    /// always false, so adjacent autolinks never merge.
257    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
276/// `LinkNode.insertNewAfter(_, restoreSelection)`: a copy of the link
277/// (`$copyNode`), after it.
278fn 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
287/// `LinkNode.extractWithChild(child, selection, destination)`: a range
288/// selection that starts and ends in the link, and selects some text, takes
289/// the link with it.
290fn 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
305/// `LinkNode`'s config chain (see its [`LexicalNode::static_node_config_chain`]).
306fn 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
340/// The `LinkNode` fields of a schema accessor's link.
341fn 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
352/// `linkNodeSchema`: `rel`, `target` and `title` (an empty string imports
353/// as `null`) and `url`, each the field it names.
354pub fn link_node_schema() -> NodeSchema {
355    LINK_NODE_SCHEMA.with(Clone::clone)
356}
357
358/// `autoLinkNodeSchema`: the `isUnlinked` field.
359pub 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    /// The `$config()` of `LinkNode`: `inline: true`, `children: 'inline'`
405    /// and `mergeAdjacent: {by: ['url', 'target', 'rel', 'title']}`, what
406    /// `shouldMergeAdjacentLink` compares. The method stays the authority:
407    /// `$linkNodeTransform` calls it, and a subclass that inherits the
408    /// declaration is never merged by the normalization.
409    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    /// `LinkNode.isInline()`.
443    fn is_inline(&self) -> bool {
444        true
445    }
446
447    /// `LinkNode.canBeEmpty()`.
448    fn can_be_empty(&self) -> bool {
449        false
450    }
451
452    /// `LinkNode.canInsertTextBefore()`: text typed at the link's start
453    /// goes before it.
454    fn can_insert_text_before(&self) -> bool {
455        false
456    }
457
458    /// `LinkNode.canInsertTextAfter()`: text typed at the link's end goes
459    /// after it.
460    fn can_insert_text_after(&self) -> bool {
461        false
462    }
463
464    /// `LinkNode.insertNewAfter(selection, restoreSelection)`.
465    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    /// `LinkNode.extractWithChild(child, selection, destination)`.
475    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    /// `exportLinkNode` and `exportCompactLinkNode`.
486    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    /// `updateLinkNode`.
495    fn generated_update_from_json(&mut self, json: &Object) -> bool {
496        update_link_node(self, json);
497        true
498    }
499}
500
501/// `AutoLinkNode` overrides none of what `LinkNode` overrides here (not
502/// `canInsertTextAfter` either, whatever its class comment says), so each
503/// hook is `LinkNode`'s.
504impl 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    /// The `$config()` of `AutoLinkNode`: `extends: LinkNode` and
513    /// `mergeAdjacent: false` (adjacent autolinks never merge, see
514    /// `shouldMergeAdjacentLink`).
515    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    /// `AutoLinkNode.updateDOM(prevNode)`: `LinkNode`'s (which keeps its
529    /// DOM), or made again when `isUnlinked` changes.
530    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    /// `AutoLinkNode extends LinkNode`.
539    #[cfg(feature = "html")]
540    fn super_types(&self) -> Vec<&'static str> {
541        vec!["link"]
542    }
543    /// `AutoLinkNode.createDOM(config)`: a `<span>` once unlinked, else
544    /// `LinkNode`'s `<a>`.
545    #[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    /// `LinkNode.insertNewAfter`, which `$copyNode` makes an `AutoLinkNode`
587    /// with the same `isUnlinked`.
588    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    /// `exportAutoLinkNode` and `exportCompactAutoLinkNode`.
608    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    /// `updateAutoLinkNode`.
617    fn generated_update_from_json(&mut self, json: &Object) -> bool {
618        update_auto_link_node(self, json);
619        true
620    }
621}
622
623/// `[next, next.getFlipped()]`: a selection point as carets both ways.
624type CaretPair = [PointCaret; 2];
625
626/// `$saveCaretPair(point)`.
627fn 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
633/// `$restoreCaretPair(point, pair)`: the point at the first caret of the
634/// pair whose node is still attached.
635fn 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
649/// The merge boundary fix of `$linkNodeTransform`
650/// (`$fixMergeBoundaryCaret`): a caret pair that points to the end of the
651/// absorbing link, which would shift when the merging link's children are
652/// appended to it, moves to the merging link's start.
653fn 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    // Resolve the merge boundary from the merging link's start, since
664    // those children survive the move and represent the boundary position.
665    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
672/// `$linkNodeTransform(link)`: lifts block children out of a link, splitting
673/// its ancestors as needed to keep the document valid, and merges the link
674/// with an adjacent link that `shouldMergeAdjacentLink` matches, keeping the
675/// selection where it was. `registerLink` registers it for `LinkNode`.
676///
677/// Where `NodeStructureExtension` enforces declared structure, it lifts
678/// blocks out of links itself (`LinkNode` declares `children: 'inline'`),
679/// and merges equal adjacent `LinkNode`s (`$structureMerges`), the same way
680/// whichever node is dirty, so this transform leaves them to it.
681pub 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/// `TOGGLE_LINK_COMMAND`'s payload when it isn't `null` (`None`, which
772/// removes the links): a URL, or a URL with attributes.
773#[derive(Clone, Debug, PartialEq, Eq)]
774pub enum ToggleLinkPayload {
775    Url(String),
776    Attributes {
777        url: String,
778        attributes: LinkAttributes,
779    },
780}
781
782// Like the core's commands (`commands.rs`), a constant, with an id counting
783// down from where the list commands stop.
784
785/// `TOGGLE_LINK_COMMAND`: dispatched to link the selection, change the
786/// links in it, or with `None` remove them.
787pub const TOGGLE_LINK_COMMAND: LexicalCommand<Option<ToggleLinkPayload>> =
788    LexicalCommand::constant(u64::MAX - 25, "TOGGLE_LINK_COMMAND");
789
790/// `$getPointNode(point, offset)`: the child at an element point's offset
791/// plus `offset`, if any.
792fn 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
807/// `$withSelectedNodes($fn)`: runs `f`, keeping the logical start and end of
808/// a range selection whose element points `f` may reparent.
809fn 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
853/// `$splitLinkAtSelection(parentLink, extractedNodes)`: takes the selected
854/// children out of a link, at its start, its end or its middle (splitting
855/// it in two).
856fn 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    // Check if a child is an extracted node OR contains an extracted node
868    // This handles nested structures like LinkNode > HeadingNode > TextNode
869    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        // The selection only touches the link at a boundary (e.g. it ends at
885        // offset 0 of the link's first text node, or starts at the end of its
886        // last one), so extract() returned the LinkNode itself but none of its
887        // content. There is nothing to unlink.
888        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
938/// A `LinkNode` that is not an `AutoLinkNode`, which is what removing or
939/// updating a link looks for.
940fn is_non_auto_link(node: &NodeRef) -> bool {
941    !is_auto_link_node(node) && is_link_node(node)
942}
943
944/// `$toggleLink(url, attributes)`: links the selection to `url`, or updates
945/// the links it is in; with `url` `None` (JS `null`), removes the links
946/// around it and keeps their children. `rel` defaults to `noreferrer`;
947/// another attribute that is `None` (`undefined`) leaves an existing link's
948/// as it is.
949///
950/// JS also takes `{url, ...attributes}` as the first argument, whose
951/// attributes the second argument's override; here a caller passes the URL
952/// and the merged attributes ([`LinkAttributes::merging`]).
953pub 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        // Handle all selected nodes
987        for node in &nodes {
988            match url {
989                None => {
990                    // Remove link
991                    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                    // Add/Update link
1000                    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    // Handle RangeSelection
1033    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    // Add or merge LinkNodes
1058    if nodes.len() == 1 {
1059        // if the first node is a LinkNode or if its
1060        // parent is a LinkNode, we update the URL, target and rel.
1061        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                    // Ignore block nodes, if there are any children we will see them
1080                    // later and wrap in a new LinkNode
1081                    continue;
1082                }
1083                if is_link_node(node) {
1084                    // If it's not an autolink node and we don't already have a LinkNode
1085                    // in this block then we can update it and re-use it
1086                    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                    // Unwrap LinkNode, we already have one or it's an AutoLinkNode
1096                    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
1119/// `PHONE_NUMBER_REGEX`, `/^\+?[0-9\s()-]{5,}$/`.
1120fn 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
1128/// JS's `\s`.
1129fn 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
1146/// Whether `/^[a-z][a-z0-9+.-]*:/i` matches: the URL starts with a scheme.
1147fn 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
1163/// `formatUrl(url)`: the URL with the protocol it is missing. One with a
1164/// scheme or a relative path (`/`, `#` or `.` first) is kept; an email
1165/// address gets `mailto:`, a phone number `tel:`, and anything else
1166/// `https://`.
1167pub fn format_url(url: &str) -> String {
1168    // Check if URL already has a protocol
1169    if has_scheme(url) {
1170        // URL already has a protocol, leave it as is
1171        url.to_owned()
1172    }
1173    // Check if it's a relative path (starting with '/', '.', or '#')
1174    else if url.starts_with(['/', '#', '.']) {
1175        // Relative path, leave it as is
1176        url.to_owned()
1177    }
1178    // Check for email address
1179    else if url.contains('@') {
1180        format!("mailto:{url}")
1181    }
1182    // Check for phone number
1183    else if is_phone_number(url) {
1184        format!("tel:{url}")
1185    }
1186    // For everything else, return with https:// prefix
1187    else {
1188        format!("https://{url}")
1189    }
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194    use super::format_url;
1195
1196    /// `formatUrl` as Node gives it for these inputs.
1197    // upstream: lexical-link/src/__tests__/unit/LexicalLinkNode.test.ts::formatUrl > should not modify URLs with protocols
1198    // upstream: lexical-link/src/__tests__/unit/LexicalLinkNode.test.ts::formatUrl > should not modify relative paths
1199    // upstream: lexical-link/src/__tests__/unit/LexicalLinkNode.test.ts::formatUrl > should add mailto: to email addresses
1200    // upstream: lexical-link/src/__tests__/unit/LexicalLinkNode.test.ts::formatUrl > should add tel: to phone numbers
1201    // upstream: lexical-link/src/__tests__/unit/LexicalLinkNode.test.ts::formatUrl > should add https:// to URLs without protocols
1202    #[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
1227// The DOM side of `LinkNode` and `AutoLinkNode` (the `html` feature).
1228
1229/// `LinkNode.sanitizeUrl`, which `createDOM` and `ClickableLinkExtension`
1230/// call.
1231pub(crate) mod sanitize {
1232    use super::{format_url, is_js_whitespace};
1233
1234    /// `SUPPORTED_URL_PROTOCOLS`.
1235    const SUPPORTED_URL_PROTOCOLS: [&str; 5] = ["http:", "https:", "mailto:", "sms:", "tel:"];
1236
1237    /// The scheme `/^([a-z][a-z0-9+.-]*):/i` matches at the start.
1238    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    /// The `protocol` of `new URL(url)`, or `None` where it throws. Like
1248    /// Swift's (`swift/Sources/LexicalLink/LinkNode.swift`), this follows
1249    /// the WHATWG URL parser as far as an absolute URL's scheme and host
1250    /// decide whether it parses, without IDNA or IPv4 parsing.
1251    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    /// `LinkNode.sanitizeUrl(url)`: `about:blank` for a URL whose scheme
1336    /// isn't supported, else the URL with `formatUrl`'s protocol.
1337    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                // `new URL()` threw: an explicit scheme in the input, once
1348                // C0 controls, DEL and whitespace are dropped, that isn't
1349                // supported is neutralized.
1350                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    /// `LinkNode.createDOM(config)`: an `<a>` with the sanitized URL, the
1377    /// target, rel and title it has (`updateLinkDOM(null, ...)`), and the
1378    /// theme's `link` class names.
1379    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    /// `LinkNode`'s `importDOM`: `<a>`.
1397    pub(crate) fn import_dom() -> DomConversionMap {
1398        vec![("a".to_owned(), importer(1, convert_anchor_element))]
1399    }
1400
1401    /// `$convertAnchorElement(domNode)`: a link for an `<a>` with content.
1402    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}