summaryrefslogtreecommitdiff
path: root/library/src/meta/link.rs
blob: 93b9999dbd4f925aeb4ca22170a0dd4281809af4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use crate::prelude::*;
use crate::text::{Hyphenate, TextElem};

/// Link to a URL or a location in the document.
///
/// The link function makes its positional `body` argument clickable and links
/// it to the destination specified by the `dest` argument. By default, links
/// are not styled any different from normal text. However, you can easily apply
/// a style of your choice with a show rule.
///
/// ## Example { #example }
/// ```example
/// #show link: underline
///
/// https://example.com \
///
/// #link("https://example.com") \
/// #link("https://example.com")[
///   See example.com
/// ]
/// ```
///
/// ## Syntax { #syntax }
/// This function also has dedicated syntax: Text that starts with `http://` or
/// `https://` is automatically turned into a link.
///
/// Display: Link
/// Category: meta
#[element(Show)]
pub struct LinkElem {
    /// The destination the link points to.
    ///
    /// - To link to web pages, `dest` should be a valid URL string. If the URL
    ///   is in the `mailto:` or `tel:` scheme and the `body` parameter is
    ///   omitted, the email address or phone number will be the link's body,
    ///   without the scheme.
    ///
    /// - To link to another part of the document, `dest` can take one of three
    ///   forms:
    ///   - A [label]($func/label) attached to an element. If you also want
    ///     automatic text for the link based on the element, consider using
    ///     a [reference]($func/ref) instead.
    ///
    ///   - A [location]($func/locate) resulting from a [`locate`]($func/locate)
    ///     call or [`query`]($func/query).
    ///
    ///   - A dictionary with a `page` key of type [integer]($type/integer) and
    ///     `x` and `y` coordinates of type [length]($type/length). Pages are
    ///     counted from one, and the coordinates are relative to the page's top
    ///     left corner.
    ///
    /// ```example
    /// = Introduction <intro>
    /// #link("mailto:hello@typst.app") \
    /// #link(<intro>)[Go to intro] \
    /// #link((page: 1, x: 0pt, y: 0pt))[
    ///   Go to top
    /// ]
    /// ```
    #[required]
    #[parse(
        let dest = args.expect::<LinkTarget>("destination")?;
        dest.clone()
    )]
    pub dest: LinkTarget,

    /// The content that should become a link.
    ///
    /// If `dest` is an URL string, the parameter can be omitted. In this case,
    /// the URL will be shown as the link.
    #[required]
    #[parse(match &dest {
        LinkTarget::Dest(Destination::Url(url)) => match args.eat()? {
            Some(body) => body,
            None => body_from_url(url),
        },
        _ => args.expect("body")?,
    })]
    pub body: Content,
}

impl LinkElem {
    /// Create a link element from a URL with its bare text.
    pub fn from_url(url: EcoString) -> Self {
        let body = body_from_url(&url);
        Self::new(LinkTarget::Dest(Destination::Url(url)), body)
    }
}

impl Show for LinkElem {
    #[tracing::instrument(name = "LinkElem::show", skip(self, vt))]
    fn show(&self, vt: &mut Vt, _: StyleChain) -> SourceResult<Content> {
        let body = self.body();
        let dest = match self.dest() {
            LinkTarget::Dest(dest) => dest,
            LinkTarget::Label(label) => {
                if !vt.introspector.init() {
                    return Ok(body);
                }

                let elem = vt.introspector.query_label(&label).at(self.span())?;
                Destination::Location(elem.location().unwrap())
            }
        };

        Ok(body
            .linked(dest)
            .styled(TextElem::set_hyphenate(Hyphenate(Smart::Custom(false)))))
    }
}

fn body_from_url(url: &EcoString) -> Content {
    let mut text = url.as_str();
    for prefix in ["mailto:", "tel:"] {
        text = text.trim_start_matches(prefix);
    }
    let shorter = text.len() < url.len();
    TextElem::packed(if shorter { text.into() } else { url.clone() })
}

/// A target where a link can go.
#[derive(Debug, Clone)]
pub enum LinkTarget {
    Dest(Destination),
    Label(Label),
}

cast_from_value! {
    LinkTarget,
    v: Destination => Self::Dest(v),
    v: Label => Self::Label(v),
}

cast_to_value! {
    v: LinkTarget => match v {
        LinkTarget::Dest(v) => v.into(),
        LinkTarget::Label(v) => v.into(),
    }
}

impl From<Destination> for LinkTarget {
    fn from(dest: Destination) -> Self {
        Self::Dest(dest)
    }
}