@nativue/core 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,69 @@
1
+ package dev.nativue
2
+
3
+ import android.content.Context
4
+ import android.provider.Settings
5
+ import android.view.View
6
+ import android.view.ViewGroup
7
+ import android.view.accessibility.AccessibilityManager
8
+ import android.view.accessibility.AccessibilityNodeInfo
9
+
10
+ private val CLASS_NAME_BY_ROLE = mapOf(
11
+ "button" to "android.widget.Button",
12
+ "img" to "android.widget.ImageView",
13
+ "text" to "android.widget.TextView",
14
+ "switch" to "android.widget.Switch",
15
+ "checkbox" to "android.widget.CheckBox",
16
+ )
17
+
18
+ /** role, alt and aria-*, from the renderer: all of them, whenever one changes. */
19
+ fun View.applyAccessibility(attributes: Map<*, *>) {
20
+ val role = attributes["role"] as? String
21
+ val label = attributes["label"] as? String
22
+ val isHidden = attributes["hidden"] != null
23
+ val isElement = !isHidden && role != "none" && (role != null || label != null)
24
+
25
+ contentDescription = label
26
+ importantForAccessibility = when {
27
+ isHidden -> View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
28
+ role == "none" -> View.IMPORTANT_FOR_ACCESSIBILITY_NO
29
+ isElement -> View.IMPORTANT_FOR_ACCESSIBILITY_YES
30
+ else -> View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
31
+ }
32
+ // TalkBack reads a focusable container as one element: the text inside it, as a <button> does on the web.
33
+ isScreenReaderFocusable = isElement && this is ViewGroup
34
+ isAccessibilityHeading = role == "heading"
35
+ accessibilityDelegate = AccessibilityAttributes(role, attributes)
36
+ }
37
+
38
+ private class AccessibilityAttributes(
39
+ private val role: String?,
40
+ private val attributes: Map<*, *>,
41
+ ) : View.AccessibilityDelegate() {
42
+ override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo) {
43
+ super.onInitializeAccessibilityNodeInfo(host, info)
44
+
45
+ CLASS_NAME_BY_ROLE[role]?.let { info.className = it }
46
+ // Where TalkBack reads a role description (androidx sets the same key).
47
+ // Limitation: Android has no link role for views; this description is English whatever the language.
48
+ if (role == "link") info.extras.putCharSequence("AccessibilityNodeInfo.roleDescription", "link")
49
+ (attributes["hint"] as? String)?.let { info.hintText = it }
50
+ if (attributes["disabled"] != null) info.isEnabled = false
51
+ if (attributes["selected"] != null) info.isSelected = true
52
+ if (role == "switch" || role == "checkbox") {
53
+ info.isCheckable = true
54
+ @Suppress("DEPRECATION") // its replacement, setChecked(Int), is API 36+
55
+ info.isChecked = attributes["checked"] != null
56
+ }
57
+ }
58
+ }
59
+
60
+ /** For AccessibilityInfo; both are safe to read off the main thread. */
61
+ fun accessibilityStatus(context: Context): Map<String, Boolean> {
62
+ val accessibilityManager = context.getSystemService(AccessibilityManager::class.java)
63
+ val animationScale = Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f)
64
+
65
+ return mapOf(
66
+ "screenReaderEnabled" to accessibilityManager.isTouchExplorationEnabled,
67
+ "reduceMotionEnabled" to (animationScale == 0f),
68
+ )
69
+ }
@@ -127,8 +127,50 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
127
127
  null
128
128
  }
129
129
 
130
- /** The system may have switched between light and dark: nativue's views repaint, then JS is told. */
131
130
  fun onConfigurationChanged() {
131
+ updateFontScale()
132
+ updateColorScheme()
133
+ updateWindowSize()
134
+ }
135
+
136
+ /** Rotation and split view resize the window. */
137
+ private fun updateWindowSize() {
138
+ val nextWindowSize = windowSize()
139
+ if (nextWindowSize == windowSize) return
140
+
141
+ windowSize = nextWindowSize
142
+ evaluate { runtime?.call("__windowSizeChanged", nextWindowSize) }
143
+ }
144
+
145
+ private var fontScale = activity.resources.configuration.fontScale
146
+
147
+ /** The system's text size changed: text is sized again, and laid out again. */
148
+ private fun updateFontScale() {
149
+ val nextFontScale = activity.resources.configuration.fontScale
150
+ if (nextFontScale == fontScale) return
151
+
152
+ val nodeViews = nodesById.values.mapTo(HashSet()) { it.view }
153
+ rescaleText(activity.window.decorView, nodeViews, nextFontScale / fontScale)
154
+ fontScale = nextFontScale
155
+ nodesById.values.forEach { it.updateFontSize() }
156
+ rootView.requestLayout()
157
+ }
158
+
159
+ /**
160
+ * Headers set their text in sp once: scale it by as much as the system's text size changed. Text in dp
161
+ * (tab labels) keeps its size.
162
+ */
163
+ private fun rescaleText(view: View, nodeViews: Set<View>, ratio: Float) {
164
+ if (view is TextView && view !in nodeViews && view.textSizeUnit != TypedValue.COMPLEX_UNIT_DIP) {
165
+ view.setTextSize(TypedValue.COMPLEX_UNIT_PX, view.textSize * ratio)
166
+ }
167
+ if (view !is ViewGroup) return
168
+
169
+ for (index in 0 until view.childCount) rescaleText(view.getChildAt(index), nodeViews, ratio)
170
+ }
171
+
172
+ /** The system may have switched between light and dark: nativue's views repaint, then JS is told. */
173
+ private fun updateColorScheme() {
132
174
  if (!ThemeColors.update(activity)) return
133
175
 
134
176
  applyThemeColors(activity.window.decorView)
@@ -275,9 +317,15 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
275
317
  private fun nativeFunctions(): Map<String, NativeFunction> = buildMap {
276
318
  put("log") { arguments -> Log.i(TAG, "[JS] ${arguments[0]}") }
277
319
  put("reportError") { arguments -> reportError(arguments[0] as String, arguments[1] as String) }
278
- put("windowSize") { _ -> windowSize() }
320
+ put("windowSize") { _ -> windowSize }
279
321
  put("platform") { _ -> "android" }
280
322
  put("colorScheme") { _ -> colorScheme() }
323
+ put("accessibilityInfo") { _ -> accessibilityStatus(activity) }
324
+ put("announce") { arguments ->
325
+ val message = arguments[0] as String
326
+ @Suppress("DEPRECATION") // its replacements (live regions, pane titles) need a view to describe
327
+ mainHandler.post { rootView.announceForAccessibility(message) }
328
+ }
281
329
  // Prefixed, so a plugin can't replace nativue's own functions.
282
330
  pluginRegistry.functions.forEach { (name, function) -> put("plugin:$name", function) }
283
331
  pluginRegistry.asyncFunctions.forEach { (name, function) -> put("pluginAsync:$name", asyncCall(function)) }
@@ -312,11 +360,13 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
312
360
  putAll(fetchFunctions())
313
361
  }
314
362
 
315
- /** `windowSize` is read from JS, off the main thread: the display's size doesn't need the views. */
363
+ /** Read from JS, off the main thread: the window's size doesn't need the views. */
364
+ @Volatile private var windowSize = windowSize()
365
+
316
366
  private fun windowSize(): Map<String, Float> {
317
- val metrics = activity.resources.displayMetrics
367
+ val bounds = activity.windowManager.currentWindowMetrics.bounds
318
368
 
319
- return mapOf("width" to metrics.widthPixels / density, "height" to metrics.heightPixels / density)
369
+ return mapOf("width" to bounds.width() / density, "height" to bounds.height() / density)
320
370
  }
321
371
 
322
372
  /** A timer of a runtime that has since been reloaded doesn't fire. */
@@ -627,14 +677,14 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
627
677
 
628
678
  private fun makeTextView() = TextLabel(activity).apply {
629
679
  applyThemeColors()
630
- setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17f)
680
+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f)
631
681
  includeFontPadding = false
632
682
  }
633
683
 
634
684
  private fun makeTextInput(id: Int): TextInputView {
635
685
  val textInput = TextInputView(activity)
636
686
  textInput.background = null
637
- textInput.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17f)
687
+ textInput.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f)
638
688
  textInput.applyThemeColors()
639
689
  textInput.isSingleLine = true
640
690
  textInput.gravity = Gravity.CENTER_VERTICAL
@@ -764,6 +814,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
764
814
  (view as? ToggleSwitch)?.setCheckedFromJavaScript(isTruthyAttribute(value))
765
815
  }
766
816
 
817
+ "accessibility" -> view.applyAccessibility(value as? Map<*, *> ?: emptyMap<Any, Any>())
818
+
767
819
  "disabled" -> {
768
820
  view.isEnabled = !isTruthyAttribute(value)
769
821
  if (view is TextView && view !is EditText) view.alpha = if (view.isEnabled) 1f else 0.38f
@@ -781,7 +833,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
781
833
 
782
834
  "keyboardShouldPersistTaps" -> (view as? ScrollContainerView)?.dismissesKeyboardOnTap = (value as? String ?: "never") == "never"
783
835
 
784
- "onPan", "onPinch", "onRotate" -> gestureReporter(id, view).setReporting(key.drop(2).lowercase(), isTruthyAttribute(value))
836
+ "onPan", "onPinch", "onRotate" -> gestureReporter(id, view)?.setReporting(key.drop(2).lowercase(), isTruthyAttribute(value))
785
837
 
786
838
  "animating" -> view.visibility = if (isTruthyAttribute(value)) View.VISIBLE else View.INVISIBLE
787
839
 
@@ -836,7 +888,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
836
888
  val scrollView = view as? ScrollContainerView
837
889
  if (scrollView == null || eventName != "scroll") {
838
890
  val fieldsToNodeIds = mapping?.entries?.associate { (field, nodeId) -> field.toString() to int(nodeId) }
839
- return gestureReporter(viewId, view).setAnimatedMapping(eventName, fieldsToNodeIds)
891
+ gestureReporter(viewId, view)?.setAnimatedMapping(eventName, fieldsToNodeIds)
892
+ return
840
893
  }
841
894
 
842
895
  if (mapping == null) {
@@ -852,13 +905,19 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
852
905
  }
853
906
  }
854
907
 
855
- private fun gestureReporter(id: Int, view: View): GestureReporter = gestureReportersByNodeId.getOrPut(id) {
908
+ /** Gestures are on <View>s, which are containers. */
909
+ private fun gestureReporter(id: Int, view: View): GestureReporter? {
910
+ if (view !is ContainerView) return null
911
+
912
+ return gestureReportersByNodeId.getOrPut(id) { makeGestureReporter(id, view) }
913
+ }
914
+
915
+ private fun makeGestureReporter(id: Int, view: ContainerView) =
856
916
  GestureReporter(
857
917
  view,
858
918
  report = { eventName, payload -> dispatchEvent(eventName, id, payload) },
859
919
  setAnimatedValue = { nodeId, value -> animatedGraph.setValue(value, nodeId) },
860
920
  )
861
- }
862
921
 
863
922
  private fun reportScroll(node: NativeNode, id: Int): (Int, Int) -> Unit = { x, y ->
864
923
  val payload = mapOf(
@@ -17,14 +17,14 @@ import kotlin.math.hypot
17
17
  * gesture's state ("began", "changed", "ended", "cancelled"), so it can move the view through its
18
18
  * style; with Animated.event the values move natively and JS only hears the start and the end.
19
19
  * Numbers are in dp (and dp per second); rotation in radians. Mirrors ios/GestureReporter.swift.
20
- * Limitation: Unlike on iOS, a parent doesn't see touches a child consumes (a <Pressable> inside a draggable
21
- * card); intercept moves past the touch slop if that's needed.
20
+ * It sees every touch on its view, children's included (see ContainerView.dispatchTouchEvent), so a
21
+ * <Pressable> inside a draggable card still lets the card be dragged.
22
22
  */
23
23
  class GestureReporter(
24
- private val view: View,
24
+ private val view: ContainerView,
25
25
  private val report: (eventName: String, payload: Map<String, Any>) -> Unit,
26
26
  private val setAnimatedValue: (nodeId: Int, value: Double) -> Unit,
27
- ) : View.OnTouchListener {
27
+ ) {
28
28
  private val reportedEvents = mutableSetOf<String>()
29
29
 
30
30
  /** From Animated.event: event field -> animated value id. */
@@ -50,17 +50,19 @@ class GestureReporter(
50
50
  private var lastRotation = 0f
51
51
  private var lastTime = 0L
52
52
 
53
+ /** Once a gesture is recognized, the view takes the touch from its children. */
54
+ val isRecognizing get() = isPanning || isPinching || isRotating
55
+
53
56
  fun setReporting(eventName: String, isReporting: Boolean) {
54
57
  if (isReporting) reportedEvents.add(eventName) else reportedEvents.remove(eventName)
55
- view.setOnTouchListener(if (reportedEvents.isEmpty()) null else this)
58
+ view.gestureReporter = if (reportedEvents.isEmpty()) null else this
56
59
  }
57
60
 
58
61
  fun setAnimatedMapping(eventName: String, mapping: Map<String, Int>?) {
59
62
  if (mapping == null) animatedMappingsByEvent.remove(eventName) else animatedMappingsByEvent[eventName] = mapping
60
63
  }
61
64
 
62
- @SuppressLint("ClickableViewAccessibility")
63
- override fun onTouch(touchedView: View, event: MotionEvent): Boolean {
65
+ fun handle(event: MotionEvent) {
64
66
  val tracker = velocityTracker ?: VelocityTracker.obtain().also { velocityTracker = it }
65
67
  // Raw coordinates: moving the view with a transform doesn't skew the numbers.
66
68
  val rawEvent = MotionEvent.obtain(event).apply { setLocation(event.rawX, event.rawY) }
@@ -74,8 +76,6 @@ class GestureReporter(
74
76
  MotionEvent.ACTION_UP -> finish("ended")
75
77
  MotionEvent.ACTION_CANCEL -> finish("cancelled")
76
78
  }
77
-
78
- return true
79
79
  }
80
80
 
81
81
  private fun track(event: MotionEvent) {
@@ -647,7 +647,8 @@ private class TabItemView(context: Context) : LinearLayout(context) {
647
647
  clipChildren = false
648
648
 
649
649
  indicator.addView(icon, FrameLayout.LayoutParams(dp(24f), dp(24f), Gravity.CENTER))
650
- badge.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f)
650
+ // In dp: like iOS's, tab labels keep their size whatever the system's text size, so they fit the bar.
651
+ badge.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11f)
651
652
  badge.setTextColor(0xFFFFFFFF.toInt())
652
653
  badge.gravity = Gravity.CENTER
653
654
  badge.setPadding(dp(4f), 0, dp(4f), 0)
@@ -663,7 +664,7 @@ private class TabItemView(context: Context) : LinearLayout(context) {
663
664
  indicator.clipChildren = false
664
665
  addView(indicator, LayoutParams(dp(64f), dp(32f)))
665
666
 
666
- label.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
667
+ label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12f)
667
668
  label.typeface = Typeface.create(Typeface.DEFAULT, 500, false)
668
669
  label.gravity = Gravity.CENTER
669
670
  label.isSingleLine = true
@@ -111,8 +111,17 @@ private fun NativeNode.applyFont(changes: Map<String, Any?>) {
111
111
  changes["fontWeight"]?.let { weightName -> fontWeight = fontWeightOf(weightName) }
112
112
 
113
113
  val textView = view as? TextView ?: return
114
- textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize)
115
114
  textView.typeface = Typeface.create(Typeface.DEFAULT, fontWeight, false)
115
+ updateFontSize()
116
+ }
117
+
118
+ /**
119
+ * In sp: scaled to the system's text size, like the platform's own text. Android converts sp when it's
120
+ * set, so this runs again when that size changes.
121
+ */
122
+ fun NativeNode.updateFontSize() {
123
+ val textView = view as? TextView ?: return
124
+ textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize)
116
125
 
117
126
  markContentChanged()
118
127
  }
@@ -32,6 +32,35 @@ open class ContainerView(context: Context) : ViewGroup(context) {
32
32
  clipChildren = false
33
33
  }
34
34
 
35
+ /** Set while it reports @pan, @pinch or @rotate. */
36
+ var gestureReporter: GestureReporter? = null
37
+
38
+ /** A descendant took this touch (a scroll view scrolling, an inner gesture): its own gesture stands down. */
39
+ private var isTouchClaimedByChild = false
40
+
41
+ override fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
42
+ isTouchClaimedByChild = disallowIntercept
43
+ super.requestDisallowInterceptTouchEvent(disallowIntercept)
44
+ }
45
+
46
+ /**
47
+ * Children get each touch first, then the gesture sees it too, like iOS's gesture recognizers. Once
48
+ * the gesture is recognized, onInterceptTouchEvent takes the touch: the child gets a cancel (a
49
+ * <Pressable> doesn't fire @press).
50
+ */
51
+ override fun dispatchTouchEvent(event: MotionEvent): Boolean {
52
+ val reporter = gestureReporter ?: return super.dispatchTouchEvent(event)
53
+ if (event.actionMasked == MotionEvent.ACTION_DOWN) isTouchClaimedByChild = false
54
+
55
+ super.dispatchTouchEvent(event)
56
+ if (!isTouchClaimedByChild || reporter.isRecognizing) reporter.handle(event)
57
+
58
+ return true
59
+ }
60
+
61
+ override fun onInterceptTouchEvent(event: MotionEvent): Boolean =
62
+ gestureReporter?.isRecognizing == true || super.onInterceptTouchEvent(event)
63
+
35
64
  /** Without an exact size (inside a scroll view), the size set in its layout params. */
36
65
  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
37
66
  setMeasuredDimension(
@@ -81,6 +110,22 @@ class PressableView(context: Context) : ContainerView(context) {
81
110
  private val longPressHandler = Handler(Looper.getMainLooper())
82
111
  private var didLongPress = false
83
112
 
113
+ init {
114
+ isClickable = true // so TalkBack can activate it
115
+ }
116
+
117
+ /** TalkBack's double tap. Touches don't come through here: onTouchEvent reports them. */
118
+ override fun performClick(): Boolean {
119
+ super.performClick()
120
+ if (!isEnabled) return false
121
+
122
+ onEvent("pressin")
123
+ onEvent("pressout")
124
+ onEvent("press")
125
+
126
+ return true
127
+ }
128
+
84
129
  @SuppressLint("ClickableViewAccessibility")
85
130
  override fun onTouchEvent(event: MotionEvent): Boolean {
86
131
  // Consumed but ignored, as disabled Android buttons do: the touch doesn't reach a parent.
package/cli/nativue.mjs CHANGED
@@ -13,7 +13,7 @@ import net from 'node:net'
13
13
  import { execFileSync } from 'node:child_process'
14
14
  import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync } from 'node:fs'
15
15
  import { createRequire } from 'node:module'
16
- import { dirname } from 'node:path'
16
+ import { dirname, relative } from 'node:path'
17
17
  import { fileURLToPath } from 'node:url'
18
18
  import { linkIosPlugins } from './link.mjs'
19
19
  import { runOnAndroid, runOnIOS } from './run.mjs'
@@ -86,6 +86,30 @@ function finishBundle(mode) {
86
86
  }
87
87
  }
88
88
 
89
+ // A .vue file's <style> would become CSS that native views never read: warn instead of dropping it
90
+ // silently, once per file, and leave the CSS out of the build.
91
+ function ignoreStyleBlocks() {
92
+ const warnedFiles = new Set()
93
+
94
+ return {
95
+ name: 'nativue-ignore-style-blocks',
96
+ enforce: 'pre',
97
+ load(id) {
98
+ if (!id.includes('?vue&type=style')) return null
99
+
100
+ const file = relative(process.cwd(), id.split('?')[0])
101
+ if (!warnedFiles.has(file)) {
102
+ warnedFiles.add(file)
103
+ this.warn(
104
+ `${file}: <style> blocks aren't supported, native views don't read CSS. Use StyleSheet or @nativue/tailwind instead: https://github.com/nativue/nativue/blob/main/docs/styling.md`,
105
+ )
106
+ }
107
+
108
+ return ''
109
+ },
110
+ }
111
+ }
112
+
89
113
  const CONFIG_FILES = [
90
114
  'nativue.config.ts',
91
115
  'nativue.config.mts',
@@ -143,6 +167,7 @@ function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
143
167
  compilerOptions: { isCustomElement: (tag) => NATIVE_COMPONENT_TAGS.includes(tag) },
144
168
  },
145
169
  }),
170
+ ignoreStyleBlocks(),
146
171
  ...APP_VITE_PLUGINS,
147
172
  finishBundle(mode),
148
173
  ...plugins,
@@ -0,0 +1,68 @@
1
+ import UIKit
2
+
3
+ extension NativeNode {
4
+ private static let traitsByRole: [String: UIAccessibilityTraits] = [
5
+ "button": .button,
6
+ "link": .link,
7
+ "heading": .header,
8
+ "img": .image,
9
+ "text": .staticText,
10
+ "switch": .toggleButton,
11
+ "checkbox": .toggleButton,
12
+ ]
13
+
14
+ /// role, alt and aria-*, from the renderer: all of them, whenever one changes.
15
+ func applyAccessibility(_ attributes: [String: Any]) {
16
+ let role = attributes["role"] as? String
17
+ let label = attributes["label"] as? String
18
+ let isHidden = attributes["hidden"] != nil
19
+ let isElement = !isHidden && role != "none" && (role != nil || label != nil || defaultAccessibility.isElement)
20
+
21
+ view.accessibilityElementsHidden = isHidden
22
+ view.isAccessibilityElement = isElement
23
+ view.accessibilityLabel = label
24
+ view.accessibilityHint = attributes["hint"] as? String
25
+ view.accessibilityTraits = traits(role: role, attributes: attributes)
26
+ // A container read as one element says the text inside it, as a <button> does on the web.
27
+ view.accessibilityLabelBlock = isElement && label == nil && !defaultAccessibility.isElement
28
+ ? { [weak view] in view.map { Self.labels(inside: $0).joined(separator: ", ") } }
29
+ : nil
30
+
31
+ if role == "switch" || role == "checkbox" {
32
+ view.accessibilityValue = attributes["checked"] != nil ? "1" : "0"
33
+ }
34
+ }
35
+
36
+ private func traits(role: String?, attributes: [String: Any]) -> UIAccessibilityTraits {
37
+ var traits = defaultAccessibility.traits
38
+ if let role, let roleTraits = Self.traitsByRole[role] { traits.formUnion(roleTraits) }
39
+ if attributes["disabled"] != nil { traits.insert(.notEnabled) }
40
+ if attributes["selected"] != nil { traits.insert(.selected) }
41
+
42
+ return traits
43
+ }
44
+
45
+ private static func labels(inside view: UIView) -> [String] {
46
+ view.subviews.flatMap { subview -> [String] in
47
+ if subview.isHidden || subview.accessibilityElementsHidden { return [] }
48
+ if subview.isAccessibilityElement, let label = subview.accessibilityLabel, !label.isEmpty { return [label] }
49
+
50
+ return labels(inside: subview)
51
+ }
52
+ }
53
+ }
54
+
55
+ /// What a screen reader needs to know about the system, for AccessibilityInfo. Read on the main thread.
56
+ struct AccessibilityStatus {
57
+ var screenReaderEnabled = UIAccessibility.isVoiceOverRunning
58
+ var reduceMotionEnabled = UIAccessibility.isReduceMotionEnabled
59
+
60
+ static let changeNotifications = [
61
+ UIAccessibility.voiceOverStatusDidChangeNotification,
62
+ UIAccessibility.reduceMotionStatusDidChangeNotification,
63
+ ]
64
+
65
+ var dictionary: [String: Bool] {
66
+ ["screenReaderEnabled": screenReaderEnabled, "reduceMotionEnabled": reduceMotionEnabled]
67
+ }
68
+ }
package/ios/Bridge.swift CHANGED
@@ -34,6 +34,8 @@ final class Bridge {
34
34
  private var nextLayoutAnimation: LayoutAnimation?
35
35
  /// Appearance.getColorScheme(): read on the main thread at start, then kept up to date.
36
36
  private var colorScheme = "light"
37
+ /// Kept on the JS queue, for AccessibilityInfo.
38
+ private var accessibilityStatus = AccessibilityStatus()
37
39
 
38
40
  // Only touched on the main thread.
39
41
  var rootView: RootView!
@@ -46,7 +48,7 @@ final class Bridge {
46
48
  // here and are laid out on every pass; drop the detached ones on remove if navigators come and go.
47
49
  // Likewise a sheet a <ScreenStack> presented stays up when a v-if removes the stack (a reload closes it).
48
50
  private var contentRootsByNodeId: [Int: ContentRoot] = [:]
49
- /// Read on the main thread at start, for Dimensions.get('window').
51
+ /// For Dimensions.get('window'): the screen's at start, then the root view's, kept on the JS queue.
50
52
  private var windowSize: CGSize = .zero
51
53
  /// The bundle running now, for the error overlay's Reload.
52
54
  private var bundle = Data()
@@ -69,6 +71,18 @@ final class Bridge {
69
71
  [unowned self] (rootView: RootView, _: UITraitCollection) in
70
72
  colorSchemeDidChange(to: Self.colorScheme(of: rootView.traitCollection))
71
73
  }
74
+ _ = rootView.registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) {
75
+ [unowned self] (rootView: RootView, _: UITraitCollection) in
76
+ nodesById.values.forEach { $0.updateFont() }
77
+ rootView.setNeedsLayout()
78
+ }
79
+ }
80
+
81
+ for name in AccessibilityStatus.changeNotifications {
82
+ NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [unowned self] _ in
83
+ let nextStatus = AccessibilityStatus()
84
+ evaluate { [unowned self] in accessibilityStatus = nextStatus }
85
+ }
72
86
  }
73
87
 
74
88
  NotificationCenter.default.addObserver(forName: Self.openURLNotification, object: nil, queue: .main) {
@@ -131,6 +145,7 @@ final class Bridge {
131
145
 
132
146
  func layout() {
133
147
  nodesById[0]?.calculateLayout(width: rootView.bounds.width, height: rootView.bounds.height)
148
+ windowSizeDidChange(to: rootView.bounds.size)
134
149
 
135
150
  for contentRoot in contentRootsByNodeId.values {
136
151
  (contentRoot as? ModalController)?.dismissIfDetached()
@@ -161,6 +176,18 @@ final class Bridge {
161
176
  }
162
177
  }
163
178
 
179
+ /// Rotation and split view resize the root view.
180
+ private func windowSizeDidChange(to nextWindowSize: CGSize) {
181
+ guard nextWindowSize != .zero else { return }
182
+
183
+ evaluate { [unowned self] in
184
+ guard nextWindowSize != windowSize else { return }
185
+
186
+ windowSize = nextWindowSize
187
+ runtime?.call("__windowSizeChanged", arguments: [["width": windowSize.width, "height": windowSize.height]])
188
+ }
189
+ }
190
+
164
191
  /// Queued on the JS queue, so a URL that opens the app arrives after the bundle has run.
165
192
  private func openURL(_ url: URL) {
166
193
  evaluate { [unowned self] in
@@ -224,13 +251,19 @@ final class Bridge {
224
251
  reportError(message: string(arguments[0]), details: string(arguments[1]))
225
252
  }
226
253
 
227
- // Limitation: The size at launch; report rotation and split view changes if the app supports them.
228
254
  defineGetter("windowSize") { [unowned self] _ in
229
255
  ["width": windowSize.width, "height": windowSize.height]
230
256
  }
231
257
 
232
258
  defineGetter("platform") { _ in "ios" }
233
259
 
260
+ defineGetter("accessibilityInfo") { [unowned self] _ in accessibilityStatus.dictionary }
261
+
262
+ define("announce") { arguments in
263
+ let message = string(arguments[0])
264
+ DispatchQueue.main.async { UIAccessibility.post(notification: .announcement, argument: message) }
265
+ }
266
+
234
267
  // Prefixed, so a plugin can't replace nativue's own functions.
235
268
  for (name, function) in pluginRegistry.functions {
236
269
  defineGetter("plugin:\(name)", function)
@@ -397,7 +430,18 @@ final class Bridge {
397
430
  contentRootsByNodeId[id] as? ScreenController
398
431
  }
399
432
 
433
+ /// Text views start at the platform's size, scaled to the system's text size like styled ones.
400
434
  private func makeNode(type: String, id: Int) -> NativeNode {
435
+ let node = makeUnstyledNode(type: type, id: id)
436
+ if let button = node.view as? UIButton, let systemFont = button.titleLabel?.font {
437
+ node.fontSize = systemFont.pointSize
438
+ }
439
+ node.updateFont()
440
+
441
+ return node
442
+ }
443
+
444
+ private func makeUnstyledNode(type: String, id: Int) -> NativeNode {
401
445
  switch type {
402
446
  case "Text":
403
447
  let label = UILabel()
@@ -756,6 +800,9 @@ final class Bridge {
756
800
  case "disabled":
757
801
  (node.view as? UIControl)?.isEnabled = !isTruthyAttribute(value)
758
802
 
803
+ case "accessibility":
804
+ node.applyAccessibility(value as? [String: Any] ?? [:])
805
+
759
806
  case "animating":
760
807
  guard let indicator = node.view as? UIActivityIndicatorView else { break }
761
808
  if isTruthyAttribute(value) { indicator.startAnimating() } else { indicator.stopAnimating() }
@@ -17,6 +17,9 @@ final class NativeNode {
17
17
  /// Where children go when it isn't this node (a <Modal>'s children live in the presented controller).
18
18
  var contentNode: NativeNode?
19
19
 
20
+ /// The view's own, before role and aria-* change them: read the first time they're applied.
21
+ lazy var defaultAccessibility = (isElement: view.isAccessibilityElement, traits: view.accessibilityTraits)
22
+
20
23
  var fontSize: CGFloat = UIFont.labelFontSize
21
24
  var fontWeight: UIFont.Weight = .regular
22
25
 
@@ -54,6 +54,17 @@ final class PressableView: UIControl {
54
54
  .contains { $0 is UIControl || $0 is UIScrollView || !($0.gestureRecognizers ?? []).isEmpty }
55
55
  }
56
56
 
57
+ /// VoiceOver's double tap: a press, even when something interactive sits under the activation point.
58
+ override func accessibilityActivate() -> Bool {
59
+ guard isEnabled else { return false }
60
+
61
+ onEvent?("pressin")
62
+ onEvent?("pressout")
63
+ onEvent?("press")
64
+
65
+ return true
66
+ }
67
+
57
68
  @objc private func handleLongPress(_ recognizer: UILongPressGestureRecognizer) {
58
69
  guard recognizer.state == .began, isEnabled else { return }
59
70
 
package/ios/Style.swift CHANGED
@@ -96,9 +96,15 @@ extension NativeNode {
96
96
  fontWeight = fontWeights[String(describing: weightName)] ?? .regular
97
97
  }
98
98
 
99
- // Limitation: A fixed size on both platforms, ignoring the system's text size; scale it (UIFontMetrics,
100
- // sp on Android) when accessibility sizes matter.
101
- let font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
99
+ updateFont()
100
+ }
101
+
102
+ /// The node's font, scaled to the system's text size (Dynamic Type) like the platform's own text. Called
103
+ /// again when that size changes.
104
+ func updateFont() {
105
+ guard view is UILabel || view is UITextField || view is UIButton else { return }
106
+
107
+ let font = UIFontMetrics.default.scaledFont(for: UIFont.systemFont(ofSize: fontSize, weight: fontWeight))
102
108
  (view as? UILabel)?.font = font
103
109
  (view as? UITextField)?.font = font
104
110
  (view as? UIButton)?.titleLabel?.font = font
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Vue rendering real native views on iOS and Android",
5
5
  "keywords": [
6
6
  "vue",
@@ -0,0 +1,63 @@
1
+ // Screen readers (VoiceOver, TalkBack): what a view says it is, and what the system has turned on.
2
+
3
+ const native = globalThis.__native
4
+
5
+ // role, alt and aria-*, named as on the web. Native gets them together, by what they mean.
6
+ const NATIVE_NAME_BY_ATTRIBUTE: Record<string, string> = {
7
+ role: 'role',
8
+ alt: 'label',
9
+ 'aria-label': 'label',
10
+ 'aria-description': 'hint',
11
+ 'aria-hidden': 'hidden',
12
+ 'aria-disabled': 'disabled',
13
+ 'aria-selected': 'selected',
14
+ 'aria-checked': 'checked',
15
+ }
16
+ const STRING_ATTRIBUTES = new Set(['role', 'label', 'hint'])
17
+ const warnedAttributes = new Set<string>()
18
+
19
+ export type AccessibilityAttributes = Record<string, string | boolean>
20
+
21
+ export function isAccessibilityAttribute(key: string): boolean {
22
+ return key in NATIVE_NAME_BY_ATTRIBUTE || key.startsWith('aria-')
23
+ }
24
+
25
+ /** The attributes with this one changed, or undefined when it isn't one native reads. */
26
+ export function withAccessibilityAttribute(
27
+ attributes: AccessibilityAttributes = {},
28
+ key: string,
29
+ value: unknown,
30
+ ): AccessibilityAttributes | undefined {
31
+ const nativeName = NATIVE_NAME_BY_ATTRIBUTE[key]
32
+ if (!nativeName) return warnUnsupported(key)
33
+
34
+ const nextAttributes = { ...attributes }
35
+ if (value == null || value === false || value === 'false') delete nextAttributes[nativeName]
36
+ else nextAttributes[nativeName] = STRING_ATTRIBUTES.has(nativeName) ? String(value) : true
37
+
38
+ return nextAttributes
39
+ }
40
+
41
+ function warnUnsupported(key: string): undefined {
42
+ if (warnedAttributes.has(key)) return
43
+
44
+ warnedAttributes.add(key)
45
+ console.warn(`${key} isn't supported; see the accessibility docs for the attributes that are`)
46
+ }
47
+
48
+ // AccessibilityInfo.isScreenReaderEnabled() VoiceOver or TalkBack is on
49
+ // AccessibilityInfo.isReduceMotionEnabled() the user asked for less motion
50
+ // AccessibilityInfo.announce('Saved') spoken by the screen reader
51
+ export const AccessibilityInfo = {
52
+ isScreenReaderEnabled(): boolean {
53
+ return native.accessibilityInfo().screenReaderEnabled
54
+ },
55
+
56
+ isReduceMotionEnabled(): boolean {
57
+ return native.accessibilityInfo().reduceMotionEnabled
58
+ },
59
+
60
+ announce(message: string): void {
61
+ native.announce(message)
62
+ },
63
+ }
package/src/appearance.ts CHANGED
@@ -1,13 +1,15 @@
1
- // The platform the app runs on, and the system's light or dark appearance.
1
+ // The platform the app runs on, the system's light or dark appearance, and the window's size.
2
2
  import { readonly, shallowRef, type Ref } from '@vue/runtime-core'
3
3
 
4
4
  export type ColorScheme = 'light' | 'dark'
5
5
  export type PlatformOS = 'ios' | 'android'
6
+ export type WindowSize = { width: number; height: number }
6
7
  type ColorSchemeListener = (colorScheme: ColorScheme) => void
7
8
 
8
9
  const colorSchemeListeners = new Set<ColorSchemeListener>()
9
10
  let colorScheme: ColorScheme = __native.colorScheme()
10
11
  const colorSchemeRef = shallowRef(colorScheme)
12
+ const windowSizeRef = shallowRef<WindowSize>(__native.windowSize())
11
13
 
12
14
  // Platform.OS === 'ios'
13
15
  // Platform.select({ ios: 17, android: 16 })
@@ -47,3 +49,20 @@ globalThis.__colorSchemeChanged = (nextColorScheme) => {
47
49
  colorSchemeRef.value = nextColorScheme
48
50
  colorSchemeListeners.forEach((listener) => listener(nextColorScheme))
49
51
  }
52
+
53
+ // Dimensions.get('window') -> { width, height } in points, right now.
54
+ export const Dimensions = {
55
+ get(_dimension: 'window'): WindowSize {
56
+ return windowSizeRef.value
57
+ },
58
+ }
59
+
60
+ // const window = useWindowDimensions() { width, height }, follows rotation and split view
61
+ export function useWindowDimensions(): Readonly<Ref<WindowSize>> {
62
+ return readonly(windowSizeRef)
63
+ }
64
+
65
+ // Native calls it when the window is resized: rotation, split view.
66
+ globalThis.__windowSizeChanged = (windowSize) => {
67
+ windowSizeRef.value = windowSize
68
+ }
package/src/components.ts CHANGED
@@ -70,6 +70,8 @@ export const Pressable = defineComponent({
70
70
  return h(
71
71
  'PressableView',
72
72
  {
73
+ role: 'button',
74
+ 'aria-disabled': props.disabled || undefined,
73
75
  ...attrs,
74
76
  style,
75
77
  pressed: pressed.value,
package/src/globals.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // What the JavaScript engine has globally: the bridge, the hooks native calls into, and the web APIs
2
2
  // prelude.ts (timers, console) and fetch.ts provide. No DOM.
3
- import type { ColorScheme } from './appearance'
3
+ import type { ColorScheme, WindowSize } from './appearance'
4
4
  import type { NativeModule } from './types'
5
5
 
6
6
  declare global {
@@ -9,6 +9,7 @@ declare global {
9
9
  var __openURL: (url: string) => void
10
10
  var __fireTimer: (timerId: number) => void
11
11
  var __colorSchemeChanged: (colorScheme: ColorScheme) => void
12
+ var __windowSizeChanged: (windowSize: WindowSize) => void
12
13
  var __asyncFunctionFinished: (callId: number, value: unknown, errorMessage: string | null) => void
13
14
  var __animationFinished: (animationId: number, finished: boolean) => void
14
15
  var __fetchFinished: (
@@ -5,7 +5,22 @@ import type { AnimatedEvent } from './animated'
5
5
  import type { FlatList, Pressable, Swipeable } from './components'
6
6
  import type { PanEvent, PinchEvent, RotateEvent, ScrollEvent, Style } from './types'
7
7
 
8
- type NativeComponent<Props = {}> = DefineComponent<Props & { style?: Style }>
8
+ type NativeComponent<Props = {}> = DefineComponent<Props & { style?: Style } & AccessibilityProps>
9
+ type BooleanAttribute = boolean | 'true' | 'false'
10
+ // As on the web: what a screen reader says about the view. See docs/accessibility.md.
11
+ export interface AccessibilityProps {
12
+ role?: 'button' | 'link' | 'heading' | 'img' | 'text' | 'switch' | 'checkbox' | 'none'
13
+ /** What the screen reader says. Without one, a view with a role reads the text inside it. */
14
+ 'aria-label'?: string
15
+ /** Said after the label: what happens when it's activated. */
16
+ 'aria-description'?: string
17
+ /** Hides it, and everything inside it, from the screen reader. */
18
+ 'aria-hidden'?: BooleanAttribute
19
+ 'aria-disabled'?: BooleanAttribute
20
+ 'aria-selected'?: BooleanAttribute
21
+ /** For role="switch" and role="checkbox". */
22
+ 'aria-checked'?: BooleanAttribute
23
+ }
9
24
  type EventHandler<Payload> = ((payload: Payload) => void) | AnimatedEvent<Payload>
10
25
  // [tag, attributes], e.g. ['circle', { cx: 12, cy: 12, r: 10 }]: path, circle, ellipse, rect, line,
11
26
  // polyline and polygon. Stroked with `color`; filled too when `fill` isn't 'none'.
@@ -58,6 +73,8 @@ declare module '@vue/runtime-core' {
58
73
  >
59
74
  Image: NativeComponent<{
60
75
  source: string | { uri: string }
76
+ /** What the image shows, for screen readers. Leave it out for decorative images. */
77
+ alt?: string
61
78
  resizeMode?: 'cover' | 'contain' | 'stretch' | 'center'
62
79
  }>
63
80
  Switch: NativeComponent<
package/src/renderer.ts CHANGED
@@ -13,19 +13,28 @@ import {
13
13
  type ComponentPublicInstance,
14
14
  type Directive,
15
15
  } from '@vue/runtime-core'
16
+ import {
17
+ isAccessibilityAttribute,
18
+ withAccessibilityAttribute,
19
+ type AccessibilityAttributes,
20
+ } from './accessibility'
16
21
  import { animatedEventMapping, animatedStyleBinding, isAnimatedEvent } from './animated'
17
22
  import { Appearance } from './appearance'
18
23
  import { COLOR_PROPERTIES, processColor } from './colors'
19
24
  import { FlatList, Pressable, Swipeable } from './components'
20
25
  import type { LayoutAnimationConfig, Style } from './types'
21
26
  export * from '@vue/runtime-core'
27
+ export { AccessibilityInfo } from './accessibility'
22
28
  export { Animated } from './animated'
23
29
  export {
24
30
  Appearance,
31
+ Dimensions,
25
32
  Platform,
26
33
  useColorScheme,
34
+ useWindowDimensions,
27
35
  type ColorScheme,
28
36
  type PlatformOS,
37
+ type WindowSize,
29
38
  } from './appearance'
30
39
  export { requireNativeFunction } from './native-functions'
31
40
  export { AsyncStorage } from './storage'
@@ -47,6 +56,7 @@ interface Node {
47
56
  focused?: boolean
48
57
  disabled?: boolean
49
58
  classStyle?: Style
59
+ accessibility?: AccessibilityAttributes
50
60
  }
51
61
 
52
62
  type ElementState = Pick<Node, 'pressed' | 'focused' | 'disabled'>
@@ -87,6 +97,14 @@ function forgetSubtree(node: Node) {
87
97
  node.children.forEach(forgetSubtree)
88
98
  }
89
99
 
100
+ function updateAccessibility(element: Node, key: string, value: unknown) {
101
+ const accessibility = withAccessibilityAttribute(element.accessibility, key, value)
102
+ if (!accessibility) return
103
+
104
+ element.accessibility = accessibility
105
+ native.setProp(element.id, 'accessibility', accessibility)
106
+ }
107
+
90
108
  // As the native side reads boolean props: a bare attribute (`disabled`) is '', true.
91
109
  function isTruthyAttribute(value: unknown): boolean {
92
110
  return typeof value === 'string' ? value !== 'false' : value === true
@@ -317,6 +335,7 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
317
335
  if (key === 'style') updateStyle(element, { style: nextValue })
318
336
  else if (key === 'class') updateStyle(element, { className: nextValue ?? undefined })
319
337
  else if (key === 'pressed') updateStyle(element, { pressed: nextValue })
338
+ else if (isAccessibilityAttribute(key)) updateAccessibility(element, key, nextValue)
320
339
  else if (camelize(key) === 'focusedStyle') updateStyle(element, { focusedStyle: nextValue })
321
340
  else if (key === 'disabled') {
322
341
  updateStyle(element, { disabled: isTruthyAttribute(nextValue) })
@@ -380,13 +399,6 @@ export const StyleSheet = {
380
399
  },
381
400
  }
382
401
 
383
- // Dimensions.get('window') -> { width, height } in points.
384
- export const Dimensions = {
385
- get(_dimension: 'window'): { width: number; height: number } {
386
- return native.windowSize()
387
- },
388
- }
389
-
390
402
  export const Keyboard = {
391
403
  dismiss(): void {
392
404
  native.dismissKeyboard()
package/src/types.ts CHANGED
@@ -106,6 +106,8 @@ export interface NativeModule {
106
106
  windowSize(): { width: number; height: number }
107
107
  platform(): 'ios' | 'android'
108
108
  colorScheme(): 'light' | 'dark'
109
+ accessibilityInfo(): { screenReaderEnabled: boolean; reduceMotionEnabled: boolean }
110
+ announce(message: string): void
109
111
  create(id: number, type: string): void
110
112
  insert(parentId: number, childId: number, index: number): void
111
113
  remove(id: number): void