@nativue/core 0.5.0 → 0.6.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/components.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  ref,
9
9
  watch,
10
10
  type PropType,
11
+ type SetupContext,
11
12
  type SlotsType,
12
13
  type VNode,
13
14
  } from '@vue/runtime-core'
@@ -98,30 +99,32 @@ const ESTIMATED_ROW_LENGTH = 50
98
99
  // Limitation: Rows not rendered yet count as the average measured length, so jumping far (dragging the
99
100
  // scroll indicator) can shift the rows a few points once they're measured; anchor the scroll position
100
101
  // to the first visible row if that shows.
101
- // Limitation: Items are `any` in the #item slot; make FlatList generic if typed rows are wanted.
102
102
  // Limitation: An Animated.event `:on-scroll` replaces the window's own scroll handler, and a mapped event
103
103
  // reaches JS only when a scroll starts and ends; report frames to both natively if that's needed.
104
- export const FlatList = defineComponent({
105
- name: 'FlatList',
106
- props: {
107
- data: { type: Array as PropType<any[]>, required: true },
108
- horizontal: Boolean,
109
- itemHeight: Number,
110
- itemWidth: Number,
111
- keyExtractor: {
112
- type: Function as PropType<(item: any, index: number) => string | number>,
113
- default: (_item: unknown, index: number) => index,
114
- },
115
- style: Object as PropType<Style>,
116
- },
117
- slots: Object as SlotsType<{
118
- item: { item: any; index: number }
119
- header?: {}
120
- footer?: {}
121
- empty?: {}
122
- }>,
104
+ // Generic: `item` in #item, and keyExtractor's, have the type of `data`'s elements.
105
+ export interface FlatListProps<Item> {
106
+ data: Item[]
107
+ horizontal?: boolean
108
+ itemHeight?: number
109
+ itemWidth?: number
110
+ /** The row's key; its index by default. */
111
+ keyExtractor?: (item: Item, index: number) => string | number
112
+ style?: Style
113
+ }
123
114
 
124
- setup(props, { slots }) {
115
+ type FlatListSlots<Item> = SlotsType<{
116
+ item: { item: Item; index: number }
117
+ header?: {}
118
+ footer?: {}
119
+ empty?: {}
120
+ }>
121
+
122
+ const defaultKey = (_item: unknown, index: number) => index
123
+
124
+ /** FlatList as the renderer registers it; apps get the generic type below. */
125
+ export const FlatListComponent = defineComponent(
126
+ <Item>(props: FlatListProps<Item>, { slots }: SetupContext<{}, FlatListSlots<Item>>) => {
127
+ const keyOf = (item: Item, index: number) => (props.keyExtractor ?? defaultKey)(item, index)
125
128
  const scrollPosition = ref(0)
126
129
  const viewportLength = ref(0)
127
130
  const headerLength = ref(0)
@@ -136,9 +139,7 @@ export const FlatList = defineComponent({
136
139
  const estimatedLength = averageOf(measuredLengths.values()) ?? ESTIMATED_ROW_LENGTH
137
140
  const lengths = props.data.map(
138
141
  (item, index) =>
139
- fixedLength.value ??
140
- measuredLengths.get(props.keyExtractor(item, index)) ??
141
- estimatedLength,
142
+ fixedLength.value ?? measuredLengths.get(keyOf(item, index)) ?? estimatedLength,
142
143
  )
143
144
 
144
145
  return rowOffsets(lengths)
@@ -165,9 +166,9 @@ export const FlatList = defineComponent({
165
166
  viewportLength.value = length
166
167
  }
167
168
 
168
- function renderRow(item: unknown, offset: number): VNode {
169
+ function renderRow(item: Item, offset: number): VNode {
169
170
  const index = start.value + offset
170
- const key = props.keyExtractor(item, index)
171
+ const key = keyOf(item, index)
171
172
  const sizing = fixedLength.value
172
173
  ? { style: props.horizontal ? { width: fixedLength.value } : { height: fixedLength.value } }
173
174
  : { onLayout: (layout: LayoutEvent) => measuredLengths.set(key, lengthOf(layout)) }
@@ -217,7 +218,34 @@ export const FlatList = defineComponent({
217
218
  )
218
219
  }
219
220
  },
220
- })
221
+ {
222
+ name: 'FlatList',
223
+ // At runtime too: Boolean casting (a bare `horizontal` is true) and what isn't a prop falls through.
224
+ props: {
225
+ data: { type: Array as PropType<unknown[]>, required: true },
226
+ horizontal: Boolean,
227
+ itemHeight: Number,
228
+ itemWidth: Number,
229
+ keyExtractor: Function as PropType<(item: unknown, index: number) => string | number>,
230
+ style: Object as PropType<Style>,
231
+ },
232
+ slots: Object as FlatListSlots<unknown>,
233
+ },
234
+ )
235
+
236
+ type RowSlot<Scope> = (scope: Scope) => VNode[]
237
+
238
+ // defineComponent settles Item when it's called (to unknown). Typed instead as a generic constructor,
239
+ // which templates (vue-tsc) call with the props, inferring Item from `data`.
240
+ export const FlatList = FlatListComponent as unknown as new <Item>(props: FlatListProps<Item>) => {
241
+ $props: FlatListProps<Item>
242
+ $slots: {
243
+ item: RowSlot<{ item: Item; index: number }>
244
+ header?: RowSlot<{}>
245
+ footer?: RowSlot<{}>
246
+ empty?: RowSlot<{}>
247
+ }
248
+ }
221
249
 
222
250
  function averageOf(values: Iterable<number>): number | undefined {
223
251
  let sum = 0
package/src/entry.ts CHANGED
@@ -1,6 +1,14 @@
1
1
  // The app's entry, added by the CLI: every .vue file under the project's src/app/ is a route, so
2
- // projects have no main.js. The runtime modules of nativue.config's plugins run first.
2
+ // projects have no main.js. The runtime modules of nativue.config's plugins run first. An optional
3
+ // src/app.ts sets the app up before it mounts (app.use for Vue plugins, app.provide...).
3
4
  import 'virtual:nativue/plugin-runtimes'
5
+ import type { App } from 'vue'
4
6
  import { createRouterApp } from './router'
5
7
 
6
- createRouterApp(import.meta.glob('/src/app/**/*.vue', { eager: true })).mount()
8
+ type AppSetup = { default?: (app: App) => void }
9
+
10
+ const app = createRouterApp(import.meta.glob('/src/app/**/*.vue', { eager: true }))
11
+ const setupFiles = import.meta.glob<AppSetup>('/src/app.{ts,js}', { eager: true })
12
+
13
+ Object.values(setupFiles).forEach((setupFile) => setupFile.default?.(app))
14
+ app.mount()
package/src/events.ts ADDED
@@ -0,0 +1,119 @@
1
+ // Event, ProgressEvent, EventTarget, AbortController and AbortSignal, like the browser's: Hermes has none
2
+ // of them, and XMLHttpRequest and fetch build on them.
3
+
4
+ export class Event {
5
+ readonly type: string
6
+ target: EventTarget | null = null
7
+ defaultPrevented = false
8
+
9
+ constructor(type: string) {
10
+ this.type = type
11
+ }
12
+
13
+ preventDefault(): void {
14
+ this.defaultPrevented = true
15
+ }
16
+ }
17
+
18
+ export interface ProgressEventInit {
19
+ lengthComputable?: boolean
20
+ loaded?: number
21
+ total?: number
22
+ }
23
+
24
+ export class ProgressEvent extends Event {
25
+ readonly lengthComputable: boolean
26
+ readonly loaded: number
27
+ readonly total: number
28
+
29
+ constructor(
30
+ type: string,
31
+ { lengthComputable = false, loaded = 0, total = 0 }: ProgressEventInit = {},
32
+ ) {
33
+ super(type)
34
+ this.lengthComputable = lengthComputable
35
+ this.loaded = loaded
36
+ this.total = total
37
+ }
38
+ }
39
+
40
+ type EventListener = ((event: any) => void) | { handleEvent(event: any): void }
41
+
42
+ // The `on<type>` property of a target (onload, onabort...) runs before the listeners, as in browsers.
43
+ export class EventTarget {
44
+ private readonly listenersByType = new Map<string, Set<EventListener>>()
45
+
46
+ addEventListener(type: string, listener: EventListener | null): void {
47
+ if (!listener) return
48
+
49
+ const listeners = this.listenersByType.get(type) ?? new Set()
50
+ listeners.add(listener)
51
+ this.listenersByType.set(type, listeners)
52
+ }
53
+
54
+ removeEventListener(type: string, listener: EventListener | null): void {
55
+ if (listener) this.listenersByType.get(type)?.delete(listener)
56
+ }
57
+
58
+ dispatchEvent(event: Event): boolean {
59
+ event.target = this
60
+
61
+ const handler = (this as unknown as Record<string, unknown>)[`on${event.type}`]
62
+ if (typeof handler === 'function') handler.call(this, event)
63
+
64
+ for (const listener of [...(this.listenersByType.get(event.type) ?? [])]) {
65
+ if (typeof listener === 'function') listener.call(this, event)
66
+ else listener.handleEvent(event)
67
+ }
68
+
69
+ return !event.defaultPrevented
70
+ }
71
+
72
+ protected hasListeners(type: string): boolean {
73
+ return (this.listenersByType.get(type)?.size ?? 0) > 0
74
+ }
75
+ }
76
+
77
+ // Like the browser's DOMException with that name: code checks `error.name`.
78
+ export function namedError(name: string, message: string): Error {
79
+ const error = new Error(message)
80
+ error.name = name
81
+
82
+ return error
83
+ }
84
+
85
+ export class AbortSignal extends EventTarget {
86
+ aborted = false
87
+ reason: unknown = undefined
88
+ onabort: ((event: Event) => void) | null = null
89
+
90
+ static abort(reason?: unknown): AbortSignal {
91
+ const controller = new AbortController()
92
+ controller.abort(reason)
93
+
94
+ return controller.signal
95
+ }
96
+
97
+ static timeout(milliseconds: number): AbortSignal {
98
+ const controller = new AbortController()
99
+ setTimeout(() => controller.abort(namedError('TimeoutError', 'signal timed out')), milliseconds)
100
+
101
+ return controller.signal
102
+ }
103
+
104
+ throwIfAborted(): void {
105
+ if (this.aborted) throw this.reason
106
+ }
107
+ }
108
+
109
+ export class AbortController {
110
+ readonly signal = new AbortSignal()
111
+
112
+ abort(reason: unknown = namedError('AbortError', 'signal is aborted without reason')): void {
113
+ if (this.signal.aborted) return
114
+
115
+ this.signal.aborted = true
116
+ this.signal.reason = reason
117
+ this.signal.dispatchEvent(new Event('abort'))
118
+ }
119
+ }
package/src/fetch.ts CHANGED
@@ -1,117 +1,112 @@
1
- // fetch, Headers and Response, like the browser's: native runs the request with
2
- // URLSession and calls back __fetchFinished.
3
- // Limitation: Text bodies only (no Blob, FormData or streaming) and no AbortController.
4
- const native = globalThis.__native
1
+ // fetch, Headers, Request and Response: whatwg-fetch (the browser polyfill) on top of XMLHttpRequest,
2
+ // with responses kept as native Blobs. ./networking goes first: it puts what whatwg-fetch looks for on
3
+ // globalThis.
4
+ import './networking'
5
+ import 'whatwg-fetch'
5
6
 
6
- interface PendingRequest {
7
- resolve: (response: FetchResponse) => void
8
- reject: (error: Error) => void
9
- url: string
10
- }
11
-
12
- const pendingRequestsById = new Map<number, PendingRequest>()
13
- let nextRequestId = 1
7
+ type HeadersInit = Headers | Record<string, string> | [string, string][]
8
+ type BodyInit = import('./xhr').XMLHttpRequestBody
14
9
 
15
- type HeadersInit = FetchHeaders | Record<string, string>
16
-
17
- export interface RequestInit {
10
+ interface RequestInit {
18
11
  method?: string
19
12
  headers?: HeadersInit
20
- body?: string | null
13
+ body?: BodyInit
14
+ signal?: AbortSignal | null
15
+ /** 'same-origin' (the default) and 'include' send cookies; 'omit' doesn't. */
16
+ credentials?: 'include' | 'same-origin' | 'omit'
21
17
  }
22
18
 
23
- class FetchHeaders {
24
- readonly valuesByName = new Map<string, string>()
25
-
26
- constructor(init: HeadersInit = {}) {
27
- const entries = init instanceof FetchHeaders ? init.valuesByName : Object.entries(init)
28
-
29
- for (const [name, value] of entries) this.set(name, value)
30
- }
31
-
32
- get(name: string): string | null {
33
- return this.valuesByName.get(name.toLowerCase()) ?? null
34
- }
35
-
36
- set(name: string, value: string): void {
37
- this.valuesByName.set(name.toLowerCase(), String(value))
38
- }
39
-
40
- has(name: string): boolean {
41
- return this.valuesByName.has(name.toLowerCase())
42
- }
43
-
44
- forEach(callback: (value: string, name: string, headers: FetchHeaders) => void): void {
45
- this.valuesByName.forEach((value, name) => callback(value, name, this))
46
- }
19
+ interface ResponseInit {
20
+ status?: number
21
+ statusText?: string
22
+ headers?: HeadersInit
23
+ url?: string
47
24
  }
48
25
 
49
- class FetchResponse {
50
- readonly status: number
51
- readonly ok: boolean
52
- readonly headers: FetchHeaders
53
- readonly url: string
54
- private readonly body: string
26
+ interface Body {
27
+ readonly bodyUsed: boolean
28
+ text(): Promise<string>
29
+ // `any` like the DOM's: type it at the call site.
30
+ json(): Promise<any>
31
+ blob(): Promise<Blob>
32
+ arrayBuffer(): Promise<ArrayBuffer>
33
+ formData(): Promise<FormData>
34
+ }
55
35
 
56
- constructor(
57
- { status, headers, body }: { status: number; headers: Record<string, string>; body: string },
58
- url: string,
59
- ) {
60
- this.status = status
61
- this.ok = status >= 200 && status < 300
62
- this.headers = new FetchHeaders(headers)
63
- this.url = url
64
- this.body = body
36
+ declare global {
37
+ interface Headers {
38
+ append(name: string, value: string): void
39
+ delete(name: string): void
40
+ get(name: string): string | null
41
+ has(name: string): boolean
42
+ set(name: string, value: string): void
43
+ forEach(callback: (value: string, name: string, headers: Headers) => void): void
44
+ keys(): IterableIterator<string>
45
+ values(): IterableIterator<string>
46
+ entries(): IterableIterator<[string, string]>
47
+ [Symbol.iterator](): IterableIterator<[string, string]>
65
48
  }
66
-
67
- async text(): Promise<string> {
68
- return this.body
49
+ var Headers: { new (init?: HeadersInit): Headers; prototype: Headers }
50
+
51
+ interface Request extends Body {
52
+ readonly url: string
53
+ readonly method: string
54
+ readonly headers: Headers
55
+ readonly credentials: 'include' | 'same-origin' | 'omit'
56
+ readonly signal: AbortSignal
57
+ clone(): Request
69
58
  }
70
-
71
- // Limitation: `any` like the DOM's json(); type it at the call site.
72
- async json(): Promise<any> {
73
- return JSON.parse(this.body)
59
+ var Request: { new (input: string | Request, init?: RequestInit): Request; prototype: Request }
60
+
61
+ interface Response extends Body {
62
+ readonly status: number
63
+ readonly statusText: string
64
+ readonly ok: boolean
65
+ readonly headers: Headers
66
+ readonly url: string
67
+ clone(): Response
68
+ }
69
+ var Response: {
70
+ new (body?: BodyInit, init?: ResponseInit): Response
71
+ prototype: Response
72
+ error(): Response
73
+ redirect(url: string, status?: number): Response
74
74
  }
75
- }
76
-
77
- function fetch(
78
- input: string | { toString(): string },
79
- { method = 'GET', headers = {}, body = null }: RequestInit = {},
80
- ): Promise<FetchResponse> {
81
- const url = String(input)
82
-
83
- return new Promise((resolve, reject) => {
84
- const requestId = nextRequestId++
85
- pendingRequestsById.set(requestId, { resolve, reject, url })
86
-
87
- const headerEntries = Object.fromEntries(new FetchHeaders(headers).valuesByName)
88
- native.fetch(
89
- requestId,
90
- url,
91
- method.toUpperCase(),
92
- headerEntries,
93
- body == null ? null : String(body),
94
- )
95
- })
96
- }
97
-
98
- globalThis.__fetchFinished = (requestId, response, errorMessage) => {
99
- const request = pendingRequestsById.get(requestId)
100
- if (!request) return
101
-
102
- const { resolve, reject, url } = request
103
- pendingRequestsById.delete(requestId)
104
75
 
105
- if (errorMessage || !response) reject(new TypeError(`Network request failed: ${errorMessage}`))
106
- else resolve(new FetchResponse(response, url))
76
+ function fetch(
77
+ input: string | { toString(): string } | Request,
78
+ init?: RequestInit,
79
+ ): Promise<Response>
80
+
81
+ var XMLHttpRequest: typeof import('./xhr').XMLHttpRequest
82
+ type XMLHttpRequest = import('./xhr').XMLHttpRequest
83
+ var FormData: typeof import('./xhr').FormData
84
+ type FormData = import('./xhr').FormData
85
+ var Blob: typeof import('./blob').Blob
86
+ type Blob = import('./blob').Blob
87
+ var File: typeof import('./blob').File
88
+ type File = import('./blob').File
89
+ var FileReader: typeof import('./blob').FileReader
90
+ type FileReader = import('./blob').FileReader
91
+ var AbortController: typeof import('./events').AbortController
92
+ type AbortController = import('./events').AbortController
93
+ var AbortSignal: typeof import('./events').AbortSignal
94
+ type AbortSignal = import('./events').AbortSignal
95
+ var Event: typeof import('./events').Event
96
+ type Event = import('./events').Event
97
+ var EventTarget: typeof import('./events').EventTarget
98
+ type EventTarget = import('./events').EventTarget
99
+ var ProgressEvent: typeof import('./events').ProgressEvent
100
+ type ProgressEvent = import('./events').ProgressEvent
101
+ var URL: typeof import('./url').URL
102
+ type URL = import('./url').URL
103
+ var URLSearchParams: typeof import('./url').URLSearchParams
104
+ type URLSearchParams = import('./url').URLSearchParams
105
+ var ReadableStream: typeof import('./streams').ReadableStream
106
+ type ReadableStream<Chunk = Uint8Array> = import('./streams').ReadableStream<Chunk>
107
+ var ReadableStreamDefaultReader: typeof import('./streams').ReadableStreamDefaultReader
108
+ type ReadableStreamDefaultReader<Chunk> = import('./streams').ReadableStreamDefaultReader<Chunk>
109
+ type RequestInit = import('./fetch').RequestInit
107
110
  }
108
111
 
109
- Object.assign(globalThis, { fetch, Headers: FetchHeaders, Response: FetchResponse })
110
-
111
- declare global {
112
- var fetch: (input: string | { toString(): string }, init?: RequestInit) => Promise<FetchResponse>
113
- var Headers: typeof FetchHeaders
114
- type Headers = FetchHeaders
115
- var Response: typeof FetchResponse
116
- type Response = FetchResponse
117
- }
112
+ export type { RequestInit }
package/src/globals.ts CHANGED
@@ -1,7 +1,7 @@
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
3
  import type { ColorScheme, WindowSize } from './appearance'
4
- import type { LayoutEvent, NativeModule } from './types'
4
+ import type { LayoutEvent, NativeModule, NetworkEventPayloads } from './types'
5
5
 
6
6
  declare global {
7
7
  var __native: NativeModule
@@ -13,11 +13,13 @@ declare global {
13
13
  var __windowSizeChanged: (windowSize: WindowSize) => void
14
14
  var __asyncFunctionFinished: (callId: number, value: unknown, errorMessage: string | null) => void
15
15
  var __animationFinished: (animationId: number, finished: boolean) => void
16
- var __fetchFinished: (
16
+ var __networkEvent: <Name extends keyof NetworkEventPayloads>(
17
17
  requestId: number,
18
- response: { status: number; headers: Record<string, string>; body: string } | null,
19
- errorMessage: string | null,
18
+ eventName: Name,
19
+ payload: NetworkEventPayloads[Name],
20
20
  ) => void
21
+ /** From the runtime (not __native): an object whose garbage collection releases the blob's bytes. */
22
+ var __blobCollector: ((blobId: string) => object) | undefined
21
23
 
22
24
  var console: {
23
25
  log(...values: unknown[]): void
@@ -55,6 +55,8 @@ declare module '@vue/runtime-core' {
55
55
  contentInsetAdjustmentBehavior?: 'automatic' | 'scrollableAxes' | 'never' | 'always'
56
56
  /** The keyboard insets the content, and the focused input scrolls above it. */
57
57
  automaticallyAdjustKeyboardInsets?: boolean
58
+ /** At most one @scroll per this many milliseconds (the last position always comes); 0, every frame. */
59
+ scrollEventThrottle?: number
58
60
  onScroll?: EventHandler<ScrollEvent>
59
61
  onRefresh?: () => void
60
62
  }>
@@ -0,0 +1,24 @@
1
+ // The browser's networking classes on globalThis. Its own module, imported by fetch.ts before
2
+ // whatwg-fetch: that one checks for Blob, FileReader, FormData and URLSearchParams as it loads.
3
+ import { Blob, File, FileReader } from './blob'
4
+ import { AbortController, AbortSignal, Event, EventTarget, ProgressEvent } from './events'
5
+ import { ReadableStream, ReadableStreamDefaultReader } from './streams'
6
+ import { URL, URLSearchParams } from './url'
7
+ import { FormData, XMLHttpRequest } from './xhr'
8
+
9
+ Object.assign(globalThis, {
10
+ XMLHttpRequest,
11
+ FormData,
12
+ Blob,
13
+ File,
14
+ FileReader,
15
+ AbortController,
16
+ AbortSignal,
17
+ Event,
18
+ EventTarget,
19
+ ProgressEvent,
20
+ URL,
21
+ URLSearchParams,
22
+ ReadableStream,
23
+ ReadableStreamDefaultReader,
24
+ })
package/src/renderer.ts CHANGED
@@ -21,7 +21,7 @@ import {
21
21
  import { animatedEventMapping, animatedStyleBinding, isAnimatedEvent } from './animated'
22
22
  import { Appearance } from './appearance'
23
23
  import { COLOR_PROPERTIES, processColor } from './colors'
24
- import { FlatList, ImageBackground, Pressable, Swipeable } from './components'
24
+ import { FlatListComponent, ImageBackground, Pressable, Swipeable } from './components'
25
25
  import type { LayoutAnimationConfig, Style } from './types'
26
26
  export * from '@vue/runtime-core'
27
27
  export { AccessibilityInfo } from './accessibility'
@@ -509,7 +509,7 @@ export function createApp(rootComponent: Component) {
509
509
  app.config.errorHandler = reportVueError
510
510
 
511
511
  app.component('Pressable', Pressable)
512
- app.component('FlatList', FlatList)
512
+ app.component('FlatList', FlatListComponent)
513
513
  app.component('Swipeable', Swipeable)
514
514
  app.component('ImageBackground', ImageBackground)
515
515