@nativue/core 0.15.3 → 0.16.0

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/src/renderer.ts CHANGED
@@ -25,6 +25,8 @@ import { FlatListComponent, ImageBackground, Pressable, Swipeable } from './comp
25
25
  import type { LayoutAnimationConfig, Style } from './types'
26
26
  export * from '@vue/runtime-core'
27
27
  export { AccessibilityInfo } from './accessibility'
28
+ export type { AccessibilityProps } from './native-components'
29
+ export { processColor } from './colors'
28
30
  export { Animated } from './animated'
29
31
  export {
30
32
  Appearance,
@@ -43,7 +45,6 @@ export { openSettings, usePermission } from './permissions'
43
45
  export type { PermissionResponse, PermissionResponseWith } from './permissions'
44
46
  export { AsyncStorage } from './storage'
45
47
  export type * from './types'
46
- export type { SvgElement, SvgIcon } from './native-components'
47
48
 
48
49
  interface Node {
49
50
  id: number
@@ -64,6 +65,44 @@ interface Node {
64
65
  /** <TextInput v-model.trim>: its modifiers, and the text typed last. */
65
66
  modelModifiers?: ModelModifiers
66
67
  typedText?: string
68
+ /** A drawn view's style from its own props (<svg width height>): under its class and style. */
69
+ baseStyle?: Style
70
+ }
71
+
72
+ /** An element inside a drawn view, or the view itself, as its package sees it. */
73
+ export interface DrawnElement {
74
+ readonly id: number
75
+ readonly type: string
76
+ readonly parent: DrawnElement | null
77
+ readonly children: DrawnElement[]
78
+ readonly text: string
79
+ }
80
+
81
+ /**
82
+ * A native view that draws what's inside it, like @nativue/svg's <svg>: its elements stay in JS and
83
+ * never become views. After each batch of changes, the view gets them as one prop, `drawing`.
84
+ */
85
+ export interface DrawnView {
86
+ /** The native view's type, e.g. 'Svg', which a package's plugin registers natively. */
87
+ type: string
88
+ /** The tags that create it in a template, e.g. ['svg']. */
89
+ tags: string[]
90
+ /** The tags of the elements drawn inside it, e.g. 'path'. */
91
+ partTags: string[]
92
+ /** A part's prop (an @event's handler excepted, which nativue keeps). */
93
+ setPartProp(element: DrawnElement, key: string, value: unknown): void
94
+ /**
95
+ * The view's own prop: true when only the drawing reads it, false when it also goes to the native view.
96
+ * `setBaseStyle` styles the view under its class and style.
97
+ */
98
+ setViewProp(
99
+ element: DrawnElement,
100
+ key: string,
101
+ value: unknown,
102
+ setBaseStyle: (style: Style) => void,
103
+ ): boolean
104
+ /** The view's `drawing`, once per batch of changes; undefined leaves it as it is. */
105
+ drawing(view: DrawnElement, isPressable: (element: DrawnElement) => boolean): unknown
67
106
  }
68
107
 
69
108
  type ModelModifiers = { trim?: boolean; number?: boolean; lazy?: boolean }
@@ -90,6 +129,19 @@ export function setClassStyleResolver(resolver: ClassStyleResolver): void {
90
129
  nodesWithClass.forEach((node) => updateStyle(node, {}))
91
130
  }
92
131
 
132
+ const warnedTags = new Set<string>()
133
+
134
+ // Native components are capitalized: a lowercase tag is HTML (<div>), or a drawn view's (<svg>) whose
135
+ // package isn't installed. Either way it would show nothing.
136
+ function warnIfUnknown(tag: string) {
137
+ if (!/^[a-z]/.test(tag) || drawnViewsByTag.has(tag) || warnedTags.has(tag)) return
138
+
139
+ warnedTags.add(tag)
140
+ console.warn(
141
+ `<${tag}> isn't a nativue element, so it shows nothing: use nativue's components (<View>, <Text>...), or install the package that provides <${tag}>.`,
142
+ )
143
+ }
144
+
93
145
  function createNode(type: string): Node {
94
146
  return { id: nextNodeId++, type, parent: null, children: [], text: '' }
95
147
  }
@@ -101,9 +153,76 @@ function nativeIdsIn(node: Node): number[] {
101
153
  return [...ownId, ...node.children.flatMap(nativeIdsIn)]
102
154
  }
103
155
 
104
- // '#text' and '#comment' nodes only exist in JS (Vue anchors / raw text); native never sees them.
156
+ // '#text' and '#comment' nodes only exist in JS (Vue anchors / raw text), and so do a drawn view's
157
+ // elements, which the view draws: native never sees them.
105
158
  function isNativeNode(node: Node): boolean {
106
- return !node.type.startsWith('#')
159
+ return !node.type.startsWith('#') && !drawnViewsByPartTag.has(node.type)
160
+ }
161
+
162
+ const drawnViewsByTag = new Map<string, DrawnView>()
163
+ const drawnViewsByPartTag = new Map<string, DrawnView>()
164
+ const drawnViewsByType = new Map<string, DrawnView>()
165
+ const drawnViewsToRedraw = new Set<Node>()
166
+
167
+ /** For a package's runtime module, before the app starts: see DrawnView. */
168
+ export function registerDrawnView(view: DrawnView): void {
169
+ for (const tag of [...view.tags, view.type]) drawnViewsByTag.set(tag, view)
170
+ for (const tag of view.partTags) drawnViewsByPartTag.set(tag, view)
171
+ drawnViewsByType.set(view.type, view)
172
+ }
173
+
174
+ function drawnViewOf(node: Node | null): Node | null {
175
+ let current = node
176
+
177
+ while (current && !drawnViewsByType.has(current.type)) current = current.parent
178
+
179
+ return current
180
+ }
181
+
182
+ /** Every change inside a drawn view in one batch: the drawing is sent once, after them. */
183
+ function redraw(node: Node | null) {
184
+ const view = drawnViewOf(node)
185
+ if (!view) return
186
+
187
+ if (drawnViewsToRedraw.size === 0) Promise.resolve().then(sendDrawings)
188
+ drawnViewsToRedraw.add(view)
189
+ }
190
+
191
+ function sendDrawings() {
192
+ const isPressable = (element: DrawnElement) => Boolean(eventHandlersByNodeId[element.id]?.press)
193
+ // Copied first: a drawing that fails doesn't keep the others from being sent next time.
194
+ const views = [...drawnViewsToRedraw]
195
+
196
+ drawnViewsToRedraw.clear()
197
+ for (const view of views) {
198
+ const drawing = drawnViewsByType.get(view.type)?.drawing(view, isPressable)
199
+
200
+ if (drawing !== undefined) native.setProp(view.id, 'drawing', drawing)
201
+ }
202
+ }
203
+
204
+ /** A drawn view's own props: false for those that go on as for any view. */
205
+ function patchDrawnViewProp(element: Node, key: string, value: unknown): boolean {
206
+ const name = camelize(key)
207
+
208
+ if (isEventProp(name)) redraw(element)
209
+ if (key === 'style' || key === 'class' || isEventProp(name) || isAccessibilityAttribute(key)) {
210
+ return false
211
+ }
212
+
213
+ const setBaseStyle = (style: Style) => {
214
+ const previousStyle = combinedStyle(element)
215
+
216
+ element.baseStyle = style
217
+ patchStyle(element, previousStyle, combinedStyle(element))
218
+ }
219
+ const isDrawingOnly = drawnViewsByType
220
+ .get(element.type)!
221
+ .setViewProp(element, key, value, setBaseStyle)
222
+
223
+ redraw(element)
224
+
225
+ return isDrawingOnly
107
226
  }
108
227
 
109
228
  // Vue removes only the root of an unmounted subtree: its descendants go with it.
@@ -198,9 +317,9 @@ function withoutAnimatedProperties(
198
317
  // The class's styles come first, so the style prop overrides them, as inline styles do on the web.
199
318
  function combinedStyle(element: Node): Style | null {
200
319
  const focusedStyle = element.focused ? element.focusedStyle : null
201
- if (!element.classStyle && !focusedStyle) return element.style ?? null
320
+ if (!element.classStyle && !focusedStyle && !element.baseStyle) return element.style ?? null
202
321
 
203
- return { ...element.classStyle, ...element.style, ...focusedStyle }
322
+ return { ...element.baseStyle, ...element.classStyle, ...element.style, ...focusedStyle }
204
323
  }
205
324
 
206
325
  function classStyleOf(element: Node): Style | undefined {
@@ -264,6 +383,23 @@ function reportsToJavaScript(eventName: string, handler: unknown): boolean {
264
383
  return eventName !== 'scroll' || handler.listener != null
265
384
  }
266
385
 
386
+ /** Inside a drawn view there's no native view to tell: the drawing says which elements take presses. */
387
+ function patchDrawnEventHandler(
388
+ element: Node,
389
+ key: string,
390
+ handler: unknown,
391
+ component: ComponentInternalInstance | null,
392
+ ) {
393
+ const listener = handler as Function | undefined
394
+
395
+ eventHandlersByNodeId[element.id] ??= {}
396
+ eventHandlersByNodeId[element.id][key.slice(2).toLowerCase()] =
397
+ listener &&
398
+ ((payload) =>
399
+ callWithAsyncErrorHandling(listener, component, ErrorCodes.NATIVE_EVENT_HANDLER, [payload]))
400
+ redraw(element)
401
+ }
402
+
267
403
  // An Animated.event handler writes into values natively; JS keeps only its listener. Handlers run
268
404
  // through Vue's error handling, like on the web, so an error names the component it came from.
269
405
  function patchEventHandler(
@@ -291,8 +427,12 @@ function patchEventHandler(
291
427
 
292
428
  const { createApp: createBaseApp } = createRenderer<Node, Node>({
293
429
  createElement(type) {
294
- const element = createNode(type)
295
- native.create(element.id, type)
430
+ if (drawnViewsByPartTag.has(type)) return createNode(type)
431
+
432
+ const element = createNode(drawnViewsByTag.get(type)?.type ?? type)
433
+
434
+ warnIfUnknown(type)
435
+ native.create(element.id, element.type)
296
436
  if (type === 'TextInput') textInputsById.set(element.id, element)
297
437
 
298
438
  return element
@@ -312,11 +452,16 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
312
452
  setText(textNode, text) {
313
453
  textNode.text = text
314
454
  syncTextContent(textNode.parent)
455
+ redraw(textNode.parent)
315
456
  },
316
457
 
317
458
  setElementText(element, text) {
318
459
  element.children = []
319
460
  if (element.type === 'Text') native.setText(element.id, text.trim())
461
+ if (drawnViewsByPartTag.has(element.type)) {
462
+ element.children = [{ ...createNode('#text'), text, parent: element }]
463
+ redraw(element)
464
+ }
320
465
  },
321
466
 
322
467
  insert(child, parent, anchor) {
@@ -328,6 +473,7 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
328
473
 
329
474
  if (isNativeNode(child)) native.insert(parent.id, child.id, nativeIndexBefore(parent, index))
330
475
  else syncTextContent(parent)
476
+ redraw(parent)
331
477
  },
332
478
 
333
479
  remove(child) {
@@ -336,6 +482,7 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
336
482
 
337
483
  if (isNativeNode(child)) native.remove(child.id, nativeIdsIn(child))
338
484
  else syncTextContent(parent)
485
+ redraw(parent)
339
486
  },
340
487
 
341
488
  parentNode(node) {
@@ -349,7 +496,18 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
349
496
  },
350
497
 
351
498
  patchProp(element, key, previousValue, nextValue, _namespace, component) {
352
- if (key === 'style') updateStyle(element, { style: nextValue })
499
+ const drawnView = drawnViewsByPartTag.get(element.type)
500
+
501
+ if (drawnView) {
502
+ if (isEventProp(camelize(key))) {
503
+ patchDrawnEventHandler(element, camelize(key), nextValue, component ?? null)
504
+ } else {
505
+ drawnView.setPartProp(element, key, nextValue)
506
+ redraw(element)
507
+ }
508
+ } else if (drawnViewsByType.has(element.type) && patchDrawnViewProp(element, key, nextValue)) {
509
+ return
510
+ } else if (key === 'style') updateStyle(element, { style: nextValue })
353
511
  else if (key === 'class') updateStyle(element, { className: nextValue ?? undefined })
354
512
  else if (key === 'pressed') updateStyle(element, { pressed: nextValue })
355
513
  else if (isAccessibilityAttribute(key)) updateAccessibility(element, key, nextValue)
@@ -373,6 +531,13 @@ const MODEL_EVENT_BY_NATIVE_EVENT: Record<string, string> = {
373
531
  }
374
532
 
375
533
  globalThis.__dispatch = (nodeId, eventName, payload) => {
534
+ // A press on a drawn view's elements: the innermost first, then the groups around it.
535
+ if (eventName === 'elementpress') {
536
+ const { nodeIds, ...location } = payload as { nodeIds: number[] }
537
+
538
+ return nodeIds.forEach((id) => eventHandlersByNodeId[id]?.press?.(location))
539
+ }
540
+
376
541
  updateFocus(nodeId, eventName)
377
542
 
378
543
  const handlers = eventHandlersByNodeId[nodeId]
package/src/router.ts CHANGED
@@ -28,16 +28,26 @@ import {
28
28
  } from '@vue/runtime-core'
29
29
  import { processColor } from './colors'
30
30
  import { Pressable } from './components'
31
- import type { SvgIcon } from './native-components'
32
31
  import { setURLNavigation } from './native-events'
33
32
  import { createApp } from './renderer'
34
33
 
35
34
  export type Params = Record<string, string | string[]>
36
35
 
36
+ /**
37
+ * A tab bar or header icon: an SF Symbol's name (iOS only), an image ({ uri }: an imported asset or a url),
38
+ * or one a package draws natively, like @nativue/icons' components.
39
+ */
40
+ export type NavigationIcon = string | { uri: string } | DrawnIcon
41
+
42
+ /** Drawn by the package that registered `drawer` natively (registry.addIconDrawer), e.g. @nativue/svg. */
43
+ export interface DrawnIcon {
44
+ drawnIcon: { drawer: string; [data: string]: unknown }
45
+ }
46
+
37
47
  // An icon shows instead of the title, which still names it for screen readers.
38
48
  export interface HeaderItem {
39
49
  title?: string
40
- icon?: string | SvgIcon // SF Symbol name (iOS only), or an icon from @nativue/icons
50
+ icon?: NavigationIcon
41
51
  onPress?: () => void
42
52
  }
43
53
 
@@ -52,7 +62,7 @@ export interface ScreenOptions {
52
62
  presentation?: 'card' | 'modal' | 'formSheet' | 'fullScreenModal'
53
63
  // <Tabs> only
54
64
  tabBarLabel?: string
55
- tabBarIcon?: string | SvgIcon // SF Symbol name, or an icon from @nativue/icons
65
+ tabBarIcon?: NavigationIcon
56
66
  tabBarBadge?: string | number
57
67
  tabBarActiveTintColor?: string // the whole bar's: set it in <Tabs :screen-options>
58
68
  tabBarInactiveTintColor?: string
@@ -710,7 +720,7 @@ const StackNavigatorComponent = defineComponent({
710
720
  })
711
721
 
712
722
  // A page tab gets a single-screen stack, for its header; a layout tab brings its own navigator.
713
- // Tab options: title / tabBarLabel, tabBarIcon (SF Symbol name or SvgIcon), tabBarBadge, plus the header ones, and
723
+ // Tab options: title / tabBarLabel, tabBarIcon, tabBarBadge, plus the header ones, and
714
724
  // lazy: mount the tab's content only when it's first opened (faster startup, a short build on first open).
715
725
  function tabContent(tab: Entry, options: ScreenOptions) {
716
726
  if (tab.node.type !== 'page') return screenContent(tab)
@@ -724,9 +734,12 @@ function optionalColor(color: string | undefined) {
724
734
  return color && processColor(color)
725
735
  }
726
736
 
727
- // An SF Symbol name or an icon from @nativue/icons, as the native side reads them.
728
- function iconProps(icon: string | SvgIcon | undefined) {
729
- return typeof icon === 'string' ? { systemImage: icon } : { svg: icon?.svg }
737
+ // An icon as the native side reads it: systemImage, image (a url) or drawnIcon.
738
+ function iconProps(icon: NavigationIcon | undefined) {
739
+ if (typeof icon === 'string') return { systemImage: icon }
740
+ if (icon && 'uri' in icon) return { image: icon.uri }
741
+
742
+ return { drawnIcon: icon?.drawnIcon }
730
743
  }
731
744
 
732
745
  const TabScreen = defineComponent({