@octane-xplat/platform 0.3.0 → 0.4.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.
Files changed (54) hide show
  1. package/README.md +37 -0
  2. package/package.json +11 -9
  3. package/src/a11y.native.ts +9 -5
  4. package/src/a11y.web.ts +13 -9
  5. package/src/app-info.native.ts +35 -0
  6. package/src/app-info.web.ts +10 -0
  7. package/src/biometrics.native.ts +10 -10
  8. package/src/biometrics.web.ts +9 -17
  9. package/src/clipboard.native.ts +8 -8
  10. package/src/clipboard.web.ts +8 -7
  11. package/src/connectivity.native.ts +86 -0
  12. package/src/connectivity.web.ts +62 -0
  13. package/src/deep-links.native.ts +47 -20
  14. package/src/deep-links.web.ts +16 -11
  15. package/src/device.native.ts +3 -3
  16. package/src/device.web.ts +5 -4
  17. package/src/files.native.ts +118 -18
  18. package/src/files.web.ts +20 -19
  19. package/src/geolocation.native.ts +44 -0
  20. package/src/geolocation.web.ts +50 -0
  21. package/src/haptics.native.ts +14 -10
  22. package/src/haptics.web.ts +5 -4
  23. package/src/index.ts +35 -19
  24. package/src/lifecycle.native.ts +1 -1
  25. package/src/lifecycle.native.tsrx +2 -0
  26. package/src/lifecycle.web.ts +1 -1
  27. package/src/lifecycle.web.tsrx +1 -0
  28. package/src/locale.native.ts +3 -3
  29. package/src/locale.web.ts +5 -9
  30. package/src/media.native.ts +70 -32
  31. package/src/media.web.ts +64 -22
  32. package/src/notifications.native.ts +7 -7
  33. package/src/notifications.web.ts +18 -7
  34. package/src/open-url.native.ts +45 -0
  35. package/src/open-url.web.ts +15 -0
  36. package/src/permissions.native.ts +10 -10
  37. package/src/permissions.web.ts +13 -31
  38. package/src/safe-area.native.ts +1 -1
  39. package/src/safe-area.native.tsrx +76 -17
  40. package/src/safe-area.web.ts +1 -1
  41. package/src/safe-area.web.tsrx +3 -0
  42. package/src/screen.native.ts +1 -1
  43. package/src/screen.native.tsrx +1 -0
  44. package/src/screen.web.ts +1 -1
  45. package/src/screen.web.tsrx +1 -0
  46. package/src/secure-storage.native.ts +5 -5
  47. package/src/secure-storage.web.ts +2 -2
  48. package/src/share.native.ts +6 -6
  49. package/src/share.web.ts +17 -13
  50. package/src/storage.native.ts +8 -4
  51. package/src/storage.web.ts +7 -3
  52. package/src/system-bars.native.ts +10 -8
  53. package/src/system-bars.web.ts +9 -6
  54. package/src/types.ts +93 -33
@@ -1,30 +1,130 @@
1
- // Files — native leaf. FileRef wraps a real filesystem path under the app's
2
- // documents folder; picking delegates to the imagepicker/file picker seam.
3
- import { File, knownFolders, path } from '@nativescript/core';
4
- import type { FileRef } from './types';
1
+ // Files — native leaf. FileRef wraps an opaque native URI. App-document paths
2
+ // are still used for writes; picked Android SAF references may be content://
3
+ // URIs and must be read through ContentResolver.
4
+ import { openFilePicker } from '@nativescript-community/ui-document-picker'
5
+ import { Application, File, knownFolders, path } from '@nativescript/core'
6
+ import type { FileRef } from './types'
5
7
 
6
- const docs = () => knownFolders.documents();
8
+ const docs = () => knownFolders.documents()
9
+
10
+ function pickerTypes(accept: string): { extensions: string[]; mimeTypes: string[] } {
11
+ const values = accept
12
+ .split(',')
13
+ .map((value) => value.trim())
14
+ .filter(Boolean)
15
+
16
+ return {
17
+ extensions: values
18
+ .filter((value) => value.startsWith('.'))
19
+ .map((value) => value.slice(1)),
20
+ // `*/*` is the default, not a useful iOS UTType MIME value. Leaving it
21
+ // out lets the upstream picker use its public.data fallback.
22
+ mimeTypes: values.filter((value) => value.includes('/') && value !== '*/*'),
23
+ }
24
+ }
25
+
26
+ function androidDisplayName(uri: string, nativeUri: any): string | undefined {
27
+ if (!Application.android || !uri.startsWith('content://')) {
28
+ return undefined
29
+ }
30
+
31
+ try {
32
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
33
+ const cursor = activity
34
+ ?.getContentResolver()
35
+ ?.query(nativeUri ?? android.net.Uri.parse(uri), null, null, null, null)
36
+
37
+ if (!cursor) {
38
+ return undefined
39
+ }
40
+
41
+ try {
42
+ if (!cursor.moveToFirst()) {
43
+ return undefined
44
+ }
45
+
46
+ const index = cursor.getColumnIndex('display_name')
47
+ return index >= 0 ? cursor.getString(index) : undefined
48
+ } finally {
49
+ cursor.close()
50
+ }
51
+ } catch {
52
+ return undefined
53
+ }
54
+ }
55
+
56
+ function fallbackName(uri: string): string {
57
+ const segment = uri.split('/').pop() ?? ''
58
+ try {
59
+ return decodeURIComponent(segment) || 'document'
60
+ } catch {
61
+ return segment || 'document'
62
+ }
63
+ }
64
+
65
+ async function readContentUri(uri: string): Promise<string> {
66
+ const activity = Application.android?.foregroundActivity ?? Application.android?.startActivity
67
+ const input = activity?.getContentResolver()?.openInputStream(android.net.Uri.parse(uri))
68
+
69
+ if (!input) {
70
+ throw new Error(`Unable to open picked file: ${uri}`)
71
+ }
72
+
73
+ const reader = new java.io.BufferedReader(new java.io.InputStreamReader(input))
74
+ const lines: string[] = []
75
+ try {
76
+ let line: string | null
77
+ while ((line = reader.readLine()) !== null) {
78
+ lines.push(line)
79
+ }
80
+
81
+ return lines.join('\n')
82
+ } finally {
83
+ reader.close()
84
+ }
85
+ }
7
86
 
8
87
  export const files = {
9
- /** Not implemented on native yet — file pickers are plugin-shaped;
10
- * media.pickImage covers the common case. Returns null. */
11
- async pick(_accept?: string): Promise<FileRef | null> {
12
- return null;
88
+ /** Opens the platform document picker and returns its opaque native URI. */
89
+ async pick(accept = '*/*'): Promise<FileRef | null> {
90
+ const { extensions, mimeTypes } = pickerTypes(accept)
91
+ const result = await openFilePicker({
92
+ extensions,
93
+ mimeTypes,
94
+ multipleSelection: false,
95
+ permissions: { read: true, persistable: true },
96
+ })
97
+
98
+ const uri = result.files?.[0]
99
+
100
+ if (!uri) {
101
+ return null
102
+ }
103
+
104
+ const name = androidDisplayName(uri, result.android) ?? fallbackName(uri)
105
+ return { name, uri }
13
106
  },
14
107
  async readText(ref: FileRef): Promise<string> {
15
- return File.fromPath(ref.uri).readText();
108
+ if (ref.uri.startsWith('content://')) {
109
+ return readContentUri(ref.uri)
110
+ }
111
+
112
+ return File.fromPath(ref.uri).readText()
16
113
  },
17
114
  async writeText(name: string, text: string): Promise<FileRef> {
18
- const p = path.join(docs().path, name);
19
- const f = File.fromPath(p);
20
- f.writeTextSync(text);
21
- return { name, uri: p };
115
+ const p = path.join(docs().path, name)
116
+ const f = File.fromPath(p)
117
+ f.writeTextSync(text)
118
+ return { name, uri: p }
22
119
  },
23
120
  release(ref: FileRef): void {
24
- const cachePrefix = knownFolders.temp().path + '/';
25
- if (!ref.uri.startsWith(cachePrefix)) return;
121
+ const cachePrefix = knownFolders.temp().path + '/'
122
+ if (!ref.uri.startsWith(cachePrefix)) {
123
+ return
124
+ }
125
+
26
126
  try {
27
- File.fromPath(ref.uri).removeSync();
127
+ File.fromPath(ref.uri).removeSync()
28
128
  } catch {}
29
129
  },
30
- };
130
+ }
package/src/files.web.ts CHANGED
@@ -1,34 +1,35 @@
1
1
  // Files — web leaf. Opaque FileRef: a blob/object URL plus a name; reads go
2
2
  // through FileReader/fetch on the ref's URL.
3
- import type { FileRef } from './types';
3
+ import type { FileRef } from './types'
4
4
 
5
5
  export const files = {
6
6
  async pick(accept = '*/*'): Promise<FileRef | null> {
7
7
  return new Promise((resolve) => {
8
- const input = document.createElement('input');
9
- input.type = 'file';
10
- input.accept = accept;
8
+ const input = document.createElement('input')
9
+ input.type = 'file'
10
+ input.accept = accept
11
11
  input.onchange = () => {
12
- const f = input.files?.[0];
13
- resolve(f ? { name: f.name, uri: URL.createObjectURL(f) } : null);
14
- };
15
- input.oncancel = () => resolve(null);
16
- input.click();
17
- });
12
+ const f = input.files?.[0]
13
+ resolve(f ? { name: f.name, uri: URL.createObjectURL(f) } : null)
14
+ }
15
+
16
+ input.oncancel = () => resolve(null)
17
+ input.click()
18
+ })
18
19
  },
19
20
  async readText(ref: FileRef): Promise<string> {
20
- return (await fetch(ref.uri)).text();
21
+ return (await fetch(ref.uri)).text()
21
22
  },
22
23
  /** "Write" on web = a download. Returns the object URL. */
23
24
  async writeText(name: string, text: string): Promise<FileRef> {
24
- const uri = URL.createObjectURL(new Blob([text], { type: 'text/plain' }));
25
- const a = document.createElement('a');
26
- a.href = uri;
27
- a.download = name;
28
- a.click();
29
- return { name, uri };
25
+ const uri = URL.createObjectURL(new Blob([text], { type: 'text/plain' }))
26
+ const a = document.createElement('a')
27
+ a.href = uri
28
+ a.download = name
29
+ a.click()
30
+ return { name, uri }
30
31
  },
31
32
  release(ref: FileRef): void {
32
- URL.revokeObjectURL(ref.uri);
33
+ URL.revokeObjectURL(ref.uri)
33
34
  },
34
- };
35
+ }
@@ -0,0 +1,44 @@
1
+ // Geolocation — native leaf. The plugin's enableLocationRequest() owns the
2
+ // runtime prompt; getCurrentLocation() is normalized to the web position shape.
3
+ import * as geolocationApi from '@nativescript/geolocation'
4
+ import { CoreTypes } from '@nativescript/core'
5
+ import type { Capability, GeolocationImpl, GeolocationPosition } from './types'
6
+
7
+ function asPosition(nativeLocation: any): GeolocationPosition {
8
+ return {
9
+ latitude: nativeLocation.latitude,
10
+ longitude: nativeLocation.longitude,
11
+ accuracy: nativeLocation.horizontalAccuracy ?? nativeLocation.accuracy ?? 0,
12
+ altitude: nativeLocation.altitude ?? null,
13
+ heading: nativeLocation.direction ?? nativeLocation.heading ?? null,
14
+ speed: nativeLocation.speed ?? null,
15
+ timestamp: Number(nativeLocation.timestamp ?? Date.now()),
16
+ }
17
+ }
18
+
19
+ const impl: GeolocationImpl = {
20
+ async getCurrentPosition(options) {
21
+ const nativePosition = await geolocationApi.getCurrentLocation({
22
+ desiredAccuracy: options?.enableHighAccuracy
23
+ ? CoreTypes.Accuracy.high
24
+ : CoreTypes.Accuracy.any,
25
+ maximumAge: options?.maximumAge,
26
+ timeout: options?.timeout,
27
+ })
28
+
29
+ return asPosition(nativePosition)
30
+ },
31
+ }
32
+
33
+ export const geolocation: Capability<GeolocationImpl> = {
34
+ supported: true,
35
+ async ensure() {
36
+ try {
37
+ await geolocationApi.enableLocationRequest()
38
+ return 'granted'
39
+ } catch {
40
+ return 'denied'
41
+ }
42
+ },
43
+ impl,
44
+ }
@@ -0,0 +1,50 @@
1
+ // Geolocation — web leaf. The browser owns the permission prompt and returns
2
+ // the platform-neutral position shape used by the service contract.
3
+ import type { Capability, GeolocationImpl, GeolocationOptions, GeolocationPosition } from './types'
4
+
5
+ const supported = typeof navigator !== 'undefined' && 'geolocation' in navigator
6
+
7
+ function readPosition(options?: GeolocationOptions): Promise<GeolocationPosition> {
8
+ return new Promise((resolve, reject) => {
9
+ navigator.geolocation.getCurrentPosition(
10
+ (position) =>
11
+ resolve({
12
+ latitude: position.coords.latitude,
13
+ longitude: position.coords.longitude,
14
+ accuracy: position.coords.accuracy,
15
+ altitude: position.coords.altitude,
16
+ heading: position.coords.heading,
17
+ speed: position.coords.speed,
18
+ timestamp: position.timestamp,
19
+ }),
20
+ reject,
21
+ {
22
+ enableHighAccuracy: options?.enableHighAccuracy,
23
+ timeout: options?.timeout,
24
+ maximumAge: options?.maximumAge,
25
+ },
26
+ )
27
+ })
28
+ }
29
+
30
+ const impl: GeolocationImpl = {
31
+ getCurrentPosition: readPosition,
32
+ }
33
+
34
+ export const geolocation: Capability<GeolocationImpl> = {
35
+ supported,
36
+ async ensure() {
37
+ if (!supported) {
38
+ return 'unsupported'
39
+ }
40
+
41
+ try {
42
+ await readPosition({ timeout: 15000 })
43
+ return 'granted'
44
+ } catch (error) {
45
+ const code = (error as { code?: number }).code
46
+ return code === 1 ? 'denied' : 'unsupported'
47
+ }
48
+ },
49
+ impl,
50
+ }
@@ -1,7 +1,7 @@
1
1
  // Haptics — Taptic Engine (iOS) / Vibrator (Android) via @nativescript/haptics.
2
- import { Haptics, HapticImpactType, HapticNotificationType } from '@nativescript/haptics';
3
- import type { Capability } from './types';
4
- import type { HapticsImpl } from './types';
2
+ import { Haptics, HapticImpactType, HapticNotificationType } from '@nativescript/haptics'
3
+ import type { Capability } from './types'
4
+ import type { HapticsImpl } from './types'
5
5
 
6
6
  export const haptics: Capability<HapticsImpl> = {
7
7
  supported: true,
@@ -9,16 +9,20 @@ export const haptics: Capability<HapticsImpl> = {
9
9
  impl: {
10
10
  impact: (style = 'light') =>
11
11
  Haptics.impact(
12
- style === 'heavy' ? HapticImpactType.HEAVY
13
- : style === 'medium' ? HapticImpactType.MEDIUM
14
- : HapticImpactType.LIGHT,
12
+ style === 'heavy'
13
+ ? HapticImpactType.HEAVY
14
+ : style === 'medium'
15
+ ? HapticImpactType.MEDIUM
16
+ : HapticImpactType.LIGHT,
15
17
  ),
16
18
  notification: (kind) =>
17
19
  Haptics.notification(
18
- kind === 'error' ? HapticNotificationType.ERROR
19
- : kind === 'warning' ? HapticNotificationType.WARNING
20
- : HapticNotificationType.SUCCESS,
20
+ kind === 'error'
21
+ ? HapticNotificationType.ERROR
22
+ : kind === 'warning'
23
+ ? HapticNotificationType.WARNING
24
+ : HapticNotificationType.SUCCESS,
21
25
  ),
22
26
  selection: () => Haptics.selection(),
23
27
  },
24
- };
28
+ }
@@ -1,16 +1,17 @@
1
1
  // Haptics — web leaf. navigator.vibrate exists on Android Chrome only;
2
2
  // iOS Safari and desktop report unsupported via the Capability contract.
3
- import type { Capability, HapticsImpl } from './types';
3
+ import type { Capability, HapticsImpl } from './types'
4
4
 
5
5
  const vibrate = (ms: number | number[]) =>
6
- typeof navigator !== 'undefined' && 'vibrate' in navigator && navigator.vibrate(ms);
6
+ typeof navigator !== 'undefined' && 'vibrate' in navigator && navigator.vibrate(ms)
7
7
 
8
8
  export const haptics: Capability<HapticsImpl> = {
9
9
  supported: typeof navigator !== 'undefined' && 'vibrate' in navigator,
10
10
  ensure: async () => ('vibrate' in navigator ? 'granted' : 'unsupported'),
11
11
  impl: {
12
12
  impact: (style) => vibrate(style === 'heavy' ? 30 : style === 'medium' ? 20 : 10),
13
- notification: (kind) => vibrate(kind === 'error' ? [50, 60, 50] : kind === 'warning' ? [30, 40, 30] : 15),
13
+ notification: (kind) =>
14
+ vibrate(kind === 'error' ? [50, 60, 50] : kind === 'warning' ? [30, 40, 30] : 15),
14
15
  selection: () => vibrate(5),
15
16
  },
16
- };
17
+ }
package/src/index.ts CHANGED
@@ -4,35 +4,51 @@
4
4
  // moduleSuffixes can reach them (docs/module-resolution.md).
5
5
  export type {
6
6
  AppState,
7
+ AppInfo,
7
8
  BiometricsImpl,
8
9
  Capability,
10
+ ConnectionType,
11
+ ConnectivityImpl,
12
+ ConnectivityState,
9
13
  DeviceInfo,
10
14
  FileRef,
15
+ GeolocationImpl,
16
+ GeolocationOptions,
17
+ GeolocationPosition,
11
18
  HapticsImpl,
12
19
  PickedImage,
13
20
  Insets,
14
21
  Locale,
22
+ MediaImpl,
23
+ MediaPermissionKind,
15
24
  NotificationsImpl,
16
25
  PermissionKind,
26
+ PermissionResult,
27
+ OpenSettingsImpl,
17
28
  SecureStore,
18
29
  ShareResult,
19
30
  WindowSize,
20
- } from './types';
21
- export { device } from './device';
22
- export { storage } from './storage';
23
- export { clipboard } from './clipboard';
24
- export { share } from './share';
25
- export { haptics } from './haptics';
26
- export { secureStorage } from './secure-storage';
27
- export { files } from './files';
28
- export { notifications } from './notifications';
29
- export { permissions } from './permissions';
30
- export { systemBars } from './system-bars';
31
- export { announce } from './a11y';
32
- export { locale } from './locale';
33
- export { media } from './media';
34
- export { biometrics } from './biometrics';
35
- export { onDeepLink, consumeInitialUrl } from './deep-links';
36
- export { useAppState, useBackHandler } from './lifecycle';
37
- export { useSafeAreaInsets } from './safe-area';
38
- export { useWindowSize } from './screen';
31
+ } from './types'
32
+
33
+ export { device } from './device'
34
+ export { geolocation } from './geolocation'
35
+ export { connectivity } from './connectivity'
36
+ export { appInfo } from './app-info'
37
+ export { openUrl, openSettings } from './open-url'
38
+ export { storage } from './storage'
39
+ export { clipboard } from './clipboard'
40
+ export { share } from './share'
41
+ export { haptics } from './haptics'
42
+ export { secureStorage } from './secure-storage'
43
+ export { files } from './files'
44
+ export { notifications } from './notifications'
45
+ export { permissions } from './permissions'
46
+ export { systemBars } from './system-bars'
47
+ export { announce } from './a11y'
48
+ export { locale } from './locale'
49
+ export { media } from './media'
50
+ export { biometrics } from './biometrics'
51
+ export { onDeepLink, consumeInitialUrl } from './deep-links'
52
+ export { useAppState, useBackHandler } from './lifecycle'
53
+ export { useSafeAreaInsets } from './safe-area'
54
+ export { useWindowSize } from './screen'
@@ -1 +1 @@
1
- export { useAppState, useBackHandler } from './lifecycle.native.tsrx';
1
+ export { useAppState, useBackHandler } from './lifecycle.native.tsrx'
@@ -20,6 +20,7 @@ export function useAppState(): AppState {
20
20
  Application.off(Application.exitEvent, onExit);
21
21
  };
22
22
  }, []);
23
+
23
24
  return state;
24
25
  }
25
26
 
@@ -30,6 +31,7 @@ export function useBackHandler(fn: () => boolean): void {
30
31
  const cb = (e: { cancel: boolean }) => {
31
32
  if (fn()) e.cancel = true;
32
33
  };
34
+
33
35
  Application.android.on(Application.AndroidApplication.activityBackPressedEvent, cb);
34
36
  return () => {
35
37
  Application.android.off(Application.AndroidApplication.activityBackPressedEvent, cb);
@@ -1,2 +1,2 @@
1
1
  // tsc shim — moduleSuffixes doesn't reach .tsrx (see docs/module-resolution.md).
2
- export { useAppState, useBackHandler } from './lifecycle.web.tsrx';
2
+ export { useAppState, useBackHandler } from './lifecycle.web.tsrx'
@@ -17,6 +17,7 @@ export function useAppState(): AppState {
17
17
  window.removeEventListener('pageshow', onVis);
18
18
  };
19
19
  }, []);
20
+
20
21
  return state;
21
22
  }
22
23
 
@@ -1,9 +1,9 @@
1
1
  // Locale — Device.language/region on native.
2
- import { Device } from '@nativescript/core';
3
- import type { Locale } from './types';
2
+ import { Device } from '@nativescript/core'
3
+ import type { Locale } from './types'
4
4
 
5
5
  export const locale: Locale = {
6
6
  tag: `${Device.language}-${Device.region}`,
7
7
  language: Device.language.split('-')[0] ?? '',
8
8
  region: Device.region,
9
- };
9
+ }
package/src/locale.web.ts CHANGED
@@ -1,12 +1,8 @@
1
1
  // Locale — navigator.language on web ("en-US" → tag + parts).
2
- export interface Locale {
3
- tag: string;
4
- language: string;
5
- region: string;
6
- }
2
+ import type { Locale } from './types'
7
3
 
8
4
  export const locale: Locale = (() => {
9
- const tag = navigator.language ?? '';
10
- const [language = '', region = ''] = tag.split('-');
11
- return { tag, language, region };
12
- })();
5
+ const tag = navigator.language ?? ''
6
+ const [language = '', region = ''] = tag.split('-')
7
+ return { tag, language, region }
8
+ })()
@@ -1,37 +1,75 @@
1
1
  // Media picking — store a temporary JPEG for NativeScript Image and return a
2
2
  // data URL for APIs that persist image payloads.
3
- import { create as createImagePicker, ImagePickerMediaType } from '@nativescript/imagepicker';
4
- import { ImageSource, knownFolders, path } from '@nativescript/core';
5
- import { files } from './files';
6
- import type { PickedImage } from './types';
3
+ import { create as createImagePicker } from '@nativescript/imagepicker'
4
+ // Ambient const enum — verbatimModuleSyntax forbids value access; Image = 1.
5
+ import type { ImagePickerMediaType } from '@nativescript/imagepicker'
6
+ import { ImageSource, knownFolders, path } from '@nativescript/core'
7
+ import { files } from './files'
8
+ import type { MediaImpl, MediaPermissionKind, PermissionResult, PickedImage } from './types'
7
9
 
8
- export const media = {
9
- /** Opens the native image picker; returns null when permission is denied or selection is canceled. */
10
- async pickImage(): Promise<PickedImage | null> {
11
- const picker = createImagePicker({ mode: 'single', mediaType: ImagePickerMediaType.Image });
12
- const permission = await picker.authorize();
13
- if (!permission.authorized) return null;
14
-
15
- const [selection] = await picker.present();
16
- if (!selection) return null;
17
-
18
- const source = await ImageSource.fromAsset(selection.asset);
19
- const filename = `octane-image-${Date.now()}-${Math.random().toString(36).slice(2)}.jpg`;
20
- const uri = path.join(knownFolders.temp().path, filename);
21
- const ref = {
22
- name: selection.originalFilename || selection.filename || 'image.jpg',
23
- uri,
24
- };
25
-
26
- try {
27
- const saved = await source.saveToFileAsync(uri, 'jpeg', 85);
28
- if (!saved) throw new Error('Could not save the selected image to temporary storage');
29
-
30
- const base64 = await source.toBase64StringAsync('jpeg', 85);
31
- return { ...ref, dataUrl: `data:image/jpeg;base64,${base64}` };
32
- } catch (error) {
33
- files.release(ref);
34
- throw error;
10
+ async function ensurePhotos(): Promise<PermissionResult> {
11
+ try {
12
+ const picker = createImagePicker({ mode: 'single', mediaType: 1 as ImagePickerMediaType })
13
+ const permission = (await picker.authorize()) as { authorized?: boolean } | boolean
14
+ return permission === true || (typeof permission === 'object' && permission.authorized === true)
15
+ ? 'granted'
16
+ : 'denied'
17
+ } catch {
18
+ return 'denied'
19
+ }
20
+ }
21
+
22
+ async function pickSelections(mode: 'single' | 'multiple'): Promise<PickedImage[]> {
23
+ const picker = createImagePicker({ mode, mediaType: 1 as ImagePickerMediaType })
24
+ const permission = (await picker.authorize()) as { authorized?: boolean } | boolean
25
+ if (
26
+ !(permission === true || (typeof permission === 'object' && permission.authorized === true))
27
+ ) {
28
+ return []
29
+ }
30
+
31
+ const selections = await picker.present()
32
+ const refs: PickedImage[] = []
33
+ try {
34
+ for (const selection of selections) {
35
+ const source = await ImageSource.fromAsset(selection.asset)
36
+ const filename = `octane-image-${Date.now()}-${Math.random().toString(36).slice(2)}.jpg`
37
+ const uri = path.join(knownFolders.temp().path, filename)
38
+ const ref = {
39
+ name: selection.originalFilename || selection.filename || 'image.jpg',
40
+ uri,
41
+ }
42
+
43
+ const saved = await source.saveToFileAsync(uri, 'jpeg', 85)
44
+ if (!saved) {
45
+ throw new Error('Could not save the selected image to temporary storage')
46
+ }
47
+
48
+ const base64 = await source.toBase64StringAsync('jpeg', 85)
49
+ refs.push({ ...ref, dataUrl: `data:image/jpeg;base64,${base64}` })
50
+ }
51
+
52
+ return refs
53
+ } catch (error) {
54
+ for (const ref of refs) {
55
+ files.release(ref)
35
56
  }
57
+
58
+ throw error
59
+ }
60
+ }
61
+
62
+ export const media: MediaImpl = {
63
+ /** Opens the native image picker; returns null when canceled. */
64
+ async pickImage(): Promise<PickedImage | null> {
65
+ const [image] = await pickSelections('single')
66
+ return image ?? null
67
+ },
68
+ /** Opens the native image picker in multiple-selection mode. */
69
+ pickImages() {
70
+ return pickSelections('multiple')
71
+ },
72
+ async ensure(kind: MediaPermissionKind): Promise<PermissionResult> {
73
+ return kind === 'photos' ? ensurePhotos() : 'unsupported'
36
74
  },
37
- };
75
+ }