lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
//! Mentions: a token input that offers people or things as a trigger is typed, and holds what is chosen as tokens.

use std::sync::Arc;

use parking_lot::Mutex;

use super::{
  avatar::{Avatar, AvatarSize},
  field::{FieldControl, InField},
  icon::Icon,
  names,
  part_style::{Length, PartStyle},
  recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
  text_box::TextBoxSize,
  theme::{Themed, current_theme},
  token_input::{MENTION, Token, TokenInput, TokenInputPart, TokenInputView},
};
use crate::{
  app::{
    ctx::Placement,
    events::{KeyboardEvent, TextInputEvent},
    theme::{BorderSize, IconSize, OpacityLevel, PaletteColor, RadiusSize, ShadowStyle, Theme, TypographyStyle},
  },
  components::{Column, Popup, Row, TextInputController},
  core::{ElementRef, Signal},
  layout::Alignment,
  node::{CursorIcon, Element, border::Border},
};

/// The parts of a mentions field a recipe styles, besides those of the token input it is
/// ([`TokenInputPart`], whose tokens of the variant [`MENTION`] are its mentions).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MentionsPart {
  /// The place the field takes: its width.
  Root,
  /// The box that is typed in: what it lays over the token input's control, its room and its least height.
  Control,
  /// The panel that floats under the trigger: the list of what is offered.
  Panel,
  /// One offer in the list: what is pressed, and what is highlighted while it is the one Enter chooses.
  Item,
  /// The avatar of an offer, where it has one.
  ItemAvatar,
  /// The icon of an offer, where it has one and no avatar.
  ItemIcon,
  /// The text of an offer.
  ItemLabel,
}

names!(MentionsPart {
  Root => "root",
  Control => "control",
  Panel => "panel",
  Item => "item",
  ItemAvatar => "item_avatar",
  ItemIcon => "item_icon",
  ItemLabel => "item_label",
});

/// The sizes of a mentions field: an input's, the type of its text and mentions 13, 14 or 15.
pub type MentionsSize = TextBoxSize;

/// The states of a mentions field a recipe styles, besides those of its box. The two last are an offer's own:
/// its parts are resolved in them.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MentionsState {
  /// The list is open under a trigger.
  Open,
  /// The offer is the one Enter chooses.
  Highlighted,
  /// The offer is shown and cannot be chosen.
  Disabled,
  /// The field is in a fluid field ([`Field::fluid`](super::Field::fluid)): the field's label is inside its box,
  /// over its text.
  Fluid,
}

names!(MentionsState {
  Open => "open",
  Highlighted => "highlighted",
  Disabled => "disabled",
  Fluid => "fluid",
});

/// What builds a mentions field's nodes: a theme's in place of the default one.
pub type MentionsRenderer = Arc<dyn Fn(MentionsView) -> Element + Send + Sync>;

/// A person or a thing a [`Mentions`] offers after its trigger.
///
/// ```
/// use lurq::ui::{Avatar, Mention, icons};
///
/// let ivan = Mention::new("Ivan Zaida").avatar(Avatar::new("Ivan Zaida"));
/// // The text it puts in the field, in place of the trigger and its label.
/// let channel = Mention::new("design").text("#design").icon(icons::USERS);
/// // Shown, and not to be chosen.
/// let away = Mention::new("Ivy Chen").disabled(true).id("ivy");
/// ```
pub struct Mention {
  label: Arc<str>,
  text: Option<Arc<str>>,
  avatar: Option<Avatar>,
  icon: Option<Name>,
  disabled: bool,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl Mention {
  /// An offer called `label`, which puts the trigger and the label in the field.
  pub fn new(label: &str) -> Self {
    Self {
      label: Arc::from(label),
      text: None,
      avatar: None,
      icon: None,
      disabled: false,
      id: None,
      key: None,
    }
  }

  /// The text the offer puts in the field, the trigger included: the app's text for it, which the field's value
  /// holds and tooling reads.
  pub fn text(mut self, text: &str) -> Self {
    self.text = Some(Arc::from(text));
    self
  }

  /// An avatar before the label: a person's.
  pub fn avatar(mut self, avatar: Avatar) -> Self {
    self.avatar = Some(avatar);
    self
  }

  /// An icon before the label, by its name in the theme's set, where the offer has no avatar.
  pub fn icon(mut self, name: impl Into<Name>) -> Self {
    self.icon = Some(name.into());
    self
  }

  /// Whether the offer is shown dimmed and cannot be chosen: a click does nothing, and Up and Down pass it by.
  pub fn disabled(mut self, disabled: bool) -> Self {
    self.disabled = disabled;
    self
  }

  /// The id of the offer's row in the list.
  pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
    self.id = Some(id.into());
    self
  }

  /// The key of the offer's row in the list.
  pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
    self.key = Some(key.into());
    self
  }

  /// What the offer is called.
  pub fn label(&self) -> &str {
    &self.label
  }

  /// The text it puts in the field after `trigger`.
  fn inserted(&self, trigger: char) -> Arc<str> {
    self
      .text
      .clone()
      .unwrap_or_else(|| Arc::from(format!("{trigger}{}", self.label)))
  }
}

/// What a trigger offers: a list, which the field narrows to the offers whose label or text has what was typed
/// after the trigger, or a function of what was typed.
pub enum MentionSource {
  List(Vec<Mention>),
  Find(Box<dyn Fn(&str) -> Vec<Mention> + Send + Sync>),
}

impl From<Vec<Mention>> for MentionSource {
  fn from(list: Vec<Mention>) -> Self {
    Self::List(list)
  }
}

impl<F: Fn(&str) -> Vec<Mention> + Send + Sync + 'static> From<F> for MentionSource {
  fn from(find: F) -> Self {
    Self::Find(Box::new(find))
  }
}

/// The most offers a list shows.
pub const MENTIONS_LIMIT: usize = 8;

impl MentionSource {
  /// The offers for `query`, typed after `trigger`.
  fn offers(self, trigger: char, query: &str) -> Vec<Mention> {
    let mut offers = match self {
      Self::Find(find) => find(query),
      Self::List(list) => {
        let query = query.to_lowercase();
        list
          .into_iter()
          .filter(|offer| {
            offer.label.to_lowercase().contains(&query) || offer.inserted(trigger).to_lowercase().contains(&query)
          })
          .collect()
      }
    };
    offers.truncate(MENTIONS_LIMIT);
    offers
  }
}

/// What a mentions field keeps from one render to the next, which the app keeps for it as it keeps its value: the
/// controller of its text, the offer Enter chooses, whether Escape put the list away, and the mentions chosen.
#[derive(Clone)]
pub struct MentionsController {
  input: TextInputController,
  inner: Arc<Mutex<Kept>>,
  /// Changed to render the field again where its text did not change: a key that moved the caret or the offer.
  tick: Signal<u64>,
  anchor: ElementRef,
}

#[derive(Default)]
struct Kept {
  active: usize,
  /// Where the trigger is and what was typed after it, as the list was last drawn.
  query: Option<(usize, String)>,
  /// The trigger Escape put the list away from.
  dismissed: Option<usize>,
  chosen: Vec<Arc<str>>,
}

impl Default for MentionsController {
  fn default() -> Self {
    Self::new()
  }
}

impl MentionsController {
  pub fn new() -> Self {
    Self {
      input: TextInputController::new(),
      inner: Arc::default(),
      tick: Signal::new(0),
      anchor: ElementRef::new(),
    }
  }

  /// The controller of the field's text: its selection, and text put at it.
  pub fn input(&self) -> TextInputController {
    self.input.clone()
  }

  /// Makes `text` a mention wherever the field's text has it as a word of its own: what a field loaded with a
  /// message that has mentions in it holds.
  pub fn mention(&self, text: &str) {
    let mut kept = self.inner.lock();
    if !kept.chosen.iter().any(|chosen| chosen.as_ref() == text) && !text.is_empty() {
      kept.chosen.push(Arc::from(text));
    }
    drop(kept);
    self.redraw();
  }

  /// The mentions chosen so far, as their text.
  pub fn mentioned(&self) -> Vec<Arc<str>> {
    self.inner.lock().chosen.clone()
  }

  fn redraw(&self) {
    self.tick.update(|tick| *tick = tick.wrapping_add(1));
  }

  /// Puts `text` and a space in place of the trigger at `trigger` and what was typed after it up to the caret,
  /// as one edit, and makes it a mention.
  fn choose(&self, trigger: usize, text: &str) {
    let Ok(selection) = self.input.selection() else {
      return;
    };
    if self.input.select(trigger, selection.caret.max(trigger)).is_err() {
      return;
    }
    if self.input.replace_selection(&format!("{text} ")).unwrap_or(false) {
      let mut kept = self.inner.lock();
      if !kept.chosen.iter().any(|chosen| chosen.as_ref() == text) {
        kept.chosen.push(Arc::from(text));
      }
      kept.active = 0;
      kept.query = None;
      kept.dismissed = None;
    }
    self.redraw();
  }
}

/// A trigger and what it offers.
struct Trigger {
  character: char,
  source: MentionSource,
}

/// A mentions field: text that a person types, in which a trigger (`@`, `#`, `/`) opens a list of what can be
/// mentioned, and what is chosen stands as a token. A comment, a message, a prompt.
///
/// ```
/// use lurq::{core::Signal, ui::{Avatar, Mention, Mentions, MentionsController}};
///
/// let message = Signal::new(String::new());
/// // Kept by the app, with the value, from one render to the next.
/// let mentions = MentionsController::new();
/// let people = vec![
///   Mention::new("Ivan Zaida").avatar(Avatar::new("Ivan Zaida")),
///   Mention::new("Ivy Chen").avatar(Avatar::new("Ivy Chen")),
/// ];
/// let field = Mentions::new(message, &mentions)
///   .trigger('@', people)
///   .trigger('#', |typed: &str| vec![Mention::new(&format!("{typed}-channel"))])
///   .placeholder("Write a comment");
/// ```
///
/// It is a [`TokenInput`] on rows. Typing a trigger at the start of a word opens the list under it, of the offers
/// whose label has what is typed after it (or those a function gives for it); Up and Down move the offer Enter
/// (or Tab) chooses, a click chooses one, and Escape puts the list away to go on typing plain text. A choice puts
/// the offer's text in place of the trigger and what was typed, and from then on that text is a mention: a token
/// of the variant [`MENTION`], one thing to the caret, which Backspace selects and then deletes. The value is the
/// text, mentions and all, as the app's text for each.
pub struct Mentions {
  input: TokenInput,
  controller: MentionsController,
  triggers: Vec<Trigger>,
  states: Vec<Name>,
  rules: Recipe,
  forced: Option<Interaction>,
  on_mention: Vec<Arc<dyn Fn(&str) + Send + Sync>>,
  read_only: bool,
  disabled: bool,
  full_width: bool,
  /// Whether it is in a fluid field, which draws its label inside the box.
  fluid: bool,
  /// The id the control has, which the panel's parts are named after.
  id: Option<Arc<str>>,
}

impl Mentions {
  /// A mentions field bound to `value`, keeping what it keeps in `controller`.
  pub fn new(value: Signal<String>, controller: &MentionsController) -> Self {
    Self {
      input: TokenInput::new(value).rows(2, 8),
      controller: controller.clone(),
      triggers: Vec::new(),
      states: Vec::new(),
      rules: Recipe::new(),
      forced: None,
      on_mention: Vec::new(),
      read_only: false,
      disabled: false,
      full_width: false,
      fluid: false,
      id: None,
    }
  }

  /// Offers `options` after `trigger`: a list of [`Mention`]s, narrowed to what is typed after the trigger, or a
  /// function of what is typed.
  pub fn trigger(mut self, trigger: char, options: impl Into<MentionSource>) -> Self {
    self.triggers.retain(|held| held.character != trigger);
    self.triggers.push(Trigger {
      character: trigger,
      source: options.into(),
    });
    self
  }

  /// Called with the text of an offer as it is chosen.
  pub fn on_mention(mut self, handler: impl Fn(&str) + Send + Sync + 'static) -> Self {
    self.on_mention.push(Arc::new(handler));
    self
  }

  /// Other tokens of the app's in the text, besides the mentions: how it finds them.
  pub fn find_tokens(mut self, find: impl Fn(&str) -> Vec<Token> + Send + Sync + 'static) -> Self {
    self.input = self.input.find_tokens(find);
    self
  }

  /// The rows the field shows while it holds less, and grows to before it scrolls: 2 and 8 unless told.
  pub fn rows(mut self, min_rows: usize, max_rows: usize) -> Self {
    self.input = self.input.rows(min_rows, max_rows);
    self
  }

  /// Whether the field is as wide as what holds it, in place of the design's 280.
  pub fn full_width(mut self, full_width: bool) -> Self {
    self.full_width = full_width;
    self.input = self.input.full_width(full_width);
    self
  }

  /// What the field says while it is empty.
  pub fn placeholder(mut self, placeholder: &str) -> Self {
    self.input = self.input.placeholder(placeholder);
    self
  }

  /// A [`MentionsSize`]: the type of its text and mentions, 13, 14 or 15.
  pub fn size(mut self, size: impl Into<Name>) -> Self {
    self.input = self.input.size(size);
    self
  }

  /// Whether what the field holds is wrong.
  pub fn invalid(mut self, invalid: bool) -> Self {
    self.input = self.input.invalid(invalid);
    self
  }

  /// Whether what the field holds is allowed with a caveat.
  pub fn warning(mut self, warning: bool) -> Self {
    self.input = self.input.warning(warning);
    self
  }

  /// Whether what the field holds was checked and is right.
  pub fn valid(mut self, valid: bool) -> Self {
    self.input = self.input.valid(valid);
    self
  }

  /// Whether the field can be read and not changed: a trigger opens nothing.
  pub fn read_only(mut self, read_only: bool) -> Self {
    self.read_only = read_only;
    self.input = self.input.read_only(read_only);
    self
  }

  /// Whether the field takes no input.
  pub fn disabled(mut self, disabled: bool) -> Self {
    self.disabled = disabled;
    self.input = self.input.disabled(disabled);
    self
  }

  /// What the field is called, to what reads the tree.
  pub fn label(mut self, label: &str) -> Self {
    self.input = self.input.label(label);
    self
  }

  /// Called before an edit is made, with what the field will hold; a handler may refuse it. Choosing an offer is
  /// an edit too.
  pub fn on_input(mut self, handler: impl Fn(&TextInputEvent) + Send + Sync + 'static) -> Self {
    self.input = self.input.on_input(handler);
    self
  }

  /// The name the field's value has in the form it is in.
  #[cfg(feature = "form")]
  pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
    self.input = self.input.name(name);
    self
  }

  /// Puts the field in a state the theme's recipe names, or takes it out.
  pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
    let state = state.into();
    self.states.retain(|held| *held != state);
    if on {
      self.states.push(state);
    }
    self
  }

  /// Styles one part of this field over what the theme gives it.
  pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.rules = self.rules.base(part, style);
    self
  }

  /// Lays rules over the theme's recipe for this field.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

  /// Lays rules over the token input the field is: its box and its tokens.
  pub fn input_rules(mut self, rules: &Recipe) -> Self {
    self.input = self.input.rules(rules);
    self
  }

  /// Draws the box as it is under the pointer or focused, and the active offer highlighted: for a gallery or a
  /// test.
  pub fn force(mut self, interaction: Option<Interaction>) -> Self {
    self.forced = interaction;
    self.input = self.input.force(interaction);
    self
  }

  /// The id of the control: what is typed in and focused.
  pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
    let id = id.into();
    self.input = self.input.id(id.clone());
    self.id = Some(id);
    self
  }

  pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
    self.input = self.input.key(key);
    self
  }

  /// Builds the field in `theme`. Converting a mentions field into an element does this in the theme of what is
  /// being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    let controller = self.controller.clone();
    // Read so that what renders the field renders it again when a key moves the offer or the caret, and when the
    // focus comes and goes.
    controller.tick.get();
    let focused = controller.input.element_ref().focus_signal().get();
    let base = Case {
      variant: None,
      size: None,
      density: None,
      breakpoint: super::current_breakpoint(),
      states: self.states.clone(),
    }
    .state(MentionsState::Fluid, self.fluid);
    let own = theme.resolve::<Mentions>(&base, Some(&self.rules));
    // The box's room and least height are the field's own, over the token input's.
    let control = own.part(MentionsPart::Control).rest();
    let root = own.part(MentionsPart::Root).rest();
    let mut box_rules = Recipe::new().base(TokenInputPart::Control, move |s| s.merged(&control));
    if !self.full_width {
      box_rules = box_rules.base(TokenInputPart::Root, move |s| s.merged(&root));
    }
    let chosen = controller.inner.lock().chosen.clone();
    let input = self
      .input
      .controller(controller.input.clone())
      .rules(&box_rules)
      .view(theme, move |text| mentions_in(text, &chosen));
    let text = input.text.clone();
    let caret = controller
      .input
      .selection()
      .ok()
      .filter(|selection| selection.range().is_empty());
    let mut triggers = self.triggers;
    let characters: Vec<char> = triggers.iter().map(|trigger| trigger.character).collect();
    let pending = caret
      .filter(|_| focused && !self.read_only && !self.disabled)
      .and_then(|selection| pending_trigger(&text, selection.caret, &characters, &input.tokens));
    let mut kept = controller.inner.lock();
    // Escape puts the list away while the caret is in that trigger's word; elsewhere it is forgotten.
    if pending.as_ref().map(|(at, ..)| *at) != kept.dismissed {
      kept.dismissed = None;
    }
    let pending = pending.filter(|(at, ..)| kept.dismissed != Some(*at));
    let offers = match &pending {
      Some((at, character, query)) => {
        let index = triggers.iter().position(|trigger| trigger.character == *character);
        let source = index.map(|index| triggers.swap_remove(index).source);
        let offers = source
          .map(|source| source.offers(*character, query))
          .unwrap_or_default();
        // A new query starts at the first offer.
        if kept.query.as_ref() != Some(&(*at, query.clone())) {
          kept.query = Some((*at, query.clone()));
          kept.active = 0;
        }
        offers
      }
      None => {
        kept.query = None;
        Vec::new()
      }
    };
    let active = settle_active(&offers, kept.active.min(offers.len().saturating_sub(1)));
    kept.active = active;
    drop(kept);
    let open = !offers.is_empty();
    let trigger = pending.as_ref().map(|(at, character, _)| (*at, *character));
    let case = base.state(MentionsState::Open, open);
    let view = MentionsView {
      input,
      offers,
      active,
      trigger,
      open,
      recipe: theme
        .resolve::<Mentions>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      case,
      rules: self.rules,
      forced: self.forced,
      controller,
      on_mention: self.on_mention,
    };
    match theme.renderer::<Mentions>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

/// The offer Enter chooses, at `at` or the first after it that is not disabled, else the first before it.
fn settle_active(offers: &[Mention], at: usize) -> usize {
  (at..offers.len())
    .chain((0..at).rev())
    .find(|index| !offers[*index].disabled)
    .unwrap_or(at)
}

/// The next offer from `at` that is not disabled, `by` one step forward or back, round the list.
fn step_active(choosable: &[bool], at: usize, forward: bool) -> usize {
  let count = choosable.len();
  (1..=count)
    .map(|step| {
      if forward {
        (at + step) % count
      } else {
        (at + count * step - step) % count
      }
    })
    .find(|index| choosable[*index])
    .unwrap_or(at)
}

/// The mentions in `text`: every place a chosen mention's text stands as a word of its own.
fn mentions_in(text: &str, chosen: &[Arc<str>]) -> Vec<Token> {
  let mut tokens = Vec::new();
  for mention in chosen {
    for (at, found) in text.match_indices(mention.as_ref()) {
      let end = at + found.len();
      let starts = text[..at].chars().next_back().is_none_or(char::is_whitespace);
      let ends = text[end..]
        .chars()
        .next()
        .is_none_or(|next| next.is_whitespace() || next.is_ascii_punctuation());
      if starts && ends {
        tokens.push(Token::new(at..end).variant(MENTION).removable(false));
      }
    }
  }
  tokens
}

/// The trigger the caret is in the word of: where it is, which it is, and what is typed after it up to the caret.
/// The word starts with the trigger, at the start of the text or after a space, and is no token.
fn pending_trigger(text: &str, caret: usize, triggers: &[char], tokens: &[Token]) -> Option<(usize, char, String)> {
  let before = text.get(..caret)?;
  let start = before
    .char_indices()
    .rev()
    .find(|(_, character)| character.is_whitespace())
    .map_or(0, |(at, character)| at + character.len_utf8());
  let word = &before[start..];
  let character = word.chars().next()?;
  if !triggers.contains(&character) {
    return None;
  }
  if tokens
    .iter()
    .any(|token| token.range().start <= start && start < token.range().end)
  {
    return None;
  }
  Some((start, character, word[character.len_utf8()..].to_owned()))
}

impl FieldControl for Mentions {
  /// Named, judged and disabled by the field as a token input is.
  fn in_field(mut self, field: &InField) -> Element {
    self.disabled |= field.disabled;
    self.fluid |= field.fluid;
    self.input = self.input.in_field(field);
    self.into()
  }

  fn has_fluid_form(&self) -> bool {
    true
  }
}

impl From<Mentions> for Element {
  fn from(mentions: Mentions) -> Self {
    mentions.build(&current_theme())
  }
}

/// A mentions field as a renderer sees it: the token input it is, the offers for the trigger being typed, and the
/// style of its own parts.
pub struct MentionsView {
  /// The token input the field is, its mentions among its tokens.
  pub input: TokenInputView,
  /// What the list offers, in its order: none while it is closed.
  pub offers: Vec<Mention>,
  /// The offer Enter chooses: never a disabled one where another can be chosen.
  pub active: usize,
  /// The trigger being typed: where it is in the text, and which it is.
  pub trigger: Option<(usize, char)>,
  /// Whether the list is open.
  pub open: bool,
  /// The style of each of its own parts.
  pub recipe: ResolvedRecipe,
  case: Case,
  rules: Recipe,
  forced: Option<Interaction>,
  controller: MentionsController,
  on_mention: Vec<Arc<dyn Fn(&str) + Send + Sync>>,
}

impl MentionsView {
  /// The style of a part, as this field is to be drawn.
  pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
    self.recipe.part(part)
  }

  pub fn theme(&self) -> &Theme {
    self.recipe.theme()
  }

  /// What choosing the offer at `index` does: its text in place of the trigger and what was typed, as a mention.
  /// None for an offer that is disabled.
  fn chooser(&self, offer: &Mention) -> Option<Arc<dyn Fn() + Send + Sync>> {
    if offer.disabled {
      return None;
    }
    let (at, character) = self.trigger?;
    let text = offer.inserted(character);
    let (controller, handlers) = (self.controller.clone(), self.on_mention.clone());
    Some(Arc::new(move || {
      controller.choose(at, &text);
      for handler in &handlers {
        handler(&text);
      }
    }))
  }

  /// The token input's control, with the keys of the list: Up and Down move the offer Enter and Tab choose,
  /// Escape puts the list away. Any other key, and a press, has the field look again for a trigger at the caret.
  pub fn control(&self) -> crate::components::TextInput {
    let controller = self.controller.clone();
    let choosers: Vec<_> = self.offers.iter().map(|offer| self.chooser(offer)).collect();
    let choosable: Vec<bool> = choosers.iter().map(Option::is_some).collect();
    let (open, trigger) = (self.open, self.trigger);
    let mut control = self.input.control().on_key_down(move |event: KeyboardEvent| {
      if !event.focus_within {
        return;
      }
      let plain = !event.ctrl && !event.alt && !event.meta;
      if open && plain && choosable.iter().any(|can| *can) {
        let count = choosers.len();
        let mut kept = controller.inner.lock();
        match event.key.as_str() {
          "ArrowDown" if !event.shift => {
            event.prevent_default();
            kept.active = step_active(&choosable, kept.active.min(count - 1), true);
          }
          "ArrowUp" if !event.shift => {
            event.prevent_default();
            kept.active = step_active(&choosable, kept.active.min(count - 1), false);
          }
          "Enter" | "Tab" if !event.shift => {
            event.prevent_default();
            let chosen = choosers[kept.active.min(count - 1)].clone();
            drop(kept);
            if let Some(chosen) = chosen {
              chosen();
            }
            return;
          }
          "Escape" => {
            event.prevent_default();
            kept.dismissed = trigger.map(|(at, _)| at);
          }
          _ => {}
        }
      }
      controller.redraw();
    });
    // The list hangs from the trigger, where the input's layout puts the anchor.
    if let Some((at, _)) = self.trigger {
      control = control.anchor_at(self.controller.anchor.clone(), at);
    }
    let controller = self.controller.clone();
    control = control
      .on_mouse_down(move |_| controller.redraw())
      .describe("a11y_haspopup", "listbox")
      .describe("a11y_expanded", if self.open { "true" } else { "false" });
    control
  }

  /// One offer: its avatar or icon and its label, in a row that a click chooses by and that keeps the focus in the
  /// field. A disabled offer is dimmed, and neither a click nor the pointer coming onto it does anything.
  pub fn item(&self, index: usize, offer: Mention) -> Element {
    let active = index == self.active && !offer.disabled;
    let choose = self.chooser(&offer);
    let case = self
      .case
      .clone()
      .state(MentionsState::Highlighted, active)
      .state(MentionsState::Disabled, offer.disabled);
    // An offer the app gave an id names its parts after it, one it gave a key after the field's id and the key.
    let recipe = self
      .theme()
      .resolve::<Mentions>(&case, Some(&self.rules))
      .owned_like(&self.recipe);
    let recipe = match (&offer.id, &offer.key) {
      (None, Some(key)) => recipe.keyed_item(key, MentionsPart::Item),
      (id, _) => recipe.item(id.as_ref(), MentionsPart::Item),
    };
    let part = recipe.part(MentionsPart::Item).forced(self.forced.filter(|_| active));
    let mut row = Row::new()
      .align_items(Alignment::Center)
      .focusable(false)
      .describe("a11y_role", "option")
      .describe("a11y_name", offer.label.clone())
      .describe("a11y_selected", if active { "true" } else { "false" })
      .part(&part);
    if offer.disabled {
      // The engine passes a disabled row by: no press reaches it, and the pointer does not light it.
      row = row.disabled(true);
    }
    if let Some(id) = &offer.id {
      row = row.id(id.clone());
    }
    if let Some(key) = &offer.key {
      row = row.key(key.clone());
    }
    if let Some(avatar) = offer.avatar {
      row = row.child(
        Row::new()
          // The avatar stands for the part, and has its id.
          .part(&recipe.part(MentionsPart::ItemAvatar).unnamed())
          .child(
            avatar
              .size(AvatarSize::Sm)
              .rules(&recipe.lend(MentionsPart::ItemAvatar))
              .build(self.theme()),
          ),
      );
    } else if let Some(name) = offer.icon {
      let icon = recipe.part(MentionsPart::ItemIcon);
      let side = icon.rest().width.unwrap_or(Length::Icon(IconSize::Md));
      row = row.child(
        Row::new()
          .part(&icon)
          .child(Icon::new(name).size(side).build(self.theme())),
      );
    }
    let label = recipe.part(MentionsPart::ItemLabel);
    row = row.child(Row::new().part(&label).child(label.text(&offer.label).nowrap()));
    if let Some(choose) = choose {
      row = row.on_click(move |_| choose());
    }
    if offer.disabled {
      return row.into();
    }
    let controller = self.controller.clone();
    row
      .on_mouse_enter(move || {
        let mut kept = controller.inner.lock();
        if kept.active != index {
          kept.active = index;
          drop(kept);
          controller.redraw();
        }
      })
      .into()
  }

  /// The list of offers, hung under the trigger: a panel in the style of its part, open while there are offers.
  /// It takes no focus: the keys stay in the field.
  pub fn panel(&mut self) -> Element {
    let offers = std::mem::take(&mut self.offers);
    let mut panel = Column::new()
      .align_items(Alignment::Stretch)
      .part(&self.part(MentionsPart::Panel))
      .describe("a11y_role", "listbox");
    for (index, offer) in offers.into_iter().enumerate() {
      panel = panel.child(self.item(index, offer));
    }
    Popup::new(self.controller.anchor.clone(), panel)
      .open_when(self.open)
      .placement(Placement::BottomStart)
      .offset(0.0, 4.0)
      .takes_focus(false)
      .dismiss_on_outside_click(false)
      .dismiss_on_escape(false)
      .switch_on_anchor_press(false)
      .into()
  }

  /// How the default renderer builds a mentions field: the token input's control, which puts the panel's anchor at
  /// the trigger, and the panel.
  pub fn render(mut self) -> Element {
    let control = self.control();
    let panel = self.panel();
    self.input.root(control).overflow_visible().child(panel).into()
  }
}

impl crate::ui::Styled for Mentions {
  type Component = Self;

  fn rules(self, rules: &crate::ui::Recipe) -> Self {
    Self::rules(self, rules)
  }

  fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
    Self::state(self, state, on)
  }
}

impl Themed for Mentions {
  const NAME: &'static str = "mentions";
  type Renderer = MentionsRenderer;

  fn parts() -> crate::ui::Declared {
    MentionsPart::declared()
  }

  fn states() -> crate::ui::Declared {
    MentionsState::declared()
  }

  /// The design's mentions (`pencil/lurq-design-system.pen`, Mentions): a box 280 wide and at least 64 high,
  /// padded 12 across and 8 down, its text in the body's type with lines of 1.5. The list hangs 4 under the
  /// trigger: 220 wide, in the popover's color with the large radius, an edge of 1 in the border's color, the
  /// medium shadow and 4 of padding. An offer is 36 high, padded 8, with the small radius and 8 between its avatar
  /// of 24 (or icon of 16, muted) and its label in the body's type; the active one is filled with the highlight,
  /// as an offer under the pointer is. In a fluid field the box is the token input's fluid one, as wide as the field:
  /// its rows with the 29 over them, where the field's label stands, and the 10 under.
  fn recipe() -> Recipe {
    use MentionsPart::{Control, Item, ItemAvatar, ItemIcon, ItemLabel, Panel, Root};
    use PaletteColor::{Foreground, Highlight, MutedForeground, Popover, PopoverForeground};
    Recipe::new()
      .base(Root, |s| s.width(280.0).max_width(Length::Fill))
      .state(MentionsState::Fluid, Root, |s| s.width(Length::Fill))
      .base(Control, |s| {
        s.padding_x(12.0).padding_y(8.0).min_height(64.0).line_height(1.5)
      })
      .base(Panel, |s| {
        s.width(220.0)
          .padding_x(4.0)
          .padding_y(4.0)
          .radius(RadiusSize::Lg)
          .background(Popover)
          .foreground(PopoverForeground)
          .border(Border::inside(BorderSize::Sm, PaletteColor::Border))
          .shadow(ShadowStyle::Md)
      })
      .base(Item, |s| {
        s.height(36.0)
          .padding_x(8.0)
          .gap(8.0)
          .radius(RadiusSize::Sm)
          .cursor(CursorIcon::Pointer)
      })
      .base(ItemAvatar, |s| s.square(24.0))
      .base(ItemIcon, |s| s.square(IconSize::Md).foreground(MutedForeground))
      .base(ItemLabel, |s| {
        s.typography(TypographyStyle::Body)
          .foreground(Foreground)
          .width(Length::Fill)
      })
      .hovered(Item, |s| s.background(Highlight))
      .state(MentionsState::Highlighted, Item, |s| s.background(Highlight))
      // A disabled offer is dimmed and lit by nothing.
      .state(MentionsState::Disabled, Item, |s| {
        s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
      })
  }
}