1pub mod clipboard;
6pub mod web_evaluation;
7
8use crate::geometry::{Edges, Points, Size};
9
10pub const TAB_BAR_COMPONENT: &str = "nsh/tab-bar";
14
15pub fn is_reserved_component(name: &str) -> bool {
19 name.starts_with("nsh/")
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum ColorScheme {
25 #[default]
27 Light,
28 Dark,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
35pub enum Appearance {
36 #[default]
38 System,
39 Light,
41 Dark,
43}
44
45impl Appearance {
46 pub fn resolve(self, system: ColorScheme) -> ColorScheme {
48 match self {
49 Appearance::System => system,
50 Appearance::Light => ColorScheme::Light,
51 Appearance::Dark => ColorScheme::Dark,
52 }
53 }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum InputModality {
61 Keyboard,
64 Pointer,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Os {
71 Ios,
73 Android,
75 MacOs,
77 Windows,
79 Linux,
81 Web,
84}
85
86impl Os {
87 pub fn name(self) -> &'static str {
89 match self {
90 Os::Ios => "ios",
91 Os::Android => "android",
92 Os::MacOs => "macos",
93 Os::Windows => "windows",
94 Os::Linux => "linux",
95 Os::Web => "web",
96 }
97 }
98
99 pub fn is_desktop(self) -> bool {
105 matches!(self, Os::MacOs | Os::Windows | Os::Linux)
106 }
107
108 pub fn is_catalyst(self) -> bool {
113 self == Os::Ios && cfg!(target_abi = "macabi")
114 }
115}
116
117impl Default for Os {
118 fn default() -> Self {
121 if cfg!(target_os = "android") {
122 Os::Android
123 } else {
124 Os::Ios
125 }
126 }
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
131pub enum Idiom {
132 #[default]
134 Phone,
135 Pad,
137 Mac,
140 Tv,
142 Desktop,
146 Terminal,
149}
150
151impl Idiom {
152 pub fn desktop_on(self, os: Os) -> bool {
159 os.is_desktop() || (os == Os::Web && self == Idiom::Desktop) || self == Idiom::Terminal
160 }
161
162 pub fn reported_on(self, os: Os) -> Idiom {
168 if self == Idiom::Terminal {
169 Idiom::Terminal
170 } else if self.desktop_on(os) {
171 Idiom::Desktop
172 } else if self == Idiom::Desktop {
173 Idiom::Phone
174 } else {
175 self
176 }
177 }
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
183pub enum Lifecycle {
184 #[default]
186 Active,
187 Inactive,
191 Background,
194}
195
196impl Lifecycle {
197 pub fn name(self) -> &'static str {
199 match self {
200 Lifecycle::Active => "active",
201 Lifecycle::Inactive => "inactive",
202 Lifecycle::Background => "background",
203 }
204 }
205}
206
207#[derive(Debug, Clone, Copy, PartialEq)]
209pub struct Environment {
210 pub window: Size<Points>,
212 pub safe_area: Edges<Points>,
214 pub title_bar: Edges<Points>,
220 pub window_state: Option<crate::desktop::WindowState>,
225 pub keyboard_height: Points,
227 pub keyboard_duration: f32,
229 pub color_scheme: ColorScheme,
231 pub font_scale: f32,
233 pub rtl: bool,
235 pub reduce_motion: bool,
238 pub pixel_ratio: f32,
240 pub screen_reader: bool,
242 pub os: Os,
244 pub platform: Option<&'static str>,
250 pub os_version: (u16, u16),
253 pub idiom: Idiom,
255 pub apple_keyboard: bool,
260 pub ctrl_for_command: bool,
265 pub locale: Locale,
267 pub locale_settings: LocaleSettings,
270 pub host: bool,
273 pub lifecycle: Lifecycle,
277 pub screen_color: bool,
281 pub file_requests: bool,
286 pub speech: bool,
290 pub notifications: bool,
294 pub audio: bool,
298 pub cell: Option<Size<Points>>,
305 pub web_input: bool,
309 pub web_evaluate: bool,
312 pub web_views: bool,
319 pub shaders: bool,
327}
328
329impl Environment {
330 pub fn platform_name(&self) -> &'static str {
334 self.platform.unwrap_or(self.os.name())
335 }
336
337 pub fn desktop(&self) -> bool {
342 self.idiom.desktop_on(self.os)
343 }
344
345 pub fn reported_idiom(&self) -> Idiom {
347 self.idiom.reported_on(self.os)
348 }
349}
350
351impl Default for Environment {
352 fn default() -> Self {
353 Self {
354 window: Size::default(),
355 safe_area: Edges::default(),
356 title_bar: Edges::default(),
357 window_state: None,
358 keyboard_height: Points(0.0),
359 keyboard_duration: 250.0,
360 color_scheme: ColorScheme::Light,
361 font_scale: 1.0,
362 rtl: false,
363 reduce_motion: false,
364 pixel_ratio: 1.0,
365 screen_reader: false,
366 os: Os::default(),
367 platform: None,
368 os_version: (0, 0),
369 idiom: Idiom::Phone,
370 apple_keyboard: false,
371 ctrl_for_command: false,
372 locale: Locale::EN_US,
373 locale_settings: LocaleSettings::EN_US,
374 host: false,
375 lifecycle: Lifecycle::Active,
376 screen_color: false,
377 file_requests: false,
378 speech: false,
379 notifications: false,
380 audio: false,
381 cell: None,
382 web_input: false,
383 web_evaluate: false,
384 web_views: true,
385 shaders: true,
386 }
387 }
388}
389
390#[derive(Debug, Clone, Copy, PartialEq, Default)]
397pub struct HostEnvironment {
398 pub locale: Option<Locale>,
400 pub font_scale: Option<f32>,
403}
404
405impl HostEnvironment {
406 pub fn apply(&self, env: &mut Environment) {
408 if let Some(locale) = self.locale {
409 env.locale = locale;
410 env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
411 }
412 if let Some(scale) = self.font_scale.filter(|s| s.is_finite() && *s > 0.0) {
413 env.font_scale = scale;
414 }
415 }
416}
417
418#[derive(Clone, Copy, PartialEq, Eq, Hash)]
422pub struct Locale {
423 bytes: [u8; Locale::CAPACITY],
424 len: u8,
425}
426
427impl Locale {
428 const CAPACITY: usize = 15;
429
430 pub const EN_US: Locale = Locale {
432 bytes: *b"en-US\0\0\0\0\0\0\0\0\0\0",
433 len: 5,
434 };
435
436 pub fn parse(identifier: &str) -> Option<Locale> {
441 let identifier = identifier.split(['@', '.']).next().unwrap_or_default();
442 let mut bytes = [0u8; Self::CAPACITY];
443 let mut len = 0;
444 for (i, part) in identifier.split(['-', '_']).enumerate() {
445 let keep = if i == 0 {
446 (2..=3).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphabetic())
447 } else {
448 (part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()))
450 || (part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()))
451 || (part.len() == 3 && part.bytes().all(|b| b.is_ascii_digit()))
452 };
453 if !keep {
454 if i == 0 {
455 return None;
456 }
457 break;
459 }
460 if len + part.len() + usize::from(i > 0) > Self::CAPACITY {
461 break;
462 }
463 if i > 0 {
464 bytes[len] = b'-';
465 len += 1;
466 }
467 for (j, b) in part.bytes().enumerate() {
468 bytes[len] = match (i, part.len()) {
469 (0, _) => b.to_ascii_lowercase(),
470 (_, 4) if j == 0 => b.to_ascii_uppercase(),
471 (_, 4) => b.to_ascii_lowercase(),
472 _ => b.to_ascii_uppercase(),
473 };
474 len += 1;
475 }
476 }
477 Some(Locale {
478 bytes,
479 len: len as u8,
480 })
481 }
482
483 pub fn as_str(&self) -> &str {
485 std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("en-US")
487 }
488
489 pub fn language(&self) -> &str {
491 self.as_str().split('-').next().unwrap_or_default()
492 }
493
494 pub fn region(&self) -> Option<&str> {
496 self.as_str().split('-').skip(1).find(|s| s.len() != 4)
498 }
499}
500
501impl Default for Locale {
502 fn default() -> Self {
503 Self::EN_US
504 }
505}
506
507impl std::fmt::Debug for Locale {
508 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
509 write!(f, "Locale({})", self.as_str())
510 }
511}
512
513impl std::fmt::Display for Locale {
514 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515 f.write_str(self.as_str())
516 }
517}
518
519#[derive(Clone, Copy, PartialEq, Eq, Hash)]
523pub struct Languages {
524 tags: [Locale; Languages::CAPACITY],
525 len: u8,
526}
527
528impl Languages {
529 const CAPACITY: usize = 8;
532
533 pub(crate) const EN_US: Languages = Languages {
535 tags: [Locale::EN_US; Languages::CAPACITY],
536 len: 1,
537 };
538
539 #[doc(hidden)]
541 pub const fn one(locale: Locale) -> Languages {
542 Languages {
543 tags: [locale; Languages::CAPACITY],
544 len: 1,
545 }
546 }
547
548 #[doc(hidden)]
553 pub fn parse<'a>(identifiers: impl IntoIterator<Item = &'a str>) -> Option<Languages> {
554 let mut languages = Languages::EN_US;
555 languages.len = 0;
556 for locale in identifiers.into_iter().filter_map(Locale::parse) {
557 if usize::from(languages.len) == Self::CAPACITY {
558 break;
559 }
560 if !languages.as_slice().contains(&locale) {
561 languages.tags[usize::from(languages.len)] = locale;
562 languages.len += 1;
563 }
564 }
565 (languages.len > 0).then_some(languages)
566 }
567
568 pub fn preferring(&self, locale: Locale) -> Languages {
572 let mut languages = Languages::one(locale);
573 for &other in self.as_slice() {
574 if usize::from(languages.len) == Self::CAPACITY {
575 break;
576 }
577 if other != locale {
578 languages.tags[usize::from(languages.len)] = other;
579 languages.len += 1;
580 }
581 }
582 languages
583 }
584
585 pub fn first(&self) -> Locale {
587 self.tags[0]
588 }
589
590 pub fn as_slice(&self) -> &[Locale] {
592 &self.tags[..usize::from(self.len)]
593 }
594
595 pub fn iter(&self) -> impl Iterator<Item = Locale> + '_ {
597 self.as_slice().iter().copied()
598 }
599}
600
601impl Default for Languages {
602 fn default() -> Self {
603 Self::EN_US
604 }
605}
606
607impl std::fmt::Debug for Languages {
608 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
609 f.debug_list()
610 .entries(self.iter().map(|l| l.to_string()))
611 .finish()
612 }
613}
614
615#[derive(Clone, Copy, PartialEq, Eq, Hash)]
620#[non_exhaustive]
621pub struct TimeZone {
622 bytes: [u8; TimeZone::CAPACITY],
623 len: u8,
624}
625
626impl TimeZone {
627 const CAPACITY: usize = 63;
632
633 pub const UTC: TimeZone = {
635 let mut bytes = [0u8; TimeZone::CAPACITY];
636 bytes[0] = b'U';
637 bytes[1] = b'T';
638 bytes[2] = b'C';
639 TimeZone { bytes, len: 3 }
640 };
641
642 pub fn parse(identifier: &str) -> Option<TimeZone> {
649 let identifier = identifier.trim();
650 let name = match identifier.rsplit_once("zoneinfo/") {
651 Some((_, name)) => name,
652 None => identifier.strip_prefix(':').unwrap_or(identifier),
653 };
654 let valid = !name.is_empty()
655 && name.len() <= Self::CAPACITY
656 && name
657 .bytes()
658 .all(|b| b.is_ascii_alphanumeric() || b"/_-+:".contains(&b))
659 && name
660 .split('/')
661 .all(|part| !part.is_empty() && part != "." && part != "..");
662 if !valid {
663 return None;
664 }
665 let mut bytes = [0u8; Self::CAPACITY];
666 bytes[..name.len()].copy_from_slice(name.as_bytes());
667 Some(TimeZone {
668 bytes,
669 len: name.len() as u8,
670 })
671 }
672
673 #[doc(hidden)]
688 pub fn posix(tz: Option<&str>, system: impl FnOnce() -> Option<TimeZone>) -> TimeZone {
689 let zone = match tz.map(str::trim) {
690 None => None,
691 Some("") => Some(Self::UTC),
693 Some(tz) => {
694 let name = tz.strip_prefix(':').unwrap_or(tz);
695 if is_posix_rule(name) && !RULE_NAMED_ZONES.contains(&name) {
696 None
697 } else {
698 Self::parse(name)
699 }
700 }
701 };
702 zone.or_else(system).unwrap_or_default()
703 }
704
705 pub fn as_str(&self) -> &str {
707 std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("UTC")
709 }
710}
711
712const RULE_NAMED_ZONES: [&str; 7] = [
716 "EST5EDT", "CST6CDT", "MST7MDT", "PST8PDT", "GMT0", "GMT+0", "GMT-0",
717];
718
719fn is_posix_rule(tz: &str) -> bool {
725 let letters = tz.bytes().take_while(u8::is_ascii_alphabetic).count();
726 tz.starts_with('<')
727 || letters >= 3
728 && tz
729 .as_bytes()
730 .get(letters)
731 .is_some_and(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-'))
732}
733
734impl Default for TimeZone {
735 fn default() -> Self {
736 Self::UTC
737 }
738}
739
740impl std::fmt::Debug for TimeZone {
741 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
742 write!(f, "TimeZone({})", self.as_str())
743 }
744}
745
746impl std::fmt::Display for TimeZone {
747 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
748 f.write_str(self.as_str())
749 }
750}
751
752#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
761#[non_exhaustive]
762pub struct LocaleSettings {
763 pub languages: Languages,
766 pub time_zone: TimeZone,
768 pub hour_cycle: HourCycle,
770 pub first_day_of_week: Weekday,
772 pub measurement_system: MeasurementSystem,
774 pub temperature_unit: TemperatureUnit,
776}
777
778impl LocaleSettings {
779 pub(crate) const EN_US: LocaleSettings = LocaleSettings {
782 languages: Languages::EN_US,
783 time_zone: TimeZone::UTC,
784 hour_cycle: HourCycle::H12,
785 first_day_of_week: Weekday::Sunday,
786 measurement_system: MeasurementSystem::Us,
787 temperature_unit: TemperatureUnit::Fahrenheit,
788 };
789
790 #[doc(hidden)]
795 pub fn of(locale: Locale) -> LocaleSettings {
796 LocaleSettings {
797 languages: Languages::one(locale),
798 ..Self::of_region(locale.language(), locale.region().unwrap_or("001"))
799 }
800 }
801
802 #[doc(hidden)]
812 pub fn parse(identifier: &str) -> LocaleSettings {
813 let identifier = identifier.trim();
814 let (tag, icu) = identifier.split_once('@').unwrap_or((identifier, ""));
815 let mut keywords = Keywords::default();
816 let mut extension = false;
819 let mut key = "";
820 for subtag in tag.split('.').next().unwrap_or_default().split(['-', '_']) {
821 if subtag.len() == 1 {
822 extension = subtag.eq_ignore_ascii_case("u");
823 key = "";
824 } else if extension && subtag.len() == 2 {
825 key = subtag;
826 } else if extension && !key.is_empty() {
827 keywords.set(key, subtag);
828 key = "";
829 }
830 }
831 for keyword in icu.split(';') {
832 if let Some((key, value)) = keyword.split_once('=') {
833 keywords.set(key.trim(), value.trim());
834 }
835 }
836 let locale = Locale::parse(identifier);
837 let language = locale.as_ref().map_or("", Locale::language);
838 let region = match &keywords.region {
839 Some((bytes, len)) => std::str::from_utf8(&bytes[..*len]).unwrap_or("001"),
840 None => locale.as_ref().and_then(Locale::region).unwrap_or("001"),
841 };
842 let own = Self::of_region(language, region);
843 LocaleSettings {
844 languages: Languages::one(locale.unwrap_or(Locale::EN_US)),
845 hour_cycle: keywords.hour_cycle.unwrap_or(own.hour_cycle),
846 first_day_of_week: keywords.first_day_of_week.unwrap_or(own.first_day_of_week),
847 measurement_system: keywords
848 .measurement_system
849 .unwrap_or(own.measurement_system),
850 temperature_unit: keywords.temperature_unit.unwrap_or(own.temperature_unit),
851 ..own
852 }
853 }
854
855 fn of_region(language: &str, region: &str) -> LocaleSettings {
857 let listed = |regions: &[&str]| regions.binary_search(®ion).is_ok();
858 LocaleSettings {
859 hour_cycle: match (language, region) {
860 ("fr", "CA") | ("ku", "SY") => HourCycle::H23,
862 ("ar" | "en", "001") => HourCycle::H12,
863 _ if listed(HOUR12_REGIONS) => HourCycle::H12,
864 _ => HourCycle::H23,
865 },
866 first_day_of_week: if listed(SUNDAY_REGIONS) {
867 Weekday::Sunday
868 } else if listed(SATURDAY_REGIONS) {
869 Weekday::Saturday
870 } else if listed(FRIDAY_REGIONS) {
871 Weekday::Friday
872 } else {
873 Weekday::Monday
874 },
875 measurement_system: match region {
876 "LR" | "US" => MeasurementSystem::Us,
877 "GB" | "MM" => MeasurementSystem::Uk,
878 _ => MeasurementSystem::Metric,
879 },
880 temperature_unit: match region {
881 "BS" | "BZ" | "KY" | "PR" | "PW" | "US" => TemperatureUnit::Fahrenheit,
882 _ => TemperatureUnit::Celsius,
883 },
884 ..Self::default()
885 }
886 }
887}
888
889impl Default for LocaleSettings {
890 fn default() -> Self {
891 Self::EN_US
892 }
893}
894
895#[derive(Default)]
897struct Keywords {
898 hour_cycle: Option<HourCycle>,
899 first_day_of_week: Option<Weekday>,
900 measurement_system: Option<MeasurementSystem>,
901 temperature_unit: Option<TemperatureUnit>,
902 region: Option<([u8; 3], usize)>,
904}
905
906impl Keywords {
907 fn set(&mut self, key: &str, value: &str) {
909 let is = |names: &[&str]| names.iter().any(|n| key.eq_ignore_ascii_case(n));
910 let value_is = |name: &str| value.eq_ignore_ascii_case(name);
911 if is(&["hc", "hours"]) {
912 self.hour_cycle = HourCycle::parse(value).or(self.hour_cycle);
913 } else if is(&["fw"]) {
914 self.first_day_of_week = Weekday::ALL
915 .into_iter()
916 .find(|d| value_is(d.code()))
917 .or(self.first_day_of_week);
918 } else if is(&["ms", "measure"]) {
919 self.measurement_system = match () {
920 _ if value_is("metric") => Some(MeasurementSystem::Metric),
921 _ if value_is("ussystem") => Some(MeasurementSystem::Us),
922 _ if value_is("uksystem") => Some(MeasurementSystem::Uk),
923 _ => self.measurement_system,
924 };
925 } else if is(&["mu"]) {
926 let unit = match value_is("fahrenhe") {
928 true => Some(TemperatureUnit::Fahrenheit),
929 false => TemperatureUnit::parse(value),
930 };
931 self.temperature_unit = unit.or(self.temperature_unit);
932 } else if is(&["rg"]) {
933 let bytes = value.as_bytes();
936 let len = match bytes {
937 [a, b, c, ..] if [a, b, c].iter().all(|b| b.is_ascii_digit()) => 3,
938 [a, b, ..] if a.is_ascii_alphabetic() && b.is_ascii_alphabetic() => 2,
939 _ => return,
940 };
941 let mut region = [0u8; 3];
942 for (to, from) in region.iter_mut().zip(bytes) {
943 *to = from.to_ascii_uppercase();
944 }
945 self.region = Some((region, len));
946 }
947 }
948}
949
950const HOUR12_REGIONS: &[&str] = &[
952 "419", "AE", "AG", "AL", "AR", "AS", "AU", "BB", "BD", "BH", "BM", "BN", "BO", "BS", "BT",
953 "CA", "CL", "CO", "CR", "CU", "CY", "DJ", "DM", "DO", "DZ", "EC", "EG", "EH", "ER", "ET", "FJ",
954 "FM", "GD", "GH", "GM", "GR", "GT", "GU", "GY", "HK", "HN", "IN", "IQ", "JM", "JO", "KH", "KI",
955 "KN", "KP", "KR", "KW", "KY", "LB", "LC", "LR", "LS", "LY", "MH", "MO", "MP", "MR", "MW", "MX",
956 "MY", "NA", "NI", "NZ", "OM", "PA", "PE", "PG", "PH", "PK", "PR", "PS", "PW", "PY", "QA", "SA",
957 "SB", "SD", "SG", "SL", "SO", "SS", "SV", "SY", "SZ", "TC", "TD", "TN", "TO", "TT", "TW", "UM",
958 "US", "UY", "VC", "VE", "VG", "VI", "VU", "WS", "YE", "ZM",
959];
960
961const SUNDAY_REGIONS: &[&str] = &[
963 "AG", "AS", "BD", "BR", "BS", "BT", "BW", "BZ", "CA", "CO", "DM", "DO", "ET", "GT", "GU", "HK",
964 "HN", "ID", "IL", "IN", "IS", "JM", "JP", "KE", "KH", "KR", "LA", "MH", "MM", "MO", "MT", "MX",
965 "MZ", "NI", "NP", "PA", "PE", "PH", "PK", "PR", "PT", "PY", "SA", "SG", "SV", "TH", "TT", "TW",
966 "UM", "US", "VE", "VI", "WS", "YE", "ZA", "ZW",
967];
968
969const SATURDAY_REGIONS: &[&str] = &[
971 "AF", "BH", "DJ", "DZ", "EG", "IQ", "IR", "JO", "KW", "LY", "OM", "QA", "SD", "SY",
972];
973
974const FRIDAY_REGIONS: &[&str] = &["MV"];
976
977#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
979pub enum HourCycle {
980 H11,
982 #[default]
984 H12,
985 H23,
987 H24,
989}
990
991impl HourCycle {
992 pub fn name(self) -> &'static str {
994 match self {
995 HourCycle::H11 => "h11",
996 HourCycle::H12 => "h12",
997 HourCycle::H23 => "h23",
998 HourCycle::H24 => "h24",
999 }
1000 }
1001
1002 pub fn parse(name: &str) -> Option<HourCycle> {
1004 [
1005 HourCycle::H11,
1006 HourCycle::H12,
1007 HourCycle::H23,
1008 HourCycle::H24,
1009 ]
1010 .into_iter()
1011 .find(|c| name.eq_ignore_ascii_case(c.name()))
1012 }
1013
1014 #[doc(hidden)]
1019 pub fn of_pattern(pattern: &str) -> Option<HourCycle> {
1020 let mut quoted = false;
1021 pattern.chars().find_map(|c| match c {
1022 '\'' => {
1023 quoted = !quoted;
1024 None
1025 }
1026 _ if quoted => None,
1027 'h' => Some(HourCycle::H12),
1028 'H' => Some(HourCycle::H23),
1029 'K' => Some(HourCycle::H11),
1030 'k' => Some(HourCycle::H24),
1031 _ => None,
1032 })
1033 }
1034
1035 pub fn twelve_hour(self) -> bool {
1037 matches!(self, HourCycle::H11 | HourCycle::H12)
1038 }
1039}
1040
1041#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1043pub enum Weekday {
1044 Monday = 1,
1046 Tuesday,
1048 Wednesday,
1050 Thursday,
1052 Friday,
1054 Saturday,
1056 Sunday,
1058}
1059
1060impl Weekday {
1061 const ALL: [Weekday; 7] = [
1063 Weekday::Monday,
1064 Weekday::Tuesday,
1065 Weekday::Wednesday,
1066 Weekday::Thursday,
1067 Weekday::Friday,
1068 Weekday::Saturday,
1069 Weekday::Sunday,
1070 ];
1071
1072 pub fn number(self) -> u8 {
1075 self as u8
1076 }
1077
1078 pub fn from_number(number: u8) -> Option<Weekday> {
1080 Self::ALL.get(usize::from(number).checked_sub(1)?).copied()
1081 }
1082
1083 fn code(self) -> &'static str {
1085 match self {
1086 Weekday::Monday => "mon",
1087 Weekday::Tuesday => "tue",
1088 Weekday::Wednesday => "wed",
1089 Weekday::Thursday => "thu",
1090 Weekday::Friday => "fri",
1091 Weekday::Saturday => "sat",
1092 Weekday::Sunday => "sun",
1093 }
1094 }
1095}
1096
1097#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1099pub enum MeasurementSystem {
1100 #[default]
1102 Metric,
1103 Us,
1105 Uk,
1107}
1108
1109impl MeasurementSystem {
1110 pub fn name(self) -> &'static str {
1112 match self {
1113 MeasurementSystem::Metric => "metric",
1114 MeasurementSystem::Us => "us",
1115 MeasurementSystem::Uk => "uk",
1116 }
1117 }
1118
1119 pub fn parse(name: &str) -> Option<MeasurementSystem> {
1121 [
1122 MeasurementSystem::Metric,
1123 MeasurementSystem::Us,
1124 MeasurementSystem::Uk,
1125 ]
1126 .into_iter()
1127 .find(|s| name.eq_ignore_ascii_case(s.name()))
1128 }
1129}
1130
1131#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1133pub enum TemperatureUnit {
1134 #[default]
1136 Celsius,
1137 Fahrenheit,
1139}
1140
1141impl TemperatureUnit {
1142 pub fn name(self) -> &'static str {
1144 match self {
1145 TemperatureUnit::Celsius => "celsius",
1146 TemperatureUnit::Fahrenheit => "fahrenheit",
1147 }
1148 }
1149
1150 pub fn parse(name: &str) -> Option<TemperatureUnit> {
1152 [TemperatureUnit::Celsius, TemperatureUnit::Fahrenheit]
1153 .into_iter()
1154 .find(|u| name.eq_ignore_ascii_case(u.name()))
1155 }
1156}
1157
1158#[derive(Debug, Clone, PartialEq, Eq)]
1161pub struct HttpRequest {
1162 pub method: String,
1164 pub url: String,
1166 pub headers: Vec<(String, String)>,
1168 pub body: HttpBody,
1170 pub follow_redirects: bool,
1172}
1173
1174impl HttpRequest {
1175 pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
1178 Self {
1179 method: method.into().to_ascii_uppercase(),
1180 url: url.into(),
1181 headers: Vec::new(),
1182 body: HttpBody::Empty,
1183 follow_redirects: true,
1184 }
1185 }
1186
1187 pub fn get(url: impl Into<String>) -> Self {
1189 Self::new("GET", url)
1190 }
1191
1192 pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
1194 Self::new("POST", url).body(body)
1195 }
1196
1197 #[must_use]
1199 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1200 self.headers.push((name.into(), value.into()));
1201 self
1202 }
1203
1204 #[must_use]
1206 pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
1207 self.body = HttpBody::Bytes(body.into());
1208 self
1209 }
1210}
1211
1212impl From<&str> for HttpRequest {
1213 fn from(url: &str) -> Self {
1214 Self::get(url)
1215 }
1216}
1217
1218impl From<String> for HttpRequest {
1219 fn from(url: String) -> Self {
1220 Self::get(url)
1221 }
1222}
1223
1224#[derive(Debug, Clone, PartialEq, Eq, Default)]
1226pub enum HttpBody {
1227 #[default]
1229 Empty,
1230 Bytes(Vec<u8>),
1232 Stream,
1236}
1237
1238impl HttpBody {
1239 pub fn is_empty(&self) -> bool {
1241 match self {
1242 HttpBody::Empty => true,
1243 HttpBody::Bytes(b) => b.is_empty(),
1244 HttpBody::Stream => false,
1245 }
1246 }
1247}
1248
1249#[derive(Debug, Clone, PartialEq, Eq, Default)]
1251pub struct HttpHead {
1252 pub status: u16,
1254 pub status_text: String,
1256 pub url: String,
1258 pub redirected: bool,
1260 pub headers: Vec<(String, String)>,
1262}
1263
1264#[doc(hidden)]
1271pub fn content_type(path: &str) -> &'static str {
1272 match std::path::Path::new(path)
1273 .extension()
1274 .and_then(|e| e.to_str())
1275 .map(str::to_ascii_lowercase)
1276 .as_deref()
1277 {
1278 Some("html") => "text/html; charset=utf-8",
1279 Some("js" | "mjs") => "text/javascript; charset=utf-8",
1280 Some("json" | "map") => "application/json",
1281 Some("webmanifest") => "application/manifest+json",
1282 Some("wasm") => "application/wasm",
1283 Some("css") => "text/css; charset=utf-8",
1284 Some("txt") => "text/plain; charset=utf-8",
1285 Some("png") => "image/png",
1286 Some("jpg" | "jpeg") => "image/jpeg",
1287 Some("gif") => "image/gif",
1288 Some("webp") => "image/webp",
1289 Some("avif") => "image/avif",
1290 Some("svg") => "image/svg+xml",
1291 Some("ico") => "image/x-icon",
1292 Some("heic") => "image/heic",
1293 Some("ttf") => "font/ttf",
1294 Some("otf") => "font/otf",
1295 Some("woff") => "font/woff",
1296 Some("woff2") => "font/woff2",
1297 Some("mp4" | "m4v") => "video/mp4",
1298 Some("webm") => "video/webm",
1299 Some("mov") => "video/quicktime",
1300 Some("mp3") => "audio/mpeg",
1301 Some("m4a") => "audio/mp4",
1302 Some("aac") => "audio/aac",
1303 Some("wav") => "audio/wav",
1304 Some("ogg" | "oga" | "opus") => "audio/ogg",
1305 Some("flac") => "audio/flac",
1306 Some("aif" | "aiff") => "audio/aiff",
1307 Some("caf") => "audio/x-caf",
1308 _ => "application/octet-stream",
1309 }
1310}
1311
1312#[doc(hidden)]
1319pub fn file_mime_type(uri: &str) -> &'static str {
1320 let path = uri.split(['?', '#']).next().unwrap_or_default();
1321 let name = path.rsplit('/').next().unwrap_or_default();
1322 let Some((stem, ext)) = name.rsplit_once('.') else {
1323 return "";
1324 };
1325 if stem.is_empty() {
1326 return "";
1328 }
1329 match ext.to_ascii_lowercase().as_str() {
1330 "png" => "image/png",
1331 "jpg" | "jpeg" | "jpe" => "image/jpeg",
1332 "gif" => "image/gif",
1333 "webp" => "image/webp",
1334 "avif" => "image/avif",
1335 "heic" => "image/heic",
1336 "heif" => "image/heif",
1337 "svg" => "image/svg+xml",
1338 "bmp" => "image/bmp",
1339 "tif" | "tiff" => "image/tiff",
1340 "ico" => "image/x-icon",
1341 "mp4" | "m4v" => "video/mp4",
1342 "mov" => "video/quicktime",
1343 "webm" => "video/webm",
1344 "mkv" => "video/x-matroska",
1345 "avi" => "video/x-msvideo",
1346 "mp3" => "audio/mpeg",
1347 "m4a" => "audio/mp4",
1348 "aac" => "audio/aac",
1349 "wav" => "audio/wav",
1350 "ogg" | "oga" | "opus" => "audio/ogg",
1351 "flac" => "audio/flac",
1352 "aif" | "aiff" => "audio/aiff",
1353 "caf" => "audio/x-caf",
1354 "txt" | "text" | "log" => "text/plain",
1355 "md" | "markdown" => "text/markdown",
1356 "csv" => "text/csv",
1357 "tsv" => "text/tab-separated-values",
1358 "html" | "htm" => "text/html",
1359 "css" => "text/css",
1360 "js" | "mjs" => "text/javascript",
1361 "json" => "application/json",
1362 "xml" => "application/xml",
1363 "yaml" | "yml" => "application/yaml",
1364 "pdf" => "application/pdf",
1365 "rtf" => "application/rtf",
1366 "doc" => "application/msword",
1367 "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1368 "xls" => "application/vnd.ms-excel",
1369 "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1370 "ppt" => "application/vnd.ms-powerpoint",
1371 "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1372 "zip" => "application/zip",
1373 "gz" | "tgz" => "application/gzip",
1374 "tar" => "application/x-tar",
1375 "7z" => "application/x-7z-compressed",
1376 "rar" => "application/vnd.rar",
1377 "wasm" => "application/wasm",
1378 "ttf" => "font/ttf",
1379 "otf" => "font/otf",
1380 "woff" => "font/woff",
1381 "woff2" => "font/woff2",
1382 _ => "",
1383 }
1384}
1385
1386#[derive(Debug, Clone, PartialEq, Eq)]
1390pub enum FetchEvent {
1391 BodyWanted,
1394 Head(HttpHead),
1396 Data(Vec<u8>),
1398 End,
1400 Failed(String),
1402}
1403
1404#[derive(Debug, Clone, PartialEq, Eq)]
1407pub enum FetchOp {
1408 Start(HttpRequest),
1410 Send(Vec<u8>),
1412 Finish,
1414 Pause(bool),
1417 Cancel,
1419}
1420
1421#[cfg(test)]
1422mod tests {
1423 use super::{
1424 Environment, HostEnvironment, HourCycle, Idiom, Languages, Locale, LocaleSettings,
1425 MeasurementSystem, Os, TemperatureUnit, TimeZone, Weekday, content_type, file_mime_type,
1426 };
1427
1428 #[test]
1429 fn desktop_is_a_desktop_os_or_a_desktop_browser() {
1430 let desktop = |os: Os, idiom: Idiom| Environment {
1431 os,
1432 idiom,
1433 ..Environment::default()
1434 };
1435 for (os, idiom, expected) in [
1436 (Os::MacOs, Idiom::Desktop, true),
1437 (Os::Windows, Idiom::Desktop, true),
1438 (Os::Linux, Idiom::Desktop, true),
1439 (Os::Linux, Idiom::Phone, true),
1441 (Os::Web, Idiom::Desktop, true),
1442 (Os::Web, Idiom::Pad, false),
1443 (Os::Web, Idiom::Phone, false),
1444 (Os::Ios, Idiom::Phone, false),
1445 (Os::Ios, Idiom::Pad, false),
1446 (Os::Ios, Idiom::Mac, false),
1448 (Os::Ios, Idiom::Desktop, false),
1449 (Os::Android, Idiom::Tv, false),
1450 ] {
1451 let env = desktop(os, idiom);
1452 assert_eq!(env.desktop(), expected, "{os:?} {idiom:?}");
1453 assert_eq!(
1455 env.reported_idiom() == Idiom::Desktop,
1456 expected,
1457 "{os:?} {idiom:?}"
1458 );
1459 }
1460 assert_eq!(desktop(Os::Ios, Idiom::Mac).reported_idiom(), Idiom::Mac);
1461 assert_eq!(
1462 desktop(Os::Ios, Idiom::Desktop).reported_idiom(),
1463 Idiom::Phone
1464 );
1465 assert!(!Os::MacOs.is_catalyst() && !Os::Web.is_catalyst());
1466 assert_eq!(Os::Ios.is_catalyst(), cfg!(target_abi = "macabi"));
1467 }
1468
1469 #[test]
1470 fn desktop_behavior_applies_in_the_terminal_idiom_on_any_os() {
1471 for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Ios, Os::Web] {
1472 assert!(Idiom::Terminal.desktop_on(os), "{os:?}");
1473 assert_eq!(Idiom::Terminal.reported_on(os), Idiom::Terminal, "{os:?}");
1474 }
1475 }
1476
1477 #[test]
1478 fn a_host_environment_replaces_what_it_sets() {
1479 let mut env = Environment {
1480 font_scale: 1.25,
1481 ..Environment::default()
1482 };
1483 HostEnvironment::default().apply(&mut env);
1484 assert_eq!((env.locale, env.font_scale), (Locale::EN_US, 1.25));
1485 let zh = Locale::parse("zh-Hans-CN").unwrap();
1486 HostEnvironment {
1487 locale: Some(zh),
1488 font_scale: Some(f32::NAN),
1489 }
1490 .apply(&mut env);
1491 assert_eq!((env.locale, env.font_scale), (zh, 1.25));
1492 HostEnvironment {
1493 locale: None,
1494 font_scale: Some(1.5),
1495 }
1496 .apply(&mut env);
1497 assert_eq!((env.locale, env.font_scale), (zh, 1.5));
1498 }
1499
1500 #[test]
1501 fn languages_parse_platform_identifiers_and_an_embedding_app_goes_first() {
1502 let tags = |l: Languages| l.iter().map(|l| l.to_string()).collect::<Vec<_>>();
1503 let system = Languages::parse(["de_DE", "C", "en-US", "de-DE", "fr"]).unwrap();
1504 assert_eq!(tags(system), ["de-DE", "en-US", "fr"]);
1505 assert_eq!(system.first().as_str(), "de-DE");
1506 assert_eq!(Languages::parse(["C", ""]), None);
1507 let many: Vec<String> = (0..20)
1508 .map(|i| format!("x{}", (b'a' + i) as char))
1509 .collect();
1510 let many = Languages::parse(many.iter().map(String::as_str)).unwrap();
1511 assert_eq!(many.as_slice().len(), Languages::CAPACITY);
1512 let fr = Locale::parse("fr").unwrap();
1513 assert_eq!(tags(system.preferring(fr)), ["fr", "de-DE", "en-US"]);
1514 let ja = Locale::parse("ja-JP").unwrap();
1515 assert_eq!(
1516 tags(system.preferring(ja)),
1517 ["ja-JP", "de-DE", "en-US", "fr"]
1518 );
1519 assert_eq!(tags(Languages::default()), ["en-US"]);
1520 let mut env = Environment::default();
1522 env.locale_settings.languages = system;
1523 HostEnvironment {
1524 locale: Some(ja),
1525 font_scale: None,
1526 }
1527 .apply(&mut env);
1528 assert_eq!(
1529 tags(env.locale_settings.languages),
1530 ["ja-JP", "de-DE", "en-US", "fr"]
1531 );
1532 }
1533
1534 #[test]
1535 fn locales_parse_platform_identifiers() {
1536 let tag = |s: &str| Locale::parse(s).map(|l| l.as_str().to_owned());
1537 assert_eq!(tag("en_US").as_deref(), Some("en-US"));
1538 assert_eq!(tag("zh-hans_cn").as_deref(), Some("zh-Hans-CN"));
1539 assert_eq!(tag("de_DE@calendar=gregorian").as_deref(), Some("de-DE"));
1540 assert_eq!(tag("pt_BR.UTF-8").as_deref(), Some("pt-BR"));
1541 assert_eq!(tag("es-419").as_deref(), Some("es-419"));
1542 assert_eq!(tag("en-US-u-hc-h23").as_deref(), Some("en-US"));
1543 assert_eq!(tag("C"), None);
1544 assert_eq!(Locale::default().as_str(), "en-US");
1545 let zh = Locale::parse("zh-Hans-CN").unwrap();
1546 assert_eq!((zh.language(), zh.region()), ("zh", Some("CN")));
1547 assert_eq!(Locale::parse("zh-Hans").unwrap().region(), None);
1548 assert_eq!(Locale::parse("es-419").unwrap().region(), Some("419"));
1549 }
1550
1551 #[test]
1552 fn regional_preferences_are_the_regions_unless_the_locale_sets_others() {
1553 type Regional = (HourCycle, Weekday, MeasurementSystem, TemperatureUnit);
1555 let regional = |s: LocaleSettings| -> Regional {
1556 (
1557 s.hour_cycle,
1558 s.first_day_of_week,
1559 s.measurement_system,
1560 s.temperature_unit,
1561 )
1562 };
1563 let of = |tag: &str| LocaleSettings::of(Locale::parse(tag).unwrap());
1564 let us = regional(LocaleSettings::default());
1565 let world = (
1566 HourCycle::H23,
1567 Weekday::Monday,
1568 MeasurementSystem::Metric,
1569 TemperatureUnit::Celsius,
1570 );
1571 assert_eq!(regional(of("en-US")), us);
1572 assert_eq!(
1573 LocaleSettings::default().languages.as_slice(),
1574 &[Locale::EN_US]
1575 );
1576 assert_eq!(LocaleSettings::default().time_zone, TimeZone::UTC);
1577 assert_eq!(
1579 of("de-DE").languages.as_slice(),
1580 &[Locale::parse("de-DE").unwrap()]
1581 );
1582 assert_eq!(regional(of("de-DE")), world);
1583 assert_eq!(regional(of("ja")), world);
1585 assert_eq!(of("en-CA").hour_cycle, HourCycle::H12);
1586 assert_eq!(of("fr-CA").hour_cycle, HourCycle::H23);
1588 assert_eq!(of("fr-CA").first_day_of_week, Weekday::Sunday);
1589 assert_eq!(of("en-001").hour_cycle, HourCycle::H12);
1590 assert_eq!(of("es-419").hour_cycle, HourCycle::H12);
1591 assert_eq!(of("ar-EG").first_day_of_week, Weekday::Saturday);
1592 assert_eq!(of("dv-MV").first_day_of_week, Weekday::Friday);
1593 let gb = of("en-GB");
1594 assert_eq!(gb.measurement_system, MeasurementSystem::Uk);
1595 assert_eq!(gb.temperature_unit, TemperatureUnit::Celsius);
1596 assert_eq!(of("en-LR").temperature_unit, TemperatureUnit::Celsius);
1597 assert_eq!(of("es-PR").temperature_unit, TemperatureUnit::Fahrenheit);
1598
1599 let parse = |identifier: &str| regional(LocaleSettings::parse(identifier));
1600 assert_eq!(
1601 parse("en-US-u-fw-mon-mu-celsius"),
1602 (
1603 HourCycle::H12,
1604 Weekday::Monday,
1605 MeasurementSystem::Us,
1606 TemperatureUnit::Celsius
1607 )
1608 );
1609 assert_eq!(
1610 parse("en_US@hours=h23;measure=metric"),
1611 (
1612 HourCycle::H23,
1613 Weekday::Sunday,
1614 MeasurementSystem::Metric,
1615 TemperatureUnit::Fahrenheit
1616 )
1617 );
1618 assert_eq!(parse("en_US@rg=gbzzzz"), regional(gb));
1619 assert_eq!(
1620 parse("ar-u-ca-islamic-umalqura-hc-h11-rg-uszzzz"),
1621 (HourCycle::H11, us.1, us.2, us.3)
1622 );
1623 assert_eq!(
1624 LocaleSettings::parse("en-GB-u-ms-ussystem-mu-fahrenhe").measurement_system,
1625 MeasurementSystem::Us
1626 );
1627 assert_eq!(parse("de_DE.UTF-8@fw=xyz;hours=h99;rg=1"), world);
1629 assert_eq!(parse("en-US-x-hc-h23"), us);
1630 assert_eq!(parse("C"), world);
1631 assert_eq!(
1633 LocaleSettings::parse("de_DE.UTF-8").languages.as_slice(),
1634 &[Locale::parse("de-DE").unwrap()]
1635 );
1636 assert_eq!(
1637 LocaleSettings::parse("C").languages.as_slice(),
1638 &[Locale::EN_US]
1639 );
1640 assert_eq!(Weekday::from_number(7), Some(Weekday::Sunday));
1641 assert_eq!(Weekday::from_number(0), None);
1642 assert_eq!(Weekday::Monday.number(), 1);
1643 assert!(HourCycle::H11.twelve_hour() && !HourCycle::H24.twelve_hour());
1644 assert_eq!(HourCycle::of_pattern("h:mm a"), Some(HourCycle::H12));
1645 assert_eq!(HourCycle::of_pattern("HH 'Uhr'"), Some(HourCycle::H23));
1646 assert_eq!(HourCycle::of_pattern("'h' K:mm"), Some(HourCycle::H11));
1647 assert_eq!(HourCycle::of_pattern("mm:ss"), None);
1648 }
1649
1650 #[test]
1651 fn time_zones_parse_platform_identifiers() {
1652 let zone = |s: &str| TimeZone::parse(s).map(|z| z.as_str().to_owned());
1653 assert_eq!(zone("Europe/Berlin").as_deref(), Some("Europe/Berlin"));
1654 assert_eq!(zone(":Asia/Tokyo").as_deref(), Some("Asia/Tokyo"));
1655 assert_eq!(
1656 zone("/var/db/timezone/zoneinfo/America/Argentina/Buenos_Aires").as_deref(),
1657 Some("America/Argentina/Buenos_Aires")
1658 );
1659 assert_eq!(
1660 zone("/usr/share/zoneinfo/Etc/GMT+5").as_deref(),
1661 Some("Etc/GMT+5")
1662 );
1663 assert_eq!(zone("GMT+01:00").as_deref(), Some("GMT+01:00"));
1664 assert_eq!(
1665 zone("America/Argentina/ComodRivadavia").as_deref(),
1666 Some("America/Argentina/ComodRivadavia")
1667 );
1668 assert_eq!(zone(""), None);
1669 assert_eq!(zone("Europe//Berlin"), None);
1670 assert_eq!(zone("../etc/passwd"), None);
1671 assert_eq!(zone("Central European Standard Time"), None);
1672 let parts = ["Abcdefghijklmn"; 4].join("/");
1673 assert_eq!(zone(&parts).as_deref(), Some(parts.as_str()));
1674 assert_eq!(zone(&"A".repeat(64)), None);
1675 assert_eq!(TimeZone::default().as_str(), "UTC");
1676 assert_eq!(
1677 Environment::default().locale_settings.time_zone,
1678 TimeZone::UTC
1679 );
1680 }
1681
1682 #[test]
1683 fn posix_time_zones_follow_the_zone_tz_names() {
1684 let singapore = || TimeZone::parse("Asia/Singapore");
1686 let zone = |tz: Option<&str>| TimeZone::posix(tz, singapore).as_str().to_owned();
1687 assert_eq!(zone(Some("GMT")), "GMT");
1689 assert_eq!(
1690 TimeZone::posix(Some("GMT"), || unreachable!("TZ names the zone")).as_str(),
1691 "GMT"
1692 );
1693 for name in [
1695 "UTC",
1696 "EST",
1697 "Japan",
1698 "NZ-CHAT",
1699 "Etc/GMT+5",
1700 "Europe/Berlin",
1701 "EST5EDT",
1702 "GMT0",
1703 "GMT-0",
1704 ] {
1705 assert_eq!(zone(Some(name)), name);
1706 assert_eq!(zone(Some(&format!(":{name}"))), name);
1707 }
1708 assert_eq!(zone(Some(":/usr/share/zoneinfo/Asia/Tokyo")), "Asia/Tokyo");
1709 assert_eq!(zone(Some("")), "UTC");
1711 for tz in [
1713 "JST-9",
1714 "EST5",
1715 "CET-1CEST",
1716 "<+08>-8",
1717 "CET-1CEST,M3.5.0,M10.5.0/3",
1718 "GMT+01:00",
1719 ":/etc/localtime",
1720 ":",
1721 ] {
1722 assert_eq!(zone(Some(tz)), "Asia/Singapore", "TZ={tz}");
1723 }
1724 assert_eq!(zone(None), "Asia/Singapore");
1725 assert_eq!(TimeZone::posix(None, || None), TimeZone::UTC);
1726 }
1727
1728 #[test]
1729 fn content_types_follow_the_extension_of_paths_and_asset_urls() {
1730 assert_eq!(
1731 content_type("dist/app.js"),
1732 "text/javascript; charset=utf-8"
1733 );
1734 assert_eq!(content_type("nsh.WASM"), "application/wasm");
1735 assert_eq!(
1736 content_type("asset:/@app/locales/en.json"),
1737 "application/json"
1738 );
1739 assert_eq!(content_type("asset:/images/flag@2x.png"), "image/png");
1740 assert_eq!(content_type("asset:/fonts/Inter.woff2"), "font/woff2");
1741 assert_eq!(content_type("asset:/sounds/chime.OGG"), "audio/ogg");
1742 for unknown in ["asset:/data.bin", "asset:/README", "asset:/.png"] {
1743 assert_eq!(
1744 content_type(unknown),
1745 "application/octet-stream",
1746 "{unknown}"
1747 );
1748 }
1749 }
1750
1751 #[test]
1752 fn file_mime_types_come_from_the_name_alone() {
1753 assert_eq!(file_mime_type("file:///tmp/a%20b.PNG"), "image/png");
1754 assert_eq!(file_mime_type("file:///tmp/%E4%B8%AD.jpeg"), "image/jpeg");
1755 assert_eq!(file_mime_type("/Users/me/Report.pdf"), "application/pdf");
1756 assert_eq!(
1757 file_mime_type("file:///tmp/notes.md?x=1#y"),
1758 "text/markdown"
1759 );
1760 assert_eq!(file_mime_type("C:/Users/me/Clip.mov"), "video/quicktime");
1761 for none in [
1763 "file:///tmp/photos.d/",
1764 "file:///tmp/README",
1765 "file:///tmp/.env",
1766 "file:///tmp/a.unknownext",
1767 "",
1768 ] {
1769 assert_eq!(file_mime_type(none), "", "{none}");
1770 }
1771 }
1772}