@nativue/core 0.4.2 → 0.4.4

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.
package/ios/Style.swift CHANGED
@@ -1,16 +1,15 @@
1
1
  import UIKit
2
2
  import yoga
3
3
 
4
- // Limitation: Removed layout properties arrive as null and keep their last value; reset them to Yoga's
5
- // defaults when it matters. Visual properties already fall back to UIKit's defaults on null.
6
4
  extension NativeNode {
7
- /// Receives only the properties that changed: the JS renderer diffs style objects before sending.
5
+ /// Receives only the properties that changed: the JS renderer diffs style objects before sending. A
6
+ /// removed property arrives as null and goes back to its default, as in CSS.
8
7
  func applyStyle(_ changes: [String: Any]) {
9
8
  for (property, value) in changes {
10
9
  if isDrivenByNativeView(property) { continue }
11
10
 
12
- if let applyLayoutProperty = layoutPropertySetters[property], !(value is NSNull) {
13
- applyLayoutProperty(yogaNode, value)
11
+ if let applyLayoutProperty = layoutPropertySetters[property] {
12
+ applyLayoutProperty(yogaNode, value is NSNull ? layoutDefaults[property] ?? undefinedLayoutValue : value)
14
13
  }
15
14
  // Some properties are both: overflow also clips the view.
16
15
  applyVisualProperty(property, value)
@@ -88,17 +87,23 @@ extension NativeNode {
88
87
 
89
88
  /// Font size and weight can change independently, so the node remembers both.
90
89
  private func applyFont(_ changes: [String: Any]) {
91
- if let size = number(changes["fontSize"] as Any) {
92
- fontSize = CGFloat(size)
90
+ if let size = changes["fontSize"] {
91
+ fontSize = number(size).map { CGFloat($0) } ?? defaultFontSize
93
92
  }
94
93
 
95
- if let weightName = changes["fontWeight"], !(weightName is NSNull) {
94
+ if let weightName = changes["fontWeight"] {
96
95
  fontWeight = fontWeights[String(describing: weightName)] ?? .regular
97
96
  }
98
97
 
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)
98
+ updateFont()
99
+ }
100
+
101
+ /// The node's font, scaled to the system's text size (Dynamic Type) like the platform's own text. Called
102
+ /// again when that size changes.
103
+ func updateFont() {
104
+ guard view is UILabel || view is UITextField || view is UIButton else { return }
105
+
106
+ let font = UIFontMetrics.default.scaledFont(for: UIFont.systemFont(ofSize: fontSize, weight: fontWeight))
102
107
  (view as? UILabel)?.font = font
103
108
  (view as? UITextField)?.font = font
104
109
  (view as? UIButton)?.titleLabel?.font = font
@@ -111,6 +116,23 @@ extension NativeNode {
111
116
 
112
117
  private typealias LayoutPropertySetter = (YGNodeRef, Any) -> Void
113
118
 
119
+ /// What a removed property goes back to: Yoga's defaults. The others are undefined (unset).
120
+ private let layoutDefaults: [String: Any] = [
121
+ "flexDirection": "column",
122
+ "justifyContent": "flex-start",
123
+ "alignItems": "stretch",
124
+ "alignSelf": "auto",
125
+ "alignContent": "flex-start",
126
+ "flexWrap": "nowrap",
127
+ "position": "relative",
128
+ "display": "flex",
129
+ "overflow": "visible",
130
+ "flexBasis": "auto",
131
+ "width": "auto",
132
+ "height": "auto",
133
+ ]
134
+ private let undefinedLayoutValue = NSNumber(value: Float.nan)
135
+
114
136
  private let layoutPropertySetters: [String: LayoutPropertySetter] = {
115
137
  var setters: [String: LayoutPropertySetter] = [
116
138
  "flexDirection": enumSetter(flexDirections, YGNodeStyleSetFlexDirection),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
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
@@ -4,13 +4,15 @@ import {
4
4
  defineComponent,
5
5
  h,
6
6
  onBeforeUnmount,
7
+ reactive,
7
8
  ref,
8
9
  watch,
9
10
  type PropType,
10
11
  type SlotsType,
11
12
  type VNode,
12
13
  } from '@vue/runtime-core'
13
- import type { ScrollEvent, Style } from './types'
14
+ import { rowAt, rowOffsets } from './list-window'
15
+ import type { LayoutEvent, ScrollEvent, Style } from './types'
14
16
 
15
17
  type Listener = ((payload: unknown) => void) | undefined
16
18
 
@@ -70,6 +72,8 @@ export const Pressable = defineComponent({
70
72
  return h(
71
73
  'PressableView',
72
74
  {
75
+ role: 'button',
76
+ 'aria-disabled': props.disabled || undefined,
73
77
  ...attrs,
74
78
  style,
75
79
  pressed: pressed.value,
@@ -84,12 +88,15 @@ export const Pressable = defineComponent({
84
88
  })
85
89
 
86
90
  const OFFSCREEN_ROWS_RENDERED = 10
91
+ // What a row not yet measured counts as, until some are: then their average.
92
+ const ESTIMATED_ROW_HEIGHT = 50
87
93
 
88
94
  // Renders only the rows near the visible area; the rest is empty padding of the same height.
89
- // Slots: #item="{ item, index }", plus #header, #footer and #empty.
90
- // Limitation: Rows have a fixed `itemHeight`; measure rows natively if
91
- // variable heights are ever needed. Vertical only. The window ignores the header's height, which the
92
- // offscreen rows absorb while the header is shorter than them; measure it if tall headers show gaps.
95
+ // Slots: #item="{ item, index }", plus #header, #footer and #empty. With `item-height`, every row is that
96
+ // tall; without it, rows size to their content and are measured as they render. Vertical only.
97
+ // Limitation: Rows not rendered yet count as the average measured height, so jumping far (dragging the
98
+ // scroll indicator) can shift the rows a few points once they're measured; anchor the scroll position
99
+ // to the first visible row if that shows.
93
100
  // Limitation: Items are `any` in the #item slot; make FlatList generic if typed rows are wanted.
94
101
  // Limitation: An Animated.event `:on-scroll` replaces the window's own scroll handler, and a mapped event
95
102
  // reaches JS only when a scroll starts and ends; report frames to both natively if that's needed.
@@ -97,7 +104,7 @@ export const FlatList = defineComponent({
97
104
  name: 'FlatList',
98
105
  props: {
99
106
  data: { type: Array as PropType<any[]>, required: true },
100
- itemHeight: { type: Number, required: true },
107
+ itemHeight: Number,
101
108
  keyExtractor: {
102
109
  type: Function as PropType<(item: any, index: number) => string | number>,
103
110
  default: (_item: unknown, index: number) => index,
@@ -112,51 +119,74 @@ export const FlatList = defineComponent({
112
119
  }>,
113
120
 
114
121
  setup(props, { slots }) {
115
- // Whole rows, so scrolling within a row doesn't re-render (refs ignore same-value writes).
116
- const firstVisibleRow = ref(0)
117
- const visibleRowCount = ref(0)
118
-
119
- const visibleRange = computed(() => {
120
- const start = Math.max(0, firstVisibleRow.value - OFFSCREEN_ROWS_RENDERED)
121
- const end = Math.min(
122
- props.data.length,
123
- firstVisibleRow.value + visibleRowCount.value + OFFSCREEN_ROWS_RENDERED,
122
+ const scrollTop = ref(0)
123
+ const viewportHeight = ref(0)
124
+ const headerHeight = ref(0)
125
+ const measuredHeights = reactive(new Map<string | number, number>())
126
+
127
+ const offsets = computed(() => {
128
+ const estimatedHeight = averageOf(measuredHeights.values()) ?? ESTIMATED_ROW_HEIGHT
129
+ const heights = props.data.map(
130
+ (item, index) =>
131
+ props.itemHeight ??
132
+ measuredHeights.get(props.keyExtractor(item, index)) ??
133
+ estimatedHeight,
124
134
  )
125
135
 
126
- return { start, end }
136
+ return rowOffsets(heights)
137
+ })
138
+
139
+ // Numbers, so scrolling within the same rows doesn't re-render.
140
+ const start = computed(() =>
141
+ Math.max(0, rowAt(offsets.value, scrollTop.value) - OFFSCREEN_ROWS_RENDERED),
142
+ )
143
+ const end = computed(() => {
144
+ const lastVisibleRow = rowAt(offsets.value, scrollTop.value + viewportHeight.value)
145
+
146
+ return Math.min(props.data.length, lastVisibleRow + 1 + OFFSCREEN_ROWS_RENDERED)
127
147
  })
128
148
 
129
149
  // Bouncing past either edge reports offsets outside the list: clamp them, or the window (and the
130
150
  // layout) would change on every frame of the bounce.
131
151
  function handleScroll({ y, height }: ScrollEvent) {
132
- const maxScrollTop = Math.max(0, props.data.length * props.itemHeight - height)
133
- const scrollTop = Math.min(Math.max(y, 0), maxScrollTop)
152
+ const maxScrollTop = Math.max(0, offsets.value[props.data.length] - height)
134
153
 
135
- firstVisibleRow.value = Math.floor(scrollTop / props.itemHeight)
136
- visibleRowCount.value = Math.ceil(height / props.itemHeight)
154
+ scrollTop.value = Math.min(Math.max(y - headerHeight.value, 0), maxScrollTop)
155
+ viewportHeight.value = height
137
156
  }
138
157
 
139
158
  function renderRow(item: unknown, offset: number): VNode {
140
- const index = visibleRange.value.start + offset
159
+ const index = start.value + offset
160
+ const key = props.keyExtractor(item, index)
161
+ const sizing = props.itemHeight
162
+ ? { style: { height: props.itemHeight } }
163
+ : { onLayout: ({ height }: LayoutEvent) => measuredHeights.set(key, height) }
141
164
 
142
- return h(
143
- 'View',
144
- { key: props.keyExtractor(item, index), style: { height: props.itemHeight } },
145
- slots.item?.({ item, index }),
146
- )
165
+ return h('View', { key, ...sizing }, slots.item?.({ item, index }))
166
+ }
167
+
168
+ function renderHeader(): VNode | null {
169
+ if (!slots.header) return null
170
+
171
+ const onLayout = ({ height }: LayoutEvent) => (headerHeight.value = height)
172
+
173
+ return h('View', { onLayout }, slots.header({}))
147
174
  }
148
175
 
149
176
  return () => {
150
- const { start, end } = visibleRange.value
177
+ const total = offsets.value[props.data.length]
178
+ // overflow: 'scroll' tells Yoga the rows may reach past the window's box: otherwise it caps a row
179
+ // that sizes to its content at the space the paddings leave, which is none.
151
180
  const window = {
152
- paddingTop: start * props.itemHeight,
153
- paddingBottom: (props.data.length - end) * props.itemHeight,
181
+ paddingTop: offsets.value[start.value],
182
+ paddingBottom: total - offsets.value[end.value],
183
+ overflow: 'scroll' as const,
154
184
  }
155
185
 
156
186
  // Other attributes (refreshing, @refresh...) fall through to the ScrollView.
157
187
  return h('ScrollView', { style: props.style, onScroll: handleScroll }, [
158
- slots.header?.({}),
159
- h('View', { style: window }, props.data.slice(start, end).map(renderRow)),
188
+ renderHeader(),
189
+ h('View', { style: window }, props.data.slice(start.value, end.value).map(renderRow)),
160
190
  props.data.length === 0 ? slots.empty?.({}) : null,
161
191
  slots.footer?.({}),
162
192
  ])
@@ -164,6 +194,17 @@ export const FlatList = defineComponent({
164
194
  },
165
195
  })
166
196
 
197
+ function averageOf(values: Iterable<number>): number | undefined {
198
+ let sum = 0
199
+ let count = 0
200
+ for (const value of values) {
201
+ sum += value
202
+ count++
203
+ }
204
+
205
+ return count === 0 ? undefined : sum / count
206
+ }
207
+
167
208
  const SWIPE_ACTIONS_STYLE: Style = { position: 'absolute', top: 0, bottom: 0, flexDirection: 'row' }
168
209
  const SWIPE_LEFT_ACTIONS_STYLE: Style = { ...SWIPE_ACTIONS_STYLE, left: 0 }
169
210
  const SWIPE_RIGHT_ACTIONS_STYLE: Style = { ...SWIPE_ACTIONS_STYLE, right: 0 }
package/src/globals.ts CHANGED
@@ -1,14 +1,16 @@
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'
4
- import type { NativeModule } from './types'
3
+ import type { ColorScheme, WindowSize } from './appearance'
4
+ import type { LayoutEvent, NativeModule } from './types'
5
5
 
6
6
  declare global {
7
7
  var __native: NativeModule
8
8
  var __dispatch: (nodeId: number, eventName: string, payload: unknown) => void
9
+ var __layoutsChanged: (layouts: ({ id: number } & LayoutEvent)[]) => void
9
10
  var __openURL: (url: string) => void
10
11
  var __fireTimer: (timerId: number) => void
11
12
  var __colorSchemeChanged: (colorScheme: ColorScheme) => void
13
+ var __windowSizeChanged: (windowSize: WindowSize) => void
12
14
  var __asyncFunctionFinished: (callId: number, value: unknown, errorMessage: string | null) => void
13
15
  var __animationFinished: (animationId: number, finished: boolean) => void
14
16
  var __fetchFinished: (
@@ -0,0 +1,23 @@
1
+ // FlatList's windowing math: where each row starts, and which rows a scroll position shows.
2
+
3
+ /** Where each row starts, plus where the last one ends: `heights.length + 1` offsets. */
4
+ export function rowOffsets(heights: number[]): number[] {
5
+ const offsets = [0]
6
+ for (const height of heights) offsets.push(offsets[offsets.length - 1] + height)
7
+
8
+ return offsets
9
+ }
10
+
11
+ /** The row at `position`, clamped to the rows there are: a bounce past either end stays on them. */
12
+ export function rowAt(offsets: number[], position: number): number {
13
+ let low = 0
14
+ let high = offsets.length - 2
15
+
16
+ while (low < high) {
17
+ const middle = Math.ceil((low + high) / 2)
18
+ if (offsets[middle] <= position) low = middle
19
+ else high = middle - 1
20
+ }
21
+
22
+ return Math.max(low, 0)
23
+ }
@@ -3,9 +3,26 @@
3
3
  import type { DefineComponent } from '@vue/runtime-core'
4
4
  import type { AnimatedEvent } from './animated'
5
5
  import type { FlatList, Pressable, Swipeable } from './components'
6
- import type { PanEvent, PinchEvent, RotateEvent, ScrollEvent, Style } from './types'
6
+ import type { LayoutEvent, PanEvent, PinchEvent, RotateEvent, ScrollEvent, Style } from './types'
7
7
 
8
- type NativeComponent<Props = {}> = DefineComponent<Props & { style?: Style }>
8
+ type NativeComponent<Props = {}> = DefineComponent<
9
+ Props & { style?: Style; onLayout?: (event: LayoutEvent) => void } & AccessibilityProps
10
+ >
11
+ type BooleanAttribute = boolean | 'true' | 'false'
12
+ // As on the web: what a screen reader says about the view. See docs/accessibility.md.
13
+ export interface AccessibilityProps {
14
+ role?: 'button' | 'link' | 'heading' | 'img' | 'text' | 'switch' | 'checkbox' | 'none'
15
+ /** What the screen reader says. Without one, a view with a role reads the text inside it. */
16
+ 'aria-label'?: string
17
+ /** Said after the label: what happens when it's activated. */
18
+ 'aria-description'?: string
19
+ /** Hides it, and everything inside it, from the screen reader. */
20
+ 'aria-hidden'?: BooleanAttribute
21
+ 'aria-disabled'?: BooleanAttribute
22
+ 'aria-selected'?: BooleanAttribute
23
+ /** For role="switch" and role="checkbox". */
24
+ 'aria-checked'?: BooleanAttribute
25
+ }
9
26
  type EventHandler<Payload> = ((payload: Payload) => void) | AnimatedEvent<Payload>
10
27
  // [tag, attributes], e.g. ['circle', { cx: 12, cy: 12, r: 10 }]: path, circle, ellipse, rect, line,
11
28
  // polyline and polygon. Stroked with `color`; filled too when `fill` isn't 'none'.
@@ -58,6 +75,8 @@ declare module '@vue/runtime-core' {
58
75
  >
59
76
  Image: NativeComponent<{
60
77
  source: string | { uri: string }
78
+ /** What the image shows, for screen readers. Leave it out for decorative images. */
79
+ alt?: string
61
80
  resizeMode?: 'cover' | 'contain' | 'stretch' | 'center'
62
81
  }>
63
82
  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,8 +56,14 @@ interface Node {
47
56
  focused?: boolean
48
57
  disabled?: boolean
49
58
  classStyle?: Style
59
+ accessibility?: AccessibilityAttributes
60
+ /** <TextInput v-model.trim>: its modifiers, and the text typed last. */
61
+ modelModifiers?: ModelModifiers
62
+ typedText?: string
50
63
  }
51
64
 
65
+ type ModelModifiers = { trim?: boolean; number?: boolean; lazy?: boolean }
66
+
52
67
  type ElementState = Pick<Node, 'pressed' | 'focused' | 'disabled'>
53
68
 
54
69
  type EventHandler = (payload: unknown) => void
@@ -74,6 +89,13 @@ function createNode(type: string): Node {
74
89
  return { id: nextNodeId++, type, parent: null, children: [], text: '' }
75
90
  }
76
91
 
92
+ // What native forgets with a removed subtree: Vue removes only its root.
93
+ function nativeIdsIn(node: Node): number[] {
94
+ const ownId = isNativeNode(node) ? [node.id] : []
95
+
96
+ return [...ownId, ...node.children.flatMap(nativeIdsIn)]
97
+ }
98
+
77
99
  // '#text' and '#comment' nodes only exist in JS (Vue anchors / raw text); native never sees them.
78
100
  function isNativeNode(node: Node): boolean {
79
101
  return !node.type.startsWith('#')
@@ -87,6 +109,14 @@ function forgetSubtree(node: Node) {
87
109
  node.children.forEach(forgetSubtree)
88
110
  }
89
111
 
112
+ function updateAccessibility(element: Node, key: string, value: unknown) {
113
+ const accessibility = withAccessibilityAttribute(element.accessibility, key, value)
114
+ if (!accessibility) return
115
+
116
+ element.accessibility = accessibility
117
+ native.setProp(element.id, 'accessibility', accessibility)
118
+ }
119
+
90
120
  // As the native side reads boolean props: a bare attribute (`disabled`) is '', true.
91
121
  function isTruthyAttribute(value: unknown): boolean {
92
122
  return typeof value === 'string' ? value !== 'false' : value === true
@@ -299,7 +329,7 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
299
329
  const parent = detachFromParent(child)
300
330
  forgetSubtree(child)
301
331
 
302
- if (isNativeNode(child)) native.remove(child.id)
332
+ if (isNativeNode(child)) native.remove(child.id, nativeIdsIn(child))
303
333
  else syncTextContent(parent)
304
334
  },
305
335
 
@@ -317,6 +347,7 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
317
347
  if (key === 'style') updateStyle(element, { style: nextValue })
318
348
  else if (key === 'class') updateStyle(element, { className: nextValue ?? undefined })
319
349
  else if (key === 'pressed') updateStyle(element, { pressed: nextValue })
350
+ else if (isAccessibilityAttribute(key)) updateAccessibility(element, key, nextValue)
320
351
  else if (camelize(key) === 'focusedStyle') updateStyle(element, { focusedStyle: nextValue })
321
352
  else if (key === 'disabled') {
322
353
  updateStyle(element, { disabled: isTruthyAttribute(nextValue) })
@@ -343,7 +374,41 @@ globalThis.__dispatch = (nodeId, eventName, payload) => {
343
374
  if (!handlers) return
344
375
 
345
376
  handlers[eventName]?.(payload)
346
- handlers[MODEL_EVENT_BY_NATIVE_EVENT[eventName]]?.(payload)
377
+ updateModel(nodeId, eventName, payload, handlers['update:modelvalue'])
378
+ }
379
+
380
+ // One call per layout pass: the handlers' changes then render together, once.
381
+ globalThis.__layoutsChanged = (layouts) => {
382
+ for (const { id, ...layout } of layouts) globalThis.__dispatch(id, 'layout', layout)
383
+ }
384
+
385
+ // v-model's modifiers, as on the web: .lazy updates when editing ends rather than on every keystroke;
386
+ // .trim and .number change the value the model gets.
387
+ function updateModel(nodeId: number, eventName: string, payload: unknown, update?: EventHandler) {
388
+ const textInput = textInputsById.get(nodeId)
389
+ if (textInput && eventName === 'changetext') textInput.typedText = payload as string
390
+ if (!update) return
391
+
392
+ const modifiers = textInput?.modelModifiers ?? {}
393
+ if (!modifiers.lazy) {
394
+ if (MODEL_EVENT_BY_NATIVE_EVENT[eventName]) update(modelValue(modifiers, payload))
395
+ return
396
+ }
397
+
398
+ const editingEnded = eventName === 'blur' || eventName === 'submitediting'
399
+ const typedText = textInput?.typedText
400
+ if (editingEnded && typedText !== undefined) update(modelValue(modifiers, typedText))
401
+ }
402
+
403
+ function modelValue(modifiers: ModelModifiers, value: unknown): unknown {
404
+ if (typeof value !== 'string') return value
405
+
406
+ const text = modifiers.trim ? value.trim() : value
407
+ if (!modifiers.number) return text
408
+
409
+ const number = parseFloat(text)
410
+
411
+ return Number.isNaN(number) ? text : number
347
412
  }
348
413
 
349
414
  // A <TextInput>'s focus, for its class's focus: styles and its focused-style.
@@ -380,13 +445,6 @@ export const StyleSheet = {
380
445
  },
381
446
  }
382
447
 
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
448
  export const Keyboard = {
391
449
  dismiss(): void {
392
450
  native.dismissKeyboard()
@@ -395,17 +453,30 @@ export const Keyboard = {
395
453
 
396
454
  // Replaces Vue's DOM-only vModelText, which the template compiler emits for v-model on
397
455
  // <TextInput> and <Switch>.
398
- // Limitation: v-model modifiers (.trim, .number, .lazy) are not supported yet.
399
456
  export const vModelText: Directive<Node> = {
400
- created(element, { value }) {
401
- native.setProp(element.id, 'value', value ?? '')
457
+ created(element, { value, modifiers }) {
458
+ element.modelModifiers = modifiers
459
+ native.setProp(element.id, 'value', nativeModelValue(value))
402
460
  },
403
461
 
404
- beforeUpdate(element, { value, oldValue }) {
405
- if (value !== oldValue) native.setProp(element.id, 'value', value ?? '')
462
+ beforeUpdate(element, { value, oldValue, modifiers }) {
463
+ if (value === oldValue || showsModelValue(element, value, modifiers)) return
464
+
465
+ native.setProp(element.id, 'value', nativeModelValue(value))
406
466
  },
407
467
  }
408
468
 
469
+ // The field keeps what was typed when it already gives the model's value: with .trim, "hello " stays
470
+ // as typed instead of losing its space mid-word.
471
+ function showsModelValue(element: Node, value: unknown, modifiers: ModelModifiers): boolean {
472
+ return element.typedText !== undefined && modelValue(modifiers, element.typedText) === value
473
+ }
474
+
475
+ // A <TextInput> shows text, so a v-model.number's number goes as text; a <Switch> takes its boolean.
476
+ function nativeModelValue(value: unknown): unknown {
477
+ return typeof value === 'number' ? String(value) : (value ?? '')
478
+ }
479
+
409
480
  const rootNode: Node = { id: 0, type: 'root', parent: null, children: [], text: '' }
410
481
 
411
482
  // Errors in templates, setup, hooks and handlers: shown natively, with where they happened (in
package/src/types.ts CHANGED
@@ -66,6 +66,14 @@ export type Style = {
66
66
 
67
67
  export type GestureState = 'began' | 'changed' | 'ended' | 'cancelled' | 'failed'
68
68
 
69
+ // @layout: the view's box in its parent, in points.
70
+ export interface LayoutEvent {
71
+ x: number
72
+ y: number
73
+ width: number
74
+ height: number
75
+ }
76
+
69
77
  export interface ScrollEvent {
70
78
  x: number
71
79
  y: number
@@ -106,9 +114,12 @@ export interface NativeModule {
106
114
  windowSize(): { width: number; height: number }
107
115
  platform(): 'ios' | 'android'
108
116
  colorScheme(): 'light' | 'dark'
117
+ accessibilityInfo(): { screenReaderEnabled: boolean; reduceMotionEnabled: boolean }
118
+ announce(message: string): void
109
119
  create(id: number, type: string): void
110
120
  insert(parentId: number, childId: number, index: number): void
111
- remove(id: number): void
121
+ /** Detaches the view `id`; `subtreeIds` (it and every native descendant) are forgotten. */
122
+ remove(id: number, subtreeIds: number[]): void
112
123
  setProp(id: number, key: string, value: unknown): void
113
124
  setText(id: number, text: string): void
114
125
  setTimer(timerId: number, delay: number): void