concord 2.2.9

A terminal user interface client for Discord
Documentation
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
use crate::discord::ids::{
    Id,
    marker::{ChannelMarker, EmojiMarker, RoleMarker, UserMarker},
};

use crate::discord::{
    ApplicationCommandIdentity, ApplicationCommandInfo, ApplicationCommandOptionInfo, ChannelState,
    CustomEmojiInfo, PresenceStatus, RoleState, builtin_slash_commands,
};

use super::super::{MemberEntry, emoji::custom_emoji_can_be_used_directly};

/// Maximum number of suggestions composer pickers show at once. Candidate
/// builders still return every match. Rendering scrolls this many rows.
pub const MAX_MENTION_PICKER_VISIBLE: usize = 8;

/// One entry in the rendered @-mention picker list.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct MentionPickerEntry {
    pub target: MentionPickerTarget,
    pub display_name: String,
    /// Discord login handle. Shown as a hint in the picker so the user can
    /// tell which entry matches when they typed against the username instead
    /// of the alias.
    pub username: Option<String>,
    pub status: PresenceStatus,
    pub is_bot: bool,
    pub role_color: Option<u32>,
}

impl MentionPickerEntry {
    pub fn display_label(&self) -> &str {
        self.display_name
            .strip_prefix(self.target.visible_prefix())
            .unwrap_or(&self.display_name)
    }

    pub fn visible_text(&self) -> String {
        if self.display_name.starts_with(self.target.visible_prefix()) {
            self.display_name.clone()
        } else {
            format!("{}{}", self.target.visible_prefix(), self.display_name)
        }
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum MentionPickerTarget {
    User(Id<UserMarker>),
    Everyone(Id<RoleMarker>),
    Role(Id<RoleMarker>),
    Channel(Id<ChannelMarker>),
}

impl MentionPickerTarget {
    pub fn wire_format(self) -> String {
        match self {
            Self::User(id) => format!("<@{}>", id.get()),
            Self::Everyone(_) => "@everyone".to_owned(),
            Self::Role(id) => format!("<@&{}>", id.get()),
            Self::Channel(id) => format!("<#{}>", id.get()),
        }
    }

    pub fn command_wire_format(self) -> String {
        match self {
            Self::Everyone(id) => format!("<@&{}>", id.get()),
            target => target.wire_format(),
        }
    }

    pub fn visible_prefix(self) -> &'static str {
        match self {
            Self::User(_) | Self::Everyone(_) | Self::Role(_) => "@",
            Self::Channel(_) => "#",
        }
    }
}

/// One entry in the rendered emoji shortcode picker list.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct EmojiPickerEntry {
    pub emoji: String,
    pub shortcode: String,
    pub name: String,
    pub wire_format: Option<String>,
    pub available: bool,
    pub available_as_link: bool,
    pub custom_image_url: Option<String>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct CommandPickerEntry {
    pub label: String,
    pub detail: String,
    pub replacement: String,
    pub top_level: bool,
    pub command_identity: Option<ApplicationCommandIdentity>,
}

pub(super) fn build_builtin_command_candidates(query: &str) -> Vec<CommandPickerEntry> {
    let needle = query.to_ascii_lowercase();
    builtin_slash_commands()
        .iter()
        .filter(|command| needle.is_empty() || command.name.starts_with(&needle))
        .map(|command| CommandPickerEntry {
            label: format!("/{}", command.name),
            detail: command.description.to_owned(),
            replacement: command.replacement.to_owned(),
            top_level: true,
            command_identity: None,
        })
        .collect()
}

pub(super) fn build_command_candidates(
    query: &str,
    commands: &[ApplicationCommandInfo],
) -> Vec<CommandPickerEntry> {
    let needle = query.to_ascii_lowercase();
    let mut scored: Vec<(u8, String, CommandPickerEntry)> = commands
        .iter()
        .filter_map(|command| {
            let lowered = command.name.to_ascii_lowercase();
            let rank = if needle.is_empty() {
                1
            } else if lowered.starts_with(&needle) {
                0
            } else if lowered.contains(&needle) {
                2
            } else {
                return None;
            };
            Some((
                rank,
                lowered,
                CommandPickerEntry {
                    label: format!("/{}", command.name),
                    detail: command_picker_detail(command),
                    replacement: format!("/{} ", command.name),
                    top_level: true,
                    command_identity: Some(command.identity()),
                },
            ))
        })
        .collect();
    scored.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    scored.into_iter().map(|(_, _, entry)| entry).collect()
}

fn command_picker_detail(command: &ApplicationCommandInfo) -> String {
    match command.application_name.as_deref() {
        Some(name) if !command.description.is_empty() => {
            format!("{name} - {}", command.description)
        }
        Some(name) => name.to_owned(),
        None => command.description.clone(),
    }
}

pub(super) fn build_command_option_candidates(
    query: &str,
    options: &[ApplicationCommandOptionInfo],
) -> Vec<CommandPickerEntry> {
    let needle = query.to_ascii_lowercase();
    options
        .iter()
        .filter(|option| needle.is_empty() || option.name.to_ascii_lowercase().starts_with(&needle))
        .map(|option| CommandPickerEntry {
            label: command_option_label(option),
            detail: command_option_detail(option),
            replacement: command_option_replacement(option),
            top_level: false,
            command_identity: None,
        })
        .collect()
}

fn command_option_detail(option: &ApplicationCommandOptionInfo) -> String {
    if matches!(option.kind, 1 | 2) {
        return option.description.clone();
    }

    let requirement = if option.required {
        "required"
    } else {
        "optional"
    };
    if option.description.is_empty() {
        requirement.to_owned()
    } else {
        format!("{requirement} - {}", option.description)
    }
}

fn command_option_label(option: &ApplicationCommandOptionInfo) -> String {
    if matches!(option.kind, 1 | 2) {
        option.name.clone()
    } else {
        format!("{}:", option.name)
    }
}

fn command_option_replacement(option: &ApplicationCommandOptionInfo) -> String {
    if matches!(option.kind, 1 | 2) {
        format!("{} ", option.name)
    } else {
        format!("{}:", option.name)
    }
}

pub(super) fn build_command_choice_candidates(
    query: &str,
    option: &ApplicationCommandOptionInfo,
) -> Vec<CommandPickerEntry> {
    let needle = query.to_ascii_lowercase();
    option
        .choices
        .iter()
        .filter(|choice| choice.name.to_ascii_lowercase().contains(&needle))
        .map(|choice| CommandPickerEntry {
            label: choice.name.clone(),
            detail: choice.value.as_str().unwrap_or_default().to_owned(),
            replacement: format!(
                "{} ",
                choice
                    .value
                    .as_str()
                    .map(str::to_owned)
                    .unwrap_or_else(|| choice.value.to_string())
            ),
            top_level: false,
            command_identity: None,
        })
        .collect()
}

pub(super) fn build_mention_candidates(
    query: &str,
    entries: Vec<MemberEntry<'_>>,
    roles: Vec<&RoleState>,
    everyone_role_id: Option<Id<RoleMarker>>,
) -> Vec<MentionPickerEntry> {
    let needle = query.to_lowercase();
    let mut scored: Vec<(u8, String, MentionPickerEntry)> = entries
        .into_iter()
        .filter_map(|entry| {
            let display_name = entry.display_name();
            let username = entry.username();
            let lowered_display = display_name.to_lowercase();
            let lowered_username = username.as_deref().map(str::to_lowercase);

            // Lower rank wins. We deliberately stagger the ladder so an alias
            // prefix beats a username prefix and either beats a substring hit
            // on the other field.
            let rank = if needle.is_empty() {
                2
            } else if lowered_display.starts_with(&needle) {
                0
            } else if lowered_username
                .as_deref()
                .is_some_and(|name| name.starts_with(&needle))
            {
                1
            } else if lowered_display.contains(&needle) {
                2
            } else if lowered_username
                .as_deref()
                .is_some_and(|name| name.contains(&needle))
            {
                3
            } else {
                return None;
            };
            Some((
                rank,
                lowered_display,
                MentionPickerEntry {
                    target: MentionPickerTarget::User(entry.user_id()),
                    display_name,
                    username,
                    status: entry.status(),
                    is_bot: entry.is_bot(),
                    role_color: None,
                },
            ))
        })
        .collect();

    scored.extend(roles.into_iter().filter_map(|role| {
        let lowered_name = role.name.trim_start_matches('@').to_lowercase();
        let rank = match_name(&needle, &lowered_name)?;
        Some((
            rank.saturating_add(1),
            lowered_name,
            MentionPickerEntry {
                target: if Some(role.id) == everyone_role_id {
                    MentionPickerTarget::Everyone(role.id)
                } else {
                    MentionPickerTarget::Role(role.id)
                },
                display_name: role.name.clone(),
                username: None,
                status: PresenceStatus::Unknown,
                is_bot: false,
                role_color: role.color,
            },
        ))
    }));

    scored.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    scored.into_iter().map(|(_, _, entry)| entry).collect()
}

pub(super) fn build_channel_mention_candidates(
    query: &str,
    channels: Vec<&ChannelState>,
) -> Vec<MentionPickerEntry> {
    let needle = query.to_lowercase();
    let mut scored: Vec<(u8, String, MentionPickerEntry)> = channels
        .into_iter()
        .filter(|channel| !channel.is_category())
        .filter_map(|channel| {
            let lowered_name = channel.name.to_lowercase();
            let rank = match_name(&needle, &lowered_name)?;
            Some((
                rank,
                lowered_name,
                MentionPickerEntry {
                    target: MentionPickerTarget::Channel(channel.id),
                    display_name: channel.name.clone(),
                    username: None,
                    status: PresenceStatus::Unknown,
                    is_bot: false,
                    role_color: None,
                },
            ))
        })
        .collect();
    scored.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    scored.into_iter().map(|(_, _, entry)| entry).collect()
}

fn match_name(needle: &str, lowered_name: &str) -> Option<u8> {
    if needle.is_empty() {
        Some(2)
    } else if lowered_name.starts_with(needle) {
        Some(0)
    } else if lowered_name.contains(needle) {
        Some(2)
    } else {
        None
    }
}

pub(super) fn move_picker_selection(selected: usize, len: usize, delta: isize) -> usize {
    if len == 0 {
        return 0;
    }
    let current = selected.min(len - 1) as isize;
    (current + delta).clamp(0, len as isize - 1) as usize
}

pub(in crate::tui::state) fn build_emoji_candidates<'a>(
    query: &str,
    foreign_emojis: impl Iterator<Item = &'a CustomEmojiInfo>,
    guild_emojis: impl Iterator<Item = &'a CustomEmojiInfo>,
    has_nitro: bool,
    emojis_as_links: bool,
) -> Vec<EmojiPickerEntry> {
    let needle = query.to_ascii_lowercase();
    if needle.chars().count() < 2 {
        return Vec::new();
    }

    let make_entry = |is_foreign: bool| {
        move |emoji: &CustomEmojiInfo| {
            let can_send_directly = custom_emoji_can_be_used_directly(emoji, is_foreign, has_nitro);
            let as_link = emojis_as_links && !can_send_directly;
            let shortcode = emoji.name.clone();
            let marker = if emoji.animated { "â—‡" } else { "â—†" };
            let label = if emoji.animated {
                "animated custom emoji"
            } else {
                "custom emoji"
            };
            (
                0,
                shortcode.to_ascii_lowercase(),
                EmojiPickerEntry {
                    emoji: marker.to_owned(),
                    shortcode: shortcode.clone(),
                    name: label.to_owned(),
                    wire_format: Some(custom_emoji_markup(
                        &shortcode,
                        emoji.id,
                        emoji.animated,
                        as_link,
                    )),
                    available: emoji.available && (can_send_directly || as_link),
                    available_as_link: emoji.available && as_link,
                    custom_image_url: Some(custom_emoji_image_url(emoji.id, emoji.animated)),
                },
            )
        }
    };
    let mut scored: Vec<(u8, String, EmojiPickerEntry)> = guild_emojis
        .filter(|emoji| emoji.name.to_ascii_lowercase().starts_with(&needle))
        .map(|emoji| make_entry(false)(emoji))
        .collect();

    if has_nitro || emojis_as_links {
        scored.extend(
            foreign_emojis
                .filter(|emoji| emoji.name.to_ascii_lowercase().starts_with(&needle))
                .map(|emoji| make_entry(true)(emoji)),
        );
    }

    scored.extend(emojis::iter().flat_map(|emoji| {
        emoji
            .shortcodes()
            .filter(|shortcode| shortcode.starts_with(&needle))
            .map(|shortcode| {
                (
                    1,
                    shortcode.to_owned(),
                    EmojiPickerEntry {
                        emoji: emoji.as_str().to_owned(),
                        shortcode: shortcode.to_owned(),
                        name: emoji.name().to_owned(),
                        wire_format: None,
                        available: true,
                        available_as_link: false,
                        custom_image_url: None,
                    },
                )
            })
    }));
    scored.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    scored.into_iter().map(|(_, _, entry)| entry).collect()
}

fn custom_emoji_markup(name: &str, id: Id<EmojiMarker>, animated: bool, as_link: bool) -> String {
    if as_link {
        let link = custom_emoji_image_url(id, animated);
        format!("[{name}]({link}?size=48&name={name}&lossless=true)")
    } else if animated {
        format!("<a:{name}:{}>", id.get())
    } else {
        format!("<:{name}:{}>", id.get())
    }
}

fn custom_emoji_image_url(id: Id<EmojiMarker>, animated: bool) -> String {
    let extension = if animated { "gif" } else { "png" };
    format!("https://cdn.discordapp.com/emojis/{}.{extension}", id.get())
}

pub(in crate::tui::state) fn should_start_completion_query(input: &str) -> bool {
    input.chars().last().is_none_or(char::is_whitespace)
}

pub(super) fn is_mention_query_char(value: char) -> bool {
    value.is_alphanumeric() || matches!(value, '_' | '.' | '-')
}

pub(in crate::tui::state) fn is_emoji_query_char(value: char) -> bool {
    value.is_ascii_alphanumeric() || matches!(value, '_' | '-' | '+')
}

pub(super) fn is_command_query_char(value: char) -> bool {
    value.is_ascii_alphanumeric() || matches!(value, '_' | '-')
}

pub(in crate::tui::state) fn expand_emoji_shortcodes(input: &str) -> String {
    let mut rest = input;
    let mut output = String::with_capacity(input.len());

    while let Some((start, name_start, name_end, end)) = rest.find(':').and_then(|start| {
        let name_start = start + ':'.len_utf8();
        rest[name_start..].find(':').map(|relative_end| {
            (
                start,
                name_start,
                name_start + relative_end,
                name_start + relative_end + ':'.len_utf8(),
            )
        })
    }) {
        if starts_custom_emoji_markup(rest, start) {
            output.push_str(&rest[..name_start]);
            rest = &rest[name_start..];
            continue;
        }

        let shortcode = &rest[name_start..name_end];
        if shortcode.is_empty() {
            let colon_run_end = rest[start..]
                .char_indices()
                .find_map(|(offset, value)| (value != ':').then_some(start + offset))
                .unwrap_or(rest.len());
            let keep_to = if colon_run_end < rest.len() {
                colon_run_end - ':'.len_utf8()
            } else {
                colon_run_end
            };
            output.push_str(&rest[..keep_to]);
            rest = &rest[keep_to..];
            continue;
        }
        if let Some(emoji) = emojis::get_by_shortcode(shortcode) {
            output.push_str(&rest[..start]);
            output.push_str(emoji.as_str());
            rest = &rest[end..];
        } else {
            output.push_str(&rest[..name_end]);
            rest = &rest[name_end..];
        }
    }

    output.push_str(rest);
    output
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct EmojiCompletion {
    pub(super) byte_start: usize,
    pub(super) byte_end: usize,
    pub(super) replacement: String,
    pub(super) custom_image_url: Option<String>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub(in crate::tui) struct ComposerEmojiImageCompletion {
    pub(in crate::tui) byte_start: usize,
    pub(in crate::tui) byte_end: usize,
    pub(in crate::tui) url: String,
}

fn starts_custom_emoji_markup(input: &str, colon_start: usize) -> bool {
    input[..colon_start].ends_with('<') || input[..colon_start].ends_with("<a")
}

/// A previously confirmed mention recorded by byte range inside the composer
/// input. The composer keeps the human-readable `@displayname` text in the
/// editor so the user can see what they wrote, and rewrites these ranges to
/// `<@USER_ID>` only at submission time.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(in crate::tui::state) struct MentionCompletion {
    pub(super) byte_start: usize,
    pub(super) byte_end: usize,
    pub(super) target: MentionPickerTarget,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::tui::state) enum MentionExpansionMode {
    Message,
    Command,
}

/// Rewrites recorded mention and custom emoji ranges in one back-to-front pass.
/// Both completion kinds store byte ranges against the visible composer text, so
/// applying them together prevents earlier replacements from shifting later
/// ranges before they are used.
pub(super) fn expand_composer_completions(
    input: &str,
    mention_completions: &[MentionCompletion],
    emoji_completions: &[EmojiCompletion],
    mention_mode: MentionExpansionMode,
) -> String {
    if mention_completions.is_empty() && emoji_completions.is_empty() {
        return input.to_owned();
    }

    let mut replacements: Vec<CompletionReplacement> = mention_completions
        .iter()
        .filter(|completion| completion.byte_end <= input.len())
        .map(|completion| CompletionReplacement {
            byte_start: completion.byte_start,
            byte_end: completion.byte_end,
            replacement: match mention_mode {
                MentionExpansionMode::Message => completion.target.wire_format(),
                MentionExpansionMode::Command => completion.target.command_wire_format(),
            },
        })
        .collect();

    replacements.extend(
        emoji_completions
            .iter()
            .filter(|completion| completion.byte_end <= input.len())
            .map(|completion| CompletionReplacement {
                byte_start: completion.byte_start,
                byte_end: completion.byte_end,
                replacement: completion.replacement.clone(),
            }),
    );

    replacements.sort_by_key(|replacement| std::cmp::Reverse(replacement.byte_start));
    let mut buffer = input.to_owned();
    for replacement in replacements {
        if !buffer.is_char_boundary(replacement.byte_start)
            || !buffer.is_char_boundary(replacement.byte_end)
        {
            continue;
        }
        buffer.replace_range(
            replacement.byte_start..replacement.byte_end,
            &replacement.replacement,
        );
    }
    buffer
}

struct CompletionReplacement {
    byte_start: usize,
    byte_end: usize,
    replacement: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn role(id: u64, name: &str) -> RoleState {
        RoleState {
            id: Id::new(id),
            name: name.to_owned(),
            color: None,
            position: 0,
            hoist: false,
            permissions: 0,
        }
    }

    #[test]
    fn everyone_role_detection_uses_id_not_name() {
        let everyone = role(1, "renamed base role");
        let candidates =
            build_mention_candidates("", Vec::new(), vec![&everyone], Some(Id::new(1)));

        assert!(
            candidates
                .iter()
                .any(|entry| entry.target == MentionPickerTarget::Everyone(Id::new(1)))
        );
    }
}