DEV Community

Daniel Pertu
Daniel Pertu

Posted on

Our Expo app has 42 accessibility labels and three hints, and the hardest one was Chrome refusing to hide a focused element

The web gives you a lot for free. A <button> is focusable, announces itself as a button, responds to space and enter, and shows a focus ring, and you get all of that by typing seven characters. React Native gives you View and Pressable. A Pressable is tappable and otherwise says nothing about itself to anybody.

Munchable's app is 37 hand-written components and 20 route files, and it builds every control it has out of those primitives. There is no component library underneath it. So I went and counted what the semantics actually cost, by grepping for every accessibility prop in src/ and app/:

Pressable / TouchableOpacity   129
accessibilityLabel              42
accessibilityRole               36
accessibilityState              18
hitSlop                         15
accessibilityHint                3
accessible={false}               1
StyleSheet.create                2
Enter fullscreen mode Exit fullscreen mode

Three of those numbers are worth defending and one of them is the whole post.

Why roles are fewer than pressables, and hints are nearly none

129 against 36 looks like a 72 per cent failure rate. It is not, because most of those 129 occurrences are inside the 37 components rather than inside the 20 screens: Button, ChoiceRow, ConditionRow, AllergyRow, RecipeRow, Chip, Collapsible and the rest each wrap a Pressable once and set the role once, and then a screen uses the component 14 times. The role is typed where the control is defined, not where it is used, which is the only version of this that stays correct.

The 18 accessibilityState uses are the toggles: conditions, allergies, shopping preferences, the sensitivity steps. Those screens are mostly lists of things that are on or off, and selected or checked is the entire difference between "Lactose, button" and "Lactose, selected, button". It is the cheapest accessibility prop in React Native and the easiest to forget, because the visual state is already obvious on screen to you, the person who built it.

Three hints is deliberate. accessibilityHint is read after a pause, it is verbose, and the standard advice is to use it only where the result of the action is genuinely not predictable from the label. Most of this app is predictable from the label. Three places are not, and they have hints, and I would rather have three good ones than 129 readings of "Double tap to activate".

Five components make themselves invisible

The opposite job matters as much. Every screen in the app sits on a soft warm wash of blurred colour, drawn in SVG, which is decoration and nothing else:

<View
  accessibilityElementsHidden
  importantForAccessibility="no-hide-descendants"
  style={[StyleSheet.absoluteFill, { pointerEvents: 'none' }]}
>
Enter fullscreen mode Exit fullscreen mode

Both props, because they are the same instruction for two platforms: accessibilityElementsHidden is iOS, importantForAccessibility="no-hide-descendants" is Android, and setting one gets you an app that is tidy on half the phones. They appear together in five components, and nowhere is one without the other.

The more interesting use is on the result screen. The verdict is drawn as a coloured disc with an icon in it, next to a word, with a sentence under it. Announced naively, a screen reader works through a decorative circle, an icon, a word and a sentence as four separate things. So the disc is hidden, and the composition is labelled once, as a sentence. The parts that are only there to be looked at are not in the accessibility tree at all.

That is also why the verdict is never colour alone. Every verdict state carries a colour, a distinct icon shape and a text label, and the three travel together through the token file, so there is no way to render one without the other two:

<Icon name={icon} color={c.on} size={12} />
<Text variant="label" color={c.on}>{label}</Text>
Enter fullscreen mode Exit fullscreen mode

You can see the same discipline in the places the app and the site share: the condition guides on the site, like the coeliac one, use the same three channels for the same reason.

The hard one: aria-hidden loses an argument with document.activeElement

The app also runs on the web, built by Expo, which is where this gets interesting. Two completely separate components in this repo contain the same eleven lines, and both arrived at them by hitting the same wall.

The setup is the same in both cases. Something is being hidden from assistive technology while staying mounted in the DOM. In the navigation stack, a route that is no longer the focused one gets aria-hidden so a screen reader does not read the page underneath the one you are on. In the Collapsible, a closed row keeps its children mounted purely so they can be measured for the open animation, and marks them aria-hidden so nothing reads a shut row.

And in both cases, the element the browser is focused on at that exact moment is inside the thing being hidden. You tapped a button to navigate, so the focused element is the button on the page that just stopped being current. You tapped a row header to close it, so the focused element is in the row that just closed.

Chrome will not do it. Hiding the focused element from the accessibility tree would leave assistive tech pointed at something that no longer exists, so it refuses the attribute and logs a warning. Not an error, not a thrown exception: a console warning and an element that is still perfectly visible to a screen reader, which is the worst kind of failure because the code looks like it worked.

The fix is to stop being focused, first, in the same task:

const host = useRef<View>(null);
useLayoutEffect(() => {
  if (open || typeof document === 'undefined') return;
  const node = host.current as unknown;
  const active = document.activeElement;
  if (node instanceof HTMLElement && active instanceof HTMLElement && node.contains(active)) {
    active.blur();
  }
}, [open]);
Enter fullscreen mode Exit fullscreen mode

useLayoutEffect rather than useEffect is the entire trick. A layout effect runs synchronously in the same task as the DOM update that set the attribute, which puts the blur() ahead of the check that would have rejected it. A useEffect runs after paint, which is one frame too late: the warning has already been logged and the attribute has already been dropped.

The rest of it is the care you need around a View ref that is only an HTMLElement on one platform. typeof document === 'undefined' short-circuits native, the two instanceof guards do the narrowing, and node.contains(active) is what stops a component blurring something that was never inside it. On a native build this effect compiles down to an early return.

Writing this post is how I noticed that those eleven lines exist twice, in Stack.web.tsx and in Collapsible.tsx, with different variable names and the same comment explaining the same browser behaviour. Two instances is where I usually leave a duplication alone. This one I would rather extract, because the knowledge in it is not "blur the element", it is "Chrome's accessibility tree and your focus state have an ordering relationship", and that is not a thing a third person is going to rediscover cheaply.

Reduced motion, 15 times, and the end state rather than a faster one

useReducedMotion appears 15 times across eight files. The pattern in every one of them is the same, and it is not "a shorter animation":

const reduced = useReducedMotion();
const progress = useSharedValue(reduced ? 1 : 0);

useEffect(() => {
  progress.value = reduced ? 1 : withTiming(1, { duration, easing: motion.ease });
}, [duration, progress, reduced]);
Enter fullscreen mode Exit fullscreen mode

With Reduce Motion on, the shared value starts at its finished position and is assigned, not animated. The content is simply there, on the first frame, in place. A 120 millisecond fade is still a fade, and somebody who has told their phone they do not want motion has not asked for a quicker one.

The animation bug that was really a layout bug

One more, because it is the reason the fade component exists at all rather than the framework's.

Reanimated ships declarative entering animations, entering={FadeIn}, which are one prop and very tempting. They are compiled to a keyframe that pins the view with position: absolute while it plays, and the view can be left that way, out of the layout flow, for as long as the screen stays mounted. On the result screen that dropped the verdict word on top of the badge beneath it. Rows jumped as they opened.

So the app animates opacity and a transform through an ordinary animated style instead. Neither of those touches layout, which means the space the children occupy is identical on the first frame and the last: what is painted moves, what is reserved never does. That is a visual bug when you can see the screen and an unrecoverable one when you cannot, and the fix is 73 lines rather than one prop.

What this audit does not tell you

It counts props. It does not prove a single screen is usable with a screen reader, because nothing in this repo asserts that: there is no automated accessibility check on the app, the UI is verified by hand, and 1 instance of accessible={false} in the camera screen is exactly the sort of thing that deserves a second look rather than a count.

What the numbers do tell you is where the semantics live. 36 roles against 129 pressables is the ratio you get when controls are defined once and used often, and it is the only ratio that survives six months of a screen being edited by somebody in a hurry. If you are building a React Native app with no component library under it, the thing to get right early is not the labels. It is that there is exactly one place a label could go.

The app's web build is at app.munchable.app, the free tier needs nothing but an email address, and get started is the front door. Tab through it if you want to see the navigation stack hand focus from one page to the next.

Top comments (0)