djs_formatters/link.rs
1//! Links to channels, messages and the App Directory, and e-mail and phone links.
2
3use core::fmt::{self, Write as _};
4
5use djs_model::id::{ApplicationId, ChannelId, GuildId, MessageId, SkuId};
6
7/// Where Discord's web links point.
8const CHANNELS: &str = "https://discord.com/channels";
9
10/// The part of a channel or message link naming the server, or `@me` for a DM.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12struct Server(Option<GuildId>);
13
14impl fmt::Display for Server {
15 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16 match self.0 {
17 Some(guild) => fmt::Display::fmt(&guild, f),
18 None => f.write_str("@me"),
19 }
20 }
21}
22
23/// A link to a channel: `https://discord.com/channels/GUILD_ID/CHANNEL_ID`, or `@me` in place
24/// of the server for a DM. Returned by [`channel_link`].
25///
26/// discord.js counterpart: the string `channelLink` returns (`@discordjs/formatters`).
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
28#[must_use = "a formatter does nothing until it is written"]
29pub struct ChannelLink {
30 channel: ChannelId,
31 guild: Server,
32}
33
34/// Links to the channel `channel`, a DM unless the [`guild`](ChannelLink::guild) is set
35/// (D-213).
36///
37/// Unlike a [`channel_mention`](crate::channel_mention), a link works outside Discord too.
38///
39/// discord.js counterpart: `channelLink`.
40///
41/// # Examples
42///
43/// ```
44/// use djs_formatters::channel_link;
45/// use djs_model::id::{ChannelId, GuildId};
46///
47/// let channel = ChannelId::new(222_197_033_908_436_994);
48/// assert_eq!(channel_link(channel).to_string(), "https://discord.com/channels/@me/222197033908436994");
49/// assert_eq!(
50/// channel_link(channel).guild(GuildId::new(81_384_788_765_712_384)).to_string(),
51/// "https://discord.com/channels/81384788765712384/222197033908436994"
52/// );
53/// ```
54pub const fn channel_link(channel: ChannelId) -> ChannelLink {
55 ChannelLink {
56 channel,
57 guild: Server(None),
58 }
59}
60
61impl ChannelLink {
62 /// Sets the server the channel is in.
63 ///
64 /// discord.js counterpart: the `guildId` argument of `channelLink` (`@discordjs/formatters`).
65 pub const fn guild(mut self, guild: GuildId) -> Self {
66 self.guild = Server(Some(guild));
67 self
68 }
69}
70
71impl fmt::Display for ChannelLink {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 write!(f, "{CHANNELS}/{}/{}", self.guild, self.channel)
74 }
75}
76
77/// A link to a message: `https://discord.com/channels/GUILD_ID/CHANNEL_ID/MESSAGE_ID`.
78/// Returned by [`message_link`].
79///
80/// discord.js counterpart: the string `messageLink` returns (`@discordjs/formatters`).
81#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
82#[must_use = "a formatter does nothing until it is written"]
83pub struct MessageLink {
84 channel: ChannelLink,
85 message: MessageId,
86}
87
88/// Links to the message `message` of the channel `channel`, a DM unless the
89/// [`guild`](MessageLink::guild) is set (D-213).
90///
91/// discord.js counterpart: `messageLink`.
92///
93/// # Examples
94///
95/// ```
96/// use djs_formatters::message_link;
97/// use djs_model::id::{ChannelId, GuildId, MessageId};
98///
99/// let link = message_link(ChannelId::new(2), MessageId::new(3)).guild(GuildId::new(1));
100/// assert_eq!(link.to_string(), "https://discord.com/channels/1/2/3");
101/// ```
102pub const fn message_link(channel: ChannelId, message: MessageId) -> MessageLink {
103 MessageLink {
104 channel: channel_link(channel),
105 message,
106 }
107}
108
109impl MessageLink {
110 /// Sets the server the message's channel is in.
111 ///
112 /// discord.js counterpart: the `guildId` argument of `messageLink` (`@discordjs/formatters`).
113 pub const fn guild(mut self, guild: GuildId) -> Self {
114 self.channel = self.channel.guild(guild);
115 self
116 }
117}
118
119impl fmt::Display for MessageLink {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 write!(f, "{}/{}", self.channel, self.message)
122 }
123}
124
125/// A link to an app's store page in the App Directory, or to one of its SKUs. Returned by
126/// [`application_directory`].
127///
128/// discord.js counterpart: the string `applicationDirectory` returns (`@discordjs/formatters`).
129#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
130#[must_use = "a formatter does nothing until it is written"]
131pub struct ApplicationDirectory {
132 application: ApplicationId,
133 sku: Option<SkuId>,
134}
135
136/// Links to the App Directory store page of the app `application`
137/// (`https://discord.com/application-directory/ID/store`), or of one of its SKUs with
138/// [`sku`](ApplicationDirectory::sku) (D-213). Discord shows the link as a card.
139///
140/// discord.js counterpart: `applicationDirectory`.
141///
142/// # Examples
143///
144/// ```
145/// use djs_formatters::application_directory;
146/// use djs_model::id::{ApplicationId, SkuId};
147///
148/// let app = ApplicationId::new(1);
149/// assert_eq!(application_directory(app).to_string(), "https://discord.com/application-directory/1/store");
150/// assert_eq!(
151/// application_directory(app).sku(SkuId::new(2)).to_string(),
152/// "https://discord.com/application-directory/1/store/2"
153/// );
154/// ```
155pub const fn application_directory(application: ApplicationId) -> ApplicationDirectory {
156 ApplicationDirectory {
157 application,
158 sku: None,
159 }
160}
161
162impl ApplicationDirectory {
163 /// Links to the SKU `sku` of the app's store.
164 ///
165 /// discord.js counterpart: the `skuId` argument of `applicationDirectory` (`@discordjs/formatters`).
166 pub const fn sku(mut self, sku: SkuId) -> Self {
167 self.sku = Some(sku);
168 self
169 }
170}
171
172impl fmt::Display for ApplicationDirectory {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 write!(
175 f,
176 "https://discord.com/application-directory/{}/store",
177 self.application
178 )?;
179 if let Some(sku) = self.sku {
180 write!(f, "/{sku}")?;
181 }
182 Ok(())
183 }
184}
185
186/// Writes `text` as `application/x-www-form-urlencoded`, like a URL query string: letters,
187/// digits and `*-._` as they are, spaces as `+`, every other byte as `%XX`.
188fn write_form_encoded(f: &mut fmt::Formatter<'_>, text: &str, lower_case: bool) -> fmt::Result {
189 const HEX: &[u8; 16] = b"0123456789ABCDEF";
190 for &byte in text.as_bytes() {
191 match byte {
192 b'A'..=b'Z' if lower_case => f.write_char(char::from(byte.to_ascii_lowercase()))?,
193 b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'*' | b'-' | b'.' | b'_' => {
194 f.write_char(char::from(byte))?;
195 }
196 b' ' => f.write_char('+')?,
197 _ => {
198 f.write_char('%')?;
199 f.write_char(char::from(HEX[usize::from(byte >> 4)]))?;
200 f.write_char(char::from(HEX[usize::from(byte & 0x0F)]))?;
201 }
202 }
203 }
204 Ok(())
205}
206
207/// An e-mail link: `<address>` or `<address?header=value&…>`. Returned by [`email`].
208///
209/// discord.js counterpart: the string `email` returns (`@discordjs/formatters`).
210#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
211#[must_use = "a formatter does nothing until it is written"]
212pub struct Email<'a> {
213 address: &'a str,
214 headers: &'a [(&'a str, &'a str)],
215}
216
217/// Links to the e-mail address `address`; clicking it opens a new e-mail, with the
218/// [`headers`](Email::headers) (such as `subject`) filled in if set (D-213).
219///
220/// discord.js counterpart: `email`.
221///
222/// # Examples
223///
224/// ```
225/// use djs_formatters::email;
226///
227/// assert_eq!(email("help@example.com").to_string(), "<help@example.com>");
228/// assert_eq!(
229/// email("help@example.com").headers(&[("Subject", "Bug report"), ("cc", "a@b.c")]).to_string(),
230/// "<help@example.com?subject=Bug+report&cc=a%40b.c>"
231/// );
232/// ```
233pub const fn email(address: &str) -> Email<'_> {
234 Email {
235 address,
236 headers: &[],
237 }
238}
239
240impl<'a> Email<'a> {
241 /// Sets headers of the new e-mail as `(name, value)` pairs, such as `("subject", "Hi")`
242 /// or `("body", "…")`. Names are lower-cased, and names and values are encoded as in a
243 /// URL query.
244 ///
245 /// discord.js counterpart: the `headers` argument of `email` (`@discordjs/formatters`).
246 pub const fn headers(mut self, headers: &'a [(&'a str, &'a str)]) -> Self {
247 self.headers = headers;
248 self
249 }
250}
251
252impl fmt::Display for Email<'_> {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 f.write_str("<")?;
255 f.write_str(self.address)?;
256 for (index, (name, value)) in self.headers.iter().enumerate() {
257 f.write_str(if index == 0 { "?" } else { "&" })?;
258 write_form_encoded(f, name, true)?;
259 f.write_str("=")?;
260 write_form_encoded(f, value, false)?;
261 }
262 f.write_str(">")
263 }
264}
265
266/// A phone link: `<+number>`. Returned by [`phone_number`].
267///
268/// discord.js counterpart: the string `phoneNumber` returns (`@discordjs/formatters`).
269#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
270#[must_use = "a formatter does nothing until it is written"]
271pub struct PhoneNumber<'a>(&'a str);
272
273/// Links to the phone number `number`, which must be international (start with `+`); `None`
274/// otherwise (discord.js throws an error).
275///
276/// discord.js counterpart: `phoneNumber`.
277///
278/// # Examples
279///
280/// ```
281/// use djs_formatters::phone_number;
282///
283/// assert_eq!(phone_number("+1 555 0100").unwrap().to_string(), "<+1 555 0100>");
284/// assert!(phone_number("555 0100").is_none());
285/// ```
286#[must_use]
287pub fn phone_number(number: &str) -> Option<PhoneNumber<'_>> {
288 number.starts_with('+').then_some(PhoneNumber(number))
289}
290
291impl fmt::Display for PhoneNumber<'_> {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 write!(f, "<{}>", self.0)
294 }
295}