Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions apps/example/src/AnimationsScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useMemo, useRef, useState } from 'react'
import { AnimationCurve, GestureRecognizerState, PanGestureRecognizer, ScrollView, ScrollViewContent, TapGestureRecognizer, View, type ViewRef } from 'nitro-ui-renderer'
import { AnimationCurve, GestureRecognizerState, PanGestureRecognizer, ScrollView, ScrollViewContent, TapGestureRecognizer, View, type AccessibilityAction, type AccessibilityActionEvent, type ViewRef } from 'nitro-ui-renderer'
import { Text } from './Text'

type Mode = 'timing' | 'spring'
Expand Down Expand Up @@ -55,7 +55,13 @@ function apply(view: ViewRef, property: Property, changed: boolean) {
}
}

const defaultDuration = 0.6
const minimumDuration = 0.2
const durationActions: AccessibilityAction[] = [
{ name: 'increment' },
{ name: 'decrement' },
{ name: 'reset', label: 'Reset duration' },
]
const maximumDuration = 2
const durationStep = 0.2

Expand All @@ -81,14 +87,27 @@ export function AnimationsScreen() {
const box = useRef<ViewRef>(null)
const changed = useRef<Changed>({ ...unchanged })
const [mode, setMode] = useState<Mode>('timing')
const [duration, setDuration] = useState(0.6)
const [duration, setDuration] = useState(defaultDuration)
const durationLabel = duration.toFixed(1)
const shorter = useCallback(() => {
setDuration(value => Math.max(minimumDuration, Math.round((value - durationStep) * 10) / 10))
}, [])
const longer = useCallback(() => {
setDuration(value => Math.min(maximumDuration, Math.round((value + durationStep) * 10) / 10))
}, [])
const onDurationAction = useCallback((event: AccessibilityActionEvent) => {
switch (event.actionName) {
case 'increment':
longer()
break
case 'decrement':
shorter()
break
case 'reset':
setDuration(defaultDuration)
break
}
}, [longer, shorter])
const [measured, setMeasured] = useState('Tap Measure to read the box frame in the window.')

const animate = useCallback((targets: readonly Property[], next: (property: Property) => boolean) => {
Expand Down Expand Up @@ -154,6 +173,9 @@ export function AnimationsScreen() {
<Button label="Shorter" onTap={shorter} />
<Text
aria-label="Timing duration"
role="slider"
accessibilityActions={durationActions}
onAccessibilityAction={onDurationAction}
aria-valuemin={minimumDuration}
aria-valuemax={maximumDuration}
aria-valuenow={duration}
Expand Down
30 changes: 30 additions & 0 deletions docs/content/docs/accessibility.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,35 @@ The value props describe the current value of a view such as a slider or a progr
</View>
```

## Add actions

`accessibilityActions` lists what a screen reader user can do with a view, and `onAccessibilityAction` receives the action's name. These names map to the platform's own actions: `activate`, `increment`, `decrement`, `longpress`, `escape`, `magicTap`, `expand` and `collapse`. Any other name is a custom action that screen readers offer in their actions menu, read as its `label`.

```tsx
const actions = [
{ name: 'increment' },
{ name: 'decrement' },
{ name: 'delete', label: 'Delete alarm' },
]

<View
accessible
role="slider"
aria-label="Snooze"
aria-valuetext={`${minutes} minutes`}
accessibilityActions={actions}
onAccessibilityAction={(event) => {
if (event.actionName === 'increment') setMinutes(minutes + 1)
if (event.actionName === 'decrement') setMinutes(minutes - 1)
if (event.actionName === 'delete') deleteAlarm()
}}
>
<Text>{`Snooze ${minutes} min`}</Text>
</View>
```

The renderer compares actions by name and label, so an inline array or handler doesn't call native on every render. On iOS, `View` and `Text` handle the standard actions. Other components get custom actions only.

## Props

| Prop | Type | iOS | Android |
Expand All @@ -111,3 +140,4 @@ The value props describe the current value of a view such as a slider or a progr
| `aria-disabled`, `aria-selected`, `aria-checked`, `aria-expanded`, `aria-busy` | `boolean`, or `'mixed'` for `aria-checked` | Traits, value, and expanded status on iOS 18 | Node enabled, selected, checked, expand actions, state description |
| `aria-hidden` | `boolean` | `accessibilityElementsHidden` | Important for accessibility, no, hiding descendants |
| `aria-valuemin`, `aria-valuemax`, `aria-valuenow`, `aria-valuetext` | `number`, or `string` for `aria-valuetext` | `accessibilityValue` | Node range info, or state description for `aria-valuetext` |
| `accessibilityActions`, `onAccessibilityAction` | `AccessibilityAction[]`, function | Standard actions and `accessibilityCustomActions` | Node actions |
2 changes: 1 addition & 1 deletion docs/content/docs/components/view/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@ Pass `gestureRecognizers` to attach touch handlers. The `ref` exposes the native
| `style` | Style object | Accepts shared styles, a linear-gradient `background`, and an ordered `boxShadow` array. Each shadow takes `offsetX`, `offsetY`, `color`, and optional `blurRadius`, `spreadDistance`, and `inset`. Shadows require Android API 31+ on Android. [Style properties](/docs/layout#style-properties) |
| `gestureRecognizers` | `GestureRecognizer[]` | Attach these recognizers to the native view. [Gestures](/docs/gestures) |
| `isUserInteractionEnabled` | `boolean` | Set to `false` to disable touch interaction on the view. |
| `accessible`, `aria-label`, `accessibilityHint`, `role`, `aria-disabled`, `aria-selected`, `aria-checked`, `aria-expanded`, `aria-busy`, `aria-hidden`, `aria-valuemin`, `aria-valuemax`, `aria-valuenow`, `aria-valuetext` | Accessibility props | Describe the view to screen readers. [Accessibility](/docs/accessibility) |
| `accessible`, `aria-label`, `accessibilityHint`, `role`, `aria-disabled`, `aria-selected`, `aria-checked`, `aria-expanded`, `aria-busy`, `aria-hidden`, `aria-valuemin`, `aria-valuemax`, `aria-valuenow`, `aria-valuetext`, `accessibilityActions`, `onAccessibilityAction` | Accessibility props | Describe the view to screen readers. [Accessibility](/docs/accessibility) |
| `ref` | React ref | Access the native container as `ViewRef`. |
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
//
// AccessibilityActions.swift
// NitroUIRenderer
//

public import UIKit
public import NitroModules

/// A view that UIKit asks directly for the standard accessibility actions, such as
/// `accessibilityIncrement()`. Views that don't conform only get custom actions.
protocol AccessibilityActionPerforming: AnyObject {
/// Returns whether the view declared and performed the named action.
var performAccessibilityAction: ((String) -> Bool)? { get set }
}

enum AccessibilityActionNames {
/// The actions UIKit asks the view for instead of listing them as custom actions.
static let standard: Set<String> = ["activate", "increment", "decrement", "escape", "magicTap"]
}

// Callback is a NitroModules type, so these members need its public import.
public extension View {
var accessibilityActions: [AccessibilityAction]? {
get { accessibilityAttributes.actions }
set {
accessibilityAttributes.actions = newValue
updateAccessibilityActions()
}
}

var onAccessibilityAction: (any Callback<(String), Void>)? {
get { accessibilityAttributes.onAction }
set {
accessibilityAttributes.onAction = newValue
updateAccessibilityActions()
}
}

/// The closures capture the callback, not this hybrid view. React clears the callback when it
/// deletes the view, which breaks a cycle through a callback that captures the view.
private func updateAccessibilityActions() {
let performer = view as? any AccessibilityActionPerforming
guard let onAction = accessibilityAttributes.onAction,
let actions = accessibilityAttributes.actions,
!actions.isEmpty else {
view.accessibilityCustomActions = nil
performer?.performAccessibilityAction = nil
return
}
let perform: (String) -> Bool = { name in
do {
try onAction.callSync(name)
return true
} catch {
return false
}
}
let standardNames = AccessibilityActionNames.standard
view.accessibilityCustomActions = actions
.filter { !standardNames.contains($0.name) }
.map { action in
UIAccessibilityCustomAction(name: action.label ?? action.name) { _ in perform(action.name) }
}
let declaredStandardNames = standardNames.intersection(actions.map(\.name))
if declaredStandardNames.isEmpty {
performer?.performAccessibilityAction = nil
} else {
performer?.performAccessibilityAction = { name in
declaredStandardNames.contains(name) && perform(name)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//

public import UIKit
internal import NitroModules

/// Accessibility props that UIKit combines into one value, such as traits.
/// Each hybrid view stores one so the props can be read back and cleared.
Expand All @@ -18,6 +19,8 @@ public struct AccessibilityAttributes {
var valueMax: Double?
var valueNow: Double?
var valueText: String?
var actions: [AccessibilityAction]?
var onAction: (any Callback<(String), Void>)?
/// The traits the view had before a prop first changed them, restored when the props are cleared.
var defaultTraits: UIAccessibilityTraits?

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
internal import UIKit

final class LabelView: UILabel {
final class LabelView: UILabel, AccessibilityActionPerforming {
var paragraphAlignment: TextAlignment?
var resolvedParagraphAlignment: NSTextAlignment {
switch paragraphAlignment {
Expand Down Expand Up @@ -29,4 +29,33 @@ final class LabelView: UILabel {
let contentRect = rect.inset(by: contentInsets)
super.drawText(in: contentRect)
}

// MARK: Accessibility actions

var performAccessibilityAction: ((String) -> Bool)?

override func accessibilityActivate() -> Bool {
if performAccessibilityAction?("activate") == true { return true }
return super.accessibilityActivate()
}

override func accessibilityIncrement() {
if performAccessibilityAction?("increment") == true { return }
super.accessibilityIncrement()
}

override func accessibilityDecrement() {
if performAccessibilityAction?("decrement") == true { return }
super.accessibilityDecrement()
}

override func accessibilityPerformEscape() -> Bool {
if performAccessibilityAction?("escape") == true { return true }
return super.accessibilityPerformEscape()
}

override func accessibilityPerformMagicTap() -> Bool {
if performAccessibilityAction?("magicTap") == true { return true }
return super.accessibilityPerformMagicTap()
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
internal import NitroModules
internal import UIKit

final class NativeContainerView: UIView, ShadowContentHost {
final class NativeContainerView: UIView, ShadowContentHost, AccessibilityActionPerforming {
private var shadowContent: UIView?
private var shadows: [NativeBoxShadow] = []
private var shadowGeometry: BoxShadowGeometry?
Expand Down Expand Up @@ -169,6 +169,35 @@ final class NativeContainerView: UIView, ShadowContentHost {
if !shadows.isEmpty && previousTraitCollection?.displayScale != traitCollection.displayScale { setNeedsLayout() }
}

// MARK: Accessibility actions

var performAccessibilityAction: ((String) -> Bool)?

override func accessibilityActivate() -> Bool {
if performAccessibilityAction?("activate") == true { return true }
return super.accessibilityActivate()
}

override func accessibilityIncrement() {
if performAccessibilityAction?("increment") == true { return }
super.accessibilityIncrement()
}

override func accessibilityDecrement() {
if performAccessibilityAction?("decrement") == true { return }
super.accessibilityDecrement()
}

override func accessibilityPerformEscape() -> Bool {
if performAccessibilityAction?("escape") == true { return true }
return super.accessibilityPerformEscape()
}

override func accessibilityPerformMagicTap() -> Bool {
if performAccessibilityAction?("magicTap") == true { return true }
return super.accessibilityPerformMagicTap()
}

/// A grouped view without its own label reads its children's labels, as Android does.
/// VoiceOver asks for this only while it runs, so the subtree walk costs nothing otherwise.
override var accessibilityLabel: String? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import androidx.core.view.AccessibilityDelegateCompat
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.RangeInfoCompat
import com.margelo.nitro.core.Callback
import com.margelo.nitro.core.callOnUI
import java.text.NumberFormat
import androidx.core.view.accessibility.AccessibilityNodeProviderCompat

Expand All @@ -29,12 +31,27 @@ internal class AccessibilityNodeDelegate(original: AccessibilityDelegateCompat?)
var valueMax: Double? = null
var valueNow: Double? = null
var valueText: String? = null
var actions: Array<AccessibilityAction>? = null
var onAction: Callback<(actionName: String) -> Unit>? = null

override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfoCompat) {
base.onInitializeAccessibilityNodeInfo(host, info)
hint?.let { info.hintText = it }
role?.let { applyRole(it, info) }
applyState(info)
applyActions(info)
}

private fun applyActions(info: AccessibilityNodeInfoCompat) {
if (onAction == null) return
actions?.forEachIndexed { index, action ->
val id = actionId(action.name, index)
// A standard action keeps its system label unless the action names one.
val label = action.label ?: action.name.takeIf { id >= CUSTOM_ACTION_ID }
if (info.actionList.none { it.id == id }) {
info.addAction(AccessibilityActionCompat(id, label))
}
}
}

private fun applyState(info: AccessibilityNodeInfoCompat) {
Expand Down Expand Up @@ -137,6 +154,31 @@ internal class AccessibilityNodeDelegate(original: AccessibilityDelegateCompat?)
}

override fun performAccessibilityAction(host: View, action: Int, args: Bundle?): Boolean {
val callback = onAction
actions?.forEachIndexed { index, declared ->
if (callback != null && actionId(declared.name, index) == action) {
callback.callOnUI(declared.name)
return true
}
}
return base.performAccessibilityAction(host, action, args)
}

private fun actionId(name: String, index: Int): Int {
return when (name) {
"activate" -> AccessibilityNodeInfoCompat.ACTION_CLICK
"longpress" -> AccessibilityNodeInfoCompat.ACTION_LONG_CLICK
"increment" -> AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD
"decrement" -> AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD
"expand" -> AccessibilityNodeInfoCompat.ACTION_EXPAND
"collapse" -> AccessibilityNodeInfoCompat.ACTION_COLLAPSE
"escape" -> AccessibilityNodeInfoCompat.ACTION_DISMISS
else -> CUSTOM_ACTION_ID + index
}
}

private companion object {
// Custom action ids sit outside the framework's (0x01) and the app's (0x7f) resource ids.
const val CUSTOM_ACTION_ID = 0x3f000000
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ interface ViewOperations {
var ariaValueMax: Double?
var ariaValueNow: Double?
var ariaValueText: String?
var accessibilityActions: Array<AccessibilityAction>?
var onAccessibilityAction: Callback<(actionName: String) -> Unit>?

fun setBackgroundColor(color: Double?)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,18 @@ class ViewState(
updateAccessibilityState(value == null) { it.valueText = value }
}

override var accessibilityActions: Array<AccessibilityAction>?
get() = accessibilityNodeDelegate?.actions
set(value) {
updateAccessibilityState(value == null) { it.actions = value }
}

override var onAccessibilityAction: Callback<(actionName: String) -> Unit>?
get() = accessibilityNodeDelegate?.onAction
set(value) {
updateAccessibilityState(value == null) { it.onAction = value }
}

// State changes while a screen reader is on the view, so it re-reads the node.
// sendAccessibilityEvent returns early when no accessibility service is running.
private inline fun updateAccessibilityState(clearing: Boolean, update: (AccessibilityNodeDelegate) -> Unit) {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading