pdfrum-form 0.1.0

Form interaction: events, focus, the edit control, the commit cascade
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
//! Combo boxes and list boxes: the operations over a set of rows.
//!
//! One machine covers both. Three differences are sharp enough that a
//! reasonable design would smooth them away, and none is smoothed:
//!
//! - **A combo box cannot be deselected and a list box can.**
//! - **A call that changes nothing still moves the caret**, which changes what
//!   the field reports as its focused text.
//! - **Type-ahead jumps rather than accumulates.** Typing `A`, `B`, `C` lands
//!   on the row starting with C; each character is an independent circular
//!   search from the current row.

use std::collections::BTreeSet;

use super::{ChoiceState, TextConfig};

/// Where the search that a typed character starts should land.
///
/// A circular scan from the row after `from`, comparing first characters
/// case-insensitively. **When nothing matches it returns the last row
/// probed** rather than reporting failure — which is why consecutive
/// characters read as independent jumps rather than as a growing prefix.
///
/// ```
/// use pdfrum_form::field::choice::find_next;
///
/// let labels: Vec<String> =
///     ["Apple", "Banana", "Cherry"].iter().map(|s| s.to_string()).collect();
///
/// // The scan is circular: from the last row it wraps to the first.
/// assert_eq!(find_next(&labels, 2, 'a'), Some(0));
///
/// // Nothing starting with Z: the answer is the last row probed, not `None`.
/// assert_eq!(find_next(&labels, 1, 'Z'), Some(1));
///
/// // `None` only when there are no rows at all.
/// assert_eq!(find_next(&[], 0, 'A'), None);
/// ```
#[must_use]
pub fn find_next(options: &[String], from: usize, ch: char) -> Option<usize> {
    if options.is_empty() {
        return None;
    }
    let count = options.len();
    let wanted = ch.to_uppercase().next().unwrap_or(ch);
    let mut at = from;
    for _ in 0..count {
        at = (at + 1) % count;
        let first = options
            .get(at)
            .and_then(|o| o.chars().next())
            .map(|c| c.to_uppercase().next().unwrap_or(c));
        if first == Some(wanted) {
            return Some(at);
        }
    }
    // Nothing matched. The scan's final position is the answer, deliberately.
    Some(at)
}

/// Whether a row index names a row of this field.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let state = ChoiceState::new(rows(&["Apple", "Banana"]), ChoiceConfig::default());
/// assert!(choice::in_range(&state, 1));
/// assert!(!choice::in_range(&state, 2));
/// ```
#[must_use]
pub fn in_range(state: &ChoiceState, index: usize) -> bool {
    index < state.options.len()
}

/// Selects or clears one row programmatically.
///
/// Returns whether the call was accepted, which is not the same as whether
/// anything changed:
///
/// - an out-of-range row is **rejected** by both kinds;
/// - a combo box **rejects** every clear, whatever the row;
/// - a list box **accepts** both, including a redundant one, and moves the
///   row last acted upon either way.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let combo_config = ChoiceConfig { combo: true, ..ChoiceConfig::default() };
/// let mut combo = ChoiceState::new(rows(&["Apple", "Banana"]), combo_config);
/// assert!(choice::set_index_selected(&mut combo, 1, true));
/// assert!(!choice::set_index_selected(&mut combo, 1, false), "no empty state");
/// assert!(choice::is_index_selected(&combo, 1));
///
/// // A list box accepts a clear that removes nothing — and still moves the
/// // caret, so its focused text changes.
/// let mut list = ChoiceState::new(rows(&["Apple", "Banana"]), ChoiceConfig::default());
/// choice::set_index_selected(&mut list, 0, true);
/// assert!(choice::set_index_selected(&mut list, 1, false));
/// assert!(choice::is_index_selected(&list, 0));
/// assert_eq!(list.focused_text(), "Banana");
/// ```
pub fn set_index_selected(state: &mut ChoiceState, index: usize, selected: bool) -> bool {
    if !in_range(state, index) {
        return false;
    }
    if state.config.combo {
        if !selected {
            // A combo box always shows one row; there is no empty state to
            // clear into.
            return false;
        }
        state.selected.clear();
        state.selected.insert(index);
        state.caret_index = Some(index);
        return true;
    }

    if selected {
        if !state.config.multi_select {
            state.selected.clear();
        }
        state.selected.insert(index);
    } else {
        state.selected.remove(&index);
    }
    // Both branches move the caret, so a clear that removed nothing still
    // changes what the field reports as its focused text.
    state.caret_index = Some(index);
    true
}

/// Whether a row is selected. An out-of-range row is not.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let mut state = ChoiceState::new(rows(&["Apple", "Banana"]), ChoiceConfig::default());
/// choice::select_only(&mut state, 0);
/// assert!(choice::is_index_selected(&state, 0));
/// assert!(!choice::is_index_selected(&state, 99));
/// ```
#[must_use]
pub fn is_index_selected(state: &ChoiceState, index: usize) -> bool {
    in_range(state, index) && state.selected.contains(&index)
}

/// Selects one row by a click or a keyboard move, clearing the others.
///
/// Unlike a range extend, this **re-anchors**: the row it selects becomes the
/// pivot a later shift-click measures from.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let config = ChoiceConfig { multi_select: true, ..ChoiceConfig::default() };
/// let mut list = ChoiceState::new(rows(&["Apple", "Banana", "Cherry"]), config);
/// assert!(choice::select_only(&mut list, 1));
/// assert_eq!(list.anchor, Some(1));
/// assert!(!choice::select_only(&mut list, 9), "out of range is rejected");
/// ```
pub fn select_only(state: &mut ChoiceState, index: usize) -> bool {
    if !in_range(state, index) {
        return false;
    }
    state.selected.clear();
    state.selected.insert(index);
    state.caret_index = Some(index);
    state.anchor = Some(index);
    true
}

/// Extends the selection from the anchor to `index`, clearing everything
/// else. What a shift-click does on a multi-select list box.
///
/// The anchor is deliberately **not** moved, so successive shift-clicks all
/// pivot on the row the plain click established.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let config = ChoiceConfig { multi_select: true, ..ChoiceConfig::default() };
/// let mut list =
///     ChoiceState::new(rows(&["Apple", "Banana", "Cherry", "Date"]), config);
/// choice::select_only(&mut list, 1);
/// choice::select_range_to(&mut list, 3);
/// assert_eq!(list.selected.iter().copied().collect::<Vec<_>>(), [1, 2, 3]);
/// assert_eq!(list.anchor, Some(1), "the pivot did not move");
///
/// // So a second extend measures from row 1 again, not from row 3.
/// choice::select_range_to(&mut list, 2);
/// assert_eq!(list.selected.iter().copied().collect::<Vec<_>>(), [1, 2]);
/// ```
pub fn select_range_to(state: &mut ChoiceState, index: usize) -> bool {
    if !in_range(state, index) {
        return false;
    }
    if !state.config.multi_select {
        return select_only(state, index);
    }
    let anchor = state.anchor.unwrap_or(index);
    let (lo, hi) = if anchor <= index {
        (anchor, index)
    } else {
        (index, anchor)
    };
    state.selected = (lo..=hi).collect();
    state.caret_index = Some(index);
    true
}

/// Toggles one row, keeping the rest. What an accelerator-click does on a
/// multi-select list box, and it **does** re-anchor.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let config = ChoiceConfig { multi_select: true, ..ChoiceConfig::default() };
/// let mut list =
///     ChoiceState::new(rows(&["Apple", "Banana", "Cherry", "Date"]), config);
/// choice::select_only(&mut list, 0);
/// choice::toggle_index(&mut list, 3);
/// assert_eq!(list.selected.iter().copied().collect::<Vec<_>>(), [0, 3]);
/// assert_eq!(list.anchor, Some(3), "unlike a range extend, this re-anchors");
///
/// choice::toggle_index(&mut list, 3);
/// assert_eq!(list.selected.iter().copied().collect::<Vec<_>>(), [0]);
/// ```
pub fn toggle_index(state: &mut ChoiceState, index: usize) -> bool {
    if !in_range(state, index) {
        return false;
    }
    if !state.config.multi_select {
        return select_only(state, index);
    }
    if state.selected.contains(&index) {
        state.selected.remove(&index);
    } else {
        state.selected.insert(index);
    }
    state.caret_index = Some(index);
    state.anchor = Some(index);
    true
}

/// Moves the selection one row, which is what an arrow key does.
///
/// Clamps at each end rather than wrapping or failing.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let mut list = ChoiceState::new(rows(&["Apple", "Banana"]), ChoiceConfig::default());
/// choice::select_only(&mut list, 0);
/// choice::move_selection(&mut list, -1);
/// assert!(choice::is_index_selected(&list, 0), "clamped at the top");
///
/// choice::move_selection(&mut list, 5);
/// assert!(choice::is_index_selected(&list, 1), "clamped at the bottom");
/// ```
pub fn move_selection(state: &mut ChoiceState, delta: i32) -> bool {
    if state.options.is_empty() {
        return false;
    }
    let last = state.options.len() - 1;
    let current = state
        .caret_index
        .or_else(|| state.selected.iter().next().copied())
        .unwrap_or(0);
    let next = if delta < 0 {
        current.saturating_sub(delta.unsigned_abs() as usize)
    } else {
        (current + delta.unsigned_abs() as usize).min(last)
    };
    select_only(state, next)
}

/// Moves the caret one row **with modifiers**, which is what an arrow key and
/// a wheel notch both do.
///
/// A multi-select list branches three ways, and the first is the surprising
/// one:
///
/// - **Ctrl** — nothing but the caret moves; the selection is left exactly as
///   it was. Not an oversight: it is how a user walks the caret to a row
///   before toggling it.
/// - **Shift** — deselect everything, then select the whole run from the
///   anchor to the new row.
/// - **neither** — deselect everything, select the one row, and re-anchor.
///
/// A single-select list ignores all three and just selects the row.
///
/// [`move_selection`] is this function with both flags clear, and is kept
/// because that is what most callers want.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let config = ChoiceConfig { multi_select: true, ..ChoiceConfig::default() };
/// let mut list =
///     ChoiceState::new(rows(&["Apple", "Banana", "Cherry", "Date"]), config);
/// choice::select_only(&mut list, 0);
///
/// // Ctrl walks the caret and leaves the selection exactly as it was.
/// choice::move_caret_by(&mut list, 1, false, true);
/// assert_eq!(list.caret_index, Some(1));
/// assert_eq!(list.selected.iter().copied().collect::<Vec<_>>(), [0]);
///
/// // Shift extends from the anchor, which is still row 0.
/// choice::move_caret_by(&mut list, 1, true, false);
/// assert_eq!(list.selected.iter().copied().collect::<Vec<_>>(), [0, 1, 2]);
///
/// // Neither: the one row, and a new anchor.
/// choice::move_caret_by(&mut list, 1, false, false);
/// assert_eq!(list.selected.iter().copied().collect::<Vec<_>>(), [3]);
/// assert_eq!(list.anchor, Some(3));
/// ```
pub fn move_caret_by(state: &mut ChoiceState, delta: i32, shift: bool, ctrl: bool) -> bool {
    if state.options.is_empty() {
        return false;
    }
    let last = state.options.len() - 1;
    let current = state
        .caret_index
        .or_else(|| state.selected.iter().next().copied())
        .unwrap_or(0);
    let next = if delta < 0 {
        current.saturating_sub(delta.unsigned_abs() as usize)
    } else {
        (current + delta.unsigned_abs() as usize).min(last)
    };
    if !state.config.multi_select {
        return select_only(state, next);
    }
    if ctrl {
        // The caret moves and nothing else does. Reported as a change,
        // because the caret is what a multi-select list answers its focused
        // text with and what its focus box strokes.
        let moved = state.caret_index != Some(next);
        state.caret_index = Some(next);
        return moved;
    }
    if shift {
        return select_range_to(state, next);
    }
    select_only(state, next)
}

/// Applies a typed character as type-ahead.
///
/// Returns whether a row was landed on. The search starts from the row last
/// acted upon, so each character is its own jump.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let config = ChoiceConfig { combo: true, ..ChoiceConfig::default() };
/// let mut combo = ChoiceState::new(rows(&["Apple", "Banana", "Cherry"]), config);
///
/// // A, then B, then C lands on Cherry — not on a row starting "ABC".
/// choice::type_ahead(&mut combo, 'A');
/// choice::type_ahead(&mut combo, 'B');
/// choice::type_ahead(&mut combo, 'C');
/// assert_eq!(combo.focused_text(), "Cherry");
///
/// // The match ignores case.
/// choice::type_ahead(&mut combo, 'b');
/// assert_eq!(combo.focused_text(), "Banana");
/// ```
pub fn type_ahead(state: &mut ChoiceState, ch: char) -> bool {
    let labels: Vec<String> = state.options.iter().map(|o| o.label.clone()).collect();
    let from = state
        .caret_index
        .or_else(|| state.selected.iter().next().copied())
        .unwrap_or(0);
    match find_next(&labels, from, ch) {
        Some(index) => select_only(state, index),
        None => false,
    }
}

/// Reads the initially selected rows from the field's stored value and index
/// entries.
///
/// **The value wins where the two disagree**, which is asserted by a fixture
/// built to make them disagree. The index entry is consulted only when there
/// is no value to read.
///
/// ```
/// use pdfrum_form::field::choice::initial_selection;
///
/// let options: Vec<String> =
///     ["Apple", "Banana", "Cherry"].iter().map(|s| s.to_string()).collect();
///
/// // The index entry answers only when there is no value.
/// assert_eq!(initial_selection(&options, &[], &[2]).into_iter().collect::<Vec<_>>(), [2]);
///
/// // Where the two disagree, the value wins.
/// let values = vec!["Banana".to_string()];
/// assert_eq!(
///     initial_selection(&options, &values, &[2]).into_iter().collect::<Vec<_>>(),
///     [1]
/// );
/// ```
#[must_use]
pub fn initial_selection(
    options: &[String],
    values: &[String],
    indices: &[usize],
) -> BTreeSet<usize> {
    if !values.is_empty() {
        return values
            .iter()
            .filter_map(|v| options.iter().position(|o| o == v))
            .collect();
    }
    indices
        .iter()
        .copied()
        .filter(|i| *i < options.len())
        .collect()
}

/// Where a list scrolls to so that `first_selected` is visible.
///
/// **It scrolls only far enough to fill the box**, which is why a list of ten
/// rows showing three at a time with the last row selected leaves row *eight*
/// at the top rather than row nine: scrolling to nine would leave two empty
/// rows below it. Reproduced as-asserted.
///
/// ```
/// use pdfrum_form::field::choice::top_visible_for;
///
/// // Ten rows, three visible, the last row selected: the top row is 7.
/// assert_eq!(top_visible_for(10, 3, 9), 7);
/// // A selection that leaves a full box below it scrolls exactly to it.
/// assert_eq!(top_visible_for(10, 3, 4), 4);
/// // A list that fits needs no scrolling at all.
/// assert_eq!(top_visible_for(3, 5, 2), 0);
/// ```
#[must_use]
pub fn top_visible_for(count: usize, visible_rows: usize, first_selected: usize) -> usize {
    if visible_rows == 0 || count <= visible_rows {
        return 0;
    }
    let max_top = count - visible_rows;
    first_selected.min(max_top)
}

/// The configuration an editable combo box's text half is given.
///
/// A combo box's text is single-line and unlimited whatever the field says,
/// and a non-editable one's is read-only — it still holds text and still
/// supports selecting and copying it, which is how a substring of a
/// non-editable combo's value can be selected with the mouse.
///
/// ```
/// use pdfrum_form::field::choice::combo_text_config;
///
/// let editable = combo_text_config(true, false);
/// assert!(!editable.read_only);
/// assert!(!editable.multi_line);
/// assert_eq!(editable.max_len, None, "unlimited whatever the field says");
///
/// // A non-editable combo's text half is read-only but still present.
/// assert!(combo_text_config(false, false).read_only);
/// ```
#[must_use]
pub fn combo_text_config(editable: bool, read_only: bool) -> TextConfig {
    TextConfig {
        multi_line: false,
        password: false,
        comb: false,
        max_len: None,
        read_only: read_only || !editable,
        undo_enabled: true,
        auto_scroll: true,
    }
}

/// Scrolls the view just far enough to bring `index` into it.
///
/// **Only when it is not already visible**, which is the whole rule: moving
/// the caret within the visible rows
/// scrolls nothing, and moving it past either edge scrolls by exactly the
/// overshoot. That is what keeps a run of arrow keys — or wheel notches,
/// which are the same operation — from scrolling on every step.
///
/// Answers whether the view moved.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let labels = ["a", "b", "c", "d", "e"];
/// let mut list = ChoiceState::new(rows(&labels), ChoiceConfig::default());
///
/// // Row 2 is already among the three visible rows: nothing scrolls.
/// assert!(!choice::scroll_into_view(&mut list, 2, 3));
/// assert_eq!(list.top_visible, 0);
///
/// // Row 4 is past the bottom edge, so the view moves by exactly the
/// // overshoot and the box stays full.
/// assert!(choice::scroll_into_view(&mut list, 4, 3));
/// assert_eq!(list.top_visible, 2);
/// ```
pub fn scroll_into_view(state: &mut ChoiceState, index: usize, visible_rows: usize) -> bool {
    if visible_rows == 0 {
        return false;
    }
    let was = state.top_visible;
    if index < state.top_visible {
        // Above the view: the item becomes the first visible row.
        state.top_visible = index;
    } else if index >= state.top_visible.saturating_add(visible_rows) {
        // Below it: the item becomes the last, so the box stays full.
        state.top_visible = index.saturating_sub(visible_rows - 1);
    }
    state.top_visible != was
}

/// Carries the currently selected option into the combo box's text half.
///
/// # This is where the four-item undo group comes from
///
/// It is three operations — select all, replace the selection, select all
/// again — and the middle one is itself a group of two, a removal and an
/// insertion. So choosing an option from an open combo box pushes **four**
/// undo items that
/// must undo together, which is the worst case `SessionConfig::max_undo_items`
/// is clamped to four to hold: a capacity that could not fit one whole group
/// would have to evict half of it.
///
/// The two `select_all`s are not redundant. The first is what makes the
/// replacement replace the *whole* text rather than inserting at a caret; the
/// second leaves the new text selected, so typing immediately after choosing
/// an option overwrites it rather than appending to it.
///
/// Answers whether anything was carried across, which is `false` for a combo
/// with no current selection.
///
/// ```
/// use pdfrum_form::field::{ChoiceConfig, ChoiceOption, ChoiceState, choice};
///
/// fn rows(labels: &[&str]) -> Vec<ChoiceOption> {
///     labels
///         .iter()
///         .map(|l| ChoiceOption { label: (*l).to_string(), value: (*l).to_string() })
///         .collect()
/// }
///
/// let metrics = pdfrum_doc::vt::Metrics { width: &|_| 1000, ascent: 800, descent: -200 };
/// let config = pdfrum_doc::vt::Config {
///     plate: kurbo::Rect::new(0.0, 0.0, 1000.0, 20.0),
///     font_size: 1.0,
///     ..Default::default()
/// };
///
/// let combo_config =
///     ChoiceConfig { combo: true, editable: true, ..ChoiceConfig::default() };
/// let mut combo = ChoiceState::new(rows(&["Apple", "Banana"]), combo_config);
///
/// // Nothing chosen yet: there is nothing to carry across.
/// assert!(!choice::set_select_text(&mut combo, &config, &metrics));
///
/// choice::select_only(&mut combo, 1);
/// assert!(choice::set_select_text(&mut combo, &config, &metrics));
/// assert_eq!(combo.edit_text, "Banana");
/// ```
pub fn set_select_text(
    state: &mut ChoiceState,
    config: &pdfrum_doc::vt::Config,
    metrics: &pdfrum_doc::vt::Metrics<'_>,
) -> bool {
    let Some(index) = state
        .caret_index
        .or_else(|| state.selected.iter().next().copied())
    else {
        return false;
    };
    let Some(option) = state.options.get(index) else {
        return false;
    };
    let text = option.label.clone();

    let edit = state
        .edit
        .get_or_insert_with(|| Box::new(crate::edit::TextEdit::new("", config, metrics, true)));
    edit.select_all();
    crate::edit::ops::replace_selection(edit, config, metrics, &text, None);
    edit.select_all();
    state.edit_text.clone_from(&edit.text);
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::field::{ChoiceConfig, ChoiceOption};

    fn options(labels: &[&str]) -> Vec<ChoiceOption> {
        labels
            .iter()
            .map(|l| ChoiceOption {
                label: (*l).to_string(),
                value: (*l).to_string(),
            })
            .collect()
    }

    fn combo(labels: &[&str]) -> ChoiceState {
        ChoiceState::new(
            options(labels),
            ChoiceConfig {
                combo: true,
                ..ChoiceConfig::default()
            },
        )
    }

    fn single_list(labels: &[&str]) -> ChoiceState {
        ChoiceState::new(options(labels), ChoiceConfig::default())
    }

    fn multi_list(labels: &[&str]) -> ChoiceState {
        ChoiceState::new(
            options(labels),
            ChoiceConfig {
                multi_select: true,
                ..ChoiceConfig::default()
            },
        )
    }

    const FRUIT: [&str; 5] = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];

    /// A combo box refuses every clear; a single-select list box accepts one
    /// and can be left genuinely empty.
    #[test]
    fn only_a_list_box_can_be_emptied() {
        let mut combo = combo(&FRUIT);
        assert!(set_index_selected(&mut combo, 1, true));
        assert!(
            !set_index_selected(&mut combo, 1, false),
            "a combo box has no empty state"
        );
        assert!(is_index_selected(&combo, 1), "and it did not clear");

        let mut list = single_list(&FRUIT);
        assert!(set_index_selected(&mut list, 1, true));
        assert!(set_index_selected(&mut list, 1, false));
        assert!(list.selected.is_empty());
        assert_eq!(list.focused_text(), "Banana", "the caret stayed on it");
    }

    /// Out of range is rejected by both, and changes nothing.
    #[test]
    fn an_out_of_range_row_is_rejected() {
        let mut list = single_list(&FRUIT);
        assert!(set_index_selected(&mut list, 0, true));
        assert!(!set_index_selected(&mut list, 100, true));
        assert!(!set_index_selected(&mut list, 5, true));
        assert!(is_index_selected(&list, 0));
        assert!(!is_index_selected(&list, 100));
    }

    /// The behaviour that reads as a bug and is asserted: a clear that
    /// removes nothing still reports success and still moves the caret, so
    /// the field's focused text changes.
    #[test]
    fn a_clear_that_changes_nothing_still_moves_the_caret() {
        let mut list = multi_list(&FRUIT);
        set_index_selected(&mut list, 0, true);
        assert_eq!(list.focused_text(), "Apple");

        // Row 3 was never selected; clearing it is a no-op on the selection.
        assert!(set_index_selected(&mut list, 3, false));
        assert!(!is_index_selected(&list, 3));
        assert!(is_index_selected(&list, 0), "row 0 is untouched");
        assert_eq!(list.focused_text(), "Date", "but the caret moved");
    }

    /// A multi-select list's focused text follows the row last acted upon,
    /// not the selection's contents.
    #[test]
    fn focused_text_follows_the_last_row_acted_upon() {
        let mut list = multi_list(&FRUIT);
        set_index_selected(&mut list, 1, true);
        set_index_selected(&mut list, 2, true);
        set_index_selected(&mut list, 4, true);
        assert_eq!(list.focused_text(), "Elderberry");

        set_index_selected(&mut list, 4, false);
        set_index_selected(&mut list, 1, false);
        assert_eq!(list.focused_text(), "Banana");
    }

    /// A single-select list keeps one row; a multi-select one accumulates.
    #[test]
    fn multi_select_accumulates_and_single_select_does_not() {
        let mut single = single_list(&FRUIT);
        set_index_selected(&mut single, 0, true);
        set_index_selected(&mut single, 2, true);
        assert_eq!(single.selected.len(), 1);
        assert!(is_index_selected(&single, 2));

        let mut multi = multi_list(&FRUIT);
        set_index_selected(&mut multi, 0, true);
        set_index_selected(&mut multi, 2, true);
        assert_eq!(multi.selected.len(), 2);
        assert!(is_index_selected(&multi, 0));
        assert!(is_index_selected(&multi, 2));
    }

    /// Consecutive characters are independent jumps, not a growing prefix.
    #[test]
    fn type_ahead_jumps_rather_than_accumulating() {
        let mut combo = combo(&FRUIT);
        assert!(type_ahead(&mut combo, 'A'));
        assert_eq!(combo.focused_text(), "Apple");

        // A, then B, then C lands on Cherry — not on a row starting "ABC".
        type_ahead(&mut combo, 'A');
        type_ahead(&mut combo, 'B');
        type_ahead(&mut combo, 'C');
        assert_eq!(combo.focused_text(), "Cherry");

        type_ahead(&mut combo, 'A');
        type_ahead(&mut combo, 'B');
        assert_eq!(combo.focused_text(), "Banana");
    }

    #[test]
    fn type_ahead_ignores_case() {
        let mut combo = combo(&FRUIT);
        type_ahead(&mut combo, 'd');
        assert_eq!(combo.focused_text(), "Date");
    }

    /// The scan is circular: from the last row it wraps to the first.
    #[test]
    fn type_ahead_wraps_around() {
        let labels: Vec<String> = FRUIT.iter().map(|s| (*s).to_string()).collect();
        assert_eq!(find_next(&labels, 4, 'A'), Some(0));
        assert_eq!(find_next(&labels, 0, 'B'), Some(1));
    }

    /// Nothing matching returns the last row probed rather than failing,
    /// which is exactly what makes the jumps independent.
    #[test]
    fn an_unmatched_character_lands_on_the_last_row_probed() {
        let labels: Vec<String> = FRUIT.iter().map(|s| (*s).to_string()).collect();
        // No row starts with Z; the scan ends where it began.
        assert_eq!(find_next(&labels, 2, 'Z'), Some(2));
    }

    #[test]
    fn type_ahead_on_an_empty_field_does_nothing() {
        let mut empty = combo(&[]);
        assert!(!type_ahead(&mut empty, 'A'));
        assert_eq!(find_next(&[], 0, 'A'), None);
    }

    /// The stored value wins where value and index entries disagree.
    #[test]
    fn the_value_wins_over_the_index_entry() {
        let options: Vec<String> = FRUIT.iter().map(|s| (*s).to_string()).collect();

        let by_index = initial_selection(&options, &[], &[2, 3]);
        assert_eq!(by_index, BTreeSet::from([2, 3]));

        let by_value = initial_selection(&options, &["Apple".to_string()], &[]);
        assert_eq!(by_value, BTreeSet::from([0]));

        // Disagreeing: the value's answer is the one that counts.
        let conflicting = initial_selection(&options, &["Banana".to_string()], &[3, 4]);
        assert_eq!(conflicting, BTreeSet::from([1]));
    }

    #[test]
    fn an_out_of_range_index_entry_is_dropped() {
        let options: Vec<String> = FRUIT.iter().map(|s| (*s).to_string()).collect();
        assert_eq!(
            initial_selection(&options, &[], &[1, 99]),
            BTreeSet::from([1])
        );
    }

    /// A list scrolls only far enough to fill the box, so the selected row is
    /// not necessarily the top one.
    #[test]
    fn a_list_does_not_overscroll_past_its_last_full_page() {
        // Ten rows, three visible, the last row selected: the top row is 7,
        // not 9, because scrolling to 9 would leave the box short.
        assert_eq!(top_visible_for(10, 3, 9), 7);
        // A selection inside the range scrolls exactly to it.
        assert_eq!(top_visible_for(10, 3, 4), 4);
        // A list that fits needs no scrolling at all.
        assert_eq!(top_visible_for(3, 5, 2), 0);
        assert_eq!(top_visible_for(10, 0, 5), 0);
    }

    /// Shift-extends pivot on the anchor and do not move it, so successive
    /// ones all measure from the same row.
    #[test]
    fn a_range_selection_keeps_its_pivot() {
        let mut list = multi_list(&FRUIT);
        select_only(&mut list, 1);
        assert_eq!(list.anchor, Some(1));

        select_range_to(&mut list, 3);
        assert_eq!(list.selected, BTreeSet::from([1, 2, 3]));
        assert_eq!(list.anchor, Some(1), "the pivot did not move");

        // A second extend measures from the same pivot, not from row 3.
        select_range_to(&mut list, 2);
        assert_eq!(list.selected, BTreeSet::from([1, 2]));
    }

    /// A range that runs backwards from the anchor covers the same rows.
    #[test]
    fn a_backwards_range_selects_the_same_rows() {
        let mut list = multi_list(&FRUIT);
        select_only(&mut list, 3);
        select_range_to(&mut list, 1);
        assert_eq!(list.selected, BTreeSet::from([1, 2, 3]));
    }

    /// Toggling keeps the rest of the selection and *does* re-anchor, which
    /// is the difference from a range extend.
    #[test]
    fn toggling_keeps_the_rest_and_re_anchors() {
        let mut list = multi_list(&FRUIT);
        select_only(&mut list, 0);
        toggle_index(&mut list, 3);
        assert_eq!(list.selected, BTreeSet::from([0, 3]));
        assert_eq!(list.anchor, Some(3));

        toggle_index(&mut list, 3);
        assert_eq!(list.selected, BTreeSet::from([0]));
    }

    /// A single-select list ignores both gestures and just selects the row.
    #[test]
    fn a_single_select_list_ignores_the_modifiers() {
        let mut list = single_list(&FRUIT);
        select_only(&mut list, 0);
        select_range_to(&mut list, 3);
        assert_eq!(list.selected, BTreeSet::from([3]));

        toggle_index(&mut list, 1);
        assert_eq!(list.selected, BTreeSet::from([1]));
    }

    /// Arrow movement clamps at each end rather than wrapping.
    #[test]
    fn moving_the_selection_clamps_at_both_ends() {
        let mut list = single_list(&FRUIT);
        select_only(&mut list, 0);

        move_selection(&mut list, -1);
        assert!(is_index_selected(&list, 0), "clamped at the top");

        for _ in 0..10 {
            move_selection(&mut list, 1);
        }
        assert!(is_index_selected(&list, 4), "clamped at the bottom");
    }

    #[test]
    fn moving_an_empty_field_does_nothing() {
        let mut empty = single_list(&[]);
        assert!(!move_selection(&mut empty, 1));
    }

    /// A non-editable combo's text half is read-only but still present: it
    /// holds the text and supports selecting it, which is how a substring of
    /// a field the user cannot type into can still be selected.
    #[test]
    fn a_non_editable_combo_still_has_read_only_text() {
        let editable = combo_text_config(true, false);
        assert!(!editable.read_only);

        let fixed = combo_text_config(false, false);
        assert!(fixed.read_only);

        // A read-only field is read-only whether or not it is editable.
        assert!(combo_text_config(true, true).read_only);
    }

    #[test]
    fn a_combo_text_half_is_single_line_and_unlimited() {
        let config = combo_text_config(true, false);
        assert!(!config.multi_line);
        assert_eq!(config.max_len, None);
        assert!(config.undo_enabled);
    }
}