Skip to main content

waft_material/
material_localizations.rs

1//! Flutter counterpart: material_ui's `material_localizations.dart`.
2//!
3//! US English only: [`DefaultMaterialLocalizations`] is the one implementation, and its
4//! delegate supports `en`.
5
6use std::fmt;
7use std::rc::Rc;
8
9use waft_embedder::Locale;
10use waft_foundation::{App, CompleterFuture, DateTime};
11use waft_widgets::{BuildContext, Localizations, LocalizationsDelegate, LocalizationsDelegateRef};
12
13use crate::debug::debug_check_has_material_localizations;
14use crate::time::{DayPeriod, TimeOfDay, TimeOfDayFormat};
15use crate::typography::ScriptCategory;
16
17/// Defines the localized resource values used by the Material widgets.
18///
19/// See also:
20///
21///  * [`DefaultMaterialLocalizations`], the default, English-only, implementation
22///    of this interface.
23///  * `GlobalMaterialLocalizations`, which provides material localizations for
24///    many languages.
25pub trait MaterialLocalizations: 'static {
26    /// The tooltip for the leading `AppBar` menu (a.k.a. 'hamburger') button.
27    fn open_app_drawer_tooltip(&self) -> String;
28
29    /// The `BackButton`'s tooltip.
30    fn back_button_tooltip(&self) -> String;
31
32    /// The tooltip for the clear button to clear text on `SearchAnchor`'s search view.
33    fn clear_button_tooltip(&self) -> String;
34
35    /// The `CloseButton`'s tooltip.
36    fn close_button_tooltip(&self) -> String;
37
38    /// The tooltip for the delete button on a `Chip`.
39    fn delete_button_tooltip(&self) -> String;
40
41    /// The tooltip for the more button on an overflowing text selection menu.
42    fn more_button_tooltip(&self) -> String;
43
44    /// The tooltip for the `CalendarDatePicker`'s "next month" button.
45    fn next_month_tooltip(&self) -> String;
46
47    /// The tooltip for the `CalendarDatePicker`'s "previous month" button.
48    fn previous_month_tooltip(&self) -> String;
49
50    /// The tooltip for the `PaginatedDataTable`'s "first page" button.
51    fn first_page_tooltip(&self) -> String;
52
53    /// The tooltip for the `PaginatedDataTable`'s "last page" button.
54    fn last_page_tooltip(&self) -> String;
55
56    /// The tooltip for the `PaginatedDataTable`'s "next page" button.
57    fn next_page_tooltip(&self) -> String;
58
59    /// The tooltip for the `PaginatedDataTable`'s "previous page" button.
60    fn previous_page_tooltip(&self) -> String;
61
62    /// The default `PopupMenuButton` tooltip.
63    fn show_menu_tooltip(&self) -> String;
64
65    /// The default title for `AboutListTile`.
66    fn about_list_tile_title(&self, application_name: &str) -> String;
67
68    /// Title for the `LicensePage` widget.
69    fn licenses_page_title(&self) -> String;
70
71    /// Subtitle for a package in the `LicensePage` widget.
72    fn licenses_package_detail_text(&self, license_count: i32) -> String;
73
74    /// Title for the `PaginatedDataTable`'s row info footer.
75    fn page_rows_info_title(
76        &self,
77        first_row: i32,
78        last_row: i32,
79        row_count: i32,
80        row_count_is_approximate: bool,
81    ) -> String;
82
83    /// Title for the `PaginatedDataTable`'s "rows per page" footer.
84    fn rows_per_page_title(&self) -> String;
85
86    /// The accessibility label used on a tab in a `TabBar`.
87    ///
88    /// This message describes the index of the selected tab and how many tabs
89    /// there are, e.g. 'Tab 1 of 2' in United States English.
90    ///
91    /// `tab_index` and `tab_count` must be greater than or equal to one.
92    fn tab_label(&self, tab_index: i32, tab_count: i32) -> String;
93
94    /// Title for the `PaginatedDataTable`'s selected row count header.
95    fn selected_row_count_title(&self, selected_row_count: i32) -> String;
96
97    /// Label for "cancel" buttons and menu items.
98    fn cancel_button_label(&self) -> String;
99
100    /// Label for "close" buttons and menu items.
101    fn close_button_label(&self) -> String;
102
103    /// Label for "continue" buttons and menu items.
104    fn continue_button_label(&self) -> String;
105
106    /// Label for "copy" edit buttons and menu items.
107    fn copy_button_label(&self) -> String;
108
109    /// Label for "cut" edit buttons and menu items.
110    fn cut_button_label(&self) -> String;
111
112    /// Label for "scan text" OCR edit buttons and menu items.
113    fn scan_text_button_label(&self) -> String;
114
115    /// Label for OK buttons and menu items.
116    fn ok_button_label(&self) -> String;
117
118    /// Label for "paste" edit buttons and menu items.
119    fn paste_button_label(&self) -> String;
120
121    /// Label for "select all" edit buttons and menu items.
122    fn select_all_button_label(&self) -> String;
123
124    /// Label for "look up" edit buttons and menu items.
125    fn look_up_button_label(&self) -> String;
126
127    /// Label for "search web" edit buttons and menu items.
128    fn search_web_button_label(&self) -> String;
129
130    /// Label for "share" edit buttons and menu items.
131    fn share_button_label(&self) -> String;
132
133    /// Label for the `AboutDialog` button that shows the `LicensePage`.
134    fn view_licenses_button_label(&self) -> String;
135
136    /// The abbreviation for ante meridiem (before noon) shown in the time picker.
137    fn ante_meridiem_abbreviation(&self) -> String;
138
139    /// The abbreviation for post meridiem (after noon) shown in the time picker.
140    fn post_meridiem_abbreviation(&self) -> String;
141
142    /// The text-to-speech announcement made when a time picker invoked using
143    /// `showTimePicker` is set to the hour picker mode.
144    fn time_picker_hour_mode_announcement(&self) -> String;
145
146    /// The text-to-speech announcement made when a time picker invoked using
147    /// `showTimePicker` is set to the minute picker mode.
148    fn time_picker_minute_mode_announcement(&self) -> String;
149
150    /// Label read out by accessibility tools (TalkBack or VoiceOver) for a modal
151    /// barrier to indicate that a tap dismisses the barrier.
152    ///
153    /// A modal barrier can for example be found behind an alert or popup to block
154    /// user interaction with elements behind it.
155    fn modal_barrier_dismiss_label(&self) -> String;
156
157    /// Label read out by accessibility tools (TalkBack or VoiceOver) for a
158    /// context menu to indicate that a tap dismisses the context menu.
159    fn menu_dismiss_label(&self) -> String;
160
161    /// Label read out by accessibility tools (TalkBack or VoiceOver) when a
162    /// drawer widget is opened.
163    fn drawer_label(&self) -> String;
164
165    /// Label read out by accessibility tools (TalkBack or VoiceOver) when a
166    /// popup menu widget is opened.
167    fn popup_menu_label(&self) -> String;
168
169    /// Label read out by accessibility tools (TalkBack or VoiceOver) when a
170    /// MenuBarMenu widget is opened.
171    fn menu_bar_menu_label(&self) -> String;
172
173    /// Label read out by accessibility tools (TalkBack or VoiceOver) when a
174    /// dialog widget is opened.
175    fn dialog_label(&self) -> String;
176
177    /// Label read out by accessibility tools (TalkBack or VoiceOver) when an
178    /// alert dialog widget is opened.
179    fn alert_dialog_label(&self) -> String;
180
181    /// Label indicating that a text field is a search field. This will be used
182    /// as a hint text in the text field.
183    fn search_field_label(&self) -> String;
184
185    /// Label indicating that a given date is the current date.
186    fn current_date_label(&self) -> String;
187
188    /// The semantics label to describe the selected date in the calendar picker
189    /// invoked using `showDatePicker`.
190    fn selected_date_label(&self) -> String;
191
192    /// Label for the scrim rendered underneath a `BottomSheet`.
193    fn scrim_label(&self) -> String;
194
195    /// Label for a `BottomSheet`, used as the `modalRouteContentName` of the
196    /// [`scrim_on_tap_hint`](Self::scrim_on_tap_hint).
197    fn bottom_sheet_label(&self) -> String;
198
199    /// Hint text announced when tapping on the scrim underneath the content of
200    /// a modal route.
201    fn scrim_on_tap_hint(&self, modal_route_content_name: &str) -> String;
202
203    /// The format used to lay out the time picker.
204    ///
205    /// The documentation for [`TimeOfDayFormat`] enum values provides details on
206    /// each supported layout.
207    fn time_of_day_format(&self, always_use_24_hour_format: bool) -> TimeOfDayFormat;
208
209    /// Defines the localized `TextStyle` geometry for `ThemeData.textTheme`.
210    ///
211    /// The [`script_category`](Self::script_category) defines the overall geometry of a `TextTheme` for
212    /// the `Typography.geometryThemeFor` method in terms of the
213    /// three language categories defined in <https://material.io/go/design-typography>.
214    ///
215    /// Generally speaking, font sizes for [`ScriptCategory::Tall`] and
216    /// [`ScriptCategory::Dense`] scripts - for text styles that are smaller than the
217    /// title style - are one unit larger than they are for
218    /// [`ScriptCategory::EnglishLike`] scripts.
219    fn script_category(&self) -> ScriptCategory;
220
221    /// Formats `number` as a decimal, inserting locale-appropriate thousands
222    /// separators as necessary.
223    fn format_decimal(&self, number: i64) -> String;
224
225    /// Formats [`hour`](TimeOfDay::hour) in the given time of day according to the value
226    /// of [`time_of_day_format`](Self::time_of_day_format).
227    ///
228    /// If `always_use_24_hour_format` is true, formats hour using [`HourFormat::HH`](crate::HourFormat::HH)
229    /// rather than the default for the current locale.
230    fn format_hour(&self, time_of_day: &TimeOfDay, always_use_24_hour_format: bool) -> String;
231
232    /// Formats [`minute`](TimeOfDay::minute) in the given time of day according to the value
233    /// of [`time_of_day_format`](Self::time_of_day_format).
234    fn format_minute(&self, time_of_day: &TimeOfDay) -> String;
235
236    /// Formats `time_of_day` according to the value of [`time_of_day_format`](Self::time_of_day_format).
237    ///
238    /// If `always_use_24_hour_format` is true, formats hour using [`HourFormat::HH`](crate::HourFormat::HH)
239    /// rather than the default for the current locale. This value is usually
240    /// passed from `MediaQueryData.alwaysUse24HourFormat`, which has platform-
241    /// specific behavior.
242    fn format_time_of_day(
243        &self,
244        time_of_day: &TimeOfDay,
245        always_use_24_hour_format: bool,
246    ) -> String;
247
248    /// Full unabbreviated year format, e.g. 2017 rather than 17.
249    fn format_year(&self, app: &App, date: &DateTime) -> String;
250
251    /// Formats the date in a compact format.
252    ///
253    /// Usually just the numeric values for the for day, month and year are used.
254    ///
255    /// Examples:
256    ///
257    /// - US English: 02/21/2019
258    /// - Russian: 21.02.2019
259    ///
260    /// See also:
261    ///   * [`parse_compact_date`](Self::parse_compact_date), which will convert a compact date string to a [`DateTime`].
262    fn format_compact_date(&self, app: &App, date: &DateTime) -> String;
263
264    /// Formats the date using a short-width format.
265    ///
266    /// Includes the abbreviation of the month, the day and year.
267    ///
268    /// Examples:
269    ///
270    /// - US English: Feb 21, 2019
271    /// - Russian: 21 февр. 2019 г.
272    fn format_short_date(&self, app: &App, date: &DateTime) -> String;
273
274    /// Formats the date using a medium-width format.
275    ///
276    /// Abbreviates month and days of week. This appears in the header of the date
277    /// picker invoked using `showDatePicker`.
278    ///
279    /// Examples:
280    ///
281    /// - US English: Wed, Sep 27
282    /// - Russian: ср, сент. 27
283    fn format_medium_date(&self, app: &App, date: &DateTime) -> String;
284
285    /// Formats day of week, month, day of month and year in a long-width format.
286    ///
287    /// Does not abbreviate names. Appears in spoken announcements of the date
288    /// picker invoked using `showDatePicker`, when accessibility mode is on.
289    ///
290    /// Examples:
291    ///
292    /// - US English: Wednesday, September 27, 2017
293    /// - Russian: Среда, Сентябрь 27, 2017
294    fn format_full_date(&self, app: &App, date: &DateTime) -> String;
295
296    /// Formats the month and the year of the given `date`.
297    ///
298    /// The returned string does not contain the day of the month. This appears
299    /// in the date picker invoked using `showDatePicker`.
300    fn format_month_year(&self, app: &App, date: &DateTime) -> String;
301
302    /// Formats the month and day of the given `date`.
303    ///
304    /// Examples:
305    ///
306    /// - US English: Feb 21
307    /// - Russian: 21 февр.
308    fn format_short_month_day(&self, app: &App, date: &DateTime) -> String;
309
310    /// Converts the given compact date formatted string into a [`DateTime`].
311    ///
312    /// The format of the string must be a valid compact date format for the
313    /// given locale. If the text doesn't represent a valid date, `None` will be
314    /// returned.
315    ///
316    /// See also:
317    ///   * [`format_compact_date`](Self::format_compact_date), which will convert a [`DateTime`] into a string in the compact format.
318    fn parse_compact_date(&self, app: &App, input_string: Option<&str>) -> Option<DateTime>;
319
320    /// List of week day names in narrow format, usually 1- or 2-letter
321    /// abbreviations of full names.
322    ///
323    /// The list begins with the value corresponding to Sunday and ends with
324    /// Saturday. Use [`first_day_of_week_index`](Self::first_day_of_week_index) to find the first day of week in this
325    /// list.
326    ///
327    /// Examples:
328    ///
329    /// - US English: S, M, T, W, T, F, S
330    /// - Russian: вс, пн, вт, ср, чт, пт, сб - notice that the list begins with
331    ///   вс (Sunday) even though the first day of week for Russian is Monday.
332    fn narrow_weekdays(&self) -> Vec<String>;
333
334    /// Index of the first day of week, where 0 points to Sunday, and 6 points to
335    /// Saturday.
336    ///
337    /// This getter is compatible with [`narrow_weekdays`](Self::narrow_weekdays). For example:
338    ///
339    /// ```text
340    /// let localizations = <dyn MaterialLocalizations>::of(app, context);
341    /// // The name of the first day of week for the current locale.
342    /// let first_day_of_week = &localizations.narrow_weekdays()[localizations.first_day_of_week_index() as usize];
343    /// ```
344    fn first_day_of_week_index(&self) -> i32;
345
346    /// The character string used to separate the parts of a compact date format
347    /// (i.e. mm/dd/yyyy has a separator of '/').
348    fn date_separator(&self) -> String;
349
350    /// The help text used on an empty `InputDatePickerFormField` to indicate
351    /// to the user the date format being asked for.
352    fn date_help_text(&self) -> String;
353
354    /// The semantic label used to announce when the user has entered the year
355    /// selection mode of the `CalendarDatePicker` which is used in the data picker
356    /// dialog created with `showDatePicker`.
357    fn select_year_semantics_label(&self) -> String;
358
359    /// The label used to indicate a date that has not been entered or selected
360    /// yet in the date picker.
361    fn unspecified_date(&self) -> String;
362
363    /// The label used to indicate a date range that has not been entered or
364    /// selected yet in the date range picker.
365    fn unspecified_date_range(&self) -> String;
366
367    /// The label used to describe the text field used in an `InputDatePickerFormField`.
368    fn date_input_label(&self) -> String;
369
370    /// The label used for the starting date input field in the date range picker
371    /// created with `showDateRangePicker`.
372    fn date_range_start_label(&self) -> String;
373
374    /// The label used for the ending date input field in the date range picker
375    /// created with `showDateRangePicker`.
376    fn date_range_end_label(&self) -> String;
377
378    /// The semantics label used for the selected start date in the date range
379    /// picker's day grid.
380    fn date_range_start_date_semantic_label(&self, formatted_date: &str) -> String;
381
382    /// The semantics label used for the selected end date in the date range
383    /// picker's day grid.
384    fn date_range_end_date_semantic_label(&self, formatted_date: &str) -> String;
385
386    /// Error message displayed to the user when they have entered a text string
387    /// in an `InputDatePickerFormField` that is not in a valid date format.
388    fn invalid_date_format_label(&self) -> String;
389
390    /// Error message displayed to the user when they have entered an invalid
391    /// date range in the input mode of the date range picker created with
392    /// `showDateRangePicker`.
393    fn invalid_date_range_label(&self) -> String;
394
395    /// Error message displayed to the user when they have entered a date that
396    /// is outside the valid range for the date picker.
397    /// `showDateRangePicker`.
398    fn date_out_of_range_label(&self) -> String;
399
400    /// Label for a 'SAVE' button. Currently used by the full screen mode of the
401    /// date range picker.
402    fn save_button_label(&self) -> String;
403
404    /// Label used in the header of the date picker dialog created with
405    /// `showDatePicker`.
406    fn date_picker_help_text(&self) -> String;
407
408    /// Label used in the header of the date range picker dialog created with
409    /// `showDateRangePicker`.
410    fn date_range_picker_help_text(&self) -> String;
411
412    /// Tooltip used for the calendar mode button of the date pickers.
413    fn calendar_mode_button_label(&self) -> String;
414
415    /// Tooltip used for the text input mode button of the date pickers.
416    fn input_date_mode_button_label(&self) -> String;
417
418    /// Label used in the header of the time picker dialog created with
419    /// `showTimePicker` when in `TimePickerEntryMode.dial`.
420    fn time_picker_dial_help_text(&self) -> String;
421
422    /// Label used in the header of the time picker dialog created with
423    /// `showTimePicker` when in `TimePickerEntryMode.input`.
424    fn time_picker_input_help_text(&self) -> String;
425
426    /// Label used below the hour text field of the time picker dialog created
427    /// with `showTimePicker` when in `TimePickerEntryMode.input`.
428    fn time_picker_hour_label(&self) -> String;
429
430    /// Label used below the minute text field of the time picker dialog created
431    /// with `showTimePicker` when in `TimePickerEntryMode.input`.
432    fn time_picker_minute_label(&self) -> String;
433
434    /// Error message for the time picker dialog created with `showTimePicker`
435    /// when in `TimePickerEntryMode.input`.
436    fn invalid_time_label(&self) -> String;
437
438    /// Tooltip used to put the time picker into `TimePickerEntryMode.dial`.
439    fn dial_mode_button_label(&self) -> String;
440
441    /// Tooltip used to put the time picker into `TimePickerEntryMode.input`.
442    fn input_time_mode_button_label(&self) -> String;
443
444    /// The semantics label used to indicate which account is signed in the
445    /// `UserAccountsDrawerHeader` widget.
446    fn signed_in_label(&self) -> String;
447
448    /// The semantics label used for the button on `UserAccountsDrawerHeader` that
449    /// hides the list of accounts.
450    fn hide_accounts_label(&self) -> String;
451
452    /// The semantics label used for the button on `UserAccountsDrawerHeader` that
453    /// shows the list of accounts.
454    fn show_accounts_label(&self) -> String;
455
456    /// The semantics label used for `ReorderableListView` to reorder an item in the
457    /// list to the start of the list.
458    #[deprecated(
459        note = "Use the reorderItemToStart from WidgetsLocalizations instead. This feature was deprecated after v3.10.0-2.0.pre."
460    )]
461    fn reorder_item_to_start(&self) -> String;
462
463    /// The semantics label used for `ReorderableListView` to reorder an item in the
464    /// list to the end of the list.
465    #[deprecated(
466        note = "Use the reorderItemToEnd from WidgetsLocalizations instead. This feature was deprecated after v3.10.0-2.0.pre."
467    )]
468    fn reorder_item_to_end(&self) -> String;
469
470    /// The semantics label used for `ReorderableListView` to reorder an item in the
471    /// list one space up the list.
472    #[deprecated(
473        note = "Use the reorderItemUp from WidgetsLocalizations instead. This feature was deprecated after v3.10.0-2.0.pre."
474    )]
475    fn reorder_item_up(&self) -> String;
476
477    /// The semantics label used for `ReorderableListView` to reorder an item in the
478    /// list one space down the list.
479    #[deprecated(
480        note = "Use the reorderItemDown from WidgetsLocalizations instead. This feature was deprecated after v3.10.0-2.0.pre."
481    )]
482    fn reorder_item_down(&self) -> String;
483
484    /// The semantics label used for `ReorderableListView` to reorder an item in the
485    /// list one space left in the list.
486    #[deprecated(
487        note = "Use the reorderItemLeft from WidgetsLocalizations instead. This feature was deprecated after v3.10.0-2.0.pre."
488    )]
489    fn reorder_item_left(&self) -> String;
490
491    /// The semantics label used for `ReorderableListView` to reorder an item in the
492    /// list one space right in the list.
493    #[deprecated(
494        note = "Use the reorderItemRight from WidgetsLocalizations instead. This feature was deprecated after v3.10.0-2.0.pre."
495    )]
496    fn reorder_item_right(&self) -> String;
497
498    /// The semantics hint to describe the tap action on an expanded `ExpandIcon`.
499    fn expanded_icon_tap_hint(&self) -> String {
500        String::from("Collapse")
501    }
502
503    /// The semantics hint to describe the tap action on a collapsed `ExpandIcon`.
504    fn collapsed_icon_tap_hint(&self) -> String {
505        String::from("Expand")
506    }
507
508    /// The semantics hint to describe the tap action on an expanded
509    /// `ExpansionTile` on iOS and macOS. This is appended to the [`collapsed_hint`](Self::collapsed_hint)
510    /// hint to provide a more detailed description of the action, e.g. "Expanded
511    /// double tap to collapse".
512    fn expansion_tile_expanded_hint(&self) -> String {
513        String::from("double tap to collapse")
514    }
515
516    /// The semantics hint to describe the tap action on a collapsed
517    /// `ExpansionTile` on iOS and macOS. This is appended to the [`expanded_hint`](Self::expanded_hint)
518    /// hint to provide a more detailed description of the action, e.g. "Collapsed
519    /// double tap to expand".
520    fn expansion_tile_collapsed_hint(&self) -> String {
521        String::from("double tap to expand")
522    }
523
524    /// The semantics hint to describe the tap action on an expanded `ExpansionTile`.
525    fn expansion_tile_expanded_tap_hint(&self) -> String {
526        String::from("Collapse")
527    }
528
529    /// The semantics hint to describe the tap action on a collapsed `ExpansionTile`.
530    fn expansion_tile_collapsed_tap_hint(&self) -> String {
531        String::from("Expand for more details")
532    }
533
534    /// The semantics hint to describe the `ExpansionTile` expanded state.
535    fn expanded_hint(&self) -> String {
536        String::from("Collapsed")
537    }
538
539    /// The semantics hint to describe the `ExpansionTile` collapsed state.
540    fn collapsed_hint(&self) -> String {
541        String::from("Expanded")
542    }
543
544    /// The label for the `TextField`'s character counter.
545    fn remaining_text_field_character_count(&self, remaining: i32) -> String;
546
547    /// The default semantics label for a `RefreshIndicator`.
548    fn refresh_indicator_semantic_label(&self) -> String;
549
550    /// The shortcut label for the keyboard key `LogicalKeyboardKey.alt`.
551    fn keyboard_key_alt(&self) -> String;
552
553    /// The shortcut label for the keyboard key `LogicalKeyboardKey.altGraph`.
554    fn keyboard_key_alt_graph(&self) -> String;
555
556    /// The shortcut label for the keyboard key `LogicalKeyboardKey.backspace`.
557    fn keyboard_key_backspace(&self) -> String;
558
559    /// The shortcut label for the keyboard key `LogicalKeyboardKey.capsLock`.
560    fn keyboard_key_caps_lock(&self) -> String;
561
562    /// The shortcut label for the keyboard key `LogicalKeyboardKey.channelDown`.
563    fn keyboard_key_channel_down(&self) -> String;
564
565    /// The shortcut label for the keyboard key `LogicalKeyboardKey.channelUp`.
566    fn keyboard_key_channel_up(&self) -> String;
567
568    /// The shortcut label for the keyboard key `LogicalKeyboardKey.control`.
569    fn keyboard_key_control(&self) -> String;
570
571    /// The shortcut label for the keyboard key `LogicalKeyboardKey.delete`.
572    fn keyboard_key_delete(&self) -> String;
573
574    /// The shortcut label for the keyboard key `LogicalKeyboardKey.eject`.
575    fn keyboard_key_eject(&self) -> String;
576
577    /// The shortcut label for the keyboard key `LogicalKeyboardKey.end`.
578    fn keyboard_key_end(&self) -> String;
579
580    /// The shortcut label for the keyboard key `LogicalKeyboardKey.escape`.
581    fn keyboard_key_escape(&self) -> String;
582
583    /// The shortcut label for the keyboard key `LogicalKeyboardKey.fn`.
584    fn keyboard_key_fn(&self) -> String;
585
586    /// The shortcut label for the keyboard key `LogicalKeyboardKey.home`.
587    fn keyboard_key_home(&self) -> String;
588
589    /// The shortcut label for the keyboard key `LogicalKeyboardKey.insert`.
590    fn keyboard_key_insert(&self) -> String;
591
592    /// The shortcut label for the keyboard key `LogicalKeyboardKey.meta`.
593    fn keyboard_key_meta(&self) -> String;
594
595    /// The shortcut label for the keyboard key `LogicalKeyboardKey.meta` on macOS.
596    fn keyboard_key_meta_mac_os(&self) -> String;
597
598    /// The shortcut label for the keyboard key `LogicalKeyboardKey.meta` on Windows.
599    fn keyboard_key_meta_windows(&self) -> String;
600
601    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numLock`.
602    fn keyboard_key_num_lock(&self) -> String;
603
604    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpad1`.
605    fn keyboard_key_numpad1(&self) -> String;
606
607    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpad2`.
608    fn keyboard_key_numpad2(&self) -> String;
609
610    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpad3`.
611    fn keyboard_key_numpad3(&self) -> String;
612
613    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpad4`.
614    fn keyboard_key_numpad4(&self) -> String;
615
616    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpad5`.
617    fn keyboard_key_numpad5(&self) -> String;
618
619    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpad6`.
620    fn keyboard_key_numpad6(&self) -> String;
621
622    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpad7`.
623    fn keyboard_key_numpad7(&self) -> String;
624
625    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpad8`.
626    fn keyboard_key_numpad8(&self) -> String;
627
628    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpad9`.
629    fn keyboard_key_numpad9(&self) -> String;
630
631    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpad0`.
632    fn keyboard_key_numpad0(&self) -> String;
633
634    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpadAdd`.
635    fn keyboard_key_numpad_add(&self) -> String;
636
637    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpadComma`.
638    fn keyboard_key_numpad_comma(&self) -> String;
639
640    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpadDecimal`.
641    fn keyboard_key_numpad_decimal(&self) -> String;
642
643    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpadDivide`.
644    fn keyboard_key_numpad_divide(&self) -> String;
645
646    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpadEnter`.
647    fn keyboard_key_numpad_enter(&self) -> String;
648
649    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpadEqual`.
650    fn keyboard_key_numpad_equal(&self) -> String;
651
652    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpadMultiply`.
653    fn keyboard_key_numpad_multiply(&self) -> String;
654
655    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpadParenLeft`.
656    fn keyboard_key_numpad_paren_left(&self) -> String;
657
658    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpadParenRight`.
659    fn keyboard_key_numpad_paren_right(&self) -> String;
660
661    /// The shortcut label for the keyboard key `LogicalKeyboardKey.numpadSubtract`.
662    fn keyboard_key_numpad_subtract(&self) -> String;
663
664    /// The shortcut label for the keyboard key `LogicalKeyboardKey.pageDown`.
665    fn keyboard_key_page_down(&self) -> String;
666
667    /// The shortcut label for the keyboard key `LogicalKeyboardKey.pageUp`.
668    fn keyboard_key_page_up(&self) -> String;
669
670    /// The shortcut label for the keyboard key `LogicalKeyboardKey.power`.
671    fn keyboard_key_power(&self) -> String;
672
673    /// The shortcut label for the keyboard key `LogicalKeyboardKey.powerOff`.
674    fn keyboard_key_power_off(&self) -> String;
675
676    /// The shortcut label for the keyboard key `LogicalKeyboardKey.printScreen`.
677    fn keyboard_key_print_screen(&self) -> String;
678
679    /// The shortcut label for the keyboard key `LogicalKeyboardKey.scrollLock`.
680    fn keyboard_key_scroll_lock(&self) -> String;
681
682    /// The shortcut label for the keyboard key `LogicalKeyboardKey.select`.
683    fn keyboard_key_select(&self) -> String;
684
685    /// The shortcut label for the keyboard key `LogicalKeyboardKey.shift`.
686    fn keyboard_key_shift(&self) -> String;
687
688    /// The shortcut label for the keyboard key `LogicalKeyboardKey.space`.
689    fn keyboard_key_space(&self) -> String;
690}
691
692impl dyn MaterialLocalizations {
693    /// The `MaterialLocalizations` from the closest [`Localizations`] instance
694    /// that encloses the given context.
695    ///
696    /// If no [`MaterialLocalizations`] are available in the given `context`, this
697    /// method throws an exception.
698    ///
699    /// This method is just a convenient shorthand for:
700    /// `Localizations::of::<dyn MaterialLocalizations>(app, context)`.
701    ///
702    /// References to the localized resources defined by this class are typically
703    /// written in terms of this method. For example:
704    ///
705    /// ```text
706    /// tooltip: <dyn MaterialLocalizations>::of(app, context).back_button_tooltip(),
707    /// ```
708    pub fn of(app: &mut App, context: BuildContext) -> Rc<dyn MaterialLocalizations> {
709        debug_assert!(debug_check_has_material_localizations(app, context));
710        Localizations::of::<dyn MaterialLocalizations>(app, context)
711            .expect("No MaterialLocalizations found.")
712    }
713}
714
715struct MaterialLocalizationsDelegate;
716
717impl LocalizationsDelegate<dyn MaterialLocalizations> for MaterialLocalizationsDelegate {
718    fn is_supported(&self, locale: &Locale) -> bool {
719        locale.language_code == "en"
720    }
721
722    fn load(
723        &self,
724        _app: &mut App,
725        locale: &Locale,
726    ) -> CompleterFuture<Rc<dyn MaterialLocalizations>> {
727        DefaultMaterialLocalizations::load(locale)
728    }
729
730    fn should_reload(&self, _old: &Self) -> bool {
731        false
732    }
733}
734
735impl fmt::Debug for MaterialLocalizationsDelegate {
736    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
737        f.write_str("DefaultMaterialLocalizations.delegate(en_US)")
738    }
739}
740
741/// US English strings for the material widgets.
742///
743/// See also:
744///
745///  * `GlobalMaterialLocalizations`, which provides material localizations for
746///    many languages.
747///  * `MaterialApp.localizationsDelegates`, which automatically includes
748///    [`DefaultMaterialLocalizations::delegate`] by default.
749#[derive(Debug, Default)]
750pub struct DefaultMaterialLocalizations;
751
752impl DefaultMaterialLocalizations {
753    /// Constructs an object that defines the material widgets' localized strings
754    /// for US English (only).
755    ///
756    /// [`LocalizationsDelegate`] implementations typically call the static [`load`](Self::load)
757    /// function, rather than constructing this class directly.
758    pub const fn new() -> DefaultMaterialLocalizations {
759        DefaultMaterialLocalizations
760    }
761
762    // Ordered to match DateTime.monday=1, DateTime.sunday=6
763    const SHORT_WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
764
765    // Ordered to match DateTime.monday=1, DateTime.sunday=6
766    const WEEKDAYS: [&str; 7] = [
767        "Monday",
768        "Tuesday",
769        "Wednesday",
770        "Thursday",
771        "Friday",
772        "Saturday",
773        "Sunday",
774    ];
775
776    const NARROW_WEEKDAYS: [&str; 7] = ["S", "M", "T", "W", "T", "F", "S"];
777
778    const SHORT_MONTHS: [&str; 12] = [
779        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
780    ];
781
782    const MONTHS: [&str; 12] = [
783        "January",
784        "February",
785        "March",
786        "April",
787        "May",
788        "June",
789        "July",
790        "August",
791        "September",
792        "October",
793        "November",
794        "December",
795    ];
796
797    /// Returns the number of days in a month, according to the proleptic
798    /// Gregorian calendar.
799    ///
800    /// This applies the leap year logic introduced by the Gregorian reforms of
801    /// 1582. It will not give valid results for dates prior to that time.
802    fn get_days_in_month(year: i64, month: i64) -> i64 {
803        if month == i64::from(DateTime::FEBRUARY) {
804            let is_leap_year = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
805            if is_leap_year {
806                return 29;
807            }
808            return 28;
809        }
810        const DAYS_IN_MONTH: [i64; 12] = [31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
811        DAYS_IN_MONTH[usize::try_from(month - 1).expect("a month in 1..=12")]
812    }
813
814    /// Formats `number` using two digits, assuming it's in the 0-99 inclusive
815    /// range. Not designed to format values outside this range.
816    fn format_two_digit_zero_pad(number: i32) -> String {
817        debug_assert!((0..100).contains(&number));
818
819        if number < 10 {
820            return format!("0{number}");
821        }
822
823        number.to_string()
824    }
825
826    fn format_day_period(&self, time_of_day: &TimeOfDay) -> String {
827        match time_of_day.period() {
828            DayPeriod::Am => self.ante_meridiem_abbreviation(),
829            DayPeriod::Pm => self.post_meridiem_abbreviation(),
830        }
831    }
832
833    /// Creates an object that provides US English resource values for the material
834    /// library widgets.
835    ///
836    /// The `locale` parameter is ignored.
837    ///
838    /// This method is typically used to create a [`LocalizationsDelegate`].
839    /// The `MaterialApp` does so by default.
840    pub fn load(_locale: &Locale) -> CompleterFuture<Rc<dyn MaterialLocalizations>> {
841        CompleterFuture::ready(Rc::new(DefaultMaterialLocalizations::new()))
842    }
843
844    /// A [`LocalizationsDelegate`] that uses [`DefaultMaterialLocalizations::load`]
845    /// to create an instance of this class.
846    ///
847    /// `MaterialApp` automatically adds this value to `MaterialApp.localizationsDelegates`.
848    pub fn delegate() -> LocalizationsDelegateRef {
849        LocalizationsDelegateRef::new(MaterialLocalizationsDelegate)
850    }
851}
852
853/// The index of `date`'s month in a table that starts with January.
854fn month_index(app: &App, date: &DateTime) -> usize {
855    usize::try_from(date.month(app) - DateTime::JANUARY).expect("a month in 1..=12")
856}
857
858/// The index of `date`'s weekday in a table that starts with Monday.
859fn weekday_index(app: &App, date: &DateTime) -> usize {
860    usize::try_from(date.weekday(app) - DateTime::MONDAY).expect("a weekday in 1..=7")
861}
862
863/// Dart's `int.tryParse(source, radix: 10)`: surrounding whitespace (Dart's, which counts
864/// U+FEFF) and a sign are accepted, and a value outside 64 bits is `None`.
865fn try_parse_int(source: &str) -> Option<i64> {
866    source
867        .trim_matches(|c: char| c.is_whitespace() || c == '\u{FEFF}')
868        .parse()
869        .ok()
870}
871
872/// Dart's `DateTime(year, month, day)` for a valid date from year 1 on, with the
873/// `ArgumentError` it throws past the last day a `DateTime` can represent as `None`.
874fn date_time_or_none(app: &App, year: i64, month: i64, day: i64) -> Option<DateTime> {
875    // The last instant a `DateTime` holds, 100,000,000 days after the epoch, read in the local
876    // zone: a local midnight after its date is out of range.
877    const LAST_MILLISECOND: i64 = 8_640_000_000_000_000;
878    let last = DateTime::from_milliseconds_since_epoch(LAST_MILLISECOND, false);
879    let last_day = (
880        i64::from(last.year(app)),
881        i64::from(last.month(app)),
882        i64::from(last.day(app)),
883    );
884    if (year, month, day) > last_day {
885        return None;
886    }
887    let field = |value: i64| i32::try_from(value).expect("within the representable range");
888    Some(DateTime::new(app, field(year), field(month), field(day)))
889}
890
891impl MaterialLocalizations for DefaultMaterialLocalizations {
892    fn format_hour(&self, time_of_day: &TimeOfDay, always_use_24_hour_format: bool) -> String {
893        let format = self.time_of_day_format(always_use_24_hour_format);
894        match format {
895            TimeOfDayFormat::h_colon_mm_space_a => {
896                self.format_decimal(i64::from(if time_of_day.hour_of_period() == 0 {
897                    12
898                } else {
899                    time_of_day.hour_of_period()
900                }))
901            }
902            TimeOfDayFormat::HH_colon_mm => Self::format_two_digit_zero_pad(time_of_day.hour),
903            TimeOfDayFormat::a_space_h_colon_mm
904            | TimeOfDayFormat::FrenchCanadian
905            | TimeOfDayFormat::H_colon_mm
906            | TimeOfDayFormat::HH_dot_mm => {
907                panic!("DefaultMaterialLocalizations does not support {format:?}.")
908            }
909        }
910    }
911
912    fn format_minute(&self, time_of_day: &TimeOfDay) -> String {
913        let minute = time_of_day.minute;
914        if minute < 10 {
915            format!("0{minute}")
916        } else {
917            minute.to_string()
918        }
919    }
920
921    fn format_year(&self, app: &App, date: &DateTime) -> String {
922        date.year(app).to_string()
923    }
924
925    fn format_compact_date(&self, app: &App, date: &DateTime) -> String {
926        // Assumes US mm/dd/yyyy format
927        let month = Self::format_two_digit_zero_pad(date.month(app));
928        let day = Self::format_two_digit_zero_pad(date.day(app));
929        let year = format!("{:0>4}", date.year(app).to_string());
930        format!("{month}/{day}/{year}")
931    }
932
933    fn format_short_date(&self, app: &App, date: &DateTime) -> String {
934        let month = Self::SHORT_MONTHS[month_index(app, date)];
935        format!("{month} {}, {}", date.day(app), date.year(app))
936    }
937
938    fn format_medium_date(&self, app: &App, date: &DateTime) -> String {
939        let day = Self::SHORT_WEEKDAYS[weekday_index(app, date)];
940        let month = Self::SHORT_MONTHS[month_index(app, date)];
941        format!("{day}, {month} {}", date.day(app))
942    }
943
944    fn format_full_date(&self, app: &App, date: &DateTime) -> String {
945        let month = Self::MONTHS[month_index(app, date)];
946        format!(
947            "{}, {month} {}, {}",
948            Self::WEEKDAYS[weekday_index(app, date)],
949            date.day(app),
950            date.year(app)
951        )
952    }
953
954    fn format_month_year(&self, app: &App, date: &DateTime) -> String {
955        let year = self.format_year(app, date);
956        let month = Self::MONTHS[month_index(app, date)];
957        format!("{month} {year}")
958    }
959
960    fn format_short_month_day(&self, app: &App, date: &DateTime) -> String {
961        let month = Self::SHORT_MONTHS[month_index(app, date)];
962        format!("{month} {}", date.day(app))
963    }
964
965    fn parse_compact_date(&self, app: &App, input_string: Option<&str>) -> Option<DateTime> {
966        let input_string = input_string?;
967
968        // Assumes US mm/dd/yyyy format
969        let input_parts: Vec<&str> = input_string.split('/').collect();
970        if input_parts.len() != 3 {
971            return None;
972        }
973
974        let year = try_parse_int(input_parts[2]).filter(|&year| year >= 1)?;
975
976        let month = try_parse_int(input_parts[0]).filter(|month| (1..=12).contains(month))?;
977
978        let day = try_parse_int(input_parts[1])
979            .filter(|&day| day >= 1 && day <= Self::get_days_in_month(year, month))?;
980
981        date_time_or_none(app, year, month, day)
982    }
983
984    fn narrow_weekdays(&self) -> Vec<String> {
985        Self::NARROW_WEEKDAYS.map(String::from).to_vec()
986    }
987
988    fn first_day_of_week_index(&self) -> i32 {
989        0 // narrow_weekdays[0] is 'S' for Sunday
990    }
991
992    fn date_separator(&self) -> String {
993        String::from("/")
994    }
995
996    fn date_help_text(&self) -> String {
997        String::from("mm/dd/yyyy")
998    }
999
1000    fn select_year_semantics_label(&self) -> String {
1001        String::from("Select year")
1002    }
1003
1004    fn unspecified_date(&self) -> String {
1005        String::from("Date")
1006    }
1007
1008    fn unspecified_date_range(&self) -> String {
1009        String::from("Date Range")
1010    }
1011
1012    fn date_input_label(&self) -> String {
1013        String::from("Enter Date")
1014    }
1015
1016    fn date_range_start_label(&self) -> String {
1017        String::from("Start Date")
1018    }
1019
1020    fn date_range_end_label(&self) -> String {
1021        String::from("End Date")
1022    }
1023
1024    fn date_range_start_date_semantic_label(&self, formatted_date: &str) -> String {
1025        format!("Start date {formatted_date}")
1026    }
1027
1028    fn date_range_end_date_semantic_label(&self, formatted_date: &str) -> String {
1029        format!("End date {formatted_date}")
1030    }
1031
1032    fn invalid_date_format_label(&self) -> String {
1033        String::from("Invalid format.")
1034    }
1035
1036    fn invalid_date_range_label(&self) -> String {
1037        String::from("Invalid range.")
1038    }
1039
1040    fn date_out_of_range_label(&self) -> String {
1041        String::from("Out of range.")
1042    }
1043
1044    fn save_button_label(&self) -> String {
1045        String::from("Save")
1046    }
1047
1048    fn date_picker_help_text(&self) -> String {
1049        String::from("Select date")
1050    }
1051
1052    fn date_range_picker_help_text(&self) -> String {
1053        String::from("Select range")
1054    }
1055
1056    fn calendar_mode_button_label(&self) -> String {
1057        String::from("Switch to calendar")
1058    }
1059
1060    fn input_date_mode_button_label(&self) -> String {
1061        String::from("Switch to input")
1062    }
1063
1064    fn time_picker_dial_help_text(&self) -> String {
1065        String::from("Select time")
1066    }
1067
1068    fn time_picker_input_help_text(&self) -> String {
1069        String::from("Enter time")
1070    }
1071
1072    fn time_picker_hour_label(&self) -> String {
1073        String::from("Hour")
1074    }
1075
1076    fn time_picker_minute_label(&self) -> String {
1077        String::from("Minute")
1078    }
1079
1080    fn invalid_time_label(&self) -> String {
1081        String::from("Enter a valid time")
1082    }
1083
1084    fn dial_mode_button_label(&self) -> String {
1085        String::from("Switch to dial picker mode")
1086    }
1087
1088    fn input_time_mode_button_label(&self) -> String {
1089        String::from("Switch to text input mode")
1090    }
1091
1092    fn format_decimal(&self, number: i64) -> String {
1093        if number > -1000 && number < 1000 {
1094            return number.to_string();
1095        }
1096
1097        // Dart's 64-bit `abs`, under which the smallest int stays negative.
1098        let digits = number.wrapping_abs().to_string();
1099        let mut result = String::from(if number < 0 { "-" } else { "" });
1100        let max_digit_index = digits.len() - 1;
1101        for (i, digit) in digits.chars().enumerate() {
1102            result.push(digit);
1103            if i < max_digit_index && (max_digit_index - i).is_multiple_of(3) {
1104                result.push(',');
1105            }
1106        }
1107        result
1108    }
1109
1110    fn format_time_of_day(
1111        &self,
1112        time_of_day: &TimeOfDay,
1113        always_use_24_hour_format: bool,
1114    ) -> String {
1115        // Not using intl.DateFormat for two reasons:
1116        //
1117        // - DateFormat supports more formats than our material time picker does,
1118        //   and we want to be consistent across time picker format and the string
1119        //   formatting of the time of day.
1120        // - DateFormat operates on DateTime, which is sensitive to time eras and
1121        //   time zones, while here we want to format hour and minute within one day
1122        //   no matter what date the day falls on.
1123        let mut buffer = String::new();
1124
1125        // Add hour:minute.
1126        buffer.push_str(&self.format_hour(time_of_day, always_use_24_hour_format));
1127        buffer.push(':');
1128        buffer.push_str(&self.format_minute(time_of_day));
1129
1130        if always_use_24_hour_format {
1131            // There's no AM/PM indicator in 24-hour format.
1132            return buffer;
1133        }
1134
1135        // Add AM/PM indicator.
1136        buffer.push(' ');
1137        buffer.push_str(&self.format_day_period(time_of_day));
1138        buffer
1139    }
1140
1141    fn open_app_drawer_tooltip(&self) -> String {
1142        String::from("Open navigation menu")
1143    }
1144
1145    fn back_button_tooltip(&self) -> String {
1146        String::from("Back")
1147    }
1148
1149    fn clear_button_tooltip(&self) -> String {
1150        String::from("Clear text")
1151    }
1152
1153    fn close_button_tooltip(&self) -> String {
1154        String::from("Close")
1155    }
1156
1157    fn delete_button_tooltip(&self) -> String {
1158        String::from("Delete")
1159    }
1160
1161    fn more_button_tooltip(&self) -> String {
1162        String::from("More")
1163    }
1164
1165    fn next_month_tooltip(&self) -> String {
1166        String::from("Next month")
1167    }
1168
1169    fn previous_month_tooltip(&self) -> String {
1170        String::from("Previous month")
1171    }
1172
1173    fn next_page_tooltip(&self) -> String {
1174        String::from("Next page")
1175    }
1176
1177    fn previous_page_tooltip(&self) -> String {
1178        String::from("Previous page")
1179    }
1180
1181    fn first_page_tooltip(&self) -> String {
1182        String::from("First page")
1183    }
1184
1185    fn last_page_tooltip(&self) -> String {
1186        String::from("Last page")
1187    }
1188
1189    fn show_menu_tooltip(&self) -> String {
1190        String::from("Show menu")
1191    }
1192
1193    fn drawer_label(&self) -> String {
1194        String::from("Navigation menu")
1195    }
1196
1197    fn menu_bar_menu_label(&self) -> String {
1198        String::from("Menu bar menu")
1199    }
1200
1201    fn popup_menu_label(&self) -> String {
1202        String::from("Popup menu")
1203    }
1204
1205    fn dialog_label(&self) -> String {
1206        String::from("Dialog")
1207    }
1208
1209    fn alert_dialog_label(&self) -> String {
1210        String::from("Alert")
1211    }
1212
1213    fn search_field_label(&self) -> String {
1214        String::from("Search")
1215    }
1216
1217    fn current_date_label(&self) -> String {
1218        String::from("Today")
1219    }
1220
1221    fn selected_date_label(&self) -> String {
1222        String::from("Selected")
1223    }
1224
1225    fn scrim_label(&self) -> String {
1226        String::from("Scrim")
1227    }
1228
1229    fn bottom_sheet_label(&self) -> String {
1230        String::from("Bottom Sheet")
1231    }
1232
1233    fn scrim_on_tap_hint(&self, modal_route_content_name: &str) -> String {
1234        format!("Close {modal_route_content_name}")
1235    }
1236
1237    fn about_list_tile_title(&self, application_name: &str) -> String {
1238        format!("About {application_name}")
1239    }
1240
1241    fn licenses_page_title(&self) -> String {
1242        String::from("Licenses")
1243    }
1244
1245    fn licenses_package_detail_text(&self, license_count: i32) -> String {
1246        debug_assert!(license_count >= 0);
1247        match license_count {
1248            0 => String::from("No licenses."),
1249            1 => String::from("1 license."),
1250            _ => format!("{license_count} licenses."),
1251        }
1252    }
1253
1254    fn page_rows_info_title(
1255        &self,
1256        first_row: i32,
1257        last_row: i32,
1258        row_count: i32,
1259        row_count_is_approximate: bool,
1260    ) -> String {
1261        if row_count_is_approximate {
1262            format!("{first_row}–{last_row} of about {row_count}")
1263        } else {
1264            format!("{first_row}–{last_row} of {row_count}")
1265        }
1266    }
1267
1268    fn rows_per_page_title(&self) -> String {
1269        String::from("Rows per page:")
1270    }
1271
1272    fn tab_label(&self, tab_index: i32, tab_count: i32) -> String {
1273        debug_assert!(tab_index >= 1);
1274        debug_assert!(tab_count >= 1);
1275        format!("Tab {tab_index} of {tab_count}")
1276    }
1277
1278    fn selected_row_count_title(&self, selected_row_count: i32) -> String {
1279        match selected_row_count {
1280            0 => String::from("No items selected"),
1281            1 => String::from("1 item selected"),
1282            _ => format!("{selected_row_count} items selected"),
1283        }
1284    }
1285
1286    fn cancel_button_label(&self) -> String {
1287        String::from("Cancel")
1288    }
1289
1290    fn close_button_label(&self) -> String {
1291        String::from("Close")
1292    }
1293
1294    fn continue_button_label(&self) -> String {
1295        String::from("Continue")
1296    }
1297
1298    fn copy_button_label(&self) -> String {
1299        String::from("Copy")
1300    }
1301
1302    fn cut_button_label(&self) -> String {
1303        String::from("Cut")
1304    }
1305
1306    fn scan_text_button_label(&self) -> String {
1307        String::from("Scan text")
1308    }
1309
1310    fn ok_button_label(&self) -> String {
1311        String::from("OK")
1312    }
1313
1314    fn paste_button_label(&self) -> String {
1315        String::from("Paste")
1316    }
1317
1318    fn select_all_button_label(&self) -> String {
1319        String::from("Select all")
1320    }
1321
1322    fn look_up_button_label(&self) -> String {
1323        String::from("Look Up")
1324    }
1325
1326    fn search_web_button_label(&self) -> String {
1327        String::from("Search Web")
1328    }
1329
1330    fn share_button_label(&self) -> String {
1331        String::from("Share")
1332    }
1333
1334    fn view_licenses_button_label(&self) -> String {
1335        String::from("View licenses")
1336    }
1337
1338    fn ante_meridiem_abbreviation(&self) -> String {
1339        String::from("AM")
1340    }
1341
1342    fn post_meridiem_abbreviation(&self) -> String {
1343        String::from("PM")
1344    }
1345
1346    fn time_picker_hour_mode_announcement(&self) -> String {
1347        String::from("Select hours")
1348    }
1349
1350    fn time_picker_minute_mode_announcement(&self) -> String {
1351        String::from("Select minutes")
1352    }
1353
1354    fn modal_barrier_dismiss_label(&self) -> String {
1355        String::from("Dismiss")
1356    }
1357
1358    fn menu_dismiss_label(&self) -> String {
1359        String::from("Dismiss menu")
1360    }
1361
1362    fn script_category(&self) -> ScriptCategory {
1363        ScriptCategory::EnglishLike
1364    }
1365
1366    fn time_of_day_format(&self, always_use_24_hour_format: bool) -> TimeOfDayFormat {
1367        if always_use_24_hour_format {
1368            TimeOfDayFormat::HH_colon_mm
1369        } else {
1370            TimeOfDayFormat::h_colon_mm_space_a
1371        }
1372    }
1373
1374    fn signed_in_label(&self) -> String {
1375        String::from("Signed in")
1376    }
1377
1378    fn hide_accounts_label(&self) -> String {
1379        String::from("Hide accounts")
1380    }
1381
1382    fn show_accounts_label(&self) -> String {
1383        String::from("Show accounts")
1384    }
1385
1386    fn reorder_item_up(&self) -> String {
1387        String::from("Move up")
1388    }
1389
1390    fn reorder_item_down(&self) -> String {
1391        String::from("Move down")
1392    }
1393
1394    fn reorder_item_left(&self) -> String {
1395        String::from("Move left")
1396    }
1397
1398    fn reorder_item_right(&self) -> String {
1399        String::from("Move right")
1400    }
1401
1402    fn reorder_item_to_end(&self) -> String {
1403        String::from("Move to the end")
1404    }
1405
1406    fn reorder_item_to_start(&self) -> String {
1407        String::from("Move to the start")
1408    }
1409
1410    fn expanded_icon_tap_hint(&self) -> String {
1411        String::from("Collapse")
1412    }
1413
1414    fn collapsed_icon_tap_hint(&self) -> String {
1415        String::from("Expand")
1416    }
1417
1418    fn expansion_tile_expanded_hint(&self) -> String {
1419        String::from("double tap to collapse")
1420    }
1421
1422    fn expansion_tile_collapsed_hint(&self) -> String {
1423        String::from("double tap to expand")
1424    }
1425
1426    fn expansion_tile_expanded_tap_hint(&self) -> String {
1427        String::from("Collapse")
1428    }
1429
1430    fn expansion_tile_collapsed_tap_hint(&self) -> String {
1431        String::from("Expand for more details")
1432    }
1433
1434    fn expanded_hint(&self) -> String {
1435        String::from("Collapsed")
1436    }
1437
1438    fn collapsed_hint(&self) -> String {
1439        String::from("Expanded")
1440    }
1441
1442    fn refresh_indicator_semantic_label(&self) -> String {
1443        String::from("Refresh")
1444    }
1445
1446    fn remaining_text_field_character_count(&self, remaining: i32) -> String {
1447        match remaining {
1448            0 => String::from("No characters remaining"),
1449            1 => String::from("1 character remaining"),
1450            _ => format!("{remaining} characters remaining"),
1451        }
1452    }
1453
1454    fn keyboard_key_alt(&self) -> String {
1455        String::from("Alt")
1456    }
1457
1458    fn keyboard_key_alt_graph(&self) -> String {
1459        String::from("AltGr")
1460    }
1461
1462    fn keyboard_key_backspace(&self) -> String {
1463        String::from("Backspace")
1464    }
1465
1466    fn keyboard_key_caps_lock(&self) -> String {
1467        String::from("Caps Lock")
1468    }
1469
1470    fn keyboard_key_channel_down(&self) -> String {
1471        String::from("Channel Down")
1472    }
1473
1474    fn keyboard_key_channel_up(&self) -> String {
1475        String::from("Channel Up")
1476    }
1477
1478    fn keyboard_key_control(&self) -> String {
1479        String::from("Ctrl")
1480    }
1481
1482    fn keyboard_key_delete(&self) -> String {
1483        String::from("Del")
1484    }
1485
1486    fn keyboard_key_eject(&self) -> String {
1487        String::from("Eject")
1488    }
1489
1490    fn keyboard_key_end(&self) -> String {
1491        String::from("End")
1492    }
1493
1494    fn keyboard_key_escape(&self) -> String {
1495        String::from("Esc")
1496    }
1497
1498    fn keyboard_key_fn(&self) -> String {
1499        String::from("Fn")
1500    }
1501
1502    fn keyboard_key_home(&self) -> String {
1503        String::from("Home")
1504    }
1505
1506    fn keyboard_key_insert(&self) -> String {
1507        String::from("Insert")
1508    }
1509
1510    fn keyboard_key_meta(&self) -> String {
1511        String::from("Meta")
1512    }
1513
1514    fn keyboard_key_meta_mac_os(&self) -> String {
1515        String::from("Command")
1516    }
1517
1518    fn keyboard_key_meta_windows(&self) -> String {
1519        String::from("Win")
1520    }
1521
1522    fn keyboard_key_num_lock(&self) -> String {
1523        String::from("Num Lock")
1524    }
1525
1526    fn keyboard_key_numpad1(&self) -> String {
1527        String::from("Num 1")
1528    }
1529
1530    fn keyboard_key_numpad2(&self) -> String {
1531        String::from("Num 2")
1532    }
1533
1534    fn keyboard_key_numpad3(&self) -> String {
1535        String::from("Num 3")
1536    }
1537
1538    fn keyboard_key_numpad4(&self) -> String {
1539        String::from("Num 4")
1540    }
1541
1542    fn keyboard_key_numpad5(&self) -> String {
1543        String::from("Num 5")
1544    }
1545
1546    fn keyboard_key_numpad6(&self) -> String {
1547        String::from("Num 6")
1548    }
1549
1550    fn keyboard_key_numpad7(&self) -> String {
1551        String::from("Num 7")
1552    }
1553
1554    fn keyboard_key_numpad8(&self) -> String {
1555        String::from("Num 8")
1556    }
1557
1558    fn keyboard_key_numpad9(&self) -> String {
1559        String::from("Num 9")
1560    }
1561
1562    fn keyboard_key_numpad0(&self) -> String {
1563        String::from("Num 0")
1564    }
1565
1566    fn keyboard_key_numpad_add(&self) -> String {
1567        String::from("Num +")
1568    }
1569
1570    fn keyboard_key_numpad_comma(&self) -> String {
1571        String::from("Num ,")
1572    }
1573
1574    fn keyboard_key_numpad_decimal(&self) -> String {
1575        String::from("Num .")
1576    }
1577
1578    fn keyboard_key_numpad_divide(&self) -> String {
1579        String::from("Num /")
1580    }
1581
1582    fn keyboard_key_numpad_enter(&self) -> String {
1583        String::from("Num Enter")
1584    }
1585
1586    fn keyboard_key_numpad_equal(&self) -> String {
1587        String::from("Num =")
1588    }
1589
1590    fn keyboard_key_numpad_multiply(&self) -> String {
1591        String::from("Num *")
1592    }
1593
1594    fn keyboard_key_numpad_paren_left(&self) -> String {
1595        String::from("Num (")
1596    }
1597
1598    fn keyboard_key_numpad_paren_right(&self) -> String {
1599        String::from("Num )")
1600    }
1601
1602    fn keyboard_key_numpad_subtract(&self) -> String {
1603        String::from("Num -")
1604    }
1605
1606    fn keyboard_key_page_down(&self) -> String {
1607        String::from("PgDown")
1608    }
1609
1610    fn keyboard_key_page_up(&self) -> String {
1611        String::from("PgUp")
1612    }
1613
1614    fn keyboard_key_power(&self) -> String {
1615        String::from("Power")
1616    }
1617
1618    fn keyboard_key_power_off(&self) -> String {
1619        String::from("Power Off")
1620    }
1621
1622    fn keyboard_key_print_screen(&self) -> String {
1623        String::from("Print Screen")
1624    }
1625
1626    fn keyboard_key_scroll_lock(&self) -> String {
1627        String::from("Scroll Lock")
1628    }
1629
1630    fn keyboard_key_select(&self) -> String {
1631        String::from("Select")
1632    }
1633
1634    fn keyboard_key_shift(&self) -> String {
1635        String::from("Shift")
1636    }
1637
1638    fn keyboard_key_space(&self) -> String {
1639        String::from("Space")
1640    }
1641}
1642
1643#[cfg(test)]
1644pub(crate) mod tests {
1645    use std::cell::RefCell;
1646    use waft_widgets::testing::test_widgets;
1647
1648    use waft_widgets::{Builder, DefaultWidgetsLocalizations, IntoWidget, SizedBox, WidgetRef};
1649
1650    use waft_foundation::AppCell;
1651
1652    use super::*;
1653
1654    /// `child` under the US English widgets and Material localizations, as `MaterialApp`
1655    /// provides them.
1656    pub(crate) fn us_english<K>(child: impl IntoWidget<K>) -> WidgetRef {
1657        Localizations::new(
1658            Locale::new("en").country_code("US"),
1659            vec![
1660                DefaultWidgetsLocalizations::delegate(),
1661                DefaultMaterialLocalizations::delegate(),
1662            ],
1663        )
1664        .child(child)
1665        .into_widget()
1666    }
1667
1668    // localizations_test.dart 'English translations exist for all MaterialLocalizations
1669    // properties', with the strings themselves.
1670    #[test]
1671    #[allow(deprecated)]
1672    fn the_default_strings_are_the_us_english_ones() {
1673        let strings: &dyn MaterialLocalizations = &DefaultMaterialLocalizations::new();
1674
1675        assert_eq!(strings.script_category(), ScriptCategory::EnglishLike);
1676        assert_eq!(strings.date_separator(), "/");
1677        assert_eq!(strings.date_help_text(), "mm/dd/yyyy");
1678        assert_eq!(strings.select_year_semantics_label(), "Select year");
1679        assert_eq!(strings.unspecified_date(), "Date");
1680        assert_eq!(strings.unspecified_date_range(), "Date Range");
1681        assert_eq!(strings.date_input_label(), "Enter Date");
1682        assert_eq!(strings.date_range_start_label(), "Start Date");
1683        assert_eq!(strings.date_range_end_label(), "End Date");
1684        assert_eq!(strings.invalid_date_format_label(), "Invalid format.");
1685        assert_eq!(strings.invalid_date_range_label(), "Invalid range.");
1686        assert_eq!(strings.date_out_of_range_label(), "Out of range.");
1687        assert_eq!(strings.save_button_label(), "Save");
1688        assert_eq!(strings.date_picker_help_text(), "Select date");
1689        assert_eq!(strings.date_range_picker_help_text(), "Select range");
1690        assert_eq!(strings.calendar_mode_button_label(), "Switch to calendar");
1691        assert_eq!(strings.input_date_mode_button_label(), "Switch to input");
1692        assert_eq!(strings.time_picker_dial_help_text(), "Select time");
1693        assert_eq!(strings.time_picker_input_help_text(), "Enter time");
1694        assert_eq!(strings.time_picker_hour_label(), "Hour");
1695        assert_eq!(strings.time_picker_minute_label(), "Minute");
1696        assert_eq!(strings.invalid_time_label(), "Enter a valid time");
1697        assert_eq!(
1698            strings.dial_mode_button_label(),
1699            "Switch to dial picker mode"
1700        );
1701        assert_eq!(
1702            strings.input_time_mode_button_label(),
1703            "Switch to text input mode"
1704        );
1705        assert_eq!(strings.open_app_drawer_tooltip(), "Open navigation menu");
1706        assert_eq!(strings.back_button_tooltip(), "Back");
1707        assert_eq!(strings.clear_button_tooltip(), "Clear text");
1708        assert_eq!(strings.close_button_tooltip(), "Close");
1709        assert_eq!(strings.delete_button_tooltip(), "Delete");
1710        assert_eq!(strings.more_button_tooltip(), "More");
1711        assert_eq!(strings.next_month_tooltip(), "Next month");
1712        assert_eq!(strings.previous_month_tooltip(), "Previous month");
1713        assert_eq!(strings.next_page_tooltip(), "Next page");
1714        assert_eq!(strings.previous_page_tooltip(), "Previous page");
1715        assert_eq!(strings.first_page_tooltip(), "First page");
1716        assert_eq!(strings.last_page_tooltip(), "Last page");
1717        assert_eq!(strings.show_menu_tooltip(), "Show menu");
1718        assert_eq!(strings.drawer_label(), "Navigation menu");
1719        assert_eq!(strings.menu_bar_menu_label(), "Menu bar menu");
1720        assert_eq!(strings.popup_menu_label(), "Popup menu");
1721        assert_eq!(strings.dialog_label(), "Dialog");
1722        assert_eq!(strings.alert_dialog_label(), "Alert");
1723        assert_eq!(strings.search_field_label(), "Search");
1724        assert_eq!(strings.current_date_label(), "Today");
1725        assert_eq!(strings.selected_date_label(), "Selected");
1726        assert_eq!(strings.scrim_label(), "Scrim");
1727        assert_eq!(strings.bottom_sheet_label(), "Bottom Sheet");
1728        assert_eq!(strings.licenses_page_title(), "Licenses");
1729        assert_eq!(strings.rows_per_page_title(), "Rows per page:");
1730        assert_eq!(strings.cancel_button_label(), "Cancel");
1731        assert_eq!(strings.close_button_label(), "Close");
1732        assert_eq!(strings.continue_button_label(), "Continue");
1733        assert_eq!(strings.copy_button_label(), "Copy");
1734        assert_eq!(strings.cut_button_label(), "Cut");
1735        assert_eq!(strings.scan_text_button_label(), "Scan text");
1736        assert_eq!(strings.ok_button_label(), "OK");
1737        assert_eq!(strings.paste_button_label(), "Paste");
1738        assert_eq!(strings.select_all_button_label(), "Select all");
1739        assert_eq!(strings.look_up_button_label(), "Look Up");
1740        assert_eq!(strings.search_web_button_label(), "Search Web");
1741        assert_eq!(strings.share_button_label(), "Share");
1742        assert_eq!(strings.view_licenses_button_label(), "View licenses");
1743        assert_eq!(strings.ante_meridiem_abbreviation(), "AM");
1744        assert_eq!(strings.post_meridiem_abbreviation(), "PM");
1745        assert_eq!(strings.time_picker_hour_mode_announcement(), "Select hours");
1746        assert_eq!(
1747            strings.time_picker_minute_mode_announcement(),
1748            "Select minutes"
1749        );
1750        assert_eq!(strings.modal_barrier_dismiss_label(), "Dismiss");
1751        assert_eq!(strings.menu_dismiss_label(), "Dismiss menu");
1752        assert_eq!(strings.signed_in_label(), "Signed in");
1753        assert_eq!(strings.hide_accounts_label(), "Hide accounts");
1754        assert_eq!(strings.show_accounts_label(), "Show accounts");
1755        assert_eq!(strings.reorder_item_up(), "Move up");
1756        assert_eq!(strings.reorder_item_down(), "Move down");
1757        assert_eq!(strings.reorder_item_left(), "Move left");
1758        assert_eq!(strings.reorder_item_right(), "Move right");
1759        assert_eq!(strings.reorder_item_to_end(), "Move to the end");
1760        assert_eq!(strings.reorder_item_to_start(), "Move to the start");
1761        assert_eq!(strings.expanded_icon_tap_hint(), "Collapse");
1762        assert_eq!(strings.collapsed_icon_tap_hint(), "Expand");
1763        assert_eq!(
1764            strings.expansion_tile_expanded_hint(),
1765            "double tap to collapse"
1766        );
1767        assert_eq!(
1768            strings.expansion_tile_collapsed_hint(),
1769            "double tap to expand"
1770        );
1771        assert_eq!(strings.expansion_tile_expanded_tap_hint(), "Collapse");
1772        assert_eq!(
1773            strings.expansion_tile_collapsed_tap_hint(),
1774            "Expand for more details"
1775        );
1776        assert_eq!(strings.expanded_hint(), "Collapsed");
1777        assert_eq!(strings.collapsed_hint(), "Expanded");
1778        assert_eq!(strings.refresh_indicator_semantic_label(), "Refresh");
1779        assert_eq!(strings.keyboard_key_alt(), "Alt");
1780        assert_eq!(strings.keyboard_key_alt_graph(), "AltGr");
1781        assert_eq!(strings.keyboard_key_backspace(), "Backspace");
1782        assert_eq!(strings.keyboard_key_caps_lock(), "Caps Lock");
1783        assert_eq!(strings.keyboard_key_channel_down(), "Channel Down");
1784        assert_eq!(strings.keyboard_key_channel_up(), "Channel Up");
1785        assert_eq!(strings.keyboard_key_control(), "Ctrl");
1786        assert_eq!(strings.keyboard_key_delete(), "Del");
1787        assert_eq!(strings.keyboard_key_eject(), "Eject");
1788        assert_eq!(strings.keyboard_key_end(), "End");
1789        assert_eq!(strings.keyboard_key_escape(), "Esc");
1790        assert_eq!(strings.keyboard_key_fn(), "Fn");
1791        assert_eq!(strings.keyboard_key_home(), "Home");
1792        assert_eq!(strings.keyboard_key_insert(), "Insert");
1793        assert_eq!(strings.keyboard_key_meta(), "Meta");
1794        assert_eq!(strings.keyboard_key_meta_mac_os(), "Command");
1795        assert_eq!(strings.keyboard_key_meta_windows(), "Win");
1796        assert_eq!(strings.keyboard_key_num_lock(), "Num Lock");
1797        assert_eq!(strings.keyboard_key_numpad1(), "Num 1");
1798        assert_eq!(strings.keyboard_key_numpad2(), "Num 2");
1799        assert_eq!(strings.keyboard_key_numpad3(), "Num 3");
1800        assert_eq!(strings.keyboard_key_numpad4(), "Num 4");
1801        assert_eq!(strings.keyboard_key_numpad5(), "Num 5");
1802        assert_eq!(strings.keyboard_key_numpad6(), "Num 6");
1803        assert_eq!(strings.keyboard_key_numpad7(), "Num 7");
1804        assert_eq!(strings.keyboard_key_numpad8(), "Num 8");
1805        assert_eq!(strings.keyboard_key_numpad9(), "Num 9");
1806        assert_eq!(strings.keyboard_key_numpad0(), "Num 0");
1807        assert_eq!(strings.keyboard_key_numpad_add(), "Num +");
1808        assert_eq!(strings.keyboard_key_numpad_comma(), "Num ,");
1809        assert_eq!(strings.keyboard_key_numpad_decimal(), "Num .");
1810        assert_eq!(strings.keyboard_key_numpad_divide(), "Num /");
1811        assert_eq!(strings.keyboard_key_numpad_enter(), "Num Enter");
1812        assert_eq!(strings.keyboard_key_numpad_equal(), "Num =");
1813        assert_eq!(strings.keyboard_key_numpad_multiply(), "Num *");
1814        assert_eq!(strings.keyboard_key_numpad_paren_left(), "Num (");
1815        assert_eq!(strings.keyboard_key_numpad_paren_right(), "Num )");
1816        assert_eq!(strings.keyboard_key_numpad_subtract(), "Num -");
1817        assert_eq!(strings.keyboard_key_page_down(), "PgDown");
1818        assert_eq!(strings.keyboard_key_page_up(), "PgUp");
1819        assert_eq!(strings.keyboard_key_power(), "Power");
1820        assert_eq!(strings.keyboard_key_power_off(), "Power Off");
1821        assert_eq!(strings.keyboard_key_print_screen(), "Print Screen");
1822        assert_eq!(strings.keyboard_key_scroll_lock(), "Scroll Lock");
1823        assert_eq!(strings.keyboard_key_select(), "Select");
1824        assert_eq!(strings.keyboard_key_shift(), "Shift");
1825        assert_eq!(strings.keyboard_key_space(), "Space");
1826        assert_eq!(strings.script_category(), ScriptCategory::EnglishLike);
1827        assert_eq!(strings.date_separator(), "/");
1828        assert_eq!(strings.first_day_of_week_index(), 0);
1829        assert_eq!(
1830            strings.narrow_weekdays(),
1831            ["S", "M", "T", "W", "T", "F", "S"]
1832        );
1833        assert_eq!(
1834            strings.time_of_day_format(false),
1835            TimeOfDayFormat::h_colon_mm_space_a
1836        );
1837        assert_eq!(
1838            strings.time_of_day_format(true),
1839            TimeOfDayFormat::HH_colon_mm
1840        );
1841    }
1842
1843    // localizations_test.dart: the strings that take an argument hold it, and no Dart
1844    // placeholder is left in them.
1845    #[test]
1846    fn the_strings_with_arguments_fill_them_in_and_pluralize() {
1847        let strings = DefaultMaterialLocalizations::new();
1848
1849        assert_eq!(strings.scrim_on_tap_hint("FOO"), "Close FOO");
1850        assert_eq!(strings.about_list_tile_title("FOO"), "About FOO");
1851
1852        assert_eq!(strings.selected_row_count_title(0), "No items selected");
1853        assert_eq!(strings.selected_row_count_title(1), "1 item selected");
1854        assert_eq!(strings.selected_row_count_title(2), "2 items selected");
1855        assert_eq!(strings.selected_row_count_title(100), "100 items selected");
1856
1857        assert_eq!(
1858            strings.page_rows_info_title(1, 10, 100, true),
1859            "1–10 of about 100"
1860        );
1861        assert_eq!(
1862            strings.page_rows_info_title(1, 10, 100, false),
1863            "1–10 of 100"
1864        );
1865
1866        assert_eq!(strings.licenses_package_detail_text(0), "No licenses.");
1867        assert_eq!(strings.licenses_package_detail_text(1), "1 license.");
1868        assert_eq!(strings.licenses_package_detail_text(2), "2 licenses.");
1869        assert_eq!(strings.licenses_package_detail_text(100), "100 licenses.");
1870
1871        assert_eq!(
1872            strings.remaining_text_field_character_count(0),
1873            "No characters remaining"
1874        );
1875        assert_eq!(
1876            strings.remaining_text_field_character_count(1),
1877            "1 character remaining"
1878        );
1879        assert_eq!(
1880            strings.remaining_text_field_character_count(5),
1881            "5 characters remaining"
1882        );
1883
1884        assert_eq!(strings.tab_label(1, 2), "Tab 1 of 2");
1885        assert_eq!(
1886            strings.date_range_start_date_semantic_label("Feb 21"),
1887            "Start date Feb 21"
1888        );
1889        assert_eq!(
1890            strings.date_range_end_date_semantic_label("Feb 21"),
1891            "End date Feb 21"
1892        );
1893    }
1894
1895    #[test]
1896    fn a_time_of_day_formats_in_twelve_or_twenty_four_hours() {
1897        let strings = DefaultMaterialLocalizations::new();
1898        let format = |hour, minute, always_use_24_hour_format| {
1899            strings.format_time_of_day(&TimeOfDay::new(hour, minute), always_use_24_hour_format)
1900        };
1901
1902        assert_eq!(format(7, 0, false), "7:00 AM");
1903        assert_eq!(format(7, 0, true), "07:00");
1904        assert_eq!(format(0, 5, false), "12:05 AM");
1905        assert_eq!(format(0, 5, true), "00:05");
1906        assert_eq!(format(12, 0, false), "12:00 PM");
1907        assert_eq!(format(23, 59, false), "11:59 PM");
1908        assert_eq!(format(23, 59, true), "23:59");
1909
1910        assert_eq!(strings.format_hour(&TimeOfDay::new(13, 0), false), "1");
1911        assert_eq!(strings.format_hour(&TimeOfDay::new(13, 0), true), "13");
1912        assert_eq!(strings.format_minute(&TimeOfDay::new(9, 5)), "05");
1913        assert_eq!(strings.format_minute(&TimeOfDay::new(9, 45)), "45");
1914    }
1915
1916    // The expected values are the Dart VM's, from the Dart code of `formatDecimal`.
1917    #[test]
1918    fn format_decimal_inserts_thousands_separators() {
1919        let strings = DefaultMaterialLocalizations::new();
1920
1921        assert_eq!(strings.format_decimal(0), "0");
1922        assert_eq!(strings.format_decimal(999), "999");
1923        assert_eq!(strings.format_decimal(-999), "-999");
1924        assert_eq!(strings.format_decimal(1000), "1,000");
1925        assert_eq!(strings.format_decimal(-1000), "-1,000");
1926        assert_eq!(strings.format_decimal(100000), "100,000");
1927        assert_eq!(strings.format_decimal(1234567), "1,234,567");
1928        assert_eq!(strings.format_decimal(-1234567), "-1,234,567");
1929        assert_eq!(
1930            strings.format_decimal(i64::MAX),
1931            "9,223,372,036,854,775,807"
1932        );
1933        assert_eq!(
1934            strings.format_decimal(i64::MIN),
1935            "--9,223,372,036,854,775,808"
1936        );
1937    }
1938
1939    #[test]
1940    fn a_date_formats_in_us_english() {
1941        let cell = AppCell::new();
1942        let app = cell.borrow();
1943        let strings = DefaultMaterialLocalizations::new();
1944        let date = DateTime::new(&app, 2019, 2, 21);
1945
1946        assert_eq!(strings.format_year(&app, &date), "2019");
1947        assert_eq!(strings.format_compact_date(&app, &date), "02/21/2019");
1948        assert_eq!(
1949            strings.format_compact_date(&app, &DateTime::new(&app, 5, 1, 2)),
1950            "01/02/0005"
1951        );
1952        assert_eq!(strings.format_short_date(&app, &date), "Feb 21, 2019");
1953        assert_eq!(strings.format_medium_date(&app, &date), "Thu, Feb 21");
1954        assert_eq!(
1955            strings.format_full_date(&app, &date),
1956            "Thursday, February 21, 2019"
1957        );
1958        assert_eq!(strings.format_month_year(&app, &date), "February 2019");
1959        assert_eq!(strings.format_short_month_day(&app, &date), "Feb 21");
1960
1961        // The examples of the interface's documentation.
1962        let example = DateTime::new(&app, 2017, 9, 27);
1963        assert_eq!(strings.format_medium_date(&app, &example), "Wed, Sep 27");
1964        assert_eq!(
1965            strings.format_full_date(&app, &example),
1966            "Wednesday, September 27, 2017"
1967        );
1968    }
1969
1970    // localizations_test.dart "parseCompactDate doesn't throw an exception on invalid text",
1971    // and the Dart VM's answers for the other strings.
1972    #[test]
1973    fn parse_compact_date_reads_a_us_date_and_rejects_the_rest() {
1974        let cell = AppCell::new();
1975        let app = cell.borrow();
1976        let strings = DefaultMaterialLocalizations::new();
1977        let parse = |text| strings.parse_compact_date(&app, Some(text));
1978
1979        assert_eq!(parse("10/05/2023"), Some(DateTime::new(&app, 2023, 10, 5)));
1980        assert_eq!(parse("10/05/2023666777889"), None);
1981
1982        assert_eq!(strings.parse_compact_date(&app, None), None);
1983        assert_eq!(parse("02/21/2019"), Some(DateTime::new(&app, 2019, 2, 21)));
1984        assert_eq!(
1985            parse(" 02/ 21/+2019"),
1986            Some(DateTime::new(&app, 2019, 2, 21))
1987        );
1988        assert_eq!(parse("1/1/1"), Some(DateTime::new(&app, 1, 1, 1)));
1989        assert_eq!(parse("02/21"), None);
1990        assert_eq!(parse("a/b/c"), None);
1991        assert_eq!(parse("0x1/01/2019"), None);
1992        assert_eq!(parse("13/01/2019"), None);
1993        assert_eq!(parse("01/01/0"), None);
1994        assert_eq!(parse("02/29/2019"), None);
1995        assert_eq!(parse("02/29/2020"), Some(DateTime::new(&app, 2020, 2, 29)));
1996        assert_eq!(parse("02/29/1900"), None);
1997        assert_eq!(parse("02/29/2000"), Some(DateTime::new(&app, 2000, 2, 29)));
1998        // The last day a `DateTime` holds is a valid local date only east of UTC, where its
1999        // midnight comes before the last instant.
2000        let last = DateTime::from_milliseconds_since_epoch(8_640_000_000_000_000, false);
2001        let last_day = (last.day(&app) == 13).then(|| DateTime::new(&app, 275760, 9, 13));
2002        assert_eq!(parse("09/13/275760"), last_day);
2003        assert_eq!(parse("09/14/275760"), None);
2004    }
2005
2006    #[test]
2007    fn the_delegate_supports_english_only_and_prints_as_dart_does() {
2008        let delegate = DefaultMaterialLocalizations::delegate();
2009        assert!(delegate.is_supported(&Locale::new("en").country_code("GB")));
2010        assert!(!delegate.is_supported(&Locale::new("fr")));
2011        assert_eq!(
2012            format!("{delegate:?}"),
2013            "DefaultMaterialLocalizations.delegate(en_US)"
2014        );
2015    }
2016
2017    #[test]
2018    fn load_completes_synchronously() {
2019        let strings = DefaultMaterialLocalizations::load(&Locale::new("en"));
2020        assert!(strings.is_completed(), "Dart's SynchronousFuture");
2021        assert_eq!(
2022            strings.peek().expect("complete").back_button_tooltip(),
2023            "Back"
2024        );
2025    }
2026
2027    // localizations_test.dart 'MaterialLocalizations.of throws', the context with
2028    // localizations.
2029    #[test]
2030    fn of_finds_the_strings_through_a_localizations_ancestor() {
2031        test_widgets(|tester| {
2032            let seen = Rc::new(RefCell::new(None));
2033            let probe = Builder::new({
2034                let seen = Rc::clone(&seen);
2035                move |app, context| {
2036                    *seen.borrow_mut() =
2037                        Some(<dyn MaterialLocalizations>::of(app, context).back_button_tooltip());
2038                    SizedBox::shrink().into_widget()
2039                }
2040            });
2041            tester.pump_widget(us_english(probe));
2042            assert_eq!(seen.borrow().as_deref(), Some("Back"));
2043        });
2044    }
2045
2046    // localizations_test.dart 'MaterialLocalizations.of throws', the context without
2047    // localizations.
2048    #[test]
2049    #[should_panic(expected = "No MaterialLocalizations found")]
2050    fn of_panics_without_a_localizations_ancestor() {
2051        test_widgets(|tester| {
2052            let probe = Builder::new(|app, context| {
2053                <dyn MaterialLocalizations>::of(app, context);
2054                SizedBox::shrink().into_widget()
2055            });
2056            tester.pump_widget(probe.into_widget());
2057        });
2058    }
2059}