Skip to main content

cranpose_services/
accessibility_state.rs

1//! What the platform says about the assistive technology in use, for an app
2//! that speaks guidance, slows an automatic step down or drops a gesture-only
3//! path while a screen reader is on.
4
5use std::cell::Cell;
6
7use cranpose_core::{CompositionLocal, CompositionLocalProvider, compositionLocalOf};
8use cranpose_macros::composable;
9
10/// What the platform reports about the assistive technology in use.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
12pub struct AccessibilityState {
13    /// Whether a screen reader is on: VoiceOver on iOS, a service such as
14    /// TalkBack on Android, or a reader that connected to the app through
15    /// accesskit on the desktop. The web has no such signal and says no.
16    pub screen_reader_on: bool,
17}
18
19thread_local! {
20    static PLATFORM_ACCESSIBILITY_STATE: Cell<AccessibilityState> =
21        const { Cell::new(AccessibilityState { screen_reader_on: false }) };
22}
23
24/// Installs what the platform reports. A backend calls this on every check
25/// and forces a root render when the answer is true, so composition reads
26/// the new state.
27pub fn set_platform_accessibility_state(state: AccessibilityState) -> bool {
28    PLATFORM_ACCESSIBILITY_STATE.with(|cell| {
29        let changed = cell.get() != state;
30        cell.set(state);
31        changed
32    })
33}
34
35/// What the platform last reported.
36pub fn platform_accessibility_state() -> AccessibilityState {
37    PLATFORM_ACCESSIBILITY_STATE.with(Cell::get)
38}
39
40/// The state a composable reads: what the platform reported, unless a
41/// [`ProvideAccessibilityState`] above it says otherwise.
42pub fn local_accessibility_state() -> CompositionLocal<AccessibilityState> {
43    crate::composition_locals::cached_local(
44        |locals| &locals.accessibility_state,
45        || compositionLocalOf(platform_accessibility_state),
46    )
47}
48
49/// Gives the content below it a fixed state, for a preview or a test that
50/// wants to see the app as a screen reader user does.
51#[composable]
52pub fn ProvideAccessibilityState(state: AccessibilityState, content: impl FnOnce()) {
53    let local = local_accessibility_state();
54    CompositionLocalProvider([local.provides(state)], move || {
55        content();
56    });
57}
58
59#[cfg(test)]
60#[path = "tests/accessibility_state_tests.rs"]
61mod tests;