1
//! CSS Spatial Navigation Level 1 - the two per-container overrides.
2
//!
3
//! 9a-i-a made an arrow key try focus first and fall back to scrolling, which
4
//! is the spec's default behaviour and is right almost everywhere. These two
5
//! properties are how a container opts OUT of that default, and neither is
6
//! expressible any other way:
7
//!
8
//! - [`StyleSpatialNavigationAction`] forces the choice on a scroll container: always scroll (a
9
//!   map, a canvas, a code editor - places where an arrow means "pan", never "jump to the next
10
//!   button"), or always move focus.
11
//! - [`StyleSpatialNavigationContain`] makes an element a spatial navigation CONTAINER even when it
12
//!   is not a scroll container, so navigation inside a panel stays inside it.
13
//!
14
//! Both are from `css-nav-1`, and both have `auto` as their initial value, so
15
//! adding them changes nothing until a stylesheet asks.
16

            
17
use crate::{corety::AzString, props::formatter::PrintAsCssValue};
18

            
19
/// `spatial-navigation-action` - what an arrow key does on a scroll container.
20
///
21
/// ```css
22
/// .map     { spatial-navigation-action: scroll; }  /* arrows always pan   */
23
/// .menu    { spatial-navigation-action: focus; }   /* arrows never scroll */
24
/// ```
25
///
26
/// The default is [`Auto`](Self::Auto), which is the ordered fallback 9a-i-a
27
/// implements: move focus if there is somewhere to move it, otherwise scroll.
28
///
29
/// NOT INHERITED. The property answers "what does an arrow do when THIS
30
/// element is the scroll container", and a container that pans is routinely
31
/// full of ordinary focusable controls that must keep behaving normally -
32
/// inheriting `scroll` into them would make every button inside a map
33
/// unreachable by keyboard.
34
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
35
#[repr(C)]
36
pub enum StyleSpatialNavigationAction {
37
    /// Move focus if a candidate lies in that direction; otherwise scroll.
38
    #[default]
39
    Auto,
40
    /// Always move focus. If there is no candidate the container does NOT
41
    /// scroll - the search continues outward instead, so an arrow at the edge
42
    /// of a menu escapes it rather than nudging it.
43
    Focus,
44
    /// Always scroll, changing nothing about focus, even when focusable
45
    /// children are sitting right there. What a map, a canvas or a code
46
    /// editor wants.
47
    Scroll,
48
}
49

            
50
impl PrintAsCssValue for StyleSpatialNavigationAction {
51
3
    fn print_as_css_value(&self) -> String {
52
3
        String::from(match self {
53
1
            Self::Auto => "auto",
54
1
            Self::Focus => "focus",
55
1
            Self::Scroll => "scroll",
56
        })
57
3
    }
58
}
59

            
60
/// `spatial-navigation-contain` - whether this element is a spatial
61
/// navigation container.
62
///
63
/// ```css
64
/// .sidebar { spatial-navigation-contain: contain; }
65
/// ```
66
///
67
/// Under `auto`, only scroll containers (and the viewport) are containers,
68
/// which is the spec's default. `contain` adds one for an element that does
69
/// not scroll - a toolbar, a dialog, a sidebar - so that arrow keys resolve
70
/// among its descendants first and only leave it when nothing inside answers.
71
///
72
/// NOT INHERITED, and for a sharper reason than the action property: it marks
73
/// ONE element as a boundary. Inheriting it would make every descendant a
74
/// boundary too, which is the same as having none - each nested container
75
/// would trap navigation one level deeper until an arrow could not move at
76
/// all.
77
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
78
#[repr(C)]
79
pub enum StyleSpatialNavigationContain {
80
    /// A container only if this element is a scroll container.
81
    #[default]
82
    Auto,
83
    /// A container regardless of whether it scrolls.
84
    Contain,
85
}
86

            
87
impl PrintAsCssValue for StyleSpatialNavigationContain {
88
2
    fn print_as_css_value(&self) -> String {
89
2
        String::from(match self {
90
1
            Self::Auto => "auto",
91
1
            Self::Contain => "contain",
92
        })
93
2
    }
94
}
95

            
96
/// `spatial-navigation-action` parse error.
97
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
98
pub enum CssSpatialNavigationActionParseError<'a> {
99
    InvalidValue(&'a str),
100
}
101

            
102
impl core::fmt::Display for CssSpatialNavigationActionParseError<'_> {
103
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
104
        match self {
105
            Self::InvalidValue(v) => write!(
106
                f,
107
                "Invalid spatial-navigation-action value: \"{v}\" (expected auto, focus or scroll)"
108
            ),
109
        }
110
    }
111
}
112

            
113
/// Owned mirror of [`CssSpatialNavigationActionParseError`].
114
// `AzString`, not `String`, and `#[repr(C, u8)]`, not bare `repr(C)`. Both
115
// are FFI requirements this type cannot opt out of: it is reachable from the
116
// exposed parse-error surface, the codegen builds its mirror from `AzString`,
117
// and a payload enum with no repr compiles silently and is undefined across
118
// the boundary. `CssAppRegionParseErrorOwned` beside it is the same shape for
119
// the same reasons - api.json's own checker passes either way, so this is
120
// caught only by building the generated C ABI.
121
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
122
#[repr(C, u8)]
123
pub enum CssSpatialNavigationActionParseErrorOwned {
124
    InvalidValue(AzString),
125
}
126

            
127
impl CssSpatialNavigationActionParseError<'_> {
128
    #[must_use]
129
    pub fn to_contained(&self) -> CssSpatialNavigationActionParseErrorOwned {
130
        match self {
131
            Self::InvalidValue(v) => {
132
                CssSpatialNavigationActionParseErrorOwned::InvalidValue((*v).into())
133
            }
134
        }
135
    }
136
}
137

            
138
impl CssSpatialNavigationActionParseErrorOwned {
139
    #[must_use]
140
    pub fn to_shared(&self) -> CssSpatialNavigationActionParseError<'_> {
141
        match self {
142
            Self::InvalidValue(v) => CssSpatialNavigationActionParseError::InvalidValue(v.as_str()),
143
        }
144
    }
145
}
146

            
147
/// `spatial-navigation-contain` parse error.
148
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
149
pub enum CssSpatialNavigationContainParseError<'a> {
150
    InvalidValue(&'a str),
151
}
152

            
153
impl core::fmt::Display for CssSpatialNavigationContainParseError<'_> {
154
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
155
        match self {
156
            Self::InvalidValue(v) => write!(
157
                f,
158
                "Invalid spatial-navigation-contain value: \"{v}\" (expected auto or contain)"
159
            ),
160
        }
161
    }
162
}
163

            
164
/// Owned mirror of [`CssSpatialNavigationContainParseError`].
165
// `AzString`, not `String`, and `#[repr(C, u8)]`, not bare `repr(C)`. Both
166
// are FFI requirements this type cannot opt out of: it is reachable from the
167
// exposed parse-error surface, the codegen builds its mirror from `AzString`,
168
// and a payload enum with no repr compiles silently and is undefined across
169
// the boundary. `CssAppRegionParseErrorOwned` beside it is the same shape for
170
// the same reasons - api.json's own checker passes either way, so this is
171
// caught only by building the generated C ABI.
172
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
173
#[repr(C, u8)]
174
pub enum CssSpatialNavigationContainParseErrorOwned {
175
    InvalidValue(AzString),
176
}
177

            
178
impl CssSpatialNavigationContainParseError<'_> {
179
    #[must_use]
180
    pub fn to_contained(&self) -> CssSpatialNavigationContainParseErrorOwned {
181
        match self {
182
            Self::InvalidValue(v) => {
183
                CssSpatialNavigationContainParseErrorOwned::InvalidValue((*v).into())
184
            }
185
        }
186
    }
187
}
188

            
189
impl CssSpatialNavigationContainParseErrorOwned {
190
    #[must_use]
191
    pub fn to_shared(&self) -> CssSpatialNavigationContainParseError<'_> {
192
        match self {
193
            Self::InvalidValue(v) => {
194
                CssSpatialNavigationContainParseError::InvalidValue(v.as_str())
195
            }
196
        }
197
    }
198
}
199

            
200
#[cfg(feature = "parser")]
201
/// # Errors
202
///
203
/// Returns an error if `input` is not `auto`, `focus` or `scroll`.
204
7
pub fn parse_style_spatial_navigation_action(
205
7
    input: &str,
206
7
) -> Result<StyleSpatialNavigationAction, CssSpatialNavigationActionParseError<'_>> {
207
7
    match input.trim() {
208
7
        "auto" => Ok(StyleSpatialNavigationAction::Auto),
209
6
        "focus" => Ok(StyleSpatialNavigationAction::Focus),
210
5
        "scroll" => Ok(StyleSpatialNavigationAction::Scroll),
211
2
        _ => Err(CssSpatialNavigationActionParseError::InvalidValue(input)),
212
    }
213
7
}
214

            
215
#[cfg(feature = "parser")]
216
/// # Errors
217
///
218
/// Returns an error if `input` is not `auto` or `contain`.
219
5
pub fn parse_style_spatial_navigation_contain(
220
5
    input: &str,
221
5
) -> Result<StyleSpatialNavigationContain, CssSpatialNavigationContainParseError<'_>> {
222
5
    match input.trim() {
223
5
        "auto" => Ok(StyleSpatialNavigationContain::Auto),
224
4
        "contain" => Ok(StyleSpatialNavigationContain::Contain),
225
2
        _ => Err(CssSpatialNavigationContainParseError::InvalidValue(input)),
226
    }
227
5
}
228

            
229
#[cfg(all(test, feature = "parser"))]
230
mod tests {
231
    use super::*;
232

            
233
    #[test]
234
1
    fn the_action_keywords_parse_and_round_trip() {
235
3
        for (text, value) in [
236
1
            ("auto", StyleSpatialNavigationAction::Auto),
237
1
            ("focus", StyleSpatialNavigationAction::Focus),
238
1
            ("scroll", StyleSpatialNavigationAction::Scroll),
239
        ] {
240
3
            assert_eq!(parse_style_spatial_navigation_action(text), Ok(value));
241
3
            assert_eq!(value.print_as_css_value(), text);
242
        }
243
        // Surrounding whitespace survives the tokenizer in some paths.
244
1
        assert_eq!(
245
1
            parse_style_spatial_navigation_action("  scroll "),
246
            Ok(StyleSpatialNavigationAction::Scroll)
247
        );
248
1
    }
249

            
250
    #[test]
251
1
    fn the_contain_keywords_parse_and_round_trip() {
252
2
        for (text, value) in [
253
1
            ("auto", StyleSpatialNavigationContain::Auto),
254
1
            ("contain", StyleSpatialNavigationContain::Contain),
255
        ] {
256
2
            assert_eq!(parse_style_spatial_navigation_contain(text), Ok(value));
257
2
            assert_eq!(value.print_as_css_value(), text);
258
        }
259
1
    }
260

            
261
    /// `none` is NOT a spelling of either. Accepting it would silently turn a
262
    /// typo into the initial value, which reads as "the property did nothing".
263
    #[test]
264
1
    fn a_wrong_keyword_is_an_error_and_not_the_default() {
265
1
        assert!(parse_style_spatial_navigation_action("none").is_err());
266
1
        assert!(parse_style_spatial_navigation_action("contain").is_err());
267
1
        assert!(parse_style_spatial_navigation_contain("none").is_err());
268
1
        assert!(parse_style_spatial_navigation_contain("focus").is_err());
269
1
    }
270

            
271
    /// THE PROPERTY NAME HAS TO REACH THE PARSER, and a keyword parser that
272
    /// works in isolation proves nothing about that: the name table, the
273
    /// `CssPropertyType` arm and the dispatch all have to agree, and each is
274
    /// in a different file.
275
    #[test]
276
1
    fn both_properties_parse_from_their_css_name() {
277
        use crate::props::property::{
278
            get_css_key_map, parse_css_property, CssProperty, CssPropertyType,
279
        };
280

            
281
1
        let map = get_css_key_map();
282
1
        let ty = CssPropertyType::from_str("spatial-navigation-action", &map)
283
1
            .expect("`spatial-navigation-action` must be a known property name");
284
1
        assert_eq!(ty, CssPropertyType::SpatialNavigationAction);
285
1
        assert_eq!(
286
1
            parse_css_property(ty, "scroll"),
287
            Ok(CssProperty::SpatialNavigationAction(
288
                crate::css::CssPropertyValue::Exact(StyleSpatialNavigationAction::Scroll)
289
            ))
290
        );
291

            
292
1
        let ty = CssPropertyType::from_str("spatial-navigation-contain", &map)
293
1
            .expect("`spatial-navigation-contain` must be a known property name");
294
1
        assert_eq!(ty, CssPropertyType::SpatialNavigationContain);
295
1
        assert_eq!(
296
1
            parse_css_property(ty, "contain"),
297
            Ok(CssProperty::SpatialNavigationContain(
298
                crate::css::CssPropertyValue::Exact(StyleSpatialNavigationContain::Contain)
299
            ))
300
        );
301

            
302
        // Neither moves a box nor paints a pixel, so neither may charge a
303
        // layout pass. The default for an unlisted property is `true`, which
304
        // is why this is worth pinning.
305
1
        assert!(!CssPropertyType::SpatialNavigationAction.can_trigger_relayout());
306
1
        assert!(!CssPropertyType::SpatialNavigationContain.can_trigger_relayout());
307
1
    }
308

            
309
    /// Both default to `auto`, which is what makes adding them a no-op for
310
    /// every stylesheet that does not mention them.
311
    #[test]
312
1
    fn both_properties_default_to_auto() {
313
1
        assert_eq!(
314
1
            StyleSpatialNavigationAction::default(),
315
            StyleSpatialNavigationAction::Auto
316
        );
317
1
        assert_eq!(
318
1
            StyleSpatialNavigationContain::default(),
319
            StyleSpatialNavigationContain::Auto
320
        );
321
1
    }
322
}