返回 CodeWhale
pending_input.rs
根目录 / vendor / codewhale-ratatui / src / components / pending_input.rs
1 //! Host-reported pending input above the composer.
2 //!
3 //! The host owns the queue, the turn and every mutation. This component owns
4 //! only what a person can see: caller items with an explicit status word and
5 //! mark, attached context with an explicit state, a compact queue summary and
6 //! the action metadata a host may dispatch. The kit never advances a status,
7 //! so nothing here can claim an item was sent, delivered or verified.
8
9 use std::borrow::Cow;
10
11 use ratatui::{
12 buffer::Buffer,
13 layout::Rect,
14 style::{Modifier, Style},
15 text::{Line, Span},
16 widgets::{Paragraph, Widget},
17 };
18
19 use unicode_segmentation::UnicodeSegmentation;
20
21 use crate::{Paint, Role, Theme, glyphs, text};
22
23 /// What the host reports about one pending item. The word and the mark are
24 /// the only claims; the kit never moves an item between states.
25 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26 pub enum PendingInputStatus {
27 /// Typed input captured for a later turn.
28 Queued,
29 /// A note the host will deliver into the running turn.
30 Steering,
31 /// The person is editing this item now.
32 Editing,
33 /// The host held this item.
34 Paused,
35 /// The host reports delivery is already under way.
36 InFlight,
37 }
38
39 const ACTIONS_SEND_EDIT_DROP: [PendingInputAction; 3] = [
40 PendingInputAction::SendNow,
41 PendingInputAction::Edit,
42 PendingInputAction::Drop,
43 ];
44 const ACTIONS_EDIT_DROP: [PendingInputAction; 2] =
45 [PendingInputAction::Edit, PendingInputAction::Drop];
46 const ACTIONS_SEND_DROP: [PendingInputAction; 2] =
47 [PendingInputAction::SendNow, PendingInputAction::Drop];
48 const ACTIONS_NONE: [PendingInputAction; 0] = [];
49
50 impl PendingInputStatus {
51 pub const ALL: [Self; 5] = [
52 Self::Queued,
53 Self::Steering,
54 Self::Editing,
55 Self::Paused,
56 Self::InFlight,
57 ];
58
59 /// The word shown for this status.
60 #[must_use]
61 pub const fn word(self) -> &'static str {
62 match self {
63 Self::Queued => "queued",
64 Self::Steering => "steering",
65 Self::Editing => "editing",
66 Self::Paused => "paused",
67 Self::InFlight => "in flight",
68 }
69 }
70
71 #[must_use]
72 pub const fn role(self) -> Role {
73 match self {
74 Self::Queued => Role::Accent,
75 Self::Steering => Role::Live,
76 Self::Editing => Role::Attention,
77 Self::Paused => Role::Attention,
78 Self::InFlight => Role::Muted,
79 }
80 }
81
82 /// The mark for this terminal; `theme.ascii()` never widens the line.
83 #[must_use]
84 pub fn glyph(self, theme: &Theme) -> &'static str {
85 let ascii = theme.ascii();
86 match self {
87 Self::Queued => {
88 if ascii {
89 "o"
90 } else {
91 glyphs::AVAILABLE
92 }
93 }
94 Self::Steering => {
95 if ascii {
96 "+"
97 } else {
98 "↳"
99 }
100 }
101 Self::Editing => {
102 if ascii {
103 "e"
104 } else {
105 "✎"
106 }
107 }
108 Self::Paused => {
109 if ascii {
110 "="
111 } else {
112 glyphs::PAUSED
113 }
114 }
115 Self::InFlight => {
116 if ascii {
117 ">"
118 } else {
119 glyphs::CURRENT
120 }
121 }
122 }
123 }
124
125 /// The actions a host may dispatch for an item in this status. The kit
126 /// emits them as metadata only; it never performs one.
127 #[must_use]
128 pub const fn actions(self) -> &'static [PendingInputAction] {
129 match self {
130 Self::Queued | Self::Paused => &ACTIONS_SEND_EDIT_DROP,
131 Self::Steering => &ACTIONS_EDIT_DROP,
132 Self::Editing => &ACTIONS_SEND_DROP,
133 Self::InFlight => &ACTIONS_NONE,
134 }
135 }
136 }
137
138 /// One action a host may offer beside a pending item. The kit paints the
139 /// word and hands the choice back; mutation stays with the host.
140 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
141 pub enum PendingInputAction {
142 SendNow,
143 Edit,
144 Drop,
145 }
146
147 impl PendingInputAction {
148 pub const ALL: [Self; 3] = [Self::SendNow, Self::Edit, Self::Drop];
149
150 #[must_use]
151 pub const fn word(self) -> &'static str {
152 match self {
153 Self::SendNow => "Send now",
154 Self::Edit => "Edit",
155 Self::Drop => "Drop",
156 }
157 }
158
159 #[must_use]
160 pub const fn role(self) -> Role {
161 match self {
162 Self::SendNow => Role::Accent,
163 Self::Edit => Role::Foreground,
164 Self::Drop => Role::Danger,
165 }
166 }
167 }
168
169 /// One queued, steering, editing, paused or in-flight item.
170 ///
171 /// `content` is display text; it may hold newlines and controls, and the
172 /// component sanitizes and flattens it. `id` is the stable caller key used
173 /// for selection and for `actions_for`.
174 #[derive(Clone, Debug)]
175 pub struct PendingInputItem<'a> {
176 pub id: Cow<'a, str>,
177 pub label: Cow<'a, str>,
178 pub content: Cow<'a, str>,
179 pub status: PendingInputStatus,
180 pub status_word: Option<Cow<'a, str>>,
181 }
182
183 impl<'a> PendingInputItem<'a> {
184 #[must_use]
185 pub fn new(
186 id: impl Into<Cow<'a, str>>,
187 content: impl Into<Cow<'a, str>>,
188 status: PendingInputStatus,
189 ) -> Self {
190 Self {
191 id: id.into(),
192 label: Cow::Borrowed(""),
193 content: content.into(),
194 status,
195 status_word: None,
196 }
197 }
198
199 #[must_use]
200 pub fn label(mut self, label: impl Into<Cow<'a, str>>) -> Self {
201 self.label = label.into();
202 self
203 }
204
205 /// A caller-localized status word, replacing the default one.
206 #[must_use]
207 pub fn status_word(mut self, word: impl Into<Cow<'a, str>>) -> Self {
208 self.status_word = Some(word.into());
209 self
210 }
211
212 #[must_use]
213 pub fn word(&self) -> &str {
214 self.status_word
215 .as_deref()
216 .unwrap_or_else(|| self.status.word())
217 }
218
219 #[must_use]
220 pub fn actions(&self) -> &'static [PendingInputAction] {
221 self.status.actions()
222 }
223 }
224
225 /// What the host reports about one attached context item. `Unconfirmed` is
226 /// deliberately not `Included`: unconfirmed context is never shown as sent.
227 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
228 pub enum ContextPreviewState {
229 /// Known to be included with the message.
230 Included,
231 /// Attached, but not confirmed by the host.
232 Unconfirmed,
233 /// Attached and offered for removal.
234 Removable,
235 }
236
237 impl ContextPreviewState {
238 pub const ALL: [Self; 3] = [Self::Included, Self::Unconfirmed, Self::Removable];
239
240 #[must_use]
241 pub const fn word(self) -> &'static str {
242 match self {
243 Self::Included => "included",
244 Self::Unconfirmed => "unconfirmed",
245 Self::Removable => "removable",
246 }
247 }
248
249 #[must_use]
250 pub const fn role(self) -> Role {
251 match self {
252 Self::Included => Role::Live,
253 Self::Unconfirmed => Role::Attention,
254 Self::Removable => Role::Muted,
255 }
256 }
257
258 #[must_use]
259 pub fn glyph(self, theme: &Theme) -> &'static str {
260 let ascii = theme.ascii();
261 match self {
262 Self::Included => {
263 if ascii {
264 "+"
265 } else {
266 glyphs::DONE
267 }
268 }
269 Self::Unconfirmed => {
270 if ascii {
271 "?"
272 } else {
273 glyphs::ATTENTION
274 }
275 }
276 Self::Removable => {
277 if ascii {
278 "-"
279 } else {
280 glyphs::NEUTRAL
281 }
282 }
283 }
284 }
285 }
286
287 /// One attached context item, with its own reported state.
288 #[derive(Clone, Debug)]
289 pub struct ContextPreviewItem<'a> {
290 pub id: Cow<'a, str>,
291 pub label: Cow<'a, str>,
292 pub detail: Option<Cow<'a, str>>,
293 pub state: ContextPreviewState,
294 }
295
296 impl<'a> ContextPreviewItem<'a> {
297 #[must_use]
298 pub fn new(
299 id: impl Into<Cow<'a, str>>,
300 label: impl Into<Cow<'a, str>>,
301 state: ContextPreviewState,
302 ) -> Self {
303 Self {
304 id: id.into(),
305 label: label.into(),
306 detail: None,
307 state,
308 }
309 }
310
311 #[must_use]
312 pub fn detail(mut self, detail: impl Into<Cow<'a, str>>) -> Self {
313 self.detail = Some(detail.into());
314 self
315 }
316
317 #[must_use]
318 pub fn word(&self) -> &str {
319 self.state.word()
320 }
321
322 /// Construct a pasted-text context chip (`Pasted text · N lines` / `1 line`).
323 #[must_use]
324 pub fn pasted_text(
325 id: impl Into<Cow<'a, str>>,
326 lines: usize,
327 state: ContextPreviewState,
328 ) -> Self {
329 Self::new(
330 id,
331 format!("Pasted text · {}", pasted_line_count(lines)),
332 state,
333 )
334 }
335 }
336
337 fn pasted_line_count(lines: usize) -> String {
338 if lines == 1 {
339 "1 line".to_owned()
340 } else {
341 format!("{lines} lines")
342 }
343 }
344
345 #[derive(Clone)]
346 struct PaintedRow {
347 line: Line<'static>,
348 selected: bool,
349 }
350
351 // One geometry and paint authority for the generic list and native card.
352 struct PendingPlan {
353 width: u16,
354 max_rows: u16,
355 rows: Vec<PaintedRow>,
356 one_row: Option<PaintedRow>,
357 tail: Option<PendingTail>,
358 }
359
360 struct PendingTail {
361 hint: String,
362 omitted: String,
363 hint_style: Style,
364 omitted_style: Style,
365 }
366
367 impl PendingPlan {
368 fn new(width: u16, max_rows: u16) -> Self {
369 Self {
370 width,
371 max_rows,
372 rows: Vec::new(),
373 one_row: None,
374 tail: None,
375 }
376 }
377 fn push(&mut self, line: Line<'static>) {
378 self.rows.push(PaintedRow {
379 line,
380 selected: false,
381 });
382 }
383 fn height(&self) -> u16 {
384 if self.width < 4 {
385 return 0;
386 }
387 u16::try_from(
388 self.rows
389 .len()
390 .saturating_add(usize::from(self.tail.is_some())),
391 )
392 .unwrap_or(u16::MAX)
393 .min(self.max_rows)
394 }
395 fn shown(&self, height: u16) -> Vec<PaintedRow> {
396 let height = height.min(self.max_rows);
397 if self.width < 4 || height == 0 || self.rows.is_empty() {
398 return Vec::new();
399 }
400 if height == 1
401 && let Some(row) = &self.one_row
402 {
403 return vec![row.clone()];
404 }
405 let keep = usize::from(height).saturating_sub(usize::from(self.tail.is_some()));
406 let mut out: Vec<_> = self.rows.iter().take(keep).cloned().collect();
407 if let Some(tail) = &self.tail {
408 let hidden = self.rows.len().saturating_sub(keep);
409 let mut spans = Vec::new();
410 if hidden > 0 {
411 spans.push(Span::styled(
412 format!("+{hidden} {} ", tail.omitted),
413 tail.omitted_style,
414 ));
415 }
416 spans.push(Span::styled(tail.hint.clone(), tail.hint_style));
417 out.push(PaintedRow {
418 line: Line::from(spans),
419 selected: false,
420 });
421 }
422 out
423 }
424 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
425 if area.is_empty() {
426 return;
427 }
428 let shown = self.shown(area.height);
429 for (index, painted) in shown.iter().enumerate() {
430 let rect = Rect::new(
431 area.x,
432 area.y
433 .saturating_add(u16::try_from(index).unwrap_or(u16::MAX)),
434 area.width,
435 1,
436 );
437 if painted.selected {
438 buf.set_style(rect, theme.bg(Role::Selected));
439 }
440 }
441 // Keep native Ratatui glyph painting, including caller-owned styles
442 // on wide-character continuation cells, in one shared paint path.
443 Paragraph::new(shown.into_iter().map(|row| row.line).collect::<Vec<_>>()).render(area, buf);
444 }
445 }
446
447 /// Localized copy for the native composer preview. Templates use `{count}`
448 /// and `{number}`; key labels are resolved by the host before being supplied.
449 #[derive(Clone, Debug)]
450 pub struct PendingCardWords<'a> {
451 pub context_header: Cow<'a, str>,
452 pub inputs_header: Cow<'a, str>,
453 pub sending_prefix: Cow<'a, str>,
454 pub editing_prefix: Cow<'a, str>,
455 pub editing_restore: Cow<'a, str>,
456 pub queued_prefix: Cow<'a, str>,
457 pub queued_one_prefix: Cow<'a, str>,
458 pub queued_many_prefix: Cow<'a, str>,
459 pub queued_controls: Cow<'a, str>,
460 pub compact_controls: Cow<'a, str>,
461 pub removable: Cow<'a, str>,
462 pub selected_remove: Cow<'a, str>,
463 }
464
465 impl Default for PendingCardWords<'_> {
466 fn default() -> Self {
467 Self {
468 context_header: "Context for next send".into(),
469 inputs_header: "Pending inputs".into(),
470 sending_prefix: "Sending into this turn: ".into(),
471 editing_prefix: "Editing follow-up: ".into(),
472 editing_restore: "Esc restores the queued follow-up".into(),
473 queued_prefix: "Queued follow-up #{number}: ".into(),
474 queued_one_prefix: "Queued #1: ".into(),
475 queued_many_prefix: "Queued {count}; next: ".into(),
476 queued_controls: "Enter send now · ↑ edit".into(),
477 compact_controls: "Enter send now · ↑ edit · /queue drop 1".into(),
478 removable: "removable".into(),
479 selected_remove: "Backspace/Delete removes".into(),
480 }
481 }
482 }
483
484 /// Inclusion, removability and keyboard selection are independent host facts.
485 /// None of them advances a queue or claims delivery.
486 #[derive(Clone, Debug)]
487 pub struct PendingCardContext<'a> {
488 pub kind: Cow<'a, str>,
489 pub label: Cow<'a, str>,
490 pub detail: Option<Cow<'a, str>>,
491 pub included: bool,
492 pub removable: bool,
493 pub selected: bool,
494 }
495
496 impl PendingCardContext<'_> {
497 /// Construct a pasted-text attachment row (`Pasted text · N lines` / `1 line`).
498 #[must_use]
499 pub fn pasted_text(lines: usize, removable: bool) -> Self {
500 Self {
501 kind: Cow::Borrowed("paste"),
502 label: Cow::Borrowed("Pasted text"),
503 detail: Some(Cow::Owned(pasted_line_count(lines))),
504 included: true,
505 removable,
506 selected: false,
507 }
508 }
509 }
510
511 /// The native card's five concrete style slots. Defaults come from `Theme`;
512 /// a host retaining its palette grammar may provide these exact styles.
513 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
514 pub struct PendingCardStyles {
515 pub input: Style,
516 pub warning: Style,
517 pub context_muted: Style,
518 pub context_label: Style,
519 pub selected: Style,
520 }
521
522 impl PendingCardStyles {
523 #[must_use]
524 pub fn for_theme(theme: &Theme) -> Self {
525 Self {
526 input: theme.fg(Role::Dim).add_modifier(Modifier::DIM),
527 warning: theme.fg(Role::Attention),
528 context_muted: theme.fg(Role::Muted),
529 context_label: theme.fg(Role::Foreground),
530 selected: theme.fg(Role::Foreground).patch(theme.bg(Role::Selected)),
531 }
532 }
533 }
534
535 /// Native pending input above a composer, over caller-owned facts and copy.
536 /// The same measured row plan as `PendingInputPreview` owns height, clipping,
537 /// the one-row action fallback and painting. There is no queue or request state.
538 #[derive(Clone, Debug)]
539 pub struct PendingCard<'a> {
540 pub context: Vec<PendingCardContext<'a>>,
541 pub sending: Vec<Cow<'a, str>>,
542 pub queued: Vec<Cow<'a, str>>,
543 pub editing: Option<Cow<'a, str>>,
544 /// Already-localized notices that precede context and input, including
545 /// hidden child requests. A notice always outranks a queue action fallback.
546 pub priority_rows: Vec<Cow<'a, str>>,
547 pub words: PendingCardWords<'a>,
548 pub styles: Option<PendingCardStyles>,
549 }
550
551 impl<'a> PendingCard<'a> {
552 #[must_use]
553 pub fn new(words: PendingCardWords<'a>) -> Self {
554 Self {
555 context: Vec::new(),
556 sending: Vec::new(),
557 queued: Vec::new(),
558 editing: None,
559 priority_rows: Vec::new(),
560 words,
561 styles: None,
562 }
563 }
564
565 fn plan(&self, width: u16, theme: &Theme) -> PendingPlan {
566 let mut plan = PendingPlan::new(width, u16::MAX);
567 if width < 4 {
568 return plan;
569 }
570 let styles = self
571 .styles
572 .unwrap_or_else(|| PendingCardStyles::for_theme(theme));
573 for notice in &self.priority_rows {
574 plan.push(Line::from(Span::styled(
575 card_clip(&card_safe(notice), usize::from(width), theme.ascii()),
576 styles.warning,
577 )));
578 }
579 let queued_only = self.context.is_empty()
580 && self.sending.is_empty()
581 && self.editing.is_none()
582 && !self.queued.is_empty();
583 if queued_only {
584 let prefix = if self.queued.len() == 1 {
585 card_copy(&self.words.queued_one_prefix, theme)
586 } else {
587 card_copy(&self.words.queued_many_prefix, theme)
588 .replace("{count}", &self.queued.len().to_string())
589 };
590 let next = card_safe(&self.queued[0].replace('\n', " "));
591 plan.push(Line::from(Span::styled(
592 card_clip(
593 &format!("{prefix}{next}"),
594 usize::from(width),
595 theme.ascii(),
596 ),
597 styles.input.add_modifier(Modifier::ITALIC),
598 )));
599 let controls = Line::from(Span::styled(
600 card_clip(
601 &card_copy(&self.words.compact_controls, theme),
602 usize::from(width),
603 theme.ascii(),
604 ),
605 styles.input,
606 ));
607 if self.priority_rows.is_empty() {
608 plan.one_row = Some(PaintedRow {
609 line: controls.clone(),
610 selected: false,
611 });
612 }
613 plan.push(controls);
614 return plan;
615 }
616 let header_style = self.styles.map(|s| s.context_muted);
617 if !self.context.is_empty() {
618 plan.push(card_header(&self.words.context_header, header_style, theme));
619 for item in &self.context {
620 let prefix_style = if item.selected {
621 styles.selected.add_modifier(Modifier::BOLD)
622 } else if item.included {
623 styles.context_muted
624 } else {
625 styles.warning
626 };
627 let body_style = if item.selected {
628 styles.selected
629 } else if item.included {
630 styles.context_label
631 } else {
632 styles.context_muted
633 };
634 let mut body = format!("[{}] {}", card_safe(&item.kind), card_safe(&item.label));
635 let separator = if theme.ascii() { " . " } else { " · " };
636 if let Some(detail) = item
637 .detail
638 .as_deref()
639 .filter(|value| !value.trim().is_empty())
640 {
641 body.push_str(separator);
642 body.push_str(&card_safe(detail));
643 }
644 let action = if item.selected {
645 Some(&self.words.selected_remove)
646 } else if item.removable {
647 Some(&self.words.removable)
648 } else {
649 None
650 };
651 if let Some(action) = action {
652 body.push_str(separator);
653 body.push_str(&card_copy(action, theme));
654 }
655 for (index, segment) in
656 card_wrap(&body, usize::from(width.saturating_sub(4).max(1)))
657 .into_iter()
658 .enumerate()
659 {
660 let prefix = if index > 0 {
661 " "
662 } else if item.selected {
663 if theme.ascii() { " > " } else { " ▸ " }
664 } else if theme.ascii() {
665 " + "
666 } else {
667 " ↳ "
668 };
669 plan.push(Line::from(vec![
670 Span::styled(prefix, prefix_style),
671 Span::styled(segment, body_style),
672 ]));
673 }
674 }
675 }
676 let has_inputs =
677 !self.sending.is_empty() || !self.queued.is_empty() || self.editing.is_some();
678 if has_inputs {
679 if !self.context.is_empty() {
680 plan.push(Line::from(""));
681 }
682 plan.push(card_header(&self.words.inputs_header, header_style, theme));
683 for value in &self.sending {
684 card_item(
685 &mut plan,
686 value,
687 &card_copy(&self.words.sending_prefix, theme),
688 styles.input,
689 theme,
690 );
691 }
692 if let Some(value) = &self.editing {
693 card_item(
694 &mut plan,
695 value,
696 &card_copy(&self.words.editing_prefix, theme),
697 styles.input.add_modifier(Modifier::ITALIC),
698 theme,
699 );
700 plan.push(Line::from(Span::styled(
701 card_clip(
702 &card_copy(&self.words.editing_restore, theme),
703 usize::from(width),
704 theme.ascii(),
705 ),
706 styles.input,
707 )));
708 }
709 for (index, value) in self.queued.iter().enumerate() {
710 let prefix = card_copy(&self.words.queued_prefix, theme)
711 .replace("{number}", &(index + 1).to_string());
712 card_item(
713 &mut plan,
714 value,
715 &prefix,
716 styles.input.add_modifier(Modifier::ITALIC),
717 theme,
718 );
719 }
720 if !self.queued.is_empty() {
721 plan.push(Line::from(Span::styled(
722 card_clip(
723 &card_copy(&self.words.queued_controls, theme),
724 usize::from(width),
725 theme.ascii(),
726 ),
727 styles.input,
728 )));
729 }
730 }
731 plan
732 }
733
734 #[must_use]
735 pub fn height(&self, width: u16, theme: &Theme) -> u16 {
736 self.plan(width, theme).height()
737 }
738 }
739
740 impl Paint for PendingCard<'_> {
741 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
742 let area = area.intersection(buf.area);
743 self.plan(area.width, theme).paint(area, buf, theme);
744 }
745 fn height(&self, width: u16, theme: &Theme) -> u16 {
746 self.plan(width, theme).height()
747 }
748 }
749
750 fn card_safe(value: &str) -> String {
751 // Newlines are handled by card_item. Sanitize once before both measuring
752 // and painting; invisible control/bidi bytes do not create phantom rows.
753 text::display_safe(value).into_owned()
754 }
755
756 fn card_copy(value: &str, theme: &Theme) -> String {
757 let value = card_safe(value);
758 if !theme.ascii() {
759 return value;
760 }
761 value
762 .chars()
763 .map(|c| {
764 glyphs::ascii_fallback(c.encode_utf8(&mut [0; 4]))
765 .map_or_else(|| c.to_string(), str::to_owned)
766 })
767 .collect()
768 }
769
770 fn card_header(value: &str, style: Option<Style>, theme: &Theme) -> Line<'static> {
771 let text = format!(
772 "{} {}",
773 glyphs::pick("•", theme.ascii()),
774 card_copy(value, theme)
775 );
776 match style {
777 Some(style) => Line::from(Span::styled(text, style)),
778 None => Line::from(text),
779 }
780 }
781
782 fn card_clip(value: &str, width: usize, ascii: bool) -> String {
783 if text::width(value) <= width {
784 return value.to_owned();
785 }
786 let ellipsis = if ascii && width >= 4 {
787 "..."
788 } else if ascii {
789 "."
790 } else {
791 "…"
792 };
793 let budget = width.saturating_sub(text::width(ellipsis));
794 let mut out = String::new();
795 let mut cells = 0;
796 for g in value.graphemes(true) {
797 let next = text::width(g);
798 if cells + next > budget {
799 break;
800 }
801 out.push_str(g);
802 cells += next;
803 }
804 if width > 0 {
805 out.push_str(ellipsis);
806 }
807 out
808 }
809
810 fn card_item(plan: &mut PendingPlan, value: &str, prefix: &str, style: Style, theme: &Theme) {
811 let indent = " ".repeat(card_body_width(prefix));
812 let body_width = usize::from(plan.width)
813 .saturating_sub(card_body_width(prefix))
814 .max(1);
815 let mut produced = 0;
816 for (paragraph_index, paragraph) in value.split('\n').enumerate() {
817 for (index, segment) in card_wrap(&card_safe(paragraph), body_width)
818 .into_iter()
819 .enumerate()
820 {
821 if produced == 3 {
822 plan.push(Line::from(Span::styled(
823 format!("{indent}{}", if theme.ascii() { "..." } else { "…" }),
824 style,
825 )));
826 return;
827 }
828 let leader = if paragraph_index == 0 && index == 0 {
829 prefix
830 } else {
831 &indent
832 };
833 plan.push(Line::from(Span::styled(
834 format!("{leader}{segment}"),
835 style,
836 )));
837 produced += 1;
838 }
839 }
840 }
841
842 fn card_wrap(value: &str, width: usize) -> Vec<String> {
843 if value.is_empty() {
844 return vec![String::new()];
845 }
846 let mut out = Vec::new();
847 let mut current = String::new();
848 let mut cells = 0;
849 for word in value.split_inclusive(' ') {
850 let next = card_body_width(word);
851 if cells + next > width && !current.is_empty() {
852 out.push(std::mem::take(&mut current));
853 cells = 0;
854 }
855 if next > width {
856 // Preserve a long URL/token as one clipped row. Never split it
857 // into several misleading overflow fragments.
858 out.push(word.trim_end().to_owned());
859 } else {
860 current.push_str(word);
861 cells += next;
862 }
863 }
864 if !current.is_empty() {
865 out.push(current);
866 }
867 out
868 }
869
870 fn card_body_width(value: &str) -> usize {
871 // Native composer wrapping keeps its existing terminal contract for
872 // circled numbers and keycaps without a variation selector. Compact
873 // summaries still use ordinary Ratatui Unicode width when truncated.
874 value
875 .graphemes(true)
876 .map(|grapheme| {
877 if grapheme.contains('\u{20e3}') {
878 return 2;
879 }
880 if let Some(c) = grapheme.chars().next()
881 && c.len_utf8() == grapheme.len()
882 && matches!(c, '\u{2460}'..='\u{24ff}' | '\u{2776}'..='\u{2793}' | '\u{3248}'..='\u{324f}')
883 {
884 return 2;
885 }
886 text::width(grapheme)
887 })
888 .sum()
889 }
890
891 /// Pending items and attached context over caller-owned facts.
892 ///
893 /// The component holds borrowed items and an optional selected ID. It paints
894 /// a compact queue summary, the context row, one row per item, and an action
895 /// hint built from the union of the item actions. At one row of height the
896 /// summary and the action words share the row so an action stays
897 /// discoverable. An empty preview asks for zero rows.
898 #[derive(Clone, Debug)]
899 pub struct PendingInputPreview<'a> {
900 pub items: Vec<PendingInputItem<'a>>,
901 pub context: Vec<ContextPreviewItem<'a>>,
902 pub selected: Option<Cow<'a, str>>,
903 pub context_label: Cow<'a, str>,
904 pub hint: Cow<'a, str>,
905 pub omitted_label: Cow<'a, str>,
906 pub max_rows: u16,
907 }
908
909 impl<'a> PendingInputPreview<'a> {
910 #[must_use]
911 pub fn new(items: Vec<PendingInputItem<'a>>, context: Vec<ContextPreviewItem<'a>>) -> Self {
912 Self {
913 items,
914 context,
915 selected: None,
916 context_label: Cow::Borrowed("Context"),
917 hint: Cow::Borrowed(""),
918 omitted_label: Cow::Borrowed("more"),
919 max_rows: 8,
920 }
921 }
922
923 /// Select an item by its stable caller ID.
924 #[must_use]
925 pub fn selected(mut self, id: impl Into<Cow<'a, str>>) -> Self {
926 self.selected = Some(id.into());
927 self
928 }
929
930 #[must_use]
931 pub fn context_label(mut self, label: impl Into<Cow<'a, str>>) -> Self {
932 self.context_label = label.into();
933 self
934 }
935
936 /// Replace the action hint. Empty builds one from the item actions.
937 #[must_use]
938 pub fn hint(mut self, hint: impl Into<Cow<'a, str>>) -> Self {
939 self.hint = hint.into();
940 self
941 }
942
943 #[must_use]
944 pub fn omitted_label(mut self, label: impl Into<Cow<'a, str>>) -> Self {
945 self.omitted_label = label.into();
946 self
947 }
948
949 #[must_use]
950 pub fn max_rows(mut self, rows: u16) -> Self {
951 self.max_rows = rows;
952 self
953 }
954
955 #[must_use]
956 pub fn is_empty(&self) -> bool {
957 self.items.is_empty() && self.context.is_empty()
958 }
959
960 #[must_use]
961 pub fn pending_count(&self) -> usize {
962 self.items.len()
963 }
964
965 #[must_use]
966 pub fn selected_index(&self) -> Option<usize> {
967 let selected = self.selected.as_deref()?;
968 self.items.iter().position(|item| &*item.id == selected)
969 }
970
971 /// The union of the actions the items report, in `Send now`, `Edit`,
972 /// `Drop` order. Metadata only; the host dispatches.
973 #[must_use]
974 pub fn actions(&self) -> Vec<PendingInputAction> {
975 PendingInputAction::ALL
976 .into_iter()
977 .filter(|action| {
978 self.items
979 .iter()
980 .any(|item| item.actions().contains(action))
981 })
982 .collect()
983 }
984
985 /// The actions for one caller ID, or `None` when no item has that ID.
986 #[must_use]
987 pub fn actions_for(&self, id: &str) -> Option<&'static [PendingInputAction]> {
988 self.items
989 .iter()
990 .find(|item| &*item.id == id)
991 .map(PendingInputItem::actions)
992 }
993
994 /// Rows this preview wants at `width`. Empty input asks for zero.
995 #[must_use]
996 pub fn height(&self, width: u16, theme: &Theme) -> u16 {
997 self.plan(width, theme).height()
998 }
999
1000 fn separator(theme: &Theme) -> &'static str {
1001 if theme.ascii() { " / " } else { " · " }
1002 }
1003
1004 fn hint_text(&self, _theme: &Theme) -> String {
1005 if !self.hint.is_empty() {
1006 return text::display_safe(&self.hint).into_owned();
1007 }
1008 self.actions()
1009 .iter()
1010 .map(|action| action.word())
1011 .collect::<Vec<_>>()
1012 .join(" / ")
1013 }
1014
1015 fn summary_text(&self, theme: &Theme) -> String {
1016 let mut parts = Vec::new();
1017 for status in PendingInputStatus::ALL {
1018 let count = self
1019 .items
1020 .iter()
1021 .filter(|item| item.status == status)
1022 .count();
1023 if count > 0 {
1024 parts.push(format!("{count} {}", status.word()));
1025 }
1026 }
1027 if parts.is_empty() && !self.context.is_empty() {
1028 parts.push(format!(
1029 "{} {}",
1030 self.context.len(),
1031 text::display_safe(&self.context_label)
1032 ));
1033 }
1034 parts.join(Self::separator(theme))
1035 }
1036
1037 fn summary_line(&self, theme: &Theme) -> Line<'static> {
1038 let mut spans = Vec::new();
1039 let separator = Self::separator(theme);
1040 let mut first = true;
1041 for status in PendingInputStatus::ALL {
1042 let count = self
1043 .items
1044 .iter()
1045 .filter(|item| item.status == status)
1046 .count();
1047 if count == 0 {
1048 continue;
1049 }
1050 if !first {
1051 spans.push(Span::styled(separator, theme.fg(Role::BorderStrong)));
1052 }
1053 spans.push(Span::styled(
1054 format!("{count} {}", status.word()),
1055 theme.fg(status.role()),
1056 ));
1057 first = false;
1058 }
1059 if first {
1060 spans.push(Span::styled(
1061 format!(
1062 "{} {}",
1063 self.context.len(),
1064 text::display_safe(&self.context_label)
1065 ),
1066 theme.fg(Role::Muted),
1067 ));
1068 }
1069 Line::from(spans)
1070 }
1071
1072 fn context_line(&self, item: &ContextPreviewItem<'_>, theme: &Theme) -> Line<'static> {
1073 let mut spans = vec![
1074 Span::styled(item.state.glyph(theme), theme.fg(item.state.role())),
1075 Span::raw(" "),
1076 Span::styled(item.state.word(), theme.fg(item.state.role())),
1077 Span::raw(" / "),
1078 Span::styled(card_copy(&item.label, theme), theme.fg(Role::Foreground)),
1079 ];
1080 if let Some(detail) = &item.detail {
1081 spans.push(Span::styled(
1082 format!(" ({})", text::display_safe(detail)),
1083 theme.fg(Role::Muted),
1084 ));
1085 }
1086 Line::from(spans)
1087 }
1088
1089 fn item_line(&self, index: usize, theme: &Theme) -> Line<'static> {
1090 let item = &self.items[index];
1091 let selected = self.selected.as_deref() == Some(&*item.id);
1092 let marker = if selected {
1093 if theme.ascii() { "> " } else { "▸ " }
1094 } else {
1095 " "
1096 };
1097 let mut spans = vec![
1098 Span::styled(marker, theme.fg(Role::Accent)),
1099 Span::styled(item.status.glyph(theme), theme.fg(item.status.role())),
1100 Span::raw(" "),
1101 Span::styled(
1102 text::display_safe(item.word()).into_owned(),
1103 theme.fg(item.status.role()).add_modifier(Modifier::BOLD),
1104 ),
1105 Span::styled(": ", theme.fg(Role::BorderStrong)),
1106 ];
1107 if !item.label.is_empty() {
1108 spans.push(Span::styled(
1109 format!("{} ", text::display_safe(&item.label)),
1110 theme.fg(Role::Muted),
1111 ));
1112 }
1113 spans.push(Span::styled(
1114 one_line(&item.content),
1115 theme.fg(Role::Foreground),
1116 ));
1117 if selected {
1118 let actions = item.actions();
1119 if !actions.is_empty() {
1120 spans.push(Span::raw(" "));
1121 for (position, action) in actions.iter().enumerate() {
1122 if position > 0 {
1123 spans.push(Span::styled(" / ", theme.fg(Role::BorderStrong)));
1124 }
1125 spans.push(Span::styled(action.word(), theme.fg(action.role())));
1126 }
1127 }
1128 }
1129 Line::from(spans)
1130 }
1131
1132 fn single_line(&self, width: usize, theme: &Theme) -> Line<'static> {
1133 let ascii = theme.ascii();
1134 let hint = self.hint_text(theme);
1135 let summary = self.summary_text(theme);
1136 let separator = Self::separator(theme);
1137 let shown = if hint.is_empty() {
1138 text::truncate_words(&summary, width, ascii).into_owned()
1139 } else {
1140 let full = format!("{summary}{separator}{hint}");
1141 let short = format!(
1142 "{} pending{separator}{hint}",
1143 self.items.len() + self.context.len()
1144 );
1145 if text::width(&full) <= width {
1146 full
1147 } else if text::width(&short) <= width {
1148 short
1149 } else {
1150 text::truncate_words(&hint, width, ascii).into_owned()
1151 }
1152 };
1153 Line::from(Span::styled(shown, theme.fg(Role::Foreground)))
1154 }
1155
1156 fn plan(&self, width: u16, theme: &Theme) -> PendingPlan {
1157 let mut plan = PendingPlan::new(width, self.max_rows);
1158 if width < 4 || self.is_empty() {
1159 return plan;
1160 }
1161 plan.one_row = Some(PaintedRow {
1162 line: self.single_line(usize::from(width), theme),
1163 selected: false,
1164 });
1165 plan.push(self.summary_line(theme));
1166 let selected = self.selected_index();
1167 if let Some(index) = selected {
1168 plan.rows.push(PaintedRow {
1169 line: self.item_line(index, theme),
1170 selected: true,
1171 });
1172 }
1173 for item in &self.context {
1174 plan.push(self.context_line(item, theme));
1175 }
1176 for (index, _) in self.items.iter().enumerate() {
1177 if selected != Some(index) {
1178 plan.push(self.item_line(index, theme));
1179 }
1180 }
1181 let hint = self.hint_text(theme);
1182 if !hint.is_empty() {
1183 plan.tail = Some(PendingTail {
1184 hint,
1185 omitted: text::display_safe(&self.omitted_label).into_owned(),
1186 hint_style: theme.fg(Role::Accent),
1187 omitted_style: theme.fg(Role::Muted),
1188 });
1189 }
1190 plan
1191 }
1192 }
1193
1194 fn one_line(value: &str) -> String {
1195 text::display_safe(&value.replace(['\n', '\r', '\t'], " ")).into_owned()
1196 }
1197
1198 impl Paint for PendingInputPreview<'_> {
1199 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
1200 let area = area.intersection(buf.area);
1201 self.plan(area.width, theme).paint(area, buf, theme);
1202 }
1203 fn height(&self, width: u16, theme: &Theme) -> u16 {
1204 self.plan(width, theme).height()
1205 }
1206 }
1207
1207 lines RUST