返回 CodeWhale
language.rs
根目录 / crates / tui / src / tui / onboarding / language.rs
1 //! Language picker for first-run onboarding (#566).
2 //!
3 //! Surfaces every locale the TUI ships translations for, plus an `auto`
4 //! option that defers to `LC_ALL` / `LANG`. Selection persists via
5 //! `Settings::save` immediately so the rest of onboarding (and every
6 //! subsequent session) reads the chosen tag.
7 //!
8 //! The screen appears only when the locale cannot be confidently inferred
9 //! (see `onboarding::locale_confidently_inferred`); most first runs never
10 //! see it.
11
12 use ratatui::style::{Modifier, Style};
13 use ratatui::text::{Line, Span};
14
15 use crate::tui::app::App;
16 use codewhale_localization::MessageId;
17 use codewhale_palette as palette;
18 use unicode_width::UnicodeWidthStr;
19
20 /// Locale options shown in the picker. Order matches the keyboard hotkeys.
21 /// Each entry is `(hotkey, settings_tag, native_name, english_label)`.
22 /// `settings_tag` is what `Settings::set("locale", …)` accepts and what
23 /// `localization::Locale` resolves on next read.
24 ///
25 /// Hotkeys run `1..=9` then `a`, `b`, … so more than nine shipped locales
26 /// stay single-keystroke selectable.
27 pub const LANGUAGE_OPTIONS: &[(char, &str, &str, &str)] = &[
28 ('1', "auto", "Auto-detect", "(LC_ALL / LANG)"),
29 ('2', "en", "English", ""),
30 ('3', "ja", "日本語", "(Japanese)"),
31 ('4', "zh-Hans", "简体中文", "(Simplified Chinese)"),
32 ('5', "zh-Hant", "繁體中文", "(Traditional Chinese)"),
33 ('6', "pt-BR", "Português (Brasil)", "(Brazilian Portuguese)"),
34 (
35 '7',
36 "es-419",
37 "Español (Latinoamérica)",
38 "(Latin American Spanish)",
39 ),
40 ('8', "vi", "Tiếng Việt", "(Vietnamese)"),
41 ('9', "ko", "한국어", "(Korean)"),
42 ('a', "ca", "Català", "(Catalan)"),
43 ('b', "de", "Deutsch", "(German)"),
44 ('c', "fr", "Français", "(French)"),
45 ('d', "id", "Bahasa Indonesia", "(Indonesian)"),
46 ('e', "hi", "हिन्दी", "(Hindi)"),
47 ('f', "ru", "Русский", "(Russian)"),
48 ('g', "uk", "Українська", "(Ukrainian)"),
49 ];
50
51 /// Two columns keep every shipped locale visible at 80x24; below this width
52 /// the list falls back to one column and the English annotations return.
53 const TWO_COLUMN_MIN_WIDTH: usize = 56;
54
55 pub fn lines(app: &App, width: usize, height: usize) -> Vec<Line<'static>> {
56 let current_owned = app.current_locale_tag();
57 let current = current_owned.as_str();
58 let accent = super::theme_or(app.ui_theme.accent_primary, palette::WHALE_ACTION);
59 let body_fg = super::theme_or(app.ui_theme.text_body, palette::TEXT_PRIMARY);
60 let muted_fg = super::theme_or(app.ui_theme.text_muted, palette::TEXT_MUTED);
61
62 let title = Line::from(Span::styled(
63 app.tr(MessageId::OnboardLanguageTitle).to_string(),
64 Style::default().fg(accent).add_modifier(Modifier::BOLD),
65 ));
66
67 if height < 12 {
68 let option_rows = height.saturating_sub(1).max(1);
69 return compact_grid(title, width, option_rows, current, accent, body_fg);
70 }
71
72 let mut out: Vec<Line<'static>> = vec![title, Line::from("")];
73 for segment in super::wrap_words(&app.tr(MessageId::OnboardLanguageBlurb), width) {
74 out.push(Line::from(Span::styled(
75 segment,
76 Style::default().fg(body_fg),
77 )));
78 }
79 out.push(Line::from(""));
80
81 let two_column = width >= TWO_COLUMN_MIN_WIDTH;
82 if two_column {
83 let column_width = (width - 3) / 2;
84 let split = LANGUAGE_OPTIONS.len().div_ceil(2);
85 let (left_column, right_column) = LANGUAGE_OPTIONS.split_at(split);
86 for (idx, left) in left_column.iter().enumerate() {
87 let mut spans = option_spans_inner(left, current, false, accent, body_fg, muted_fg);
88 if let Some(right) = right_column.get(idx) {
89 let used: usize = spans
90 .iter()
91 .map(|span| UnicodeWidthStr::width(span.content.as_ref()))
92 .sum();
93 let gap = (column_width + 1).saturating_sub(used).max(2);
94 spans.push(Span::raw(" ".repeat(gap)));
95 spans.extend(option_spans_inner(
96 right, current, false, accent, body_fg, muted_fg,
97 ));
98 }
99 out.push(Line::from(spans));
100 }
101 } else {
102 for option in LANGUAGE_OPTIONS {
103 out.push(Line::from(option_spans_inner(
104 option, current, true, accent, body_fg, muted_fg,
105 )));
106 }
107 }
108
109 out
110 }
111
112 fn compact_grid(
113 title: Line<'static>,
114 width: usize,
115 rows: usize,
116 current: &str,
117 accent: ratatui::style::Color,
118 body_fg: ratatui::style::Color,
119 ) -> Vec<Line<'static>> {
120 let columns = LANGUAGE_OPTIONS.len().div_ceil(rows);
121 let gap = usize::from(columns > 1);
122 let column_width = width
123 .saturating_sub(gap.saturating_mul(columns.saturating_sub(1)))
124 .checked_div(columns)
125 .unwrap_or(1)
126 .max(1);
127 let mut out = vec![title];
128 for row in 0..rows {
129 let mut spans = Vec::new();
130 for column in 0..columns {
131 let index = row * columns + column;
132 let Some(option) = LANGUAGE_OPTIONS.get(index) else {
133 break;
134 };
135 if column > 0 {
136 spans.push(Span::raw(" ".repeat(gap)));
137 }
138 spans.extend(compact_option_spans(
139 option,
140 current,
141 column_width,
142 accent,
143 body_fg,
144 ));
145 }
146 out.push(Line::from(spans));
147 }
148 out
149 }
150
151 fn compact_option_spans(
152 option: &(char, &str, &str, &str),
153 current: &str,
154 width: usize,
155 accent: ratatui::style::Color,
156 body_fg: ratatui::style::Color,
157 ) -> Vec<Span<'static>> {
158 let (hotkey, tag, native, _) = *option;
159 let prefix = format!("[{hotkey}]");
160 let prefix_width = UnicodeWidthStr::width(prefix.as_str());
161 let label_width = width.saturating_sub(prefix_width);
162 let label = codewhale_tui_kit::ui_text::semantic_truncate(native, label_width);
163 let style = if current == tag {
164 Style::default().fg(accent).add_modifier(Modifier::BOLD)
165 } else {
166 Style::default().fg(body_fg)
167 };
168 let used = prefix_width + UnicodeWidthStr::width(label.as_str());
169 vec![
170 Span::styled(prefix, style),
171 Span::styled(label, style),
172 Span::raw(" ".repeat(width.saturating_sub(used))),
173 ]
174 }
175
176 fn option_spans_inner(
177 option: &(char, &str, &str, &str),
178 current: &str,
179 with_english: bool,
180 accent: ratatui::style::Color,
181 body_fg: ratatui::style::Color,
182 muted_fg: ratatui::style::Color,
183 ) -> Vec<Span<'static>> {
184 let (hotkey, tag, native, english) = *option;
185 let is_current = current == tag;
186 let bullet = if is_current {
187 codewhale_tui_kit::glyphs::CURRENT
188 } else {
189 codewhale_tui_kit::glyphs::AVAILABLE
190 };
191 let bullet_color = if is_current { accent } else { muted_fg };
192 let label_style = if is_current {
193 Style::default().fg(accent).add_modifier(Modifier::BOLD)
194 } else {
195 Style::default().fg(body_fg)
196 };
197 let mut spans: Vec<Span<'static>> = vec![
198 Span::styled(format!("{bullet} "), Style::default().fg(bullet_color)),
199 Span::styled(
200 format!("[{hotkey}] "),
201 Style::default()
202 .fg(if is_current { accent } else { muted_fg })
203 .add_modifier(Modifier::BOLD),
204 ),
205 Span::styled(native.to_string(), label_style),
206 ];
207 if with_english && !english.is_empty() {
208 spans.push(Span::styled(
209 format!(" {english}"),
210 Style::default().fg(muted_fg),
211 ));
212 }
213 spans
214 }
215
216 #[cfg(test)]
217 mod tests {
218 use super::*;
219 use crate::tui::app::TuiOptions;
220 use codewhale_localization::Locale;
221 use codewhale_runtime::config::Config;
222 use std::path::PathBuf;
223
224 fn app() -> App {
225 let options = TuiOptions {
226 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
227 };
228 let mut app = App::new(options, &Config::default());
229 app.ui_locale = Locale::En;
230 app
231 }
232
233 fn row_text(line: &Line<'static>) -> String {
234 line.spans
235 .iter()
236 .map(|span| span.content.as_ref())
237 .collect::<String>()
238 }
239
240 /// Every locale we ship translations for must be offered in the picker,
241 /// otherwise the footer advertises hotkeys that select nothing and users
242 /// can never reach a supported UI language (#3929).
243 #[test]
244 fn picker_offers_every_shipped_locale() {
245 let offered: Vec<&str> = LANGUAGE_OPTIONS.iter().map(|(_, tag, _, _)| *tag).collect();
246 assert!(
247 offered.contains(&"auto"),
248 "picker must keep the auto-detect entry"
249 );
250 for locale in Locale::shipped() {
251 let tag = locale.tag();
252 assert!(
253 offered.contains(&tag),
254 "shipped locale {tag} is not offered in the language picker"
255 );
256 }
257 }
258
259 /// Hotkeys must be the contiguous run `1..=9` followed by contiguous
260 /// lowercase letters `a`, `b`, … so the footer hint stays truthful and
261 /// `KeyCode::Char` lookups resolve for every option.
262 #[test]
263 fn picker_hotkeys_are_contiguous_digits_then_letters() {
264 for (idx, (hotkey, tag, _, _)) in LANGUAGE_OPTIONS.iter().enumerate() {
265 let expected = if idx < 9 {
266 char::from_digit((idx + 1) as u32, 10).expect("digit")
267 } else {
268 char::from_u32('a' as u32 + (idx - 9) as u32).expect("letter")
269 };
270 assert_eq!(
271 *hotkey, expected,
272 "option {tag} should use hotkey {expected}, not {hotkey}"
273 );
274 }
275 }
276
277 /// At 80 columns the surface body is ~72 wide, so every option must stay
278 /// on one row and the whole list must fit a 24-row terminal.
279 #[test]
280 fn every_option_is_visible_at_80_columns() {
281 let rows = lines(&app(), 72, 17);
282 let text = rows.iter().map(row_text).collect::<Vec<_>>();
283
284 for (_, tag, native, _) in LANGUAGE_OPTIONS {
285 let shown = text.iter().any(|row| row.contains(native));
286 assert!(shown, "option {tag} ({native}) missing from the picker");
287 }
288 // 17 options in 9 rows + 5 header rows fits the ~17 usable rows of a
289 // 24-line terminal under the onboarding surface.
290 assert!(
291 rows.len() <= 15,
292 "picker is {} rows; it must fit 80x24",
293 rows.len()
294 );
295 }
296
297 #[test]
298 fn compact_grid_keeps_every_language_hotkey_reachable() {
299 let rows = lines(&app(), 36, 5);
300 let text = rows.iter().map(row_text).collect::<Vec<_>>().join("\n");
301
302 assert_eq!(rows.len(), 5, "one title plus four option rows");
303 for (hotkey, tag, _, _) in LANGUAGE_OPTIONS {
304 assert!(text.contains(&format!("[{hotkey}]")), "missing {tag}");
305 }
306 }
307 }
308
308 lines RUST