Skip to main content

glory_render/
environment.rs

1//! Finite inherited direction and language metadata, independent of UI locale
2//! tables, application text, fonts, editors and platform APIs.
3use crate::{Direction, Error, NodeId, memory::Memory};
4
5#[derive(Clone, Debug, PartialEq, Eq)]
6pub struct LanguageTag(String);
7impl LanguageTag {
8    /// A bounded ASCII language tag syntax. This does not consult a language
9    /// registry or silently infer a locale's writing direction.
10    pub fn new(value: impl AsRef<str>) -> Result<Self, Error> {
11        let value = value.as_ref();
12        if value.len() > 63 || value.len() < 2 || !value.is_ascii() {
13            return Err(Error::InvalidProps("invalid bounded language tag"));
14        }
15        let mut pieces = value.split('-');
16        let first = pieces.next().expect("nonempty language tag");
17        if !(2..=8).contains(&first.len())
18            || !first.bytes().all(|byte| byte.is_ascii_alphabetic())
19            || pieces.any(|part| {
20                part.is_empty()
21                    || part.len() > 8
22                    || !part.bytes().all(|byte| byte.is_ascii_alphanumeric())
23            })
24        {
25            return Err(Error::InvalidProps("invalid bounded language tag"));
26        }
27        Ok(Self(value.to_owned()))
28    }
29    pub fn as_str(&self) -> &str {
30        &self.0
31    }
32}
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct Environment {
35    pub direction: Direction,
36    pub language: LanguageTag,
37}
38impl Memory {
39    /// Current semantic ancestry, including unplaced and suspended nodes. The
40    /// caller still applies its host's liveness and capability rules separately.
41    pub fn inherited_environment(&self, mut id: NodeId) -> Result<Option<&Environment>, Error> {
42        loop {
43            let node = self.node(id)?;
44            if let Some(environment) = node
45                .descriptor
46                .view()
47                .semantics
48                .as_ref()
49                .and_then(|value| value.environment.as_ref())
50            {
51                return Ok(Some(environment));
52            }
53            let Some(parent) = node.parent else {
54                return Ok(None);
55            };
56            id = parent;
57        }
58    }
59}