@getcortexlabs/nitroui-vue 0.0.0-stage → 0.2.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/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # NitroUI Vue
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A community Vue 3 renderer for NitroUI. Build native iOS and Android screens with Vue components, scrollable content, recycled lists and a native navigation stack.
4
+
5
+ ## Install
6
+
7
+ In a NitroUI 0.3.0 app:
8
+
9
+ ```sh
10
+ bun add @getcortexlabs/nitroui-vue @vue/runtime-core@3.5.46
11
+ ```
12
+
13
+ ## Mount a screen
14
+
15
+ ```ts
16
+ import { defineComponent, h, ref } from '@vue/runtime-core'
17
+ import { registerApp, Text, TextInput, View } from '@getcortexlabs/nitroui-vue'
18
+
19
+ const App = defineComponent(() => {
20
+ const name = ref('')
21
+ return () => h(View, { layout: { padding: 24, gap: 12 } }, () => [
22
+ h(Text, null, () => name.value ? `Hello, ${name.value}!` : 'Hello, Vue!'),
23
+ h(TextInput, {
24
+ placeholder: 'Your name',
25
+ modelValue: name.value,
26
+ 'onUpdate:modelValue': (value: string) => { name.value = value },
27
+ }),
28
+ ])
29
+ })
30
+
31
+ registerApp(App)
32
+ ```
33
+
34
+ For nested Vue templates, the Bun compiler and a native demo, see the [single-file component and compiler setup](https://github.com/getcortexlabs/nitroui-vue/tree/main/example). The package uses the public NitroUI native bindings and ships TypeScript for the NitroUI bundler.
package/compiler.d.mts ADDED
@@ -0,0 +1,5 @@
1
+ /** Compile a Vue entry and its local imports to one module for NitroUI. Requires Bun. */
2
+ export function compileVue(entry: string, output: string): Promise<void>
3
+
4
+ /** Recompile after edits under the source directory. Close the watcher to stop. */
5
+ export function watchVue(entry: string, output: string, directory?: string): Promise<{ close(): void }>
package/compiler.mjs ADDED
@@ -0,0 +1,63 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { watch } from 'node:fs'
3
+ import { readFile, rename, rm, writeFile } from 'node:fs/promises'
4
+ import { dirname, resolve } from 'node:path'
5
+ import { compileScript, compileTemplate, parse } from '@vue/compiler-sfc'
6
+
7
+ const vue = {
8
+ name: 'nitroui-vue-sfc',
9
+ setup(build) {
10
+ build.onLoad({ filter: /\.vue$/ }, async ({ path }) => {
11
+ const source = await readFile(path, 'utf8')
12
+ const { descriptor, errors } = parse(source, { filename: path })
13
+ if (errors.length) throw new Error(path + '\n' + errors.join('\n'))
14
+ if (descriptor.styles.length) throw new Error(path + ' uses an unsupported native <style> block.')
15
+ const id = createHash('sha256').update(path).digest('hex').slice(0, 10)
16
+ const compilerOptions = { runtimeModuleName: '@vue/runtime-core' }
17
+ if (descriptor.scriptSetup) {
18
+ const script = compileScript(descriptor, { id, inlineTemplate: true, templateOptions: { compilerOptions } })
19
+ return { contents: script.content, loader: 'ts' }
20
+ }
21
+ const script = descriptor.script ? compileScript(descriptor, { id, genDefaultAs: 'component' }).content : 'const component = {}'
22
+ if (!descriptor.template) return { contents: script + '\nexport default component', loader: 'ts' }
23
+ const template = compileTemplate({ source: descriptor.template.content, filename: path, id, compilerOptions })
24
+ if (template.errors.length) throw new Error(path + '\n' + template.errors.join('\n'))
25
+ return { contents: script + '\n' + template.code + '\nexport default Object.assign(component, { render })', loader: 'ts' }
26
+ })
27
+ },
28
+ }
29
+
30
+ /** Bundle a local component tree, leaving runtime packages for NitroUI's platform build. */
31
+ export async function compileVue(entry, output) {
32
+ const result = await Bun.build({ entrypoints: [resolve(entry)], target: 'browser', format: 'esm', packages: 'external', plugins: [vue], throw: false })
33
+ if (!result.success) throw new Error(result.logs.map(log => log.message).join('\n'))
34
+ if (result.outputs.length !== 1) throw new Error('Expected a single compiled Vue module.')
35
+ const temporary = output + '.' + randomUUID() + '.tmp'
36
+ try {
37
+ await writeFile(temporary, await result.outputs[0].text())
38
+ await rename(temporary, output)
39
+ } finally {
40
+ await rm(temporary, { force: true })
41
+ }
42
+ }
43
+
44
+ /** Watch local source files, preserving the last successful build on a compiler error. */
45
+ export async function watchVue(entry, output, directory = dirname(entry)) {
46
+ let pending = false
47
+ let running = false
48
+ async function rebuild() {
49
+ pending = true
50
+ if (running) return
51
+ running = true
52
+ while (pending) {
53
+ pending = false
54
+ try { await compileVue(entry, output) } catch (error) { console.error(error.message) }
55
+ }
56
+ running = false
57
+ }
58
+ const watcher = watch(directory, { recursive: true }, (_, name) => {
59
+ if (name && /\.(?:vue|[cm]?[jt]sx?)$/.test(name) && resolve(directory, name) !== resolve(output)) void rebuild()
60
+ })
61
+ await rebuild()
62
+ return watcher
63
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@getcortexlabs/nitroui-vue",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Experimental Vue 3 renderer for NitroUI.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts",
8
+ "./compiler": {
9
+ "types": "./compiler.d.mts",
10
+ "default": "./compiler.mjs"
11
+ }
12
+ },
13
+ "peerDependencies": {
14
+ "@vue/runtime-core": "^3.5.46",
15
+ "@vue/compiler-sfc": "^3.5.46",
16
+ "nitro-core": "1.0.0-alpha.nightly.137.gd4793c40b8b8",
17
+ "nitro-ui-layout": "0.3.0",
18
+ "nitro-ui-renderer": "0.3.0",
19
+ "nitro-ui-runtime": "0.3.0"
20
+ },
21
+ "peerDependenciesMeta": {
22
+ "@vue/compiler-sfc": { "optional": true }
23
+ },
24
+ "files": [
25
+ "src",
26
+ "compiler.mjs",
27
+ "compiler.d.mts"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/getcortexlabs/nitroui-vue.git",
35
+ "directory": "packages/nitroui-vue"
36
+ },
37
+ "homepage": "https://github.com/getcortexlabs/nitroui-vue#readme"
38
+ }
@@ -0,0 +1,44 @@
1
+ import { defineComponent, h, type FunctionalComponent, type PropType } from '@vue/runtime-core'
2
+ import type { Layout } from './layout'
3
+
4
+ interface ViewProps {
5
+ layout?: Layout
6
+ }
7
+
8
+ interface TextProps extends ViewProps {
9
+ fontSize?: number
10
+ }
11
+
12
+ function hostProps(props: ViewProps) {
13
+ // Read reactive layout fields during render and retain their previous values for patching.
14
+ return props.layout ? { ...props, layout: { ...props.layout } } : props
15
+ }
16
+
17
+ export const View: FunctionalComponent<ViewProps> = (props, { slots }) =>
18
+ h('nitro-view', hostProps(props), slots.default?.())
19
+
20
+ export const Text: FunctionalComponent<TextProps> = (props, { slots }) =>
21
+ h('nitro-text', hostProps(props), slots.default?.())
22
+
23
+ View.inheritAttrs = false
24
+ Text.inheritAttrs = false
25
+
26
+ export const ScrollView: FunctionalComponent<ViewProps> = (props, { slots }) =>
27
+ h('nitro-scroll', { layout: { flexGrow: 1, ...props.layout } }, [
28
+ h('nitro-scroll-content', null, slots.default?.()),
29
+ ])
30
+ ScrollView.inheritAttrs = false
31
+
32
+ export const TextInput = defineComponent({
33
+ name: 'TextInput',
34
+ props: {
35
+ modelValue: String,
36
+ placeholder: String,
37
+ layout: Object as PropType<Layout>,
38
+ },
39
+ emits: ['update:modelValue'],
40
+ setup(props, { emit }) {
41
+ const onEdit = (text: string) => emit('update:modelValue', text)
42
+ return () => h('nitro-input', { ...hostProps(props), onEdit })
43
+ },
44
+ })
package/src/index.ts ADDED
@@ -0,0 +1,20 @@
1
+ import 'nitro-ui-runtime'
2
+ import type { Component } from '@vue/runtime-core'
3
+ import { Application, ViewController, Window } from 'nitro-ui-renderer/hybrids'
4
+ import { mount } from './renderer'
5
+
6
+ export { Pressable } from './pressable'
7
+ export { NavigationStack, useNavigation } from './navigation'
8
+ export { ListView } from './list'
9
+ export { ScrollView, Text, TextInput, View } from './components'
10
+ export type { Layout } from './layout'
11
+ export { mount }
12
+
13
+ export function registerApp(component: Component) {
14
+ Application.registerRoot(scene => {
15
+ const controller = new ViewController()
16
+ controller.view.setBackgroundColor(0xffffffff)
17
+ mount(component, controller)
18
+ return new Window(scene, controller)
19
+ })
20
+ }
package/src/layout.ts ADDED
@@ -0,0 +1,56 @@
1
+ import type { NLNodeRef } from 'nitro-ui-layout'
2
+
3
+ export interface Layout {
4
+ width?: number
5
+ height?: number
6
+ padding?: number
7
+ gap?: number
8
+ flexGrow?: number
9
+ flexDirection?: 'column' | 'column-reverse' | 'row' | 'row-reverse'
10
+ alignItems?: 'flex-start' | 'center' | 'flex-end' | 'stretch' | 'baseline'
11
+ margin?: number
12
+ justifyContent?: 'flex-start' | 'center' | 'flex-end'
13
+ }
14
+
15
+ const fields: (keyof Layout)[] = ['width', 'height', 'padding', 'gap', 'flexGrow', 'justifyContent', 'flexDirection', 'alignItems', 'margin']
16
+
17
+ export function sameLayout(next: Layout = {}, previous: Layout = {}) {
18
+ return fields.every(field => Object.is(next[field], previous[field]))
19
+ }
20
+
21
+ export function updateLayout(node: NLNodeRef, next: Layout = {}, previous: Layout = {}) {
22
+ const api = nitroLayout
23
+ if (next.width !== previous.width) api.NLSetWidth(node, next.width ?? NaN, api.NLPoint)
24
+ if (next.height !== previous.height) api.NLSetHeight(node, next.height ?? NaN, api.NLPoint)
25
+ if (next.flexGrow !== previous.flexGrow) api.NLSetFlexGrow(node, next.flexGrow ?? 0)
26
+ if (next.flexDirection !== previous.flexDirection) {
27
+ const directions = { column: api.NLColumn, 'column-reverse': api.NLColumnReverse, row: api.NLRow, 'row-reverse': api.NLRowReverse }
28
+ api.NLSetFlexDirection(node, directions[next.flexDirection ?? 'column'])
29
+ }
30
+ if (next.alignItems !== previous.alignItems) {
31
+ const alignments = { 'flex-start': api.NLAlignStart, center: api.NLAlignCenter, 'flex-end': api.NLAlignEnd, stretch: api.NLAlignStretch, baseline: api.NLAlignBaseline }
32
+ api.NLSetAlignItems(node, alignments[next.alignItems ?? 'stretch'])
33
+ }
34
+ if (next.margin !== previous.margin) {
35
+ for (const edge of [api.NLLeft, api.NLTop, api.NLRight, api.NLBottom]) {
36
+ api.NLSetMargin(node, edge, next.margin ?? 0, api.NLPoint)
37
+ }
38
+ }
39
+ if (next.gap !== previous.gap) {
40
+ api.NLSetColumnGap(node, next.gap ?? 0, api.NLPoint)
41
+ api.NLSetRowGap(node, next.gap ?? 0, api.NLPoint)
42
+ }
43
+ if (next.padding !== previous.padding) {
44
+ for (const edge of [api.NLLeft, api.NLTop, api.NLRight, api.NLBottom]) {
45
+ api.NLSetPadding(node, edge, next.padding ?? 0, api.NLPoint)
46
+ }
47
+ }
48
+ if (next.justifyContent !== previous.justifyContent) {
49
+ const positions = {
50
+ 'flex-start': api.NLJustifyStart,
51
+ 'center': api.NLJustifyCenter,
52
+ 'flex-end': api.NLJustifyEnd,
53
+ }
54
+ api.NLSetJustifyContent(node, positions[next.justifyContent ?? 'flex-start'])
55
+ }
56
+ }
package/src/list.ts ADDED
@@ -0,0 +1,97 @@
1
+ import { defineComponent, getCurrentInstance, h, onBeforeUnmount, onMounted, watchEffect, type AppContext, type PropType, type VNodeChild } from '@vue/runtime-core'
2
+ import { NitroModules } from 'nitro-core'
3
+ import type { View } from 'nitro-ui-renderer/hybrids'
4
+ import type { Layout } from './layout'
5
+ import { createHost } from './renderer'
6
+
7
+ interface Descriptor { id: string; type: string; version: number; height?: number }
8
+ interface NativeList extends View {
9
+ setHorizontal(horizontal: boolean): void
10
+ setEstimatedItemSize(height?: number): void
11
+ applySnapshot(items: Descriptor[], animated: boolean, bind: (cell: number, view: View, id: string, index: number) => void, done: () => void): void
12
+ clearDataSource(): void
13
+ }
14
+ type Entry = { item: unknown; index: number; descriptor: Descriptor }
15
+ type Snapshot = Map<string, Entry>
16
+ const Cell = defineComponent({
17
+ props: { content: { type: Function as PropType<() => VNodeChild>, required: true } },
18
+ setup: props => () => props.content(),
19
+ })
20
+
21
+ export const ListView = defineComponent({
22
+ name: 'ListView',
23
+ props: {
24
+ items: { type: Array as PropType<readonly any[]>, required: true },
25
+ itemKey: { type: Function as PropType<(item: any) => string>, required: true },
26
+ itemHeight: Number,
27
+ layout: Object as PropType<Layout>,
28
+ },
29
+ setup(props, { slots }) {
30
+ const Native = NitroModules.getHybridClass<new (queue: typeof queueMicrotask) => NativeList>('renderer.ListView')
31
+ const view = new Native(queueMicrotask)
32
+ view.setHorizontal(false)
33
+ // A cell is a separate render root. Inherit the list's ancestor providers as well as app plugins.
34
+ const instance = getCurrentInstance()! as NonNullable<ReturnType<typeof getCurrentInstance>> & Pick<AppContext, 'provides'>
35
+ const context: AppContext = { ...instance.appContext, provides: instance.provides }
36
+ const cells = new Map<number, { host: ReturnType<typeof createHost>; id: string }>()
37
+ let previous: Snapshot = new Map()
38
+ let pending: Snapshot | undefined
39
+ let applying = false
40
+ let active = true
41
+ function release(cell: { host: ReturnType<typeof createHost> }) {
42
+ cell.host.stop()
43
+ cell.host.renderer.render(null, cell.host.root)
44
+ }
45
+ function apply(entries: Snapshot) {
46
+ if (applying) { pending = entries; return }
47
+ applying = true
48
+ view.applySnapshot(Array.from(entries.values(), entry => entry.descriptor), false, (cellId, container, id, index) => {
49
+ const entry = entries.get(id)
50
+ if (!active || !entry) return
51
+ let cell = cells.get(cellId)
52
+ if (!cell || !cell.host.root.native.equals(container)) {
53
+ if (cell) release(cell)
54
+ cell = { host: createHost(container, true), id }
55
+ cells.set(cellId, cell)
56
+ }
57
+ cell.id = id
58
+ const node = h(Cell, { key: id, content: () => slots.default?.({ item: entry.item, index }) })
59
+ node.appContext = context
60
+ cell.host.renderer.render(node, cell.host.root)
61
+ cell.host.flushLayout()
62
+ }, () => {
63
+ if (!active) return
64
+ for (const [key, cell] of cells) {
65
+ if (!entries.has(cell.id)) { release(cell); cells.delete(key) }
66
+ }
67
+ applying = false
68
+ const next = pending
69
+ pending = undefined
70
+ if (next) apply(next)
71
+ })
72
+ }
73
+ onMounted(() => watchEffect(() => {
74
+ const entries: Snapshot = new Map()
75
+ const height = props.itemHeight
76
+ for (const [index, item] of props.items.entries()) {
77
+ const id = props.itemKey(item)
78
+ if (typeof id !== 'string' || entries.has(id)) throw new Error('ListView itemKey must return a unique string for each row.')
79
+ const old = previous.get(id)
80
+ const unchanged = old && old.item === item && old.index === index && old.descriptor.height === height
81
+ const version = unchanged ? old.descriptor.version : (old?.descriptor.version ?? 0) + 1
82
+ entries.set(id, { item, index, descriptor: { id, type: 'row', version, height } })
83
+ }
84
+ previous = entries
85
+ view.setEstimatedItemSize(height)
86
+ apply(entries)
87
+ }, { flush: 'post' }))
88
+ onBeforeUnmount(() => {
89
+ active = false
90
+ pending = undefined
91
+ view.clearDataSource()
92
+ for (const cell of cells.values()) release(cell)
93
+ cells.clear()
94
+ })
95
+ return () => h('nitro-native', { view, layout: { flexGrow: 1, ...props.layout } })
96
+ },
97
+ })
@@ -0,0 +1,75 @@
1
+ import { defineComponent, h, inject, onBeforeUnmount, onMounted, provide, shallowRef, type Component, type InjectionKey } from '@vue/runtime-core'
2
+ import { NitroModules } from 'nitro-core'
3
+ import type { View, ViewController } from 'nitro-ui-renderer/hybrids'
4
+ import { controllerKey } from './renderer'
5
+
6
+ interface NativeStack extends View {
7
+ attachTo(controller: ViewController): void
8
+ removeFromParent(): void
9
+ addOnPopListener(callback: (count: number) => void): { remove(): void }
10
+ }
11
+
12
+ interface NativeScreen extends View {
13
+ viewController: ViewController
14
+ presentation: 'card' | 'modal'
15
+ headerShown: boolean
16
+ }
17
+
18
+ interface Navigation {
19
+ present(component: Component, props?: Record<string, unknown>): void
20
+ dismiss(): void
21
+ }
22
+ const navigationKey: InjectionKey<Navigation> = Symbol('Navigation')
23
+
24
+ export function useNavigation(): Navigation {
25
+ const navigation = inject(navigationKey)
26
+ if (!navigation) throw new Error('useNavigation() requires a NavigationStack ancestor.')
27
+ return navigation
28
+ }
29
+
30
+ const Screen = defineComponent({
31
+ props: { modal: Boolean },
32
+ setup(props, { slots }) {
33
+ const ScreenClass = NitroModules.getHybridClass<new () => NativeScreen>('navigation.NavigationScreen')
34
+ const view = new ScreenClass()
35
+ view.headerShown = false
36
+ view.presentation = props.modal ? 'modal' : 'card'
37
+ provide(controllerKey, view.viewController)
38
+ const frame = shallowRef(view.viewController.view.getFrame())
39
+ const size = view.viewController.addOnSizeChangedListener(value => {
40
+ frame.value = { ...frame.value, ...value }
41
+ })
42
+ const node = nitroLayout.NLNodeFromHandle(view.layoutNodePtr)
43
+ nitroLayout.NLSetPositionType(node, nitroLayout.NLAbsolute)
44
+ nitroLayout.NLSetInset(node, nitroLayout.NLLeft, 0, nitroLayout.NLPoint)
45
+ nitroLayout.NLSetInset(node, nitroLayout.NLTop, 0, nitroLayout.NLPoint)
46
+ onBeforeUnmount(() => size.remove())
47
+ return () => h('nitro-native', { view, layout: { width: frame.value.width, height: frame.value.height } }, slots.default?.())
48
+ },
49
+ })
50
+
51
+ export const NavigationStack = defineComponent({
52
+ name: 'NavigationStack',
53
+ setup(_, { slots }) {
54
+ const controller = inject(controllerKey)
55
+ if (!controller) throw new Error('A NavigationStack must be mounted in a NitroUI controller.')
56
+ const Stack = NitroModules.getHybridClass<new () => NativeStack>('navigation.NavigationStack')
57
+ const view = new Stack()
58
+ let nextId = 0
59
+ const screens = shallowRef<{ id: number; component: Component; props?: Record<string, unknown> }[]>([])
60
+ function pop(count: number) {
61
+ if (count > 0) screens.value = screens.value.slice(0, Math.max(0, screens.value.length - count))
62
+ }
63
+ provide(navigationKey, {
64
+ present(component, props) { screens.value = [...screens.value, { id: ++nextId, component, props }] },
65
+ dismiss() { pop(1) },
66
+ })
67
+ const back = view.addOnPopListener(pop)
68
+ onMounted(() => view.attachTo(controller))
69
+ onBeforeUnmount(() => { back.remove(); view.removeFromParent() })
70
+ return () => h('nitro-native', { view, layout: { flexGrow: 1 } }, [
71
+ h(Screen, { key: 'root' }, slots),
72
+ ...screens.value.map(screen => h(Screen, { key: screen.id, modal: true }, () => h(screen.component, screen.props))),
73
+ ])
74
+ },
75
+ })
@@ -0,0 +1,26 @@
1
+ import { defineComponent, h, onBeforeUnmount, watchEffect, type PropType } from '@vue/runtime-core'
2
+ import { Application, type View } from 'nitro-ui-renderer/hybrids'
3
+ import { NitroModules } from 'nitro-core'
4
+ import type { Layout } from './layout'
5
+
6
+ type TapGesture = NonNullable<Parameters<View['setGestureRecognizers']>[0]>[number] & { onTap?: () => void }
7
+
8
+ export const Pressable = defineComponent({
9
+ name: 'Pressable',
10
+ props: { disabled: Boolean, layout: Object as PropType<Layout> },
11
+ emits: { press: () => true },
12
+ setup(props, { slots, emit }) {
13
+ const view = Application.createView()
14
+ const Tap = NitroModules.getHybridClass<new () => TapGesture>('renderer.TapGestureRecognizer')
15
+ const tap = new Tap()
16
+ tap.onTap = () => { if (!props.disabled) emit('press') }
17
+ watchEffect(() => { tap.isEnabled = !props.disabled })
18
+ view.setGestureRecognizers([tap])
19
+ onBeforeUnmount(() => {
20
+ view.setGestureRecognizers([])
21
+ tap.onTap = undefined
22
+ tap.dispose()
23
+ })
24
+ return () => h('nitro-native', { view, layout: { ...props.layout } }, slots.default?.())
25
+ },
26
+ })
@@ -0,0 +1,199 @@
1
+ import { createRenderer, type Component, type InjectionKey } from '@vue/runtime-core'
2
+ import { Application, Label, ScrollView, ScrollViewContent, type TextInput, type View, type ViewController } from 'nitro-ui-renderer/hybrids'
3
+ import { sameLayout, updateLayout } from './layout'
4
+
5
+ export const controllerKey: InjectionKey<ViewController> = Symbol('ViewController')
6
+
7
+ type Element = {
8
+ parent: Element | null
9
+ children: HostNode[]
10
+ } & (
11
+ | { kind: 'view'; native: View }
12
+ | { kind: 'label'; native: Label }
13
+ | { kind: 'input'; native: TextInput; stopObserving: () => void; onEdit?: (text: string) => void }
14
+ )
15
+
16
+ type Marker = { kind: 'text' | 'comment'; value: string; parent: Element | null }
17
+ type HostNode = Element | Marker
18
+
19
+ function isElement(node: HostNode): node is Element {
20
+ return 'native' in node
21
+ }
22
+
23
+ function layoutNode(element: Element) {
24
+ return nitroLayout.NLNodeFromHandle(element.native.layoutNodePtr)
25
+ }
26
+
27
+ function syncLabel(parent: Element) {
28
+ if (parent.kind === 'label') {
29
+ parent.native.text = parent.children.map(child => child.kind === 'text' ? child.value : '').join('')
30
+ parent.native.afterUpdate()
31
+ }
32
+ }
33
+
34
+ function detach(child: HostNode) {
35
+ const parent = child.parent
36
+ if (!parent) return
37
+ if (isElement(child)) {
38
+ parent.native.removeChild(child.native)
39
+ nitroLayout.NLRemoveChild(layoutNode(parent), layoutNode(child))
40
+ }
41
+ parent.children.splice(parent.children.indexOf(child), 1)
42
+ child.parent = null
43
+ syncLabel(parent)
44
+ }
45
+
46
+ function dispose(node: HostNode) {
47
+ if (!isElement(node)) return
48
+ if (node.kind === 'input') node.stopObserving()
49
+ node.children.forEach(dispose)
50
+ }
51
+
52
+ export function createHost(native: View, cell = false) {
53
+ const root: Element = { kind: 'view', native, parent: null, children: [] }
54
+ let queued = false
55
+ let active = true
56
+ function flushLayout() {
57
+ if (!active || !queued) return
58
+ queued = false
59
+ const frame = cell ? undefined : native.getFrame()
60
+ const node = layoutNode(root)
61
+ nitroLayout.NLSolve(node, frame?.width ?? NaN, frame?.height ?? NaN)
62
+ nitroLayout.NLApplyLayout(node)
63
+ }
64
+ function requestLayout() {
65
+ if (queued || !active) return
66
+ queued = true
67
+ queueMicrotask(flushLayout)
68
+ }
69
+
70
+ const renderer = createRenderer<HostNode, Element>({
71
+ createElement(tag, _namespace, _is, props) {
72
+ const base = { parent: null, children: [] }
73
+ switch (tag) {
74
+ case 'nitro-native': return { ...base, kind: 'view', native: props!.view }
75
+ case 'nitro-scroll': {
76
+ const native = new ScrollView()
77
+ nitroLayout.NLSetOverflow(nitroLayout.NLNodeFromHandle(native.layoutNodePtr), nitroLayout.NLOverflowScroll)
78
+ return { ...base, kind: 'view', native }
79
+ }
80
+ case 'nitro-scroll-content': return { ...base, kind: 'view', native: new ScrollViewContent() }
81
+ case 'nitro-view': return { ...base, kind: 'view', native: Application.createView() }
82
+ case 'nitro-text': return { ...base, kind: 'label', native: new Label() }
83
+ case 'nitro-input': {
84
+ const native = Application.createTextInput(false)
85
+ const size = native.addOnLayoutInvalidatedListener(requestLayout)
86
+ const element: Element & { kind: 'input' } = {
87
+ ...base, kind: 'input', native,
88
+ stopObserving() {
89
+ size.remove()
90
+ edits.remove()
91
+ element.onEdit = undefined
92
+ },
93
+ }
94
+ const edits = native.addOnTextChangedListener(change => element.onEdit?.(change.text))
95
+ return element
96
+ }
97
+ default: throw new Error(`Unsupported NitroUI element: ${tag}`)
98
+ }
99
+ },
100
+ createText: value => ({ kind: 'text', value, parent: null }),
101
+ createComment: value => ({ kind: 'comment', value, parent: null }),
102
+ parentNode: node => node.parent,
103
+ nextSibling(node) {
104
+ const siblings = node.parent?.children
105
+ return siblings?.[siblings.indexOf(node) + 1] ?? null
106
+ },
107
+ insert(child, parent, anchor) {
108
+ if (anchor === child) return
109
+ if (isElement(child) && parent.kind !== 'view') {
110
+ throw new Error('Only View can contain native elements.')
111
+ }
112
+ if (child.kind === 'text' && child.value.trim() && parent.kind !== 'label') {
113
+ throw new Error('Wrap text in a Text component.')
114
+ }
115
+ detach(child)
116
+ // Vue uses empty text nodes and comments as fragment and v-if anchors.
117
+ const index = anchor ? parent.children.indexOf(anchor) : parent.children.length
118
+ if (isElement(child)) {
119
+ let next: Element | undefined
120
+ for (let i = index; i < parent.children.length; i++) {
121
+ const candidate = parent.children[i]
122
+ if (isElement(candidate)) { next = candidate; break }
123
+ }
124
+ if (next) {
125
+ parent.native.insertBefore(child.native, next.native)
126
+ nitroLayout.NLInsertBefore(layoutNode(parent), layoutNode(child), layoutNode(next))
127
+ } else {
128
+ parent.native.appendChild(child.native)
129
+ nitroLayout.NLAppendChild(layoutNode(parent), layoutNode(child))
130
+ }
131
+ }
132
+ parent.children.splice(index, 0, child)
133
+ child.parent = parent
134
+ syncLabel(parent)
135
+ requestLayout()
136
+ },
137
+ remove(node) {
138
+ detach(node)
139
+ dispose(node)
140
+ requestLayout()
141
+ },
142
+ setText(node, text) {
143
+ if (isElement(node)) throw new Error('Expected a Vue text node.')
144
+ node.value = text
145
+ if (node.parent) syncLabel(node.parent)
146
+ requestLayout()
147
+ },
148
+ setElementText(node, text) {
149
+ if (node.kind === 'label' && node.children.length === 1 && node.children[0].kind === 'text') {
150
+ node.children[0].value = text
151
+ syncLabel(node)
152
+ requestLayout()
153
+ return
154
+ }
155
+ for (const child of [...node.children]) {
156
+ detach(child)
157
+ dispose(child)
158
+ }
159
+ if (node.kind === 'label') {
160
+ node.children.push({ kind: 'text', value: text, parent: node })
161
+ syncLabel(node)
162
+ } else if (text.trim()) {
163
+ throw new Error('Wrap text in a Text component.')
164
+ }
165
+ requestLayout()
166
+ },
167
+ patchProp(node, key, previous, next) {
168
+ if (key === 'layout') {
169
+ if (sameLayout(next ?? {}, previous ?? {})) return
170
+ updateLayout(layoutNode(node), next ?? {}, previous ?? {})
171
+ }
172
+ else if (key === 'fontSize' && node.kind === 'label') node.native.fontSize = next ?? 17
173
+ else if (key === 'modelValue' && node.kind === 'input') node.native.setText(next ?? '')
174
+ else if (key === 'placeholder' && node.kind === 'input') node.native.placeholder = next ?? undefined
175
+ else if (key === 'onEdit' && node.kind === 'input') {
176
+ node.onEdit = next ?? undefined
177
+ return
178
+ } else return
179
+ node.native.afterUpdate()
180
+ requestLayout()
181
+ },
182
+ })
183
+
184
+ return { renderer, root, requestLayout, flushLayout, stop() { active = false } }
185
+ }
186
+
187
+ /** Mount a Vue tree into an existing native controller. Call app.unmount() to detach it. */
188
+ export function mount(component: Component, controller: ViewController) {
189
+ const host = createHost(controller.view)
190
+ const app = host.renderer.createApp(component)
191
+ app.provide(controllerKey, controller)
192
+ const size = controller.addOnSizeChangedListener(host.requestLayout)
193
+ app.onUnmount(() => {
194
+ host.stop()
195
+ size.remove()
196
+ })
197
+ app.mount(host.root)
198
+ return app
199
+ }