pub mod clipboard;
use crate::geometry::{Edges, Points, Size};
pub const TAB_BAR_COMPONENT: &str = "nsh/tab-bar";
pub fn is_reserved_component(name: &str) -> bool {
name.starts_with("nsh/")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ColorScheme {
#[default]
Light,
Dark,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
pub enum Appearance {
#[default]
System,
Light,
Dark,
}
impl Appearance {
pub fn resolve(self, system: ColorScheme) -> ColorScheme {
match self {
Appearance::System => system,
Appearance::Light => ColorScheme::Light,
Appearance::Dark => ColorScheme::Dark,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Os {
Ios,
Android,
MacOs,
Windows,
Linux,
Web,
}
impl Os {
pub fn name(self) -> &'static str {
match self {
Os::Ios => "ios",
Os::Android => "android",
Os::MacOs => "macos",
Os::Windows => "windows",
Os::Linux => "linux",
Os::Web => "web",
}
}
pub fn is_desktop(self) -> bool {
matches!(self, Os::MacOs | Os::Windows | Os::Linux)
}
}
impl Default for Os {
fn default() -> Self {
if cfg!(target_os = "android") {
Os::Android
} else {
Os::Ios
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Idiom {
#[default]
Phone,
Pad,
Mac,
Tv,
Desktop,
}
impl Idiom {
pub fn desktop_on(self, os: Os) -> bool {
os.is_desktop() || (os == Os::Web && self == Idiom::Desktop)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Environment {
pub window: Size<Points>,
pub safe_area: Edges<Points>,
pub title_bar: Edges<Points>,
pub keyboard_height: Points,
pub keyboard_duration: f32,
pub color_scheme: ColorScheme,
pub font_scale: f32,
pub rtl: bool,
pub reduce_motion: bool,
pub pixel_ratio: f32,
pub screen_reader: bool,
pub os: Os,
pub os_version: (u16, u16),
pub idiom: Idiom,
pub apple_keyboard: bool,
pub locale: Locale,
pub host: bool,
}
impl Environment {
pub fn desktop(&self) -> bool {
self.idiom.desktop_on(self.os)
}
}
impl Default for Environment {
fn default() -> Self {
Self {
window: Size::default(),
safe_area: Edges::default(),
title_bar: Edges::default(),
keyboard_height: Points(0.0),
keyboard_duration: 0.25,
color_scheme: ColorScheme::Light,
font_scale: 1.0,
rtl: false,
reduce_motion: false,
pixel_ratio: 1.0,
screen_reader: false,
os: Os::default(),
os_version: (0, 0),
idiom: Idiom::Phone,
apple_keyboard: false,
locale: Locale::EN_US,
host: false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct HostEnvironment {
pub locale: Option<Locale>,
pub font_scale: Option<f32>,
}
impl HostEnvironment {
pub fn apply(&self, env: &mut Environment) {
if let Some(locale) = self.locale {
env.locale = locale;
}
if let Some(scale) = self.font_scale.filter(|s| s.is_finite() && *s > 0.0) {
env.font_scale = scale;
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Locale {
bytes: [u8; Locale::CAPACITY],
len: u8,
}
impl Locale {
const CAPACITY: usize = 15;
pub const EN_US: Locale = Locale {
bytes: *b"en-US\0\0\0\0\0\0\0\0\0\0",
len: 5,
};
pub fn parse(identifier: &str) -> Option<Locale> {
let identifier = identifier.split(['@', '.']).next().unwrap_or_default();
let mut bytes = [0u8; Self::CAPACITY];
let mut len = 0;
for (i, part) in identifier.split(['-', '_']).enumerate() {
let keep = if i == 0 {
(2..=3).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphabetic())
} else {
(part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()))
|| (part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()))
|| (part.len() == 3 && part.bytes().all(|b| b.is_ascii_digit()))
};
if !keep {
if i == 0 {
return None;
}
break;
}
if len + part.len() + usize::from(i > 0) > Self::CAPACITY {
break;
}
if i > 0 {
bytes[len] = b'-';
len += 1;
}
for (j, b) in part.bytes().enumerate() {
bytes[len] = match (i, part.len()) {
(0, _) => b.to_ascii_lowercase(),
(_, 4) if j == 0 => b.to_ascii_uppercase(),
(_, 4) => b.to_ascii_lowercase(),
_ => b.to_ascii_uppercase(),
};
len += 1;
}
}
Some(Locale {
bytes,
len: len as u8,
})
}
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("en-US")
}
}
impl Default for Locale {
fn default() -> Self {
Self::EN_US
}
}
impl std::fmt::Debug for Locale {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Locale({})", self.as_str())
}
}
impl std::fmt::Display for Locale {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpRequest {
pub method: String,
pub url: String,
pub headers: Vec<(String, String)>,
pub body: HttpBody,
pub follow_redirects: bool,
}
impl HttpRequest {
pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
Self {
method: method.into().to_ascii_uppercase(),
url: url.into(),
headers: Vec::new(),
body: HttpBody::Empty,
follow_redirects: true,
}
}
pub fn get(url: impl Into<String>) -> Self {
Self::new("GET", url)
}
pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
Self::new("POST", url).body(body)
}
#[must_use]
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
#[must_use]
pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
self.body = HttpBody::Bytes(body.into());
self
}
}
impl From<&str> for HttpRequest {
fn from(url: &str) -> Self {
Self::get(url)
}
}
impl From<String> for HttpRequest {
fn from(url: String) -> Self {
Self::get(url)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum HttpBody {
#[default]
Empty,
Bytes(Vec<u8>),
Stream,
}
impl HttpBody {
pub fn is_empty(&self) -> bool {
match self {
HttpBody::Empty => true,
HttpBody::Bytes(b) => b.is_empty(),
HttpBody::Stream => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HttpHead {
pub status: u16,
pub status_text: String,
pub url: String,
pub redirected: bool,
pub headers: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FetchEvent {
BodyWanted,
Head(HttpHead),
Data(Vec<u8>),
End,
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FetchOp {
Start(HttpRequest),
Send(Vec<u8>),
Finish,
Pause(bool),
Cancel,
}
#[cfg(test)]
mod tests {
use super::{Environment, HostEnvironment, Locale};
#[test]
fn a_host_environment_replaces_what_it_sets() {
let mut env = Environment {
font_scale: 1.25,
..Environment::default()
};
HostEnvironment::default().apply(&mut env);
assert_eq!((env.locale, env.font_scale), (Locale::EN_US, 1.25));
let zh = Locale::parse("zh-Hans-CN").unwrap();
HostEnvironment {
locale: Some(zh),
font_scale: Some(f32::NAN),
}
.apply(&mut env);
assert_eq!((env.locale, env.font_scale), (zh, 1.25));
HostEnvironment {
locale: None,
font_scale: Some(1.5),
}
.apply(&mut env);
assert_eq!((env.locale, env.font_scale), (zh, 1.5));
}
#[test]
fn locales_parse_platform_identifiers() {
let tag = |s: &str| Locale::parse(s).map(|l| l.as_str().to_owned());
assert_eq!(tag("en_US").as_deref(), Some("en-US"));
assert_eq!(tag("zh-hans_cn").as_deref(), Some("zh-Hans-CN"));
assert_eq!(tag("de_DE@calendar=gregorian").as_deref(), Some("de-DE"));
assert_eq!(tag("pt_BR.UTF-8").as_deref(), Some("pt-BR"));
assert_eq!(tag("es-419").as_deref(), Some("es-419"));
assert_eq!(tag("en-US-u-hc-h23").as_deref(), Some("en-US"));
assert_eq!(tag("C"), None);
assert_eq!(Locale::default().as_str(), "en-US");
}
}