@octane-xplat/media 0.0.1 → 0.10.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Alec Larson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,55 @@
1
- # @octane-xplat/media
1
+ # `@octane-xplat/media`
2
2
 
3
- Version 0.0.1 is a reservation stub so the automated release can publish this package name. It has no supported API. Use a later release for the implementation.
3
+ ```sh
4
+ pnpm add @octane-xplat/media
5
+ ```
6
+
7
+ Still-image picking and OS camera capture for Octane xplat apps. iOS runs
8
+ `@nativescript/imagepicker` + `@nativescript/camera`, Android the same
9
+ plugins over its photo picker/camera intent; web uses `<input
10
+ type="file">` (with the `capture` attribute for camera shots, which mobile
11
+ browsers route to the camera app); the macOS AppKit dev host reports
12
+ `unsupported`.
13
+
14
+ ```ts
15
+ import { media } from '@octane-xplat/media'
16
+
17
+ await media.ensure('photos')
18
+ const image = await media.pickImage() // null when the user cancels
19
+ const shot = await media.capturePhoto()
20
+ ```
21
+
22
+ Every method returns a `PickedImage` — `FileRef` (`name`, opaque `uri`)
23
+ plus a `dataUrl` you can hand straight to `Image src`. Cancellation
24
+ resolves `null` (or `[]` for `pickImages`), so check the result rather
25
+ than catching. `ensure('camera' | 'photos')` resolves
26
+ `'granted' | 'denied' | 'unsupported'`.
27
+
28
+ ```tsx
29
+ import { useState } from 'octane'
30
+ import { Button, Image } from '@octane-xplat/ui'
31
+ import { media } from '@octane-xplat/media'
32
+
33
+ export function PhotoPicker() {
34
+ const [preview, setPreview] = useState<string | null>(null)
35
+ async function pickPhoto() {
36
+ if ((await media.ensure('photos')) !== 'granted') return
37
+ const photo = await media.pickImage()
38
+ if (photo) setPreview(photo.dataUrl)
39
+ }
40
+ return (
41
+ <>
42
+ <Button onPress={pickPhoto}>Choose photo</Button>
43
+ {preview && <Image src={preview} alt="Selected photo" />}
44
+ </>
45
+ )
46
+ }
47
+ ```
48
+
49
+ For a live preview surface instead of one-shot capture, use
50
+ [`@octane-xplat/camera`](../camera/README.md)'s `CameraView`.
51
+
52
+ Guide: [Using device features](../../docs/platform/platform-services.md);
53
+ per-target availability: [platform notes](../../docs/notes/platform-notes.md).
54
+ Exercised by the harness `Services` screen and
55
+ [`CameraDemo`](../demos/src/CameraDemo.tsrx).
package/package.json CHANGED
@@ -1,19 +1,71 @@
1
1
  {
2
2
  "name": "@octane-xplat/media",
3
- "version": "0.0.1",
3
+ "version": "0.10.0",
4
4
  "description": "Image picking and OS camera capture for Octane xplat — matching web + NativeScript implementations",
5
+ "keywords": [
6
+ "android",
7
+ "camera",
8
+ "cross-platform",
9
+ "image-picker",
10
+ "ios",
11
+ "media",
12
+ "nativescript",
13
+ "octane",
14
+ "photo",
15
+ "web",
16
+ "xplat"
17
+ ],
18
+ "homepage": "https://github.com/octane-xplat/octane-xplat/tree/main/packages/media",
5
19
  "license": "MIT",
6
20
  "repository": {
7
21
  "type": "git",
8
- "url": "https://github.com/octane-xplat/octane-xplat.git",
22
+ "url": "https://github.com/octane-xplat/octane-xplat",
9
23
  "directory": "packages/media"
10
24
  },
11
- "homepage": "https://github.com/octane-xplat/octane-xplat/tree/main/packages/media",
12
- "main": "./index.js",
13
- "types": "./index.d.ts",
14
25
  "files": [
15
- "README.md",
16
- "index.js",
17
- "index.d.ts"
18
- ]
19
- }
26
+ "src"
27
+ ],
28
+ "type": "module",
29
+ "exports": {
30
+ ".": {
31
+ "macos": "./src/index.macos.ts",
32
+ "default": "./src/index.ts"
33
+ },
34
+ "./*": "./src/*"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "dependencies": {
40
+ "@nativescript/camera": "7.0.0",
41
+ "@nativescript/imagepicker": "5.0.0"
42
+ },
43
+ "devDependencies": {
44
+ "@nativescript-community/octane": "0.2.4",
45
+ "@nativescript/core": "9.1.2",
46
+ "@nativescript/types": "9.0.0",
47
+ "octane": "0.6.3"
48
+ },
49
+ "peerDependencies": {
50
+ "@nativescript-community/octane": ">=0.2.1 <1",
51
+ "@nativescript/core": ">=9.1.0 <10",
52
+ "octane": ">=0.6.3 <1"
53
+ },
54
+ "peerDependenciesMeta": {
55
+ "@nativescript-community/octane": {
56
+ "optional": true
57
+ },
58
+ "@nativescript/core": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "nativescript": {
63
+ "platforms": {
64
+ "android": "9.1.0",
65
+ "ios": "9.1.0"
66
+ }
67
+ },
68
+ "scripts": {
69
+ "test": "node --test tests/*.test.mjs"
70
+ }
71
+ }
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { media } from './media.macos'
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { media } from './media'
@@ -0,0 +1,18 @@
1
+ // Media — AppKit host leaf. No picker or capture flow is wired on the
2
+ // desktop dev host.
3
+ import type { MediaImpl } from './types'
4
+
5
+ export const media: MediaImpl = {
6
+ async ensure() {
7
+ return 'unsupported'
8
+ },
9
+ async pickImage() {
10
+ return null
11
+ },
12
+ async pickImages() {
13
+ return []
14
+ },
15
+ async capturePhoto() {
16
+ return null
17
+ },
18
+ }
package/src/media.ts ADDED
@@ -0,0 +1,197 @@
1
+ // Media picking + camera capture — store a temporary JPEG for NativeScript
2
+ // Image and return a data URL for APIs that persist image payloads. Camera
3
+ // capture is stills only: @nativescript/camera presents the OS capture UI
4
+ // (UIImagePickerController on iOS, ACTION_IMAGE_CAPTURE on Android).
5
+ import { isAvailable as isCameraAvailable, takePicture } from '@nativescript/camera'
6
+
7
+ import { create as createImagePicker } from '@nativescript/imagepicker'
8
+ // Ambient const enum — verbatimModuleSyntax forbids value access; Image = 1.
9
+ import type { ImagePickerMediaType } from '@nativescript/imagepicker'
10
+ import { Application, File, ImageSource, knownFolders, path } from '@nativescript/core'
11
+ import type {
12
+ CapturePhotoOptions,
13
+ MediaImpl,
14
+ MediaPermissionKind,
15
+ PermissionResult,
16
+ PickedImage,
17
+ } from './types'
18
+
19
+ async function ensurePhotos(): Promise<PermissionResult> {
20
+ try {
21
+ const picker = createImagePicker({ mode: 'single', mediaType: 1 as ImagePickerMediaType })
22
+ const permission = (await picker.authorize()) as { authorized?: boolean } | boolean
23
+ return permission === true || (typeof permission === 'object' && permission.authorized === true)
24
+ ? 'granted'
25
+ : 'denied'
26
+ } catch {
27
+ return 'denied'
28
+ }
29
+ }
30
+
31
+ let cameraRequestCode = 7717
32
+
33
+ // Request camera access through the platform primitives directly rather than
34
+ // @nativescript/camera's requestCameraPermissions(): it delegates to
35
+ // @nativescript-community/perms, and the bundler may resolve a perms major
36
+ // whose return shape the plugin's status mapper can't read (3.x Status
37
+ // string vs the 2.x `[status, bool]` array) — a granted permission then maps
38
+ // to 'denied'. The direct paths can't drift with that dependency.
39
+ async function ensureCamera(): Promise<PermissionResult> {
40
+ try {
41
+ if (!isCameraAvailable()) {
42
+ return 'unsupported'
43
+ }
44
+
45
+ if (Application.ios) {
46
+ const av = (globalThis as any).AVCaptureDevice
47
+ const video = (globalThis as any).AVMediaTypeVideo
48
+ // 0=notDetermined 1=restricted 2=denied 3=authorized
49
+ const status = av?.authorizationStatusForMediaType?.(video)
50
+ if (status === 3) {
51
+ return 'granted'
52
+ }
53
+
54
+ if (status === 1 || status === 2) {
55
+ return 'denied'
56
+ }
57
+
58
+ return await new Promise<PermissionResult>((resolve) => {
59
+ av.requestAccessForMediaTypeCompletionHandler(video, (granted: boolean) =>
60
+ resolve(granted ? 'granted' : 'denied'),
61
+ )
62
+ })
63
+ }
64
+
65
+ const perm = 'android.permission.CAMERA'
66
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
67
+
68
+ if (
69
+ activity?.checkSelfPermission?.(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED
70
+ ) {
71
+ return 'granted'
72
+ }
73
+
74
+ if (!activity) {
75
+ return 'denied'
76
+ }
77
+
78
+ return await new Promise<PermissionResult>((resolve) => {
79
+ const requestCode = cameraRequestCode++
80
+ const onResult = (args: any) => {
81
+ if (args.requestCode !== requestCode) {
82
+ return
83
+ }
84
+
85
+ Application.android.off(Application.android.activityRequestPermissionsEvent, onResult)
86
+
87
+ resolve(
88
+ args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
89
+ ? 'granted'
90
+ : 'denied',
91
+ )
92
+ }
93
+
94
+ Application.android.on(Application.android.activityRequestPermissionsEvent, onResult)
95
+
96
+ activity.requestPermissions([perm], requestCode)
97
+ })
98
+ } catch (e) {
99
+ console.log('[media] ensureCamera error: ' + (e as Error)?.message)
100
+ return 'denied'
101
+ }
102
+ }
103
+
104
+ async function persistImage(source: ImageSource, name: string): Promise<PickedImage> {
105
+ const filename = `octane-image-${Date.now()}-${Math.random().toString(36).slice(2)}.jpg`
106
+ const uri = path.join(knownFolders.temp().path, filename)
107
+ try {
108
+ const saved = await source.saveToFileAsync(uri, 'jpeg', 85)
109
+ if (!saved) {
110
+ throw new Error('Could not save the image to temporary storage')
111
+ }
112
+
113
+ const base64 = await source.toBase64StringAsync('jpeg', 85)
114
+ return { name, uri, dataUrl: `data:image/jpeg;base64,${base64}` }
115
+ } catch (error) {
116
+ // This operation owns this generated path, including a partial save.
117
+ try {
118
+ File.fromPath(uri).removeSync()
119
+ } catch {}
120
+
121
+ throw error
122
+ }
123
+ }
124
+
125
+ async function pickSelections(mode: 'single' | 'multiple'): Promise<PickedImage[]> {
126
+ const picker = createImagePicker({ mode, mediaType: 1 as ImagePickerMediaType })
127
+ const permission = (await picker.authorize()) as { authorized?: boolean } | boolean
128
+ if (
129
+ !(permission === true || (typeof permission === 'object' && permission.authorized === true))
130
+ ) {
131
+ return []
132
+ }
133
+
134
+ const selections = await picker.present()
135
+ const refs: PickedImage[] = []
136
+ try {
137
+ for (const selection of selections) {
138
+ const source = await ImageSource.fromAsset(selection.asset)
139
+ const name = selection.originalFilename || selection.filename || 'image.jpg'
140
+ refs.push(await persistImage(source, name))
141
+ }
142
+
143
+ return refs
144
+ } catch (error) {
145
+ for (const ref of refs) {
146
+ try {
147
+ File.fromPath(ref.uri).removeSync()
148
+ } catch {}
149
+ }
150
+
151
+ throw error
152
+ }
153
+ }
154
+
155
+ export const media: MediaImpl = {
156
+ /** Opens the native image picker; returns null when canceled. */
157
+ async pickImage(): Promise<PickedImage | null> {
158
+ const [image] = await pickSelections('single')
159
+ return image ?? null
160
+ },
161
+ /** Opens the native image picker in multiple-selection mode. */
162
+ pickImages() {
163
+ return pickSelections('multiple')
164
+ },
165
+ /** Presents the OS camera UI; null when canceled, denied, or unsupported. */
166
+ async capturePhoto(options?: CapturePhotoOptions): Promise<PickedImage | null> {
167
+ if ((await ensureCamera()) !== 'granted') {
168
+ return null
169
+ }
170
+
171
+ try {
172
+ const asset = await takePicture({
173
+ width: options?.width,
174
+ height: options?.height,
175
+ keepAspectRatio: options?.keepAspectRatio,
176
+ saveToGallery: options?.saveToGallery ?? false,
177
+ cameraFacing: options?.cameraFacing,
178
+ })
179
+
180
+ const source = await ImageSource.fromAsset(asset)
181
+ return await persistImage(source, `octane-capture-${Date.now()}.jpg`)
182
+ } catch {
183
+ return null
184
+ }
185
+ },
186
+ async ensure(kind: MediaPermissionKind): Promise<PermissionResult> {
187
+ return kind === 'photos' ? ensurePhotos() : ensureCamera()
188
+ },
189
+ }
190
+
191
+ // Register the permission owners this leaf provides so
192
+ // @octane-xplat/platform's `permissions.ensure(kind)` can reach them without
193
+ // a dependency edge — the generic seam reports 'unsupported' when the leaf
194
+ // is not installed.
195
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
196
+ permissionOwners.camera = () => ensureCamera()
197
+ permissionOwners.photos = () => ensurePhotos()
@@ -0,0 +1,122 @@
1
+ // Media picking — web leaf. Keep an object URL for previews and a data URL for
2
+ // APIs that persist image payloads. The file input supports multiple photos.
3
+ import type {
4
+ CapturePhotoOptions,
5
+ MediaImpl,
6
+ MediaPermissionKind,
7
+ PermissionResult,
8
+ PickedImage,
9
+ } from './types'
10
+
11
+ function selectFiles(multiple: boolean, capture?: 'user' | 'environment'): Promise<File[]> {
12
+ return new Promise((resolve) => {
13
+ const input = document.createElement('input')
14
+ input.type = 'file'
15
+ input.accept = 'image/*'
16
+ input.multiple = multiple
17
+ if (capture) {
18
+ input.capture = capture
19
+ }
20
+
21
+ input.onchange = () => resolve(Array.from(input.files ?? []))
22
+ input.oncancel = () => resolve([])
23
+ input.click()
24
+ })
25
+ }
26
+
27
+ function readDataUrl(file: File): Promise<string> {
28
+ return new Promise((resolve, reject) => {
29
+ const reader = new FileReader()
30
+ reader.onload = () => {
31
+ if (typeof reader.result === 'string') {
32
+ resolve(reader.result)
33
+ } else {
34
+ reject(new Error('Could not read the selected image'))
35
+ }
36
+ }
37
+
38
+ reader.onerror = () => reject(reader.error ?? new Error('Could not read the selected image'))
39
+
40
+ reader.readAsDataURL(file)
41
+ })
42
+ }
43
+
44
+ async function imageRefs(selected: File[]): Promise<PickedImage[]> {
45
+ // Finish every fallible read before allocating preview URLs. A failed batch
46
+ // cannot return its successful siblings, so those need no retained previews.
47
+ const dataUrls = await Promise.all(selected.map(readDataUrl))
48
+ const refs: PickedImage[] = []
49
+ try {
50
+ for (const [index, file] of selected.entries()) {
51
+ refs.push({ name: file.name, uri: URL.createObjectURL(file), dataUrl: dataUrls[index]! })
52
+ }
53
+
54
+ return refs
55
+ } catch (error) {
56
+ for (const ref of refs) {
57
+ URL.revokeObjectURL(ref.uri)
58
+ }
59
+
60
+ throw error
61
+ }
62
+ }
63
+
64
+ async function pickFiles(multiple: boolean): Promise<PickedImage[]> {
65
+ return imageRefs(await selectFiles(multiple))
66
+ }
67
+
68
+ export const media: MediaImpl = {
69
+ /** Opens the browser image picker; returns null when selection is canceled. */
70
+ async pickImage(): Promise<PickedImage | null> {
71
+ const [image] = await pickFiles(false)
72
+ return image ?? null
73
+ },
74
+ /** Opens the browser image picker with multiple selection enabled. */
75
+ pickImages() {
76
+ return pickFiles(true)
77
+ },
78
+ /**
79
+ * Requests a camera shot via `<input type="file" capture>`. Mobile browsers
80
+ * open the camera UI; desktop browsers fall back to the file picker —
81
+ * there is no headless still-capture API without a rendered viewfinder.
82
+ * `width`/`height`/`keepAspectRatio`/`saveToGallery` have no web meaning
83
+ * and are ignored.
84
+ */
85
+ async capturePhoto(options?: CapturePhotoOptions): Promise<PickedImage | null> {
86
+ const facing = options?.cameraFacing === 'front' ? 'user' : 'environment'
87
+ const [file] = await selectFiles(false, facing)
88
+ if (!file) {
89
+ return null
90
+ }
91
+
92
+ const [image] = await imageRefs([file])
93
+ return image ?? null
94
+ },
95
+ async ensure(kind: MediaPermissionKind): Promise<PermissionResult> {
96
+ if (kind === 'photos') {
97
+ return typeof document !== 'undefined' ? 'granted' : 'unsupported'
98
+ }
99
+
100
+ if (!navigator.permissions?.query) {
101
+ return 'unsupported'
102
+ }
103
+
104
+ try {
105
+ const status = await navigator.permissions.query({ name: 'camera' as PermissionName })
106
+ if (status.state === 'granted') {
107
+ return 'granted'
108
+ }
109
+
110
+ return status.state === 'denied' ? 'denied' : 'unsupported'
111
+ } catch {
112
+ // Some browsers expose Permissions API but reject the camera descriptor.
113
+ return 'unsupported'
114
+ }
115
+ },
116
+ }
117
+
118
+ // See media.ts — registers the kinds this leaf owns for the platform
119
+ // permissions dispatcher.
120
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
121
+ permissionOwners.camera = () => media.ensure('camera')
122
+ permissionOwners.photos = () => media.ensure('photos')
package/src/types.ts ADDED
@@ -0,0 +1,57 @@
1
+ /** Optional capability — never throws for absence (docs/platform/platform-services.md). */
2
+ export interface Capability<T> {
3
+ supported: boolean
4
+ ensure(): Promise<'granted' | 'denied' | 'unsupported'>
5
+ /** usable iff supported && ensured */
6
+ impl: T | null
7
+ }
8
+
9
+ export type PermissionResult = 'granted' | 'denied' | 'unsupported'
10
+
11
+ export type MediaPermissionKind = 'camera' | 'photos'
12
+
13
+ export interface FileRef {
14
+ name: string
15
+ /**
16
+ * Opaque reference: blob/object URL on web, filesystem path on native.
17
+ */
18
+ uri: string
19
+ }
20
+
21
+ /**
22
+ * Result of `media.pickImage()`: a displayable URI and an upload data URL.
23
+ * Native URIs point to temporary JPEG files; delete them when the preview is
24
+ * no longer needed.
25
+ */
26
+ export interface PickedImage extends FileRef {
27
+ dataUrl: string
28
+ }
29
+
30
+ /**
31
+ * Options for `media.capturePhoto()`. Sizes are device-independent pixels;
32
+ * the delivered image may be larger on high-density screens and may differ
33
+ * from the request when `keepAspectRatio` applies.
34
+ */
35
+ export interface CapturePhotoOptions {
36
+ width?: number
37
+ height?: number
38
+ /** Preserve the sensor aspect ratio when resizing to width/height. Default true. */
39
+ keepAspectRatio?: boolean
40
+ /** Also write the shot to the OS photo library. Default false. */
41
+ saveToGallery?: boolean
42
+ /** Preferred lens. Default 'rear'; Android devices may ignore the hint. */
43
+ cameraFacing?: 'front' | 'rear'
44
+ }
45
+
46
+ export interface MediaImpl {
47
+ pickImage(): Promise<PickedImage | null>
48
+ pickImages(): Promise<PickedImage[]>
49
+ /**
50
+ * Still-image capture through the OS camera UI. Resolves null when the
51
+ * shot is canceled, permission is denied, or no camera exists — call
52
+ * `ensure('camera')` first to tell those apart. Video capture is not part
53
+ * of the contract: no maintained NativeScript substrate exists.
54
+ */
55
+ capturePhoto(options?: CapturePhotoOptions): Promise<PickedImage | null>
56
+ ensure(kind: MediaPermissionKind): Promise<PermissionResult>
57
+ }
package/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export {}
package/index.js DELETED
@@ -1,2 +0,0 @@
1
- // Reservation stub; implementation will arrive in a later release.
2
- module.exports = {}