@nativue/core 0.9.0 → 0.11.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/AGENTS.md ADDED
@@ -0,0 +1,98 @@
1
+ # nativue: guide for coding agents
2
+
3
+ This app is built with nativue: Vue 3 single-file components rendered as real native views on iOS and
4
+ Android. It is not a web app. There is no DOM, no browser and no CSS, so web habits produce code that
5
+ doesn't work. Full docs: https://github.com/nativue/nativue/tree/main/docs
6
+
7
+ ## What doesn't exist
8
+
9
+ - HTML elements (`<div>`, `<span>`, `<p>`, `<img>`, `<button>`, `<input>`, `<ul>`...): use the
10
+ components below.
11
+ - CSS: `<style>` blocks, class names from a stylesheet, `px`/`rem`/`em` units, `:hover`, media queries.
12
+ A `.vue` file's `<style>` block is left out of the build.
13
+ - Browser globals: `window`, `document`, `localStorage`, `sessionStorage`, `navigator`, `alert`.
14
+ Use `AsyncStorage` for storage.
15
+ - Vue Router and `main.ts`: routing is file-based (below), and nativue creates the app.
16
+
17
+ ## Components
18
+
19
+ Global, with no import: `View`, `Text`, `Image`, `ImageBackground`, `Pressable`, `Button`, `TextInput`,
20
+ `Switch`, `ScrollView`, `FlatList`, `Swipeable`, `Modal`, `ActivityIndicator`, `SafeAreaView`,
21
+ `KeyboardAvoidingView`, `Svg`.
22
+
23
+ - Text must be inside a `<Text>`, never directly in a `<View>`.
24
+ - Taps: `<Pressable @press="save">` (also `@long-press`, and `v-slot="{ pressed }"`), or
25
+ `<Button title="Save" @press="save" />`. There is no `@click`.
26
+ - Inputs: `<TextInput v-model="name" placeholder="Name" @submit-editing="save" />`.
27
+ - Images: `import logo from '@/assets/logo.png'` then `<Image :source="logo" />`; remote ones as
28
+ `:source="{ uri: url }"`. A remote image has no size until it loads: give it a width and height
29
+ where the layout shouldn't jump, like a list's rows.
30
+ - Long lists: `<FlatList :data="items" :key-extractor="(item) => item.id">` with a
31
+ `<template #item="{ item }">` slot, not `v-for` in a `ScrollView`.
32
+
33
+ ## Styling
34
+
35
+ - `style` takes an object with CSS properties in camelCase and numbers in points, no units:
36
+ `:style="{ padding: 16, borderRadius: 12, backgroundColor: '#ffffff' }"`. Arrays merge, later wins:
37
+ `:style="[styles.card, selected && styles.selected]"`.
38
+ - `StyleSheet.create({...})` (from `vue`) groups and types a screen's styles.
39
+ - Every view is a flexbox container stacking its children in a **column** by default; `flex: 1` takes
40
+ the space left. Percentages (`'50%'`) work for sizes.
41
+ - Text styles (`color`, `fontSize`, `fontWeight`, `textAlign`, `textDecorationLine`) go on the
42
+ `<Text>` itself: native views don't inherit them from their parents.
43
+ - Pressed and focused states: `pressed-style` on `Pressable`, `focused-style` on `TextInput`.
44
+ - Dark mode: `useColorScheme()` (from `vue`) gives `'light'` or `'dark'`, live.
45
+ - Platform: `Platform.OS` is `'ios'` or `'android'`; `Platform.select({ ios, android })`.
46
+ - If the app uses `@nativue/tailwind` (see `nativue.config.ts`), Tailwind classes work in `class`,
47
+ with the `active:`, `focus:`, `disabled:`, `dark:`, `ios:` and `android:` variants.
48
+
49
+ ## Navigation
50
+
51
+ Every `.vue` file in `src/app` is a screen, and its path is its URL:
52
+
53
+ | File | URL |
54
+ | --------------------- | ------------------------------------------------------ |
55
+ | `app/index.vue` | `/` |
56
+ | `app/items/[id].vue` | `/items/42`, param `id` |
57
+ | `app/(tabs)/home.vue` | `/home`: a folder in parentheses groups without a path |
58
+ | `app/_layout.vue` | the layout of its folder: a `<Stack>` or a `<Tabs>` |
59
+ | `app/+not-found.vue` | shown when no route matches |
60
+
61
+ Import navigation from `@nativue/core/router`:
62
+
63
+ - `<Link href="/items/42">` (a Pressable); `router.push(path)`, `router.navigate(path)`,
64
+ `router.replace(path)`, `router.back()`.
65
+ - `useLocalSearchParams<{ id: string }>()` reads params and the query string.
66
+ - `<Stack.Screen :options="{ title: 'Item' }" />` inside a screen sets its header; in a layout,
67
+ `<Stack.Screen name="modal" :options="{ presentation: 'modal' }" />` sets a route's options.
68
+
69
+ ## APIs
70
+
71
+ Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `LayoutAnimation`,
72
+ `Platform`, `AsyncStorage`, `Keyboard`, `Dimensions`, `useWindowDimensions`, `useColorScheme`,
73
+ `AccessibilityInfo`, `requireNativeFunction`.
74
+
75
+ - `AsyncStorage`: `getItem`, `setItem`, `removeItem`, `getAllKeys`, `multiGet`, `multiSet`,
76
+ `clear`; promise-based, string values. Store objects as JSON. For large data or queries, use
77
+ `@nativue/sqlite`.
78
+ - `fetch`, `XMLHttpRequest`, `Blob`, `FileReader`, `URL`, `URLSearchParams`, timers and `console`
79
+ work as on the web, with no import.
80
+ - Accessibility: `role` and `aria-*` attributes (`aria-label`, `aria-hidden`...) on any component.
81
+
82
+ ## Project
83
+
84
+ - `@/` points at `src/`. Shared components go in `src/components`, everything else in `src/lib`.
85
+ - Vue plugins (Pinia...) are installed in `src/app.ts`: `export default function setup(app: App)`.
86
+ - Official packages: `@nativue/icons` (icon components), `@nativue/tailwind`, `@nativue/haptics`,
87
+ `@nativue/sqlite`. A package with native code needs the app rebuilt with `npm run ios` or
88
+ `npm run android`, not just a reload.
89
+ - Commands: `npm run ios` / `npm run android` build and open the app, then reload on save;
90
+ `npm run typecheck` checks scripts and templates; `npm run build` makes the release bundle;
91
+ `npm run format` formats with Prettier.
92
+ - Native code the app needs (a platform API no package covers) goes in `native/<name>/ios` and
93
+ `native/<name>/android`, as `<Name>Plugin` classes registering functions JavaScript calls with
94
+ `requireNativeFunction`; libraries it uses (Swift packages, Maven) go in `native/<name>/nativue.json`.
95
+ See the docs' "Native code in your app". Rebuild after changing it.
96
+ - Check changes with `npm run typecheck`. `ios/` and `android/` are the native host apps: change them
97
+ only for native settings (permissions in `Info.plist` or `AndroidManifest.xml`, the app's name and
98
+ icon).
@@ -2,7 +2,10 @@
2
2
  // package.json has
3
3
  // "nativue": { "android": { "sources": "android", "plugin": "dev.nativue.haptics.HapticsPlugin" } }
4
4
  // becomes modules the app depends on (sources: the folder with build.gradle.kts, which depends on
5
- // project(":nativue")). The plugin classes reach the app as the string resource nativue_plugins.
5
+ // project(":nativue")). The app's own native code, native/<name>/android, is compiled into the app;
6
+ // its plugin is <Name>Plugin, with no package, and native/<name>/nativue.json can list the Maven
7
+ // libraries it uses: { "android": { "dependencies": ["com.squareup.okhttp3:okhttp:4.12.0"] } }.
8
+ // The plugin classes reach the app as the string resource nativue_plugins.
6
9
  import groovy.json.JsonSlurper
7
10
  import java.io.File
8
11
 
@@ -36,8 +39,24 @@ fun androidPlugin(name: String, appDirectory: File): AndroidPlugin? {
36
39
  return AndroidPlugin(projectPath, android["plugin"] as String)
37
40
  }
38
41
 
42
+ /** 'face-id' -> 'FaceId', as the CLI names the iOS side. */
43
+ fun pascalCase(name: String): String =
44
+ name.split(Regex("[^a-zA-Z0-9]+")).filter { it.isNotEmpty() }.joinToString("") { it.replaceFirstChar(Char::uppercaseChar) }
45
+
39
46
  val appDirectory: File = settingsDir.parentFile
40
47
  val androidPlugins = dependencyNames(appDirectory).mapNotNull { name -> androidPlugin(name, appDirectory) }
48
+ val appSourceDirectories = File(appDirectory, "native").listFiles().orEmpty()
49
+ .sortedBy { it.name }
50
+ .map { File(it, "android") }
51
+ .filter { it.isDirectory }
52
+ val appPluginClasses = appSourceDirectories.map { pascalCase(it.parentFile.name) + "Plugin" }
53
+ val appLibraries = appSourceDirectories
54
+ .map { File(it.parentFile, "nativue.json") }
55
+ .filter { it.isFile }
56
+ .flatMap { ((readJson(it)["android"] as? Map<*, *>)?.get("dependencies") as? List<*>).orEmpty() }
57
+ .map { it.toString() }
58
+ .distinct()
59
+ val pluginClasses = androidPlugins.map { it.pluginClass } + appPluginClasses
41
60
 
42
61
  // Through Groovy's dynamic calls: the Android Gradle plugin's types aren't on a settings script's classpath.
43
62
  gradle.beforeProject {
@@ -45,11 +64,20 @@ gradle.beforeProject {
45
64
 
46
65
  pluginManager.withPlugin("com.android.application") {
47
66
  androidPlugins.forEach { plugin -> dependencies.add("implementation", project(plugin.projectPath)) }
67
+ appLibraries.forEach { library -> dependencies.add("implementation", library) }
48
68
 
49
69
  extensions.getByName("android").withGroovyBuilder {
50
70
  "getBuildFeatures"()!!.withGroovyBuilder { "setResValues"(true) }
51
71
  "getDefaultConfig"()!!.withGroovyBuilder {
52
- "resValue"("string", "nativue_plugins", androidPlugins.joinToString(",") { it.pluginClass })
72
+ "resValue"("string", "nativue_plugins", pluginClasses.joinToString(","))
73
+ }
74
+ "getSourceSets"()!!.withGroovyBuilder {
75
+ "getByName"("main")!!.withGroovyBuilder {
76
+ // Kotlin and Java: each source set compiles only its own language.
77
+ listOf("getKotlin", "getJava").forEach { sourceSet ->
78
+ sourceSet()!!.withGroovyBuilder { appSourceDirectories.forEach { "srcDir"(it) } }
79
+ }
80
+ }
53
81
  }
54
82
  }
55
83
  }
package/cli/link.mjs CHANGED
@@ -3,6 +3,10 @@
3
3
  // ios/NativuePlugins becomes a Swift package with a target per package (a link to its sources) and
4
4
  // `nativuePlugins`, the list App.swift passes to NativueView. The app's Xcode project depends on it
5
5
  // alone; it re-exports Nativue. (Android finds them itself: android/nativue.settings.gradle.kts.)
6
+ // The app's own native code links the same way: native/<name>/ios, whose plugin is <Name>Plugin.
7
+ // Swift packages the native code uses are listed in "ios": { "dependencies": [...] }, in the
8
+ // package.json's "nativue" field or native/<name>/nativue.json:
9
+ // { "url": "https://github.com/stripe/stripe-ios-spm", "from": "24.0.0", "products": ["StripePaymentSheet"] }
6
10
  import {
7
11
  existsSync,
8
12
  mkdirSync,
@@ -18,6 +22,7 @@ import { dirname, join, relative, resolve } from 'node:path'
18
22
  const PLUGINS_DIRECTORY = 'ios/NativuePlugins'
19
23
  const SOURCES_DIRECTORY = `${PLUGINS_DIRECTORY}/Sources`
20
24
  const LIST_TARGET = 'NativuePlugins'
25
+ const APP_NATIVE_DIRECTORY = 'native'
21
26
 
22
27
  function readJson(path) {
23
28
  return JSON.parse(readFileSync(path, 'utf8'))
@@ -50,7 +55,36 @@ function iosPlugins() {
50
55
  const ios = directory && readJson(join(directory, 'package.json')).nativue?.ios
51
56
  if (!ios) return []
52
57
 
53
- return [{ module: moduleName(name), sources: join(directory, ios.sources), plugin: ios.plugin }]
58
+ return [
59
+ {
60
+ module: moduleName(name),
61
+ sources: join(directory, ios.sources),
62
+ plugin: ios.plugin,
63
+ dependencies: ios.dependencies ?? [],
64
+ },
65
+ ]
66
+ })
67
+ }
68
+
69
+ /** native/<name>/ios: module App<Name> (not <Name>, which could hide a system module like Photos). */
70
+ function appPlugins() {
71
+ if (!existsSync(APP_NATIVE_DIRECTORY)) return []
72
+
73
+ return readdirSync(APP_NATIVE_DIRECTORY).flatMap((name) => {
74
+ const sources = resolve(APP_NATIVE_DIRECTORY, name, 'ios')
75
+ if (!existsSync(sources)) return []
76
+
77
+ const settingsPath = join(APP_NATIVE_DIRECTORY, name, 'nativue.json')
78
+ const settings = existsSync(settingsPath) ? readJson(settingsPath) : {}
79
+
80
+ return [
81
+ {
82
+ module: `App${moduleName(name)}`,
83
+ sources,
84
+ plugin: `${moduleName(name)}Plugin`,
85
+ dependencies: settings.ios?.dependencies ?? [],
86
+ },
87
+ ]
54
88
  })
55
89
  }
56
90
 
@@ -81,12 +115,37 @@ function linkSources(plugins) {
81
115
  }
82
116
  }
83
117
 
118
+ /** SwiftPM's identity of a package: the last part of its URL, without .git, lowercased. */
119
+ function packageIdentity(url) {
120
+ return url
121
+ .replace(/\.git$/, '')
122
+ .split('/')
123
+ .pop()
124
+ .toLowerCase()
125
+ }
126
+
127
+ /** One `.package` per URL: the first plugin to list a package sets its version. */
128
+ function swiftPackages(plugins) {
129
+ const versionsByUrl = new Map()
130
+ plugins.forEach(({ dependencies }) =>
131
+ dependencies.forEach(({ url, from }) => versionsByUrl.has(url) || versionsByUrl.set(url, from)),
132
+ )
133
+
134
+ return [...versionsByUrl].map(
135
+ ([url, from]) => ` .package(url: "${url}", from: "${from}"),\n`,
136
+ )
137
+ }
138
+
84
139
  function packageManifest(plugins, corePath) {
85
140
  const nativue = '.product(name: "Nativue", package: "core")'
86
- const pluginTargets = plugins.map(
87
- ({ module }) =>
88
- ` .target(name: "${module}", dependencies: [${nativue}], path: "Sources/${module}"),\n`,
89
- )
141
+ const pluginTargets = plugins.map(({ module, dependencies }) => {
142
+ const products = dependencies.flatMap(({ url, products }) =>
143
+ products.map((product) => `.product(name: "${product}", package: "${packageIdentity(url)}")`),
144
+ )
145
+ const targetDependencies = [nativue, ...products].join(', ')
146
+
147
+ return ` .target(name: "${module}", dependencies: [${targetDependencies}], path: "Sources/${module}"),\n`
148
+ })
90
149
  const listDependencies = [nativue, ...plugins.map(({ module }) => `"${module}"`)].join(', ')
91
150
 
92
151
  return `// swift-tools-version: 5.9
@@ -97,7 +156,9 @@ let package = Package(
97
156
  name: "NativuePlugins",
98
157
  platforms: [.iOS(.v17)],
99
158
  products: [.library(name: "NativuePlugins", targets: ["${LIST_TARGET}"])],
100
- dependencies: [.package(path: "${corePath}")],
159
+ dependencies: [
160
+ .package(path: "${corePath}"),
161
+ ${swiftPackages(plugins).join('')} ],
101
162
  targets: [
102
163
  ${pluginTargets.join('')} .target(name: "${LIST_TARGET}", dependencies: [${listDependencies}], path: "Sources/${LIST_TARGET}"),
103
164
  ]
@@ -120,7 +181,7 @@ public let nativuePlugins: [NativuePlugin] = [${instances}]
120
181
  export function linkIosPlugins(coreDirectory) {
121
182
  if (!existsSync('ios') || !existsSync('package.json')) return
122
183
 
123
- const plugins = iosPlugins()
184
+ const plugins = [...iosPlugins(), ...appPlugins()]
124
185
  const corePath = relative(resolve(PLUGINS_DIRECTORY), coreDirectory)
125
186
 
126
187
  linkSources(plugins)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Vue rendering real native views on iOS and Android",
5
5
  "keywords": [
6
6
  "vue",
@@ -56,7 +56,8 @@
56
56
  "android/build.gradle.kts",
57
57
  "android/consumer-rules.pro",
58
58
  "android/nativue.settings.gradle.kts",
59
- "android/src"
59
+ "android/src",
60
+ "AGENTS.md"
60
61
  ],
61
62
  "publishConfig": {
62
63
  "access": "public"
package/src/xhr.ts CHANGED
@@ -381,7 +381,8 @@ export class XMLHttpRequest extends EventTarget {
381
381
 
382
382
  private parseResponse(): unknown {
383
383
  if (this.chosenResponseType === 'blob') return this.blobResponse
384
- if (this.chosenResponseType === 'arraybuffer') return (this.bytesResponse ?? new Uint8Array()).buffer
384
+ if (this.chosenResponseType === 'arraybuffer')
385
+ return (this.bytesResponse ?? new Uint8Array()).buffer
385
386
 
386
387
  try {
387
388
  return JSON.parse(this.rawResponse)