返回 CodeWhale
search_consent.rs
根目录 / crates / tui / src / tui / views / search_consent.rs
1 use std::cell::RefCell;
2 use std::time::{Duration, Instant};
3
4 use crossterm::event::{
5 KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
6 };
7 use ratatui::{
8 buffer::Buffer,
9 layout::{Position, Rect},
10 style::{Modifier, Style},
11 text::{Line, Span},
12 widgets::{Paragraph, Widget},
13 };
14 use serde_json::Value;
15 use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
16
17 use crate::tui::approval::{ENTER_ARMING_DELAY, ENTER_QUIET_GAP, ReviewDecision};
18 use crate::tui::views::{
19 ActionHint, ModalKind, ModalView, SurfaceFrame, ViewAction, ViewEvent, action_footer_lines,
20 active_modal_accent_color, render_modal_footer, render_rounded_modal,
21 };
22 use codewhale_engine::tools::web::consent::{
23 CONSENT_MARKER_KEY, CONSENT_MARKER_VERSION, is_consent_approval_key,
24 };
25 use codewhale_localization::{Locale, MessageId, tr};
26 use codewhale_palette as palette;
27 use codewhale_runtime::config::{SEARCH_PROVIDER_ANY, SearchProviderOption};
28 use codewhale_tui_kit::menu_style;
29
30 const MAX_VISIBLE_PROVIDERS: usize = 6;
31
32 #[derive(Debug, Clone, PartialEq, Eq)]
33 pub struct SearchConsentRequest {
34 pub tool_id: String,
35 pub tool_name: String,
36 pub approval_key: String,
37 pub providers: Vec<SearchProviderOption>,
38 pub selected: usize,
39 }
40
41 impl SearchConsentRequest {
42 #[must_use]
43 pub fn from_approval(
44 tool_id: &str,
45 tool_name: &str,
46 approval_key: &str,
47 input: &Value,
48 ) -> Option<Self> {
49 if !is_consent_approval_key(approval_key) {
50 return None;
51 }
52 let marker = input.get(CONSENT_MARKER_KEY)?;
53 let version = marker.get("version").and_then(Value::as_u64)?;
54 if version == 0 || version > CONSENT_MARKER_VERSION {
55 return None;
56 }
57 let providers: Vec<SearchProviderOption> =
58 serde_json::from_value(marker.get("providers")?.clone()).ok()?;
59 if providers.is_empty() {
60 return None;
61 }
62 let selected_id = marker
63 .get("selected")
64 .and_then(Value::as_str)
65 .unwrap_or(SEARCH_PROVIDER_ANY);
66 let selected = providers
67 .iter()
68 .position(|option| option.id == selected_id)
69 .unwrap_or(0);
70 Some(Self {
71 tool_id: tool_id.to_string(),
72 tool_name: tool_name.to_string(),
73 approval_key: approval_key.to_string(),
74 providers,
75 selected,
76 })
77 }
78
79 #[must_use]
80 pub fn chosen_provider(&self) -> Option<&str> {
81 self.providers
82 .get(self.selected)
83 .map(|option| option.id.as_str())
84 .filter(|id| *id != SEARCH_PROVIDER_ANY)
85 }
86 }
87
88 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
89 enum Choice {
90 Deny,
91 Enable,
92 }
93
94 pub struct SearchConsentView {
95 request: SearchConsentRequest,
96 locale: Locale,
97 timeout: Option<Duration>,
98 requested_at: Instant,
99 answerable_since: Option<Instant>,
100 last_key_at: Option<Instant>,
101 provider_hitboxes: RefCell<Vec<(usize, Rect)>>,
102 choice_hitboxes: RefCell<Vec<(Choice, Rect)>>,
103 }
104
105 impl SearchConsentView {
106 #[must_use]
107 pub fn new(request: SearchConsentRequest, locale: Locale) -> Self {
108 Self {
109 request,
110 locale,
111 timeout: None,
112 requested_at: Instant::now(),
113 answerable_since: None,
114 last_key_at: None,
115 provider_hitboxes: RefCell::new(Vec::new()),
116 choice_hitboxes: RefCell::new(Vec::new()),
117 }
118 }
119
120 #[must_use]
121 pub fn with_timeout(mut self, timeout: Option<Duration>) -> Self {
122 self.timeout = timeout;
123 self
124 }
125
126 fn provider_label(&self, option: &SearchProviderOption) -> String {
127 if option.id == SEARCH_PROVIDER_ANY {
128 tr(self.locale, MessageId::SearchConsentProviderAny).into_owned()
129 } else {
130 option.label.clone()
131 }
132 }
133
134 fn move_selection(&mut self, forward: bool) {
135 let len = self.request.providers.len();
136 if len == 0 {
137 return;
138 }
139 self.request.selected = if forward {
140 (self.request.selected + 1) % len
141 } else {
142 (self.request.selected + len - 1) % len
143 };
144 }
145
146 fn decide(&self, decision: ReviewDecision, timed_out: bool) -> ViewAction {
147 ViewAction::EmitAndClose(ViewEvent::ApprovalDecision {
148 tool_id: self.request.tool_id.clone(),
149 tool_name: self.request.tool_name.clone(),
150 decision,
151 timed_out,
152 approval_key: self.request.approval_key.clone(),
153 approval_grouping_key: self.request.approval_key.clone(),
154 persistent_rules: Vec::new(),
155 subject: None,
156 })
157 }
158
159 fn commit(&self, choice: Choice) -> ViewAction {
160 match choice {
161 Choice::Deny => self.decide(ReviewDecision::Denied, false),
162 Choice::Enable => ViewAction::EmitAndClose(ViewEvent::SearchConsentEnabled {
163 request: self.request.clone(),
164 }),
165 }
166 }
167
168 fn armed(&mut self, now: Instant, previous_key: Option<Instant>) -> bool {
169 let since = *self.answerable_since.get_or_insert(now);
170 now.saturating_duration_since(since) >= ENTER_ARMING_DELAY
171 && previous_key.is_none_or(|at| now.saturating_duration_since(at) >= ENTER_QUIET_GAP)
172 }
173
174 fn hints(&self) -> Vec<ActionHint> {
175 vec![
176 ActionHint::new("↑/↓", tr(self.locale, MessageId::SearchConsentProviderHint)),
177 ActionHint::new("Enter", tr(self.locale, MessageId::SearchConsentEnable)),
178 ActionHint::new("n", tr(self.locale, MessageId::SearchConsentDeny)),
179 ActionHint::new("Esc", tr(self.locale, MessageId::ApprovalOptionAbortTurn)),
180 ]
181 }
182
183 fn content_width(width: u16) -> u16 {
184 width.saturating_sub(4)
185 }
186
187 fn visible_providers(&self) -> usize {
188 self.request.providers.len().min(MAX_VISIBLE_PROVIDERS)
189 }
190
191 fn card_height(&self, width: u16) -> u16 {
192 let inner = Self::content_width(width);
193 let body = wrap_text(&tr(self.locale, MessageId::SearchConsentBody), inner).len();
194 let footer = action_footer_lines(&self.hints(), inner).len();
195 let rows = 2 + body + 1 + self.visible_providers() + 1 + 1 + footer;
196 u16::try_from(rows).unwrap_or(u16::MAX)
197 }
198
199 fn provider_window(&self) -> (usize, usize) {
200 let visible = self.visible_providers();
201 let len = self.request.providers.len();
202 let start = self
203 .request
204 .selected
205 .saturating_add(1)
206 .saturating_sub(visible)
207 .min(len.saturating_sub(visible));
208 (start, start + visible)
209 }
210
211 fn choice_spans(&self, width: u16) -> (Line<'static>, Vec<(Choice, u16, u16)>) {
212 let deny = format!(" {} ", tr(self.locale, MessageId::SearchConsentDeny));
213 let enable = format!(" {} ", tr(self.locale, MessageId::SearchConsentEnable));
214 let deny_width = u16::try_from(UnicodeWidthStr::width(deny.as_str())).unwrap_or(0);
215 let enable_width = u16::try_from(UnicodeWidthStr::width(enable.as_str())).unwrap_or(0);
216 let gap = 2u16;
217 let total = deny_width + gap + enable_width;
218 let lead = width.saturating_sub(total);
219 let deny_style = Style::default()
220 .fg(palette::TEXT_PRIMARY)
221 .add_modifier(Modifier::BOLD);
222 let enable_style = menu_style::selected_row_style()
223 .fg(active_modal_accent_color())
224 .add_modifier(Modifier::REVERSED | Modifier::BOLD);
225 let line = Line::from(vec![
226 Span::raw(" ".repeat(usize::from(lead))),
227 Span::styled(deny, deny_style),
228 Span::raw(" ".repeat(usize::from(gap))),
229 Span::styled(enable, enable_style),
230 ]);
231 let spans = vec![
232 (Choice::Deny, lead, deny_width),
233 (Choice::Enable, lead + deny_width + gap, enable_width),
234 ];
235 (line, spans)
236 }
237 }
238
239 fn wrap_text(text: &str, width: u16) -> Vec<String> {
240 let width = usize::from(width).max(1);
241 let mut lines = Vec::new();
242 let mut current = String::new();
243 let mut current_width = 0usize;
244 for word in text.split_whitespace() {
245 let word_width = UnicodeWidthStr::width(word);
246 if current_width > 0 && current_width + 1 + word_width > width {
247 lines.push(std::mem::take(&mut current));
248 current_width = 0;
249 }
250 if current_width > 0 {
251 current.push(' ');
252 current_width += 1;
253 }
254 for ch in word.chars() {
255 let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0);
256 if current_width > 0 && current_width + ch_width > width {
257 lines.push(std::mem::take(&mut current).trim_end().to_string());
258 current_width = 0;
259 }
260 current.push(ch);
261 current_width += ch_width;
262 }
263 }
264 if !current.is_empty() {
265 lines.push(current);
266 }
267 lines
268 }
269
270 impl ModalView for SearchConsentView {
271 fn kind(&self) -> ModalKind {
272 ModalKind::Approval
273 }
274
275 fn set_locale(&mut self, locale: Locale) {
276 self.locale = locale;
277 }
278
279 fn approval_request_id(&self) -> Option<&str> {
280 Some(&self.request.tool_id)
281 }
282
283 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
284 self
285 }
286
287 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
288 if key.kind != KeyEventKind::Press
289 || !key.modifiers.difference(KeyModifiers::SHIFT).is_empty()
290 {
291 return ViewAction::None;
292 }
293 let now = Instant::now();
294 let previous_key = if matches!(key.code, KeyCode::Enter | KeyCode::Char(_)) {
295 self.last_key_at.replace(now)
296 } else {
297 self.last_key_at
298 };
299 let answer = match key.code {
300 KeyCode::Enter | KeyCode::Char('e' | 'E' | 'y' | 'Y') => Some(Choice::Enable),
301 KeyCode::Char('n' | 'N') => Some(Choice::Deny),
302 _ => None,
303 };
304 if let Some(choice) = answer {
305 if self.armed(now, previous_key) {
306 return self.commit(choice);
307 }
308 if key.code == KeyCode::Enter {
309 return ViewAction::Emit(ViewEvent::StatusToast {
310 message: tr(self.locale, MessageId::ApprovalEnterIgnored).into_owned(),
311 level: crate::tui::app::StatusToastLevel::Info,
312 });
313 }
314 return ViewAction::None;
315 }
316 self.answerable_since.get_or_insert(now);
317 match key.code {
318 KeyCode::Up | KeyCode::Char('k') => {
319 self.move_selection(false);
320 ViewAction::None
321 }
322 KeyCode::Down | KeyCode::Tab | KeyCode::Char('j') => {
323 self.move_selection(true);
324 ViewAction::None
325 }
326 KeyCode::Esc => self.decide(ReviewDecision::Abort, false),
327 _ => ViewAction::None,
328 }
329 }
330
331 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
332 match mouse.kind {
333 MouseEventKind::ScrollUp => {
334 self.move_selection(false);
335 ViewAction::None
336 }
337 MouseEventKind::ScrollDown => {
338 self.move_selection(true);
339 ViewAction::None
340 }
341 MouseEventKind::Down(MouseButton::Left) => {
342 let pos = Position::new(mouse.column, mouse.row);
343 let choice = self
344 .choice_hitboxes
345 .borrow()
346 .iter()
347 .find_map(|(choice, rect)| rect.contains(pos).then_some(*choice));
348 if let Some(choice) = choice {
349 let previous_key = self.last_key_at;
350 if self.armed(Instant::now(), previous_key) {
351 return self.commit(choice);
352 }
353 return ViewAction::None;
354 }
355 let provider = self
356 .provider_hitboxes
357 .borrow()
358 .iter()
359 .find_map(|(index, rect)| rect.contains(pos).then_some(*index));
360 if let Some(index) = provider {
361 self.request.selected = index;
362 }
363 ViewAction::None
364 }
365 _ => ViewAction::None,
366 }
367 }
368
369 fn render(&self, area: Rect, buf: &mut Buffer) {
370 let card = self.occupied_region(area);
371 if card.width < 8 || card.height < 3 {
372 return;
373 }
374 let (inner, _) = render_rounded_modal(
375 card,
376 card,
377 buf,
378 SurfaceFrame::new(tr(self.locale, MessageId::SearchConsentTitle)),
379 );
380 let content = render_modal_footer(inner, buf, &self.hints());
381 let muted = Style::default().fg(palette::TEXT_MUTED);
382 let primary = Style::default().fg(palette::TEXT_PRIMARY);
383 let mut lines: Vec<Line<'static>> = wrap_text(
384 &tr(self.locale, MessageId::SearchConsentBody),
385 content.width,
386 )
387 .into_iter()
388 .map(|line| Line::from(Span::styled(line, primary)))
389 .collect();
390 lines.push(Line::default());
391 let provider_top = lines.len();
392 let (start, end) = self.provider_window();
393 for index in start..end {
394 let option = &self.request.providers[index];
395 let selected = index == self.request.selected;
396 let style = if selected {
397 menu_style::selected_row_style()
398 } else {
399 primary
400 };
401 let marker = if selected {
402 codewhale_tui_kit::glyphs::CURRENT
403 } else {
404 codewhale_tui_kit::glyphs::AVAILABLE
405 };
406 let pointer = codewhale_tui_kit::glyphs::selection_marker(selected);
407 let label = self.provider_label(option);
408 let row = format!("{pointer} {marker} {label}");
409 let room = usize::from(content.width);
410 let row = codewhale_tui_kit::ui_text::semantic_truncate(&row, room);
411 let pad = room.saturating_sub(UnicodeWidthStr::width(row.as_str()));
412 let mut spans = vec![Span::styled(row, style)];
413 if selected {
414 spans.push(Span::styled(" ".repeat(pad), style));
415 } else if pad > 0 {
416 spans.push(Span::styled(" ".repeat(pad), muted));
417 }
418 lines.push(Line::from(spans));
419 }
420 lines.push(Line::default());
421 let choice_top = lines.len();
422 let (choice_line, choice_spans) = self.choice_spans(content.width);
423 lines.push(choice_line);
424 Paragraph::new(lines).render(content, buf);
425
426 let mut provider_hitboxes = self.provider_hitboxes.borrow_mut();
427 provider_hitboxes.clear();
428 for (offset, index) in (start..end).enumerate() {
429 let y = content.y + u16::try_from(provider_top + offset).unwrap_or(u16::MAX);
430 if y < content.bottom() {
431 provider_hitboxes.push((index, Rect::new(content.x, y, content.width, 1)));
432 }
433 }
434 let mut choice_hitboxes = self.choice_hitboxes.borrow_mut();
435 choice_hitboxes.clear();
436 let choice_y = content.y + u16::try_from(choice_top).unwrap_or(u16::MAX);
437 if choice_y < content.bottom() {
438 for (choice, x, width) in choice_spans {
439 choice_hitboxes.push((choice, Rect::new(content.x + x, choice_y, width, 1)));
440 }
441 }
442 }
443
444 fn occupied_region(&self, area: Rect) -> Rect {
445 let height = self.card_height(area.width).min(area.height);
446 Rect::new(
447 area.x,
448 area.bottom().saturating_sub(height),
449 area.width,
450 height,
451 )
452 }
453
454 fn docked_height(&self, _width: u16) -> u16 {
455 1
456 }
457
458 fn on_became_top(&mut self, at: Instant) {
459 self.answerable_since = Some(at);
460 }
461
462 fn tick(&mut self) -> ViewAction {
463 self.answerable_since.get_or_insert_with(Instant::now);
464 if self
465 .timeout
466 .is_some_and(|timeout| self.requested_at.elapsed() >= timeout)
467 {
468 return self.decide(ReviewDecision::Denied, true);
469 }
470 ViewAction::None
471 }
472 }
473
474 #[cfg(test)]
475 mod tests {
476 use super::*;
477 use crossterm::event::KeyEvent;
478 use serde_json::json;
479
480 fn marker_input(selected: &str) -> Value {
481 json!({
482 "action": "search",
483 "query": "rust",
484 "third_party_search": {
485 "version": 1,
486 "selected": selected,
487 "providers": [
488 {"id": "any", "label": "Any", "keyless": true},
489 {"id": "firecrawl", "label": "Firecrawl", "keyless": true},
490 {"id": "duckduckgo", "label": "DuckDuckGo", "keyless": true},
491 {"id": "bing", "label": "Bing", "keyless": true}
492 ]
493 }
494 })
495 }
496
497 fn view(selected: &str) -> SearchConsentView {
498 let request = SearchConsentRequest::from_approval(
499 "search-consent:call-1",
500 "Web",
501 "search-consent:call-1",
502 &marker_input(selected),
503 )
504 .expect("consent request");
505 let mut view = SearchConsentView::new(request, Locale::En);
506 view.on_became_top(settled_at());
507 view
508 }
509
510 fn settled_at() -> Instant {
511 Instant::now()
512 .checked_sub(ENTER_ARMING_DELAY)
513 .expect("monotonic clock past the arming delay")
514 }
515
516 fn click(view: &mut SearchConsentView, choice: Choice) -> ViewAction {
517 let _ = rendered_text(view, 90, 24);
518 let rect = view
519 .choice_hitboxes
520 .borrow()
521 .iter()
522 .find_map(|(candidate, rect)| (*candidate == choice).then_some(*rect))
523 .expect("choice is on screen");
524 view.handle_mouse(MouseEvent {
525 kind: MouseEventKind::Down(MouseButton::Left),
526 column: rect.x,
527 row: rect.y,
528 modifiers: KeyModifiers::NONE,
529 })
530 }
531
532 fn press(view: &mut SearchConsentView, code: KeyCode) -> ViewAction {
533 view.handle_key(KeyEvent::new(code, KeyModifiers::NONE))
534 }
535
536 fn rendered_text(view: &SearchConsentView, width: u16, height: u16) -> String {
537 let area = Rect::new(0, 0, width, height);
538 let mut buf = Buffer::empty(area);
539 view.render(area, &mut buf);
540 (0..height)
541 .map(|y| {
542 let mut row = String::new();
543 let mut x = 0;
544 while x < width {
545 let symbol = buf[(x, y)].symbol();
546 row.push_str(symbol);
547 x += u16::try_from(UnicodeWidthStr::width(symbol))
548 .unwrap_or(1)
549 .max(1);
550 }
551 row
552 })
553 .collect::<Vec<_>>()
554 .join("\n")
555 }
556
557 #[test]
558 fn marker_parses_and_preselects_the_pinned_provider() {
559 let any = view("any");
560 assert_eq!(any.request.selected, 0);
561 assert_eq!(any.request.chosen_provider(), None);
562 let pinned = view("duckduckgo");
563 assert_eq!(pinned.request.selected, 2);
564 assert_eq!(pinned.request.chosen_provider(), Some("duckduckgo"));
565 let unknown = view("tavily");
566 assert_eq!(unknown.request.selected, 0);
567 }
568
569 #[test]
570 fn unknown_marker_versions_fall_back_to_the_generic_card() {
571 let key = "search-consent:id";
572 let mut input = marker_input("any");
573 input["third_party_search"]["version"] = json!(2);
574 assert!(SearchConsentRequest::from_approval(key, "Web", key, &input).is_none());
575 assert!(
576 SearchConsentRequest::from_approval(key, "Web", key, &json!({"query": "x"})).is_none()
577 );
578 }
579
580 #[test]
581 fn a_marker_without_the_engine_consent_key_gets_the_generic_card() {
582 let mut fetch = marker_input("any");
583 fetch["action"] = json!("fetch");
584 fetch["url"] = json!("https://example.invalid/c?d=1");
585 for (id, tool, key, input) in [
586 ("call-1", "Web", "web:fetch:example.invalid", fetch),
587 ("call-2", "exec_shell", "shell:ls", marker_input("any")),
588 (
589 "call-3",
590 "mcp__files__upload",
591 "mcp:files:upload",
592 marker_input("any"),
593 ),
594 ("call-4", "Web", "tool:Web", marker_input("any")),
595 ] {
596 assert!(
597 SearchConsentRequest::from_approval(id, tool, key, &input).is_none(),
598 "{tool} {key}"
599 );
600 }
601 }
602
603 #[test]
604 fn card_shows_the_desktop_copy() {
605 let text = rendered_text(&view("any"), 90, 24);
606 assert!(text.contains("Third-party web search"), "{text}");
607 assert!(
608 text.contains("Choose the search provider agents use to search the web."),
609 "{text}"
610 );
611 assert!(text.contains("Don't use search"), "{text}");
612 assert!(text.contains("Enable"), "{text}");
613 assert!(text.contains("Any"), "{text}");
614 assert!(text.contains("DuckDuckGo"), "{text}");
615 }
616
617 #[test]
618 fn card_is_bottom_anchored_inside_its_area() {
619 let consent = view("any");
620 let area = Rect::new(0, 0, 90, 40);
621 let region = consent.occupied_region(area);
622 assert_eq!(region.bottom(), area.bottom());
623 assert!(region.height < area.height);
624 assert_eq!(consent.docked_height(90), 1);
625 }
626
627 #[test]
628 fn enable_carries_the_chosen_provider() {
629 let mut consent = view("any");
630 assert!(matches!(
631 press(&mut consent, KeyCode::Down),
632 ViewAction::None
633 ));
634 match press(&mut consent, KeyCode::Char('e')) {
635 ViewAction::EmitAndClose(ViewEvent::SearchConsentEnabled { request }) => {
636 assert_eq!(request.chosen_provider(), Some("firecrawl"));
637 assert_eq!(request.tool_id, "search-consent:call-1");
638 }
639 _ => panic!("expected an enable decision"),
640 }
641 }
642
643 #[test]
644 fn deny_and_escape_answer_the_approval() {
645 let mut consent = view("any");
646 match press(&mut consent, KeyCode::Char('n')) {
647 ViewAction::EmitAndClose(ViewEvent::ApprovalDecision {
648 decision,
649 timed_out,
650 approval_key,
651 approval_grouping_key,
652 persistent_rules,
653 ..
654 }) => {
655 assert_eq!(decision, ReviewDecision::Denied);
656 assert!(!timed_out);
657 assert_eq!(approval_key, "search-consent:call-1");
658 assert_eq!(approval_grouping_key, approval_key);
659 assert!(persistent_rules.is_empty());
660 }
661 _ => panic!("expected a deny decision"),
662 }
663 let mut consent = view("any");
664 assert!(matches!(
665 press(&mut consent, KeyCode::Esc),
666 ViewAction::EmitAndClose(ViewEvent::ApprovalDecision {
667 decision: ReviewDecision::Abort,
668 ..
669 })
670 ));
671 }
672
673 #[test]
674 fn enter_waits_for_the_card_to_settle() {
675 let mut consent = view("any");
676 consent.on_became_top(Instant::now());
677 assert!(matches!(
678 press(&mut consent, KeyCode::Enter),
679 ViewAction::Emit(ViewEvent::StatusToast { .. })
680 ));
681 consent.on_became_top(settled_at());
682 consent.last_key_at = None;
683 assert!(matches!(
684 press(&mut consent, KeyCode::Enter),
685 ViewAction::EmitAndClose(ViewEvent::SearchConsentEnabled { .. })
686 ));
687 }
688
689 #[test]
690 fn letters_and_clicks_wait_for_the_card_to_settle() {
691 for code in ['e', 'E', 'y', 'Y', 'n', 'N'].map(KeyCode::Char) {
692 let mut consent = view("any");
693 consent.on_became_top(Instant::now());
694 assert!(
695 matches!(press(&mut consent, code), ViewAction::None),
696 "{code:?}"
697 );
698 }
699 for choice in [Choice::Enable, Choice::Deny] {
700 let mut consent = view("any");
701 consent.on_became_top(Instant::now());
702 assert!(
703 matches!(click(&mut consent, choice), ViewAction::None),
704 "{choice:?}"
705 );
706 consent.on_became_top(settled_at());
707 assert!(
708 matches!(click(&mut consent, choice), ViewAction::EmitAndClose(_)),
709 "{choice:?}"
710 );
711 }
712
713 let mut consent = view("any");
714 consent.on_became_top(Instant::now());
715 assert!(matches!(
716 press(&mut consent, KeyCode::Esc),
717 ViewAction::EmitAndClose(ViewEvent::ApprovalDecision {
718 decision: ReviewDecision::Abort,
719 ..
720 })
721 ));
722 }
723
724 #[test]
725 fn typing_into_a_settled_card_does_not_answer_it() {
726 let mut consent = view("any");
727 assert!(matches!(
728 press(&mut consent, KeyCode::Char('h')),
729 ViewAction::None
730 ));
731 assert!(matches!(
732 press(&mut consent, KeyCode::Char('e')),
733 ViewAction::None
734 ));
735 assert!(matches!(
736 press(&mut consent, KeyCode::Char('n')),
737 ViewAction::None
738 ));
739 }
740
741 #[test]
742 fn every_locale_translates_the_card() {
743 for locale in Locale::shipped() {
744 let consent = SearchConsentView::new(view("any").request.clone(), *locale);
745 let text = rendered_text(&consent, 100, 30);
746 assert!(
747 text.contains(tr(*locale, MessageId::SearchConsentTitle).as_ref()),
748 "{locale:?}: {text}"
749 );
750 if *locale != Locale::En {
751 assert_ne!(
752 tr(*locale, MessageId::SearchConsentDeny),
753 tr(Locale::En, MessageId::SearchConsentDeny),
754 "{locale:?}"
755 );
756 }
757 }
758 }
759 }
760
760 lines RUST