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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
//! A token input: text that a person types, in which the app's tokens stand as chips.
use std::{ops::Range, sync::Arc};
use super::{
field::{FieldControl, InField},
icons, names,
part_style::{Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
tag::TagVariant,
text_box::{self, BoxStates, EditHandler, Judgment, TextBoxSize},
theme::{Themed, current_theme},
token_list::{self, DraftHandler, ListHandler, Rules},
};
use crate::{
app::{
events::{KeyboardEvent, TextInputEvent},
theme::{ControlSize, IconSize, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::{self, InputToken, InputTokenIcon, InputTokenStyle, InputTokens, Stack, TextInputController},
core::Signal,
layout::{StackAlignment, text_style::TextStyle},
node::{BackgroundColor, Element, TextColor, color::Color, dimension::Dimension},
};
/// The parts of a token input a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TokenInputPart {
/// The place the input takes: its width.
Root,
/// The box that is typed in and focused: its edge, its fill, its height, the room from its edge to the text,
/// and the type of the text.
Control,
/// What the box says while it is empty. It has the type of the control, in its own color.
Placeholder,
/// A token: its fill, its edge, its corners, its height, the room before its text and after its icon, and
/// the room between its text and its icon.
Token,
/// The text of a token: its type and its color.
TokenLabel,
/// The cross at the end of a token that takes it away: its side and its color.
TokenIcon,
}
names!(TokenInputPart {
Root => "root",
Control => "control",
Placeholder => "placeholder",
Token => "token",
TokenLabel => "token_label",
TokenIcon => "token_icon",
});
/// The sizes of a token input: an input's, with tokens of 20, 24 and 28.
pub type TokenInputSize = TextBoxSize;
/// The states of a token input a recipe styles, besides what the pointer and the keyboard do to its box. The
/// two last are a token's own: its parts are resolved in them for the token the pointer is on and the tokens
/// the selection covers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TokenInputState {
/// What it holds is wrong: its edge is in the destructive color.
Invalid,
/// What it holds is allowed, with a caveat: its edge is in the warning color.
Warning,
/// What it holds was checked and is right: its edge is in the success color.
Valid,
/// It can be read, selected and copied, and not changed: its tokens have no cross.
ReadOnly,
/// It takes no input.
Disabled,
/// It is as wide as what holds it.
FullWidth,
/// Its text wraps onto as many rows as it needs, between the rows it is given.
Multiline,
/// It is in a fluid field ([`Field::fluid`](super::Field::fluid)): the field's label is inside its box, over
/// its text.
Fluid,
/// The token is under the pointer: a token's own state, resolved on its parts.
Hovered,
/// The selection covers all of the token: a token's own state, resolved on its parts.
Selected,
}
names!(TokenInputState {
Invalid => "invalid",
Warning => "warning",
Valid => "valid",
ReadOnly => "read_only",
Disabled => "disabled",
FullWidth => "full_width",
Multiline => "multiline",
Fluid => "fluid",
Hovered => "hovered",
Selected => "selected",
});
/// The variant of a token that a [`Mentions`](super::Mentions) chose: in the type of the text around it, in the
/// muted fill of the informative color, its text in the color.
pub const MENTION: &str = "mention";
/// What builds a token input's nodes: a theme's in place of the default one.
pub type TokenInputRenderer = Arc<dyn Fn(TokenInputView) -> Element + Send + Sync>;
/// A token in the text of a [`TokenInput`]: a range of the text that the app found, drawn as a chip.
///
/// ```
/// use lurq::ui::{TagVariant, Token};
///
/// let text = "rust wgpu ";
/// let rust = Token::new(0..4);
/// let wgpu = Token::new(5..9).variant(TagVariant::Info).removable(false);
/// assert_eq!(Token::separated(text, ' ').len(), 2);
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct Token {
range: Range<usize>,
variant: Name,
removable: bool,
atomic: bool,
}
impl Token {
/// The token over `range` of the text, in UTF-8 bytes: one thing to the caret, with a cross that takes it away.
pub fn new(range: Range<usize>) -> Self {
Self {
range,
variant: TagVariant::default().into(),
removable: true,
atomic: true,
}
}
/// A [`TagVariant`]: what the token says by its color, as a tag does. Or a variant the theme's recipe names.
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
/// Whether the token has the cross at its end, which a click takes it away by.
pub fn removable(mut self, removable: bool) -> Self {
self.removable = removable;
self
}
/// Whether the token is one thing to the caret (the default): the arrow keys go past it whole, a click
/// selects all of it, the first Backspace after it selects it and the next deletes it. One that is not is
/// text drawn as a token, which the caret goes into.
pub fn atomic(mut self, atomic: bool) -> Self {
self.atomic = atomic;
self
}
/// Where the token is in the text.
pub fn range(&self) -> Range<usize> {
self.range.clone()
}
/// The tokens of a list typed with `separator` between its items: every item that has a separator after it.
/// The item being typed, with none after it yet, is text; typing the separator makes it a token.
pub fn separated(text: &str, separator: char) -> Vec<Token> {
let mut tokens = Vec::new();
let mut start = 0;
for (at, character) in text.char_indices() {
if character == separator {
let item = &text[start..at];
let lead = item.len() - item.trim_start().len();
let trimmed = item.trim();
if !trimmed.is_empty() {
tokens.push(Token::new(start + lead..start + lead + trimmed.len()));
}
start = at + character.len_utf8();
}
}
tokens
}
}
/// How the app finds the tokens in the text.
type FindTokens = Arc<dyn Fn(&str) -> Vec<Token> + Send + Sync>;
/// How the app dresses the token of an item of a list.
type DressToken = Arc<dyn Fn(&str, Token) -> Token + Send + Sync>;
/// What a token input over a list is given: the list, what makes an item of what is typed, and who is told.
#[derive(Clone)]
struct ListOf {
items: Signal<Vec<String>>,
query: Option<Signal<String>>,
rules: Rules,
commit_on_blur: bool,
dress: Option<DressToken>,
on_change: Vec<ListHandler>,
on_query: Vec<DraftHandler>,
/// What puts the caret at the end of the text the list is kept as.
controller: TextInputController,
/// Keeps the text the list is kept as while the input is in the tree.
alive: Arc<()>,
}
impl ListOf {
/// Gives the input `text` in place of what it holds, with the caret at its end.
fn put(&self, value: &Signal<String>, text: String) {
// An input follows a value set from outside with its caret where it was, unless it was at the end.
let end = value.get_untracked().len();
let _ = self.controller.select(end, end);
value.set(text);
}
/// Sets the list and the draft where a person changed them, and tells the app.
fn tell(&self, items: Vec<String>, draft: &str, draft_was: &str) {
if self.items.get_untracked() != items {
self.items.set(items.clone());
for handler in &self.on_change {
handler(&items);
}
}
if let Some(held) = &self.query
&& held.get_untracked() != draft
{
held.set(draft.to_owned());
}
if draft != draft_was {
for handler in &self.on_query {
handler(draft);
}
}
}
/// Makes an item of the draft, as Enter does. Whether there was a draft to make one of.
fn commit(&self, value: &Signal<String>) -> bool {
let text = value.get_untracked();
let Some((items, draft)) = self.rules.committed(&text) else {
return false;
};
let draft_was = token_list::parse(&text).1;
self.put(value, token_list::encode(&items, &draft));
self.tell(items, &draft, &draft_was);
true
}
/// Settles an edit before it is made: the list and the draft it comes to, and the text the input holds after it.
fn settle(&self, event: &TextInputEvent) {
if event.default_prevented() {
return;
}
let old = event.value.get_untracked();
let settled = token_list::settle(&old, event.new_value(), &self.rules);
if let Some(text) = settled.text {
event.prevent_default();
if text != old {
self.put(&event.value, text);
}
}
if let Some(token) = settled.select {
let _ = self.controller.select(token.start, token.end);
}
self.tell(settled.items, &settled.draft, &token_list::parse(&old).1);
}
}
/// A token input: a box of text in which what the app recognizes stands as a token. Tags, recipients,
/// variables in a template.
///
/// ```
/// use lurq::{core::Signal, ui::{Token, TokenInput}};
///
/// // A list of tags: Enter, a comma or a space makes a token of what is typed.
/// let tags = Signal::new(vec!["rust".to_owned(), "wgpu".to_owned()]);
/// let input = TokenInput::list(tags.clone())
/// .separators([',', ' '])
/// .unique(true)
/// .placeholder("Add tag")
/// .on_change(|tags| println!("{tags:?}"));
///
/// // A template whose variables are tokens, on several rows.
/// let template = Signal::new("Hello {{name}}, your order shipped.".to_owned());
/// let prompt = TokenInput::new(template)
/// .rows(2, 6)
/// .find_tokens(|text| text.match_indices("{{name}}").map(|(at, name)| Token::new(at..at + name.len()).removable(false)).collect());
/// ```
///
/// It holds one of two things. [`TokenInput::list`] holds a list, `Signal<Vec<String>>`: each item is a token, and
/// what is typed is the draft, which is no part of the list until Enter or a separator makes an item of it. Tags,
/// recipients. [`TokenInput::new`] holds text, `Signal<String>`, in which the function given to
/// [`TokenInput::find_tokens`] finds the tokens again in every render, so an edit that changes a token's text makes it
/// what the function then says of it: variables in a template, where the text around the tokens is the value too.
/// The text is what is copied, pasted, undone, sent with a form and read by tooling, which sees a `textbox` whose
/// value is the text with each token as its own words.
///
/// It is the box of an [`Input`](super::Input) (one row, 36 high) or, with [`TokenInput::rows`], of a
/// [`Textarea`](super::Textarea), with its sizes and judgments. A token is drawn by the recipe's
/// [`TokenInputPart::Token`], [`TokenInputPart::TokenLabel`] and [`TokenInputPart::TokenIcon`], in the colors
/// of a [`Tag`](super::Tag) of its variant; under the pointer and covered by the selection it takes the looks of
/// [`TokenInputState::Hovered`] and [`TokenInputState::Selected`]. A click on a token's cross takes it
/// away, as an edit through [`TokenInput::on_input`] that undo brings back.
pub struct TokenInput {
value: Signal<String>,
list: Option<ListOf>,
find: Option<FindTokens>,
rows: Option<(usize, usize)>,
placeholder: Option<Arc<str>>,
boxed: BoxStates,
full_width: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
on_input: Vec<EditHandler>,
controller: Option<TextInputController>,
name: Option<Arc<str>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl TokenInput {
/// A token input bound to `value`: it shows what the signal holds, and what is typed is set on it.
pub fn new(value: Signal<String>) -> Self {
Self {
value,
list: None,
find: None,
rows: None,
placeholder: None,
boxed: BoxStates::default(),
full_width: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
on_input: Vec::new(),
controller: None,
name: None,
id: None,
key: None,
}
}
/// A token input over a list: each item of `items` is a token, and a person adds to the list by typing an item
/// and Enter, or one of the [`TokenInput::separators`], and takes from it by a token's cross or by Backspace.
/// What is typed and is no item yet is the draft: it is not in the list, it is the text after the tokens, and
/// [`TokenInput::query`] gives the app a signal of it. A paste of several items adds each. What is typed with the
/// caret among the tokens goes to the draft, which is always after them.
///
/// The input keeps the text it edits itself, for as long as it is in the tree: a list the app sets is shown as
/// set, with the draft kept.
pub fn list(items: Signal<Vec<String>>) -> Self {
let (text, controller, alive) = token_list::kept(items.id());
let mut input = Self::new(text);
input.list = Some(ListOf {
items,
query: None,
rules: Rules {
separators: vec![','],
unique: false,
},
commit_on_blur: false,
dress: None,
on_change: Vec::new(),
on_query: Vec::new(),
controller,
alive,
});
input
}
/// The characters that make an item of the draft as Enter does, in place of the comma: of a list
/// ([`TokenInput::list`]). An item cannot hold one of them; with none, only Enter makes an item.
pub fn separators(mut self, separators: impl IntoIterator<Item = char>) -> Self {
if let Some(list) = &mut self.list {
list.rules.separators = separators.into_iter().collect();
}
self
}
/// Whether an item the list already has is not added again: of a list. What was typed is dropped.
pub fn unique(mut self, unique: bool) -> Self {
if let Some(list) = &mut self.list {
list.rules.unique = unique;
}
self
}
/// The signal that holds the draft, what is typed and is no item yet, of a list: the query the app reads for
/// suggestions, as a [`Combobox`](super::Combobox)'s is. What the app sets on it is what the input shows after
/// its tokens.
pub fn query(mut self, query: Signal<String>) -> Self {
if let Some(list) = &mut self.list {
list.query = Some(query);
}
self
}
/// Whether the draft becomes an item when the focus leaves the input, of a list. Otherwise it stays typed.
pub fn commit_on_blur(mut self, commit: bool) -> Self {
if let Some(list) = &mut self.list {
list.commit_on_blur = commit;
}
self
}
/// How the token of each item of a list is dressed: called with the item and its token, for a variant by what
/// the item is, or a token without a cross.
pub fn dress_token(mut self, dress: impl Fn(&str, Token) -> Token + Send + Sync + 'static) -> Self {
if let Some(list) = &mut self.list {
list.dress = Some(Arc::new(dress));
}
self
}
/// Called with the list when a person changed it: an item made of the draft, pasted, or taken away. Of a list.
pub fn on_change(mut self, handler: impl Fn(&[String]) + Send + Sync + 'static) -> Self {
if let Some(list) = &mut self.list {
list.on_change.push(Arc::new(handler));
}
self
}
/// Called with the draft when a person changed it: what is typed and is no item yet, the query for
/// suggestions. Of a list.
pub fn on_query(mut self, handler: impl Fn(&str) + Send + Sync + 'static) -> Self {
if let Some(list) = &mut self.list {
list.on_query.push(Arc::new(handler));
}
self
}
/// How the app finds the tokens in the text: called with the text in every render. A list's tokens are its
/// items, and this is not asked. Tokens that overlap one
/// before them, that hold a line break or that are not on the text's characters are left out.
pub fn find_tokens(mut self, find: impl Fn(&str) -> Vec<Token> + Send + Sync + 'static) -> Self {
self.find = Some(Arc::new(find));
self
}
/// Text on several rows: the input is as high as `min_rows` while it holds less, grows to `max_rows`, and
/// then scrolls. Tokens and text share each row and wrap as words do.
pub fn rows(mut self, min_rows: usize, max_rows: usize) -> Self {
let min_rows = min_rows.max(1);
self.rows = Some((min_rows, max_rows.max(min_rows)));
self
}
/// What the input says while it is empty.
pub fn placeholder(mut self, placeholder: &str) -> Self {
self.placeholder = Some(Arc::from(placeholder));
self
}
/// A [`TokenInputSize`], or a size the theme's recipe names.
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.boxed.size = size.into();
self
}
/// Whether what the input holds is wrong. Of invalid, warning and valid, the first that is set is the one shown.
pub fn invalid(mut self, invalid: bool) -> Self {
self.boxed.invalid = invalid;
self
}
/// Whether what the input holds is allowed with a caveat.
pub fn warning(mut self, warning: bool) -> Self {
self.boxed.warning = warning;
self
}
/// Whether what the input holds was checked and is right.
pub fn valid(mut self, valid: bool) -> Self {
self.boxed.valid = valid;
self
}
/// Whether the input can be read, selected and copied, and not changed. Its tokens have no cross.
pub fn read_only(mut self, read_only: bool) -> Self {
self.boxed.read_only = read_only;
self
}
/// Whether the input takes no input. Its tokens have no cross.
pub fn disabled(mut self, disabled: bool) -> Self {
self.boxed.disabled = disabled;
self
}
/// What the input is called, to what reads the tree. A field gives it its label unless it has its own.
pub fn label(mut self, label: &str) -> Self {
self.boxed.label = Some(Arc::from(label));
self
}
/// Whether the input is as wide as what holds it, in place of the design's 260.
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
self
}
/// Puts the input 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
}
/// Called before an edit is made, with what the input will hold: a handler may refuse it
/// ([`TextInputEvent::prevent_default`]). Taking a token away by its cross is an edit too. Over a list the text
/// of the event is the one the input keeps the list as: [`TokenInput::on_change`] and [`TokenInput::on_query`]
/// say what a person did there.
pub fn on_input(mut self, handler: impl Fn(&TextInputEvent) + Send + Sync + 'static) -> Self {
self.on_input.push(Arc::new(handler));
self
}
/// The controller the app keeps for this input, which reads its selection and puts text at it: a token
/// chosen from a picker of the app's.
pub fn controller(mut self, controller: TextInputController) -> Self {
self.controller = Some(controller);
self
}
/// The name the input's value has in the form it is in.
#[cfg(feature = "form")]
pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
self.name = Some(name.into());
self
}
/// Styles one part of this input 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 input: what the component it is in says of the input in this
/// place.
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
/// Draws the box as it is under the pointer or focused, with nothing pointing at it: for a gallery or a test.
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
/// The id of the control: what is typed in and focused.
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
/// Takes what the field it is in says, as [`FieldControl::in_field`] does, and stays a builder.
pub(crate) fn in_field(mut self, field: &InField) -> Self {
self.boxed.in_field(field);
self
}
/// The view the input is drawn from in `theme`, for [`TokenInput::build`] and for what is made of a token
/// input (a [`Mentions`](super::Mentions)), with the tokens `more` finds in the text besides the input's own.
pub(crate) fn view(self, theme: &Theme, more: impl FnOnce(&str) -> Vec<Token>) -> TokenInputView {
let multiline = self.rows.is_some();
let case = self
.boxed
.case(self.states.clone())
.state(TokenInputState::FullWidth, self.full_width)
.state(TokenInputState::Multiline, multiline);
// A list is shown as the app holds it: its items, then the draft the app holds or the one that is typed.
if let Some(list) = &self.list {
let held = self.value.get_untracked();
let draft = match &list.query {
Some(query) => query.get(),
None => token_list::parse(&held).1,
};
let text = token_list::encode(&list.items.get(), &draft);
if text != held {
self.value.set(text);
}
}
// The text is read here, so that what renders the input renders it again as the text changes, and finds its
// tokens anew.
let text = self.value.get();
let mut tokens = match &self.list {
Some(list) => token_list::ranges(&text)
.into_iter()
.map(|range| {
let token = Token::new(range.clone());
match &list.dress {
Some(dress) => dress(&text[range], token),
None => token,
}
})
.collect(),
None => self.find.as_ref().map(|find| find(&text)).unwrap_or_default(),
};
tokens.extend(more(&text));
TokenInputView {
value: self.value,
list: self.list,
text: Arc::from(text),
tokens: tidy(tokens),
rows: self.rows,
placeholder: self.placeholder,
label: self.boxed.label.clone(),
invalid: self.boxed.judgment() == Some(Judgment::Invalid),
read_only: self.boxed.read_only,
disabled: self.boxed.disabled,
recipe: theme
.resolve::<TokenInput>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
case,
rules: self.rules,
forced: self.forced,
boxed: self.boxed,
on_input: self.on_input,
controller: self.controller,
name: self.name,
id: self.id,
key: self.key,
}
}
/// Builds the input in `theme`. Converting a token input into an element does this in the theme of what is
/// being rendered.
pub fn build(self, theme: &Theme) -> Element {
let view = self.view(theme, |_| Vec::new());
match theme.renderer::<TokenInput>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
/// The tokens in the order of the text, without those that overlap one before them or are empty.
fn tidy(mut tokens: Vec<Token>) -> Vec<Token> {
tokens.sort_by_key(|token| (token.range.start, token.range.end));
let mut end = 0;
tokens.retain(|token| {
let keep = token.range.start < token.range.end && token.range.start >= end;
if keep {
end = token.range.end;
}
keep
});
tokens
}
impl FieldControl for TokenInput {
/// Called by the field's label unless it has a name of its own, judged as the field is unless the app judged the
/// input itself, and disabled where the field is.
fn in_field(self, field: &InField) -> Element {
TokenInput::in_field(self, field).into()
}
fn has_fluid_form(&self) -> bool {
true
}
}
impl From<TokenInput> for Element {
fn from(input: TokenInput) -> Self {
input.build(¤t_theme())
}
}
/// A token input as a renderer sees it: what it was given, the tokens found in its text, the style of its parts,
/// and its behavior ready to be dressed.
pub struct TokenInputView {
/// What the input shows and what is typed is set on.
pub value: Signal<String>,
list: Option<ListOf>,
/// The text the tokens were found in. Over a list, the text the input keeps the list as: each item with a
/// narrow space after it, then the draft.
pub text: Arc<str>,
/// The tokens found in the text, in its order, none overlapping.
pub tokens: Vec<Token>,
/// The rows it shows and grows to, where its text wraps.
pub rows: Option<(usize, usize)>,
pub placeholder: Option<Arc<str>>,
/// What it is called to what reads the tree: its own label, or its field's.
pub label: Option<Arc<str>>,
/// Whether what it holds is wrong, as the input shows it.
pub invalid: bool,
pub read_only: bool,
pub disabled: bool,
/// The style of each part of this input, as its box is drawn.
pub recipe: ResolvedRecipe,
case: Case,
rules: Recipe,
forced: Option<Interaction>,
boxed: BoxStates,
on_input: Vec<EditHandler>,
controller: Option<TextInputController>,
// Read only where the engine has forms.
#[cfg_attr(not(feature = "form"), allow(dead_code))]
name: Option<Arc<str>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl TokenInputView {
/// The style of a part, as this input's box is to be drawn.
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
/// The type of the text: the control's.
pub fn value_style(&self) -> TextStyle {
text_box::ink(self.theme(), &self.part(TokenInputPart::Control).rest())
}
/// The type of the placeholder: the control's, with what the placeholder's part lays over it.
pub fn placeholder_style(&self) -> TextStyle {
let control = self.part(TokenInputPart::Control).rest();
text_box::ink(
self.theme(),
&control.merged(&self.part(TokenInputPart::Placeholder).rest()),
)
}
/// The recipe of a token of `variant`, in the states `states` of a token.
pub fn token_recipe(&self, variant: Name, states: &[TokenInputState]) -> ResolvedRecipe {
let mut case = self.case.clone();
case.variant = Some(variant);
let case = states.iter().fold(case, |case, state| case.state(*state, true));
self.theme().resolve::<TokenInput>(&case, Some(&self.rules))
}
/// How the engine draws a token in the style of `recipe`'s token parts: its fill, edge, corners, height and
/// room from the token part, its type and color from the label's, and, where `cross`, the theme's close icon
/// in the icon part's side and color, which takes the token away.
pub fn token_style(&self, recipe: &ResolvedRecipe, cross: bool) -> InputTokenStyle {
let theme = recipe.theme();
let token = recipe.part(TokenInputPart::Token).rest();
let text = text_box::ink(
theme,
&token.clone().merged(&recipe.part(TokenInputPart::TokenLabel).rest()),
);
let spacing = theme.spacing();
let space = |value: &Option<crate::node::SpacingValue>| value.as_ref().map(|value| value.resolve(&spacing, 0.0));
let fill = match &token.background {
Some(BackgroundColor::Color(color)) => *color,
Some(BackgroundColor::Palette(role)) => theme.palette_color(role.clone()),
Some(BackgroundColor::CurrentForeground) => text.color,
None => Color::new(0, 0, 0, 0),
};
let start = space(&token.padding_start).or(space(&token.padding_x)).unwrap_or(0.0);
let end = space(&token.padding_end).or(space(&token.padding_x)).unwrap_or(0.0);
let radius = token
.radius
.as_ref()
.map(|radius| radius.resolve(&theme.radii()).top_left)
.unwrap_or(0.0);
let mut style = InputTokenStyle::new(text.color, fill)
.padding(start)
.padding_end(end)
.radius(radius)
.text_style(text.clone());
if let Some(Dimension::Px(height)) = token.height.and_then(|height| height.resolve(theme)) {
style = style.height(height);
}
if let Some(edge) = token
.border
.as_ref()
.and_then(|border| border.resolve(&theme.palette(), &theme.border_sizes()))
.filter(|edge| edge.width > 0.0)
{
style = style.border(edge.width, edge.color);
}
if cross && let Some(glyph) = theme.icon(icons::CLOSE) {
let icon = recipe.part(TokenInputPart::TokenIcon).rest();
let side = match icon.width.unwrap_or(Length::Icon(IconSize::Xs)).resolve(theme) {
Some(Dimension::Px(side)) => side,
_ => theme.icon_size_value(IconSize::Xs),
};
let color = match &icon.foreground {
Some(TextColor::Color(color)) => *color,
Some(TextColor::Palette(role)) => theme.palette_color(role.clone()),
None => text.color,
};
let gap = space(&token.gap).unwrap_or(0.0);
style = style.icon(
InputTokenIcon::new(glyph)
.size(side)
.color(color)
.gap(gap)
.removes(true),
);
}
style
}
/// The engine's tokens for the text: each token in the style of its variant, with the looks it takes under the
/// pointer and covered by the selection. A read-only or disabled input's tokens have no cross.
pub fn input_tokens(&self) -> InputTokens {
let editable = !self.read_only && !self.disabled;
let mut looks: Vec<(Name, bool, InputTokenStyle)> = Vec::new();
let tokens = self
.tokens
.iter()
.filter(|token| {
token.range.end <= self.text.len()
&& self.text.is_char_boundary(token.range.start)
&& self.text.is_char_boundary(token.range.end)
&& !self.text[token.range.clone()].contains(['\r', '\n'])
})
.map(|token| {
let cross = token.removable && editable;
let style = match looks
.iter()
.find(|(variant, with_cross, _)| *variant == token.variant && *with_cross == cross)
{
Some((_, _, style)) => style.clone(),
None => {
let rest = self.token_style(&self.token_recipe(token.variant, &[]), cross);
let hovered = self.token_style(&self.token_recipe(token.variant, &[TokenInputState::Hovered]), cross);
let selected = self.token_style(&self.token_recipe(token.variant, &[TokenInputState::Selected]), cross);
let style = rest.hovered(hovered).selected(selected);
looks.push((token.variant, cross, style.clone()));
style
}
};
InputToken::new(token.range.clone(), style).atomic(token.atomic)
})
.collect();
// The ranges were checked against the text above: what is left is valid.
InputTokens::new(&self.text, tokens)
.unwrap_or_else(|_| InputTokens::new(&self.text, Vec::new()).expect("no tokens are always valid"))
}
/// The input's behavior with the style of its box and its tokens: the engine's text input bound to the value,
/// on one line or on its rows, with the tokens found in the text. It is a stop of Tab, a `textbox` to what reads
/// the tree, called by its label, and says whether it is invalid; a read-only one refuses every edit.
pub fn control(&self) -> components::TextInput {
let mut control = components::TextInput::new(self.value.clone())
.text_style(self.value_style())
.placeholder_style(self.placeholder_style())
.tokens(self.input_tokens());
control = match self.rows {
Some((min_rows, max_rows)) => control
.multiline()
.rows(min_rows, max_rows)
.describe("a11y_multiline", "true"),
None => control.single_line(),
};
let control = control.part(&self.part(TokenInputPart::Control));
let mut handlers = self.on_input.clone();
// Over a list every edit is settled, after the app's own handlers had their say.
let list = self.list.clone().map(|mut list| {
if let Some(controller) = &self.controller {
list.controller = controller.clone();
}
Arc::new(list)
});
if let Some(list) = &list {
let list = list.clone();
handlers.push(Arc::new(move |event: &TextInputEvent| list.settle(event)));
}
let mut control = text_box::text_box(control, &self.boxed, handlers);
if let Some(list) = &list {
control = control.controller(list.controller.clone());
if !self.disabled {
// A token and the mark that ends it are one step of Left and Right: the caret does not rest between them.
let (stepped, value) = (list.clone(), self.value.clone());
control = control.on_key_down(move |event: KeyboardEvent| {
let on = match event.key.as_str() {
"ArrowRight" => true,
"ArrowLeft" => false,
_ => return,
};
if !event.focus_within || event.composing || event.shift || event.ctrl || event.alt || event.meta {
return;
}
let Ok(selection) = stepped.controller.selection() else {
return;
};
if selection.anchor.is_some_and(|anchor| anchor != selection.caret) {
return;
}
if let Some(to) = token_list::step(&value.get(), selection.caret, on)
&& stepped.controller.select(to, to).is_ok()
{
event.prevent_default();
}
});
}
if !self.read_only && !self.disabled {
let (entered, value) = (list.clone(), self.value.clone());
// A key reaches every node: Enter acts only while the focus is in the input, and a composition keeps its own.
control = control.on_key_down(move |event: KeyboardEvent| {
if event.focus_within
&& !event.composing
&& !(event.ctrl || event.alt || event.meta)
&& event.key.as_str() == "Enter"
&& entered.commit(&value)
{
event.prevent_default();
}
});
let (left, value) = (list.clone(), self.value.clone());
control = control.on_blur(move || {
let _ = &left.alive;
if left.commit_on_blur {
left.commit(&value);
}
});
}
} else if let Some(controller) = &self.controller {
control = control.controller(controller.clone());
}
if let Some(placeholder) = &self.placeholder {
control = control.placeholder(placeholder);
}
#[cfg(feature = "form")]
if let Some(name) = &self.name {
control = control.name(name.clone());
}
if let Some(id) = &self.id {
control = control.id(id.clone());
}
if let Some(key) = &self.key {
control = control.key(key.clone());
}
control
}
/// The place the input takes, around `control`.
pub fn root(&self, control: impl Into<Element>) -> Stack {
Stack::new()
.stack_align(StackAlignment::TopStart)
.part(&self.part(TokenInputPart::Root))
.child(control)
}
/// How the default renderer builds a token input: the control in its place.
pub fn render(self) -> Element {
self.root(self.control()).into()
}
}
impl crate::ui::Styled for TokenInput {
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 TokenInput {
const NAME: &'static str = "token_input";
type Renderer = TokenInputRenderer;
fn parts() -> crate::ui::Declared {
TokenInputPart::declared()
}
fn states() -> crate::ui::Declared {
TokenInputState::declared()
}
/// The design's token input (`pencil/lurq-design-system.pen`, Token Input): the box of an input, 260 wide and
/// 36 high, padded 6 at its sides, its text in the body's type and its placeholder in the muted foreground; its
/// edge says its state as an input's does. A token is 24 high in the fill of what is secondary, with the small
/// radius, 8 before its text and 6 after its cross, its text 13 in the secondary foreground and its cross of 12
/// in the muted foreground, 4 after the text. Informative, success, warning and destructive tokens are in the
/// muted fill of their color with their text in the color, as tags are. Under the pointer a token is in the
/// secondary color's hover (a colored one keeps its fill) and its cross in the foreground; covered by the
/// selection it is in the primary color with its text and cross in the primary foreground. Small, the box is 32
/// and a token 20 with text of 12; large, 40 and 28 with text of 14. On rows, the box is padded 6 down too, and
/// its lines are 28 high (twice the text), a token's text with them. A mention ([`MENTION`]) stands in a line of
/// prose: in the informative color's muted fill and its text in the color, in the text's type with lines of 1.5,
/// 20 high and padded 4.
///
/// In a fluid field, which the board does not draw for it, the box is the fluid one, as wide as the field and
/// padded 12 at its sides, where the field's label starts: 56 high on one line, its tokens in the middle of the
/// line of the text, and on rows as high as its rows with the 29 over them and the 10 under.
fn recipe() -> Recipe {
use PaletteColor::*;
use TokenInputPart::{Control, Placeholder, Root, Token, TokenIcon, TokenLabel};
let recipe = Recipe::new()
.base(Root, |s| s.width(260.0).max_width(Length::Fill))
.base(Control, |s| {
text_box::box_style(s)
.padding_x(6.0)
.height(ControlSize::Md)
.foreground(Foreground)
.typography(TypographyStyle::Body)
})
.base(Token, |s| {
s.height(24.0)
.padding_start(8.0)
.padding_end(6.0)
.gap(4.0)
.radius(RadiusSize::Sm)
.background(Secondary)
})
.base(TokenLabel, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(SecondaryForeground)
})
.base(TokenIcon, |s| s.square(12.0).foreground(MutedForeground))
.state(TokenInputState::FullWidth, Root, |s| s.width(Length::Fill))
.size(TextBoxSize::Sm, Token, |s| {
s.height(20.0).padding_start(6.0).padding_end(4.0)
})
.size(TextBoxSize::Sm, TokenLabel, |s| s.font_size(12.0))
.size(TextBoxSize::Sm, TokenIcon, |s| s.square(10.0))
.size(TextBoxSize::Lg, Token, |s| {
s.height(28.0).padding_start(10.0).padding_end(8.0)
})
.size(TextBoxSize::Lg, TokenLabel, |s| s.font_size(14.0))
.size(TextBoxSize::Lg, TokenIcon, |s| s.square(IconSize::Sm));
let recipe = text_box::box_sizes(recipe, Control, true);
// On rows the box is as high as its rows, and each row holds a token with room above and below it.
let recipe = [
(None, 2.0, 26.0 / 13.0),
(Some(TextBoxSize::Sm), 2.0, 24.0 / 12.0),
(Some(TextBoxSize::Lg), 2.0, 32.0 / 14.0),
]
.into_iter()
.fold(recipe, |recipe, (size, line, token_line)| {
let selector = match size {
Some(size) => Selector::new().size(size).state(TokenInputState::Multiline),
None => Selector::new().state(TokenInputState::Multiline),
};
recipe
.when(selector.clone(), Control, |s| {
s.height(Length::Auto).padding_y(6.0).line_height(line)
})
.when(selector, TokenLabel, |s| s.line_height(token_line))
});
let recipe = recipe
.state(TokenInputState::Hovered, Token, |s| s.background(SecondaryHover))
.state(TokenInputState::Hovered, TokenIcon, |s| s.foreground(Foreground))
.state(TokenInputState::Selected, Token, |s| s.background(Primary))
.state(TokenInputState::Selected, TokenLabel, |s| {
s.foreground(PrimaryForeground)
})
.state(TokenInputState::Selected, TokenIcon, |s| {
s.foreground(PrimaryForeground)
});
// A token of a color keeps its fill and ink under the pointer; in a selection it is in the primary color, as
// any token is.
let colors = [
(Name::from(TagVariant::Info), InfoMuted, Info),
(Name::from(TagVariant::Success), SuccessMuted, Success),
(Name::from(TagVariant::Warning), WarningMuted, Warning),
(Name::from(TagVariant::Destructive), DestructiveMuted, Destructive),
(Name::new(MENTION), InfoMuted, Info),
];
let recipe = colors.into_iter().fold(recipe, |recipe, (variant, fill, ink)| {
let hovered = Selector::new().variant(variant).state(TokenInputState::Hovered);
recipe
.variant(variant, Token, |s| s.background(fill.clone()))
.variant(variant, TokenLabel, |s| s.foreground(ink.clone()))
.variant(variant, TokenIcon, |s| s.foreground(ink.clone()))
.when(hovered.clone(), Token, |s| s.background(fill))
.when(hovered, TokenIcon, |s| s.foreground(ink))
});
// A mention stands in a line of prose: in the text's type, its fill 20 high and padded 4, with no room
// around it that the line would not have.
let mention = Selector::new().variant(MENTION);
let recipe = recipe
.when(mention.clone(), Token, |s| {
s.height(20.0).padding_start(4.0).padding_end(4.0)
})
.when(mention.clone(), TokenLabel, |s| s.font_size(14.0))
.when(mention.clone().size(TextBoxSize::Sm), TokenLabel, |s| s.font_size(13.0))
.when(mention.clone().size(TextBoxSize::Lg), TokenLabel, |s| s.font_size(15.0))
.when(mention.state(TokenInputState::Multiline), TokenLabel, |s| {
s.line_height(1.5)
});
let recipe = text_box::box_rules(recipe, Root, Control, Placeholder);
// A line with a token in it is higher than a line of text, so a box of one line is 56 and not as high as what it
// holds; on rows it is as high as they are.
let rows = Selector::new()
.state(TokenInputState::Fluid)
.state(TokenInputState::Multiline);
text_box::fluid_rules(recipe, Root, Control)
.state(TokenInputState::Fluid, Control, |s| {
s.padding_x(12.0).height(text_box::FLUID_HEIGHT)
})
.when(rows, Control, |s| s.height(Length::Auto))
}
}