@a16n/web-sim 0.0.0-stage → 0.1.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 (279) hide show
  1. package/README.md +13 -2
  2. package/bin/cli.ts +255 -0
  3. package/bin/web-sim.js +39 -0
  4. package/overrides/@backpackapp-io/react-native-toast/overrides.ts +15 -0
  5. package/overrides/@react-native-firebase/app/overrides.ts +34 -0
  6. package/overrides/@tiktok-for-business/react-native-sdk/NativeTiktokSdk.ts +29 -0
  7. package/overrides/@tiktok-for-business/react-native-sdk/overrides.ts +9 -0
  8. package/overrides/expo-application/ExpoApplication.ts +81 -0
  9. package/overrides/expo-application/overrides.ts +16 -0
  10. package/overrides/expo-background-task/ExpoBackgroundTaskModule.ts +30 -0
  11. package/overrides/expo-background-task/overrides.ts +9 -0
  12. package/overrides/expo-constants/ExponentConstants.ts +66 -0
  13. package/overrides/expo-constants/overrides.ts +9 -0
  14. package/overrides/expo-device/ExpoDevice.ts +104 -0
  15. package/overrides/expo-device/overrides.ts +9 -0
  16. package/overrides/expo-glass-effect/GlassContainer.tsx +9 -0
  17. package/overrides/expo-glass-effect/GlassView.tsx +95 -0
  18. package/overrides/expo-glass-effect/availability.ts +14 -0
  19. package/overrides/expo-glass-effect/overrides.ts +14 -0
  20. package/overrides/expo-haptics/Haptics.ts +67 -0
  21. package/overrides/expo-haptics/overrides.ts +5 -0
  22. package/overrides/expo-mail-composer/ExpoMailComposer.ts +40 -0
  23. package/overrides/expo-mail-composer/overrides.ts +9 -0
  24. package/overrides/expo-mesh-gradient/MeshGradientView.tsx +44 -0
  25. package/overrides/expo-mesh-gradient/overrides.ts +9 -0
  26. package/overrides/expo-modules-core/overrides.ts +12 -0
  27. package/overrides/expo-navigation-bar/ExpoNavigationBar.ts +29 -0
  28. package/overrides/expo-navigation-bar/NavigationBar.ts +43 -0
  29. package/overrides/expo-navigation-bar/overrides.ts +12 -0
  30. package/overrides/expo-router/NativeStackView.tsx +74 -0
  31. package/overrides/expo-router/NativeTabsView.tsx +263 -0
  32. package/overrides/expo-router/SafeAreaProvider.ts +6 -0
  33. package/overrides/expo-router/overrides.ts +23 -0
  34. package/overrides/expo-router/statusBarRequests.ts +51 -0
  35. package/overrides/expo-screen-orientation/ExpoScreenOrientation.ts +173 -0
  36. package/overrides/expo-screen-orientation/overrides.ts +21 -0
  37. package/overrides/expo-sharing/SharingNativeModule.ts +21 -0
  38. package/overrides/expo-sharing/overrides.ts +9 -0
  39. package/overrides/expo-sms/ExpoSMS.ts +24 -0
  40. package/overrides/expo-sms/overrides.ts +9 -0
  41. package/overrides/expo-splash-screen/SplashScreen.ts +25 -0
  42. package/overrides/expo-splash-screen/overrides.ts +5 -0
  43. package/overrides/expo-status-bar/StatusBar.tsx +44 -0
  44. package/overrides/expo-status-bar/overrides.ts +5 -0
  45. package/overrides/expo-store-review/ExpoStoreReview.ts +18 -0
  46. package/overrides/expo-store-review/overrides.ts +9 -0
  47. package/overrides/expo-symbols/SymbolView.tsx +192 -0
  48. package/overrides/expo-symbols/overrides.ts +9 -0
  49. package/overrides/expo-system-ui/ExpoSystemUI.ts +34 -0
  50. package/overrides/expo-system-ui/overrides.ts +9 -0
  51. package/overrides/expo-task-manager/ExpoTaskManager.ts +39 -0
  52. package/overrides/expo-task-manager/overrides.ts +9 -0
  53. package/overrides/expo-tracking-transparency/ExpoTrackingTransparency.ts +30 -0
  54. package/overrides/expo-tracking-transparency/overrides.ts +11 -0
  55. package/overrides/expo-video/ExpoVideo.ts +16 -0
  56. package/overrides/expo-video/overrides.ts +9 -0
  57. package/overrides/lottie-react-native/LottieView.tsx +87 -0
  58. package/overrides/lottie-react-native/overrides.ts +9 -0
  59. package/overrides/react-native-pager-view/PagerViewNativeComponent.tsx +254 -0
  60. package/overrides/react-native-pager-view/overrides.ts +9 -0
  61. package/overrides/react-native-reanimated/overrides.ts +28 -0
  62. package/overrides/react-native-safe-area-context/NativeSafeAreaProvider.tsx +40 -0
  63. package/overrides/react-native-safe-area-context/overrides.ts +12 -0
  64. package/overrides/react-native-share/NativeRNShare.ts +22 -0
  65. package/overrides/react-native-share/overrides.ts +12 -0
  66. package/overrides/react-native-share/platform.ts +14 -0
  67. package/overrides/react-native-turbo-image/TurboImage.tsx +101 -0
  68. package/overrides/react-native-turbo-image/overrides.ts +9 -0
  69. package/overrides/react-native-web/RefreshControl.tsx +57 -0
  70. package/overrides/react-native-web/overrides.ts +153 -0
  71. package/overrides/react-native-web/useElementLayout.ts +140 -0
  72. package/package.json +78 -4
  73. package/plugins/battery/overrides/expo-battery/ExpoBattery.ts +57 -0
  74. package/plugins/battery/overrides/expo-battery/overrides.ts +9 -0
  75. package/plugins/battery/plugin.ts +8 -0
  76. package/plugins/battery/shell.tsx +56 -0
  77. package/plugins/battery/state.ts +11 -0
  78. package/plugins/biometrics/overrides/expo-local-authentication/ExpoLocalAuthentication.ts +90 -0
  79. package/plugins/biometrics/overrides/expo-local-authentication/overrides.ts +11 -0
  80. package/plugins/biometrics/plugin.ts +8 -0
  81. package/plugins/biometrics/shell.tsx +88 -0
  82. package/plugins/biometrics/state.ts +41 -0
  83. package/plugins/brightness/app.ts +5 -0
  84. package/plugins/brightness/overrides/expo-brightness/Brightness.ts +98 -0
  85. package/plugins/brightness/overrides/expo-brightness/overrides.ts +10 -0
  86. package/plugins/brightness/plugin.ts +9 -0
  87. package/plugins/brightness/shell.tsx +55 -0
  88. package/plugins/brightness/state.ts +19 -0
  89. package/plugins/calendar/calendar.ts +299 -0
  90. package/plugins/calendar/overrides/expo-calendar/ExpoCalendar.ts +358 -0
  91. package/plugins/calendar/overrides/expo-calendar/LegacyExpoCalendar.ts +163 -0
  92. package/plugins/calendar/overrides/expo-calendar/overrides.ts +14 -0
  93. package/plugins/calendar/plugin.ts +8 -0
  94. package/plugins/calendar/shell.tsx +123 -0
  95. package/plugins/camera/overrides/expo-camera/ExpoCamera.tsx +269 -0
  96. package/plugins/camera/overrides/expo-camera/ExpoCameraManager.ts +56 -0
  97. package/plugins/camera/overrides/expo-camera/overrides.ts +12 -0
  98. package/plugins/camera/plugin.ts +9 -0
  99. package/plugins/camera/shell.tsx +107 -0
  100. package/plugins/camera/state.ts +61 -0
  101. package/plugins/clipboard/overrides/expo-clipboard/ExpoClipboard.ts +138 -0
  102. package/plugins/clipboard/overrides/expo-clipboard/overrides.ts +9 -0
  103. package/plugins/clipboard/plugin.ts +8 -0
  104. package/plugins/clipboard/shell.tsx +122 -0
  105. package/plugins/clipboard/state.ts +93 -0
  106. package/plugins/clock/app.ts +25 -0
  107. package/plugins/clock/plugin.ts +8 -0
  108. package/plugins/clock/shell.tsx +225 -0
  109. package/plugins/clock/state.ts +12 -0
  110. package/plugins/contacts/contacts.ts +125 -0
  111. package/plugins/contacts/overrides/expo-contacts/ExpoContacts.ts +153 -0
  112. package/plugins/contacts/overrides/expo-contacts/ExpoContactsNext.ts +232 -0
  113. package/plugins/contacts/overrides/expo-contacts/overrides.ts +12 -0
  114. package/plugins/contacts/plugin.ts +8 -0
  115. package/plugins/contacts/shell.tsx +109 -0
  116. package/plugins/home-indicator/app.ts +5 -0
  117. package/plugins/home-indicator/plugin.ts +9 -0
  118. package/plugins/home-indicator/requests.ts +48 -0
  119. package/plugins/home-indicator/shell.tsx +68 -0
  120. package/plugins/home-indicator/state.ts +31 -0
  121. package/plugins/keep-awake/app.ts +5 -0
  122. package/plugins/keep-awake/overrides/expo-keep-awake/ExpoKeepAwake.ts +27 -0
  123. package/plugins/keep-awake/overrides/expo-keep-awake/overrides.ts +9 -0
  124. package/plugins/keep-awake/plugin.ts +9 -0
  125. package/plugins/keep-awake/shell.tsx +80 -0
  126. package/plugins/keep-awake/state.ts +12 -0
  127. package/plugins/keyboard/Keyboard.tsx +354 -0
  128. package/plugins/keyboard/app.ts +90 -0
  129. package/plugins/keyboard/controller.ts +384 -0
  130. package/plugins/keyboard/fields.ts +244 -0
  131. package/plugins/keyboard/icons.tsx +283 -0
  132. package/plugins/keyboard/keyboard.css +362 -0
  133. package/plugins/keyboard/layouts/android.ts +175 -0
  134. package/plugins/keyboard/layouts/index.ts +10 -0
  135. package/plugins/keyboard/layouts/ios.ts +219 -0
  136. package/plugins/keyboard/layouts/types.ts +80 -0
  137. package/plugins/keyboard/overrides/react-native-keyboard-controller/KeyboardController.tsx +470 -0
  138. package/plugins/keyboard/overrides/react-native-keyboard-controller/overrides.ts +9 -0
  139. package/plugins/keyboard/plugin.ts +13 -0
  140. package/plugins/keyboard/shell.tsx +133 -0
  141. package/plugins/keyboard/state.ts +92 -0
  142. package/plugins/keyboard/suggestions.ts +63 -0
  143. package/plugins/keyboard/taps.ts +77 -0
  144. package/plugins/keyboard/typing.ts +112 -0
  145. package/plugins/locale/app.ts +232 -0
  146. package/plugins/locale/locale.ts +143 -0
  147. package/plugins/locale/overrides/expo-localization/ExpoLocalization.ts +41 -0
  148. package/plugins/locale/overrides/expo-localization/overrides.ts +9 -0
  149. package/plugins/locale/plugin.ts +9 -0
  150. package/plugins/locale/shell.tsx +147 -0
  151. package/plugins/locale/state.ts +36 -0
  152. package/plugins/location/geo.ts +56 -0
  153. package/plugins/location/overrides/expo-location/ExpoLocation.ts +235 -0
  154. package/plugins/location/overrides/expo-location/overrides.ts +11 -0
  155. package/plugins/location/places.ts +38 -0
  156. package/plugins/location/plugin.ts +8 -0
  157. package/plugins/location/shell.tsx +188 -0
  158. package/plugins/location/state.ts +51 -0
  159. package/plugins/motion/overrides/expo-sensors/DeviceSensor.ts +169 -0
  160. package/plugins/motion/overrides/expo-sensors/ExponentPedometer.ts +54 -0
  161. package/plugins/motion/overrides/expo-sensors/overrides.ts +14 -0
  162. package/plugins/motion/plugin.ts +8 -0
  163. package/plugins/motion/sensors.ts +116 -0
  164. package/plugins/motion/shell.tsx +136 -0
  165. package/plugins/motion/state.ts +46 -0
  166. package/plugins/network/app.ts +400 -0
  167. package/plugins/network/overrides/expo-network/ExpoNetwork.ts +51 -0
  168. package/plugins/network/overrides/expo-network/overrides.ts +9 -0
  169. package/plugins/network/plugin.ts +8 -0
  170. package/plugins/network/shell.tsx +67 -0
  171. package/plugins/network/state.ts +29 -0
  172. package/plugins/notifications/center.ts +255 -0
  173. package/plugins/notifications/content.ts +36 -0
  174. package/plugins/notifications/overrides/expo-notifications/NotificationsModule.ts +175 -0
  175. package/plugins/notifications/overrides/expo-notifications/channels.ts +108 -0
  176. package/plugins/notifications/overrides/expo-notifications/getDevicePushTokenAsync.ts +19 -0
  177. package/plugins/notifications/overrides/expo-notifications/getExpoPushTokenAsync.ts +16 -0
  178. package/plugins/notifications/overrides/expo-notifications/overrides.ts +36 -0
  179. package/plugins/notifications/plugin.ts +8 -0
  180. package/plugins/notifications/shell.tsx +192 -0
  181. package/plugins/notifications/state.ts +56 -0
  182. package/plugins/notifications/tokens.ts +47 -0
  183. package/plugins/notifications/trigger.ts +107 -0
  184. package/plugins/permissions/plugin.ts +6 -0
  185. package/plugins/permissions/shell.tsx +50 -0
  186. package/plugins/permissions/state.ts +38 -0
  187. package/plugins/photos/appLibrary.ts +114 -0
  188. package/plugins/photos/library.ts +322 -0
  189. package/plugins/photos/overrides/expo-image-picker/ExponentImagePicker.ts +153 -0
  190. package/plugins/photos/overrides/expo-image-picker/overrides.ts +13 -0
  191. package/plugins/photos/overrides/expo-media-library/ExpoMediaLibrary.ts +235 -0
  192. package/plugins/photos/overrides/expo-media-library/NativeMediaLibraryModule.ts +318 -0
  193. package/plugins/photos/overrides/expo-media-library/overrides.ts +19 -0
  194. package/plugins/photos/plugin.ts +8 -0
  195. package/plugins/photos/samples.ts +367 -0
  196. package/plugins/photos/shell.tsx +164 -0
  197. package/plugins/photos/state.ts +88 -0
  198. package/plugins/storage/files.ts +351 -0
  199. package/plugins/storage/overrides/expo-file-system/ExpoFileSystem.ts +770 -0
  200. package/plugins/storage/overrides/expo-file-system/ExponentFileSystem.ts +196 -0
  201. package/plugins/storage/overrides/expo-file-system/overrides.ts +13 -0
  202. package/plugins/storage/overrides/expo-secure-store/ExpoSecureStore.ts +75 -0
  203. package/plugins/storage/overrides/expo-secure-store/overrides.ts +9 -0
  204. package/plugins/storage/plugin.ts +8 -0
  205. package/plugins/storage/reset.ts +136 -0
  206. package/plugins/storage/secure.ts +71 -0
  207. package/plugins/storage/shell.tsx +365 -0
  208. package/plugins/storage/state.ts +13 -0
  209. package/src/client/app/appDocument.ts +113 -0
  210. package/src/client/app/appFocus.ts +97 -0
  211. package/src/client/app/console.ts +118 -0
  212. package/src/client/app/fonts.ts +59 -0
  213. package/src/client/app/main.tsx +99 -0
  214. package/src/client/app/routeContext.ts +45 -0
  215. package/src/client/app/touch.ts +640 -0
  216. package/src/client/entry.ts +20 -0
  217. package/src/client/modules.d.ts +8 -0
  218. package/src/client/react-native/app.ts +57 -0
  219. package/src/client/react-native/deep.ts +13 -0
  220. package/src/client/react-native/keyboard.tsx +192 -0
  221. package/src/client/react-native/library.ts +256 -0
  222. package/src/client/shell/Cookies.tsx +95 -0
  223. package/src/client/shell/LogDrawer.tsx +415 -0
  224. package/src/client/shell/PhotoPicker.tsx +174 -0
  225. package/src/client/shell/PluginOverlays.tsx +42 -0
  226. package/src/client/shell/PluginPanels.tsx +82 -0
  227. package/src/client/shell/ResetApp.tsx +87 -0
  228. package/src/client/shell/Resizer.tsx +99 -0
  229. package/src/client/shell/Shell.tsx +531 -0
  230. package/src/client/shell/SystemBars.tsx +376 -0
  231. package/src/client/shell/SystemCamera.tsx +181 -0
  232. package/src/client/shell/SystemOverlay.tsx +422 -0
  233. package/src/client/shell/SystemSheets.tsx +462 -0
  234. package/src/client/shell/backdrop.ts +229 -0
  235. package/src/client/shell/control.ts +91 -0
  236. package/src/client/shell/events.ts +226 -0
  237. package/src/client/shell/geometry.ts +68 -0
  238. package/src/client/shell/host.ts +492 -0
  239. package/src/client/shell/icons.tsx +34 -0
  240. package/src/client/shell/logFeed.ts +102 -0
  241. package/src/client/shell/main.tsx +22 -0
  242. package/src/client/shell/permissionCopy.ts +169 -0
  243. package/src/client/shell/plugins.ts +266 -0
  244. package/src/client/shell/popout.ts +185 -0
  245. package/src/client/shell/popover.ts +27 -0
  246. package/src/client/shell/shell.css +878 -0
  247. package/src/client/shell/statusTime.ts +31 -0
  248. package/src/client/shell/tooltips.ts +104 -0
  249. package/src/client/virtual.d.ts +21 -0
  250. package/src/devices/catalog.ts +223 -0
  251. package/src/devices/types.ts +83 -0
  252. package/src/node/appInfo.ts +186 -0
  253. package/src/node/appSource.ts +138 -0
  254. package/src/node/config.ts +180 -0
  255. package/src/node/control.ts +144 -0
  256. package/src/node/doctor.ts +199 -0
  257. package/src/node/events/cli.ts +206 -0
  258. package/src/node/events/shared.ts +238 -0
  259. package/src/node/events/store.ts +266 -0
  260. package/src/node/index.ts +5 -0
  261. package/src/node/overrides/define.ts +56 -0
  262. package/src/node/overrides/packages.ts +136 -0
  263. package/src/node/overrides/platformPatch.ts +56 -0
  264. package/src/node/overrides/plugin.ts +166 -0
  265. package/src/node/overrides/registry.ts +258 -0
  266. package/src/node/paths.ts +18 -0
  267. package/src/node/platform.ts +171 -0
  268. package/src/node/plugins.ts +98 -0
  269. package/src/node/proxy.ts +421 -0
  270. package/src/node/server.ts +253 -0
  271. package/src/plugin/index.ts +33 -0
  272. package/src/plugin/types.ts +127 -0
  273. package/src/plugin/ui.tsx +562 -0
  274. package/src/runtime/clock.ts +112 -0
  275. package/src/runtime/draw.ts +196 -0
  276. package/src/runtime/index.ts +513 -0
  277. package/src/runtime/media.ts +379 -0
  278. package/src/runtime/records.ts +76 -0
  279. package/src/runtime/timezone.ts +81 -0
@@ -0,0 +1,322 @@
1
+ import { type CapturedPhoto, downscaleImage, getHost, type Platform } from 'web-sim/runtime'
2
+ import { loadImage } from '../../src/runtime/draw.ts'
3
+ import { drawSample, type SceneKind } from './samples.ts'
4
+ import type { PhotosState, StoredAlbum, StoredPhoto } from './state.ts'
5
+
6
+ /**
7
+ * The photo library, as the panel, the photo picker and the media library see it: the photos in the plugin's state
8
+ * with each platform's asset ids, file names and albums. Added photos' images are kept in IndexedDB, per app.
9
+ */
10
+
11
+ export type LibraryPhoto = {
12
+ /** The asset id: an iOS local identifier, or an Android MediaStore id. */
13
+ id: string
14
+ n: number
15
+ filename: string
16
+ width: number
17
+ height: number
18
+ /** Milliseconds since the epoch. */
19
+ creationTime: number
20
+ favorite: boolean
21
+ location: { latitude: number; longitude: number } | null
22
+ source: StoredPhoto['source']
23
+ }
24
+
25
+ export type LibraryAlbum = {
26
+ id: string
27
+ title: string
28
+ type: 'album' | 'smartAlbum'
29
+ assetIds: string[]
30
+ /** The user's album this is, which can be changed; undefined for one made from the photos. */
31
+ n?: number
32
+ }
33
+
34
+ /** A handle on the state: the plugin's, from the panel or an override. */
35
+ export type PhotosHandle = { get(): PhotosState; set(patch: Partial<PhotosState>): void }
36
+
37
+ /** iOS asset ids are UUID local identifiers; Android's are MediaStore row ids. */
38
+ export function assetId(n: number, platform: Platform): string {
39
+ if (platform === 'android') {
40
+ return String(1000000010 + n)
41
+ }
42
+ const hex = (n + 1).toString(16).toUpperCase().padStart(4, '0')
43
+ return `5A1B${hex}-0C3D-4E5F-8A9B-${hex}C0FFEE${hex.slice(0, 2)}/L0/001`
44
+ }
45
+
46
+ function albumId(n: number, platform: Platform): string {
47
+ return platform === 'android' ? String(-1000000000 - n) : `A1E0C0DE-0000-4000-8000-${String(n).padStart(12, '0')}/L0/040`
48
+ }
49
+
50
+ /** The last whole hour, less one: the newest sample was taken then, so every sample is in the past. */
51
+ function lastHour(): number {
52
+ return Math.floor(Date.now() / 3_600_000) * 3_600_000 - 3_600_000
53
+ }
54
+
55
+ /** A Pixel camera's file name: `PXL_20261202_143012345.jpg`. */
56
+ function pixelFilename(time: number): string {
57
+ const date = new Date(time)
58
+ const pad = (value: number, length = 2) => String(value).padStart(length, '0')
59
+ return `PXL_${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}${pad(date.getMilliseconds(), 3)}.jpg`
60
+ }
61
+
62
+ /** The photos in the library, newest first. */
63
+ export function libraryPhotos(state: PhotosState, platform: Platform): LibraryPhoto[] {
64
+ const newest = lastHour()
65
+ return state.photos
66
+ .map((photo): LibraryPhoto => {
67
+ const creationTime = photo.time ?? newest - photo.ago
68
+ const filename =
69
+ photo.source.kind === 'added'
70
+ ? photo.source.filename
71
+ : platform === 'ios'
72
+ ? `IMG_${String(4000 + 18 - photo.n).padStart(4, '0')}.JPG`
73
+ : pixelFilename(creationTime)
74
+ return {
75
+ id: assetId(photo.n, platform),
76
+ n: photo.n,
77
+ filename,
78
+ width: photo.width,
79
+ height: photo.height,
80
+ creationTime,
81
+ favorite: photo.favorite,
82
+ location: photo.location,
83
+ source: photo.source,
84
+ }
85
+ })
86
+ .sort((a, b) => b.creationTime - a.creationTime)
87
+ }
88
+
89
+ export function libraryPhoto(state: PhotosState, platform: Platform, id: string): LibraryPhoto | null {
90
+ return libraryPhotos(state, platform).find((photo) => photo.id === id) ?? null
91
+ }
92
+
93
+ /**
94
+ * The library's albums. iOS has its smart albums (Recents, Favorites); Android has its folders: Camera for the
95
+ * photos taken, Pictures for the ones apps saved. Then the user's albums.
96
+ */
97
+ export function libraryAlbums(state: PhotosState, platform: Platform): LibraryAlbum[] {
98
+ const photos = libraryPhotos(state, platform)
99
+ const ids = (filter: (photo: LibraryPhoto) => boolean) => photos.filter(filter).map((photo) => photo.id)
100
+ const builtIn: LibraryAlbum[] =
101
+ platform === 'ios'
102
+ ? [
103
+ { id: albumId(1, platform), title: 'Recents', type: 'smartAlbum', assetIds: ids(() => true) },
104
+ { id: albumId(2, platform), title: 'Favorites', type: 'smartAlbum', assetIds: ids((photo) => photo.favorite) },
105
+ ]
106
+ : [
107
+ { id: '-1739773001', title: 'Camera', type: 'album', assetIds: ids((photo) => photo.source.kind === 'sample' || photo.source.by === 'panel') },
108
+ { id: '-1617409521', title: 'Pictures', type: 'album', assetIds: ids((photo) => photo.source.kind === 'added' && photo.source.by === 'app') },
109
+ ].filter((album) => album.assetIds.length > 0) as LibraryAlbum[]
110
+ const order = new Map(photos.map((photo, index) => [photo.n, index]))
111
+ const own = state.albums.map(
112
+ (album): LibraryAlbum => ({
113
+ id: albumId(album.n, platform),
114
+ title: album.title,
115
+ type: 'album',
116
+ n: album.n,
117
+ assetIds: album.photos
118
+ .filter((n) => order.has(n))
119
+ .sort((a, b) => order.get(a)! - order.get(b)!)
120
+ .map((n) => assetId(n, platform)),
121
+ }),
122
+ )
123
+ return [...builtIn, ...own]
124
+ }
125
+
126
+ /** The numbers of the photos with these asset ids. */
127
+ export function photoNumbers(state: PhotosState, platform: Platform, ids: string[]): number[] {
128
+ const byId = new Map(state.photos.map((photo) => [assetId(photo.n, platform), photo.n]))
129
+ return ids.map((id) => byId.get(id)).filter((n) => n !== undefined)
130
+ }
131
+
132
+ export function albumNumber(state: PhotosState, platform: Platform, id: string): number | undefined {
133
+ return state.albums.find((album) => albumId(album.n, platform) === id)?.n
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------------------------------------------
137
+ // Changes
138
+
139
+ /**
140
+ * Adds an image to the library, re-encoded no larger than 1280px, its image kept in IndexedDB. `album` is the number
141
+ * of a user album to add it to.
142
+ */
143
+ export async function addPhoto(handle: PhotosHandle, uri: string, options: { by: 'app' | 'panel'; filename?: string; album?: number }): Promise<StoredPhoto> {
144
+ const full = await downscaleImage(uri, 1280, 0.85)
145
+ const thumb = await downscaleImage(full.uri, 240, 0.8)
146
+ // The number is taken first, so photos added at once each get their own.
147
+ const n = handle.get().next
148
+ handle.set({ next: n + 1 })
149
+ await putImage(n, { full: full.uri, thumb: thumb.uri, added: Date.now() })
150
+ const state = handle.get()
151
+ const number = state.photos.filter((photo) => photo.source.kind === 'added').length
152
+ const photo: StoredPhoto = {
153
+ n,
154
+ width: full.width,
155
+ height: full.height,
156
+ time: Date.now(),
157
+ ago: 0,
158
+ favorite: false,
159
+ location: null,
160
+ source: { kind: 'added', by: options.by, filename: options.filename ?? `IMG_${5000 + number}.JPG` },
161
+ }
162
+ handle.set({
163
+ photos: [photo, ...state.photos],
164
+ albums: options.album === undefined ? state.albums : state.albums.map((album) => (album.n === options.album ? { ...album, photos: [...album.photos, n] } : album)),
165
+ })
166
+ return photo
167
+ }
168
+
169
+ export function deletePhotos(handle: PhotosHandle, ns: number[]): void {
170
+ const state = handle.get()
171
+ const gone = new Set(ns)
172
+ handle.set({
173
+ photos: state.photos.filter((photo) => !gone.has(photo.n)),
174
+ albums: state.albums.map((album) => ({ ...album, photos: album.photos.filter((n) => !gone.has(n)) })),
175
+ })
176
+ }
177
+
178
+ export function setFavorite(handle: PhotosHandle, n: number, favorite: boolean): void {
179
+ handle.set({ photos: handle.get().photos.map((photo) => (photo.n === n ? { ...photo, favorite } : photo)) })
180
+ }
181
+
182
+ export function createAlbum(handle: PhotosHandle, title: string, photos: number[]): StoredAlbum {
183
+ const state = handle.get()
184
+ const album: StoredAlbum = { n: state.next, title, photos }
185
+ handle.set({ albums: [...state.albums, album], next: state.next + 1 })
186
+ return album
187
+ }
188
+
189
+ export function deleteAlbums(handle: PhotosHandle, ns: number[]): void {
190
+ handle.set({ albums: handle.get().albums.filter((album) => !ns.includes(album.n)) })
191
+ }
192
+
193
+ export function editAlbum(handle: PhotosHandle, n: number, change: { add?: number[]; remove?: number[] }): void {
194
+ handle.set({
195
+ albums: handle.get().albums.map((album) => {
196
+ if (album.n !== n) {
197
+ return album
198
+ }
199
+ const photos = album.photos.filter((photo) => !change.remove?.includes(photo))
200
+ return { ...album, photos: [...photos, ...(change.add ?? []).filter((photo) => !photos.includes(photo))] }
201
+ }),
202
+ })
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------------------------------------------
206
+ // Images
207
+
208
+ /**
209
+ * A library photo as a JPEG data URL, at its full size or scaled to fit `maxSize`. Samples are drawn again each
210
+ * time, the same way from their seed.
211
+ */
212
+ export async function photoDataUrl(photo: LibraryPhoto, options: { maxSize?: number; quality?: number } = {}): Promise<CapturedPhoto> {
213
+ const scale = Math.min(1, (options.maxSize ?? Infinity) / Math.max(photo.width, photo.height))
214
+ const width = Math.round(photo.width * scale)
215
+ const height = Math.round(photo.height * scale)
216
+ const canvas = document.createElement('canvas')
217
+ canvas.width = width
218
+ canvas.height = height
219
+ if (photo.source.kind === 'added') {
220
+ const stored = await getImage(photo.n)
221
+ if (stored === null) {
222
+ return { uri: blank(width, height), width, height }
223
+ }
224
+ if (scale === 1) {
225
+ return { uri: stored.full, width, height }
226
+ }
227
+ canvas.getContext('2d')!.drawImage(await loadImage(stored.full), 0, 0, width, height)
228
+ return { uri: canvas.toDataURL('image/jpeg', options.quality ?? 0.8), width, height }
229
+ }
230
+ drawSample(canvas.getContext('2d')!, photo.source.scene, photo.source.seed, width, height)
231
+ return { uri: canvas.toDataURL('image/jpeg', Math.min(options.quality ?? 0.9, 0.92)), width, height }
232
+ }
233
+
234
+ /** A small square-ish image of a photo, for grids. */
235
+ export async function photoThumbnail(photo: { n: number; width: number; height: number; source: StoredPhoto['source'] }, size = 220): Promise<string> {
236
+ if (photo.source.kind === 'added') {
237
+ return (await getImage(photo.n))?.thumb ?? blank(1, 1)
238
+ }
239
+ return sampleThumbnail(photo.source.scene, photo.source.seed, photo.width, photo.height, size)
240
+ }
241
+
242
+ export function sampleThumbnail(scene: SceneKind, seed: number, width: number, height: number, size = 220): string {
243
+ const scale = size / Math.min(width, height)
244
+ const canvas = document.createElement('canvas')
245
+ canvas.width = Math.round(width * scale)
246
+ canvas.height = Math.round(height * scale)
247
+ drawSample(canvas.getContext('2d')!, scene, seed, canvas.width, canvas.height)
248
+ return canvas.toDataURL('image/jpeg', 0.8)
249
+ }
250
+
251
+ function blank(width: number, height: number): string {
252
+ const canvas = document.createElement('canvas')
253
+ canvas.width = width
254
+ canvas.height = height
255
+ const ctx = canvas.getContext('2d')!
256
+ ctx.fillStyle = '#888'
257
+ ctx.fillRect(0, 0, width, height)
258
+ return canvas.toDataURL('image/jpeg', 0.5)
259
+ }
260
+
261
+ type StoredImage = { full: string; thumb: string; added: number }
262
+
263
+ const DATABASE = 'web-sim-photos'
264
+ const STORE = 'images'
265
+
266
+ function key(n: number): string {
267
+ return `${getHost().app.slug}/${n}`
268
+ }
269
+
270
+ function database(): Promise<IDBDatabase> {
271
+ return new Promise((resolve, reject) => {
272
+ const request = indexedDB.open(DATABASE, 1)
273
+ request.onupgradeneeded = () => request.result.createObjectStore(STORE)
274
+ request.onsuccess = () => resolve(request.result)
275
+ request.onerror = () => reject(request.error)
276
+ })
277
+ }
278
+
279
+ async function transact<T>(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
280
+ const db = await database()
281
+ try {
282
+ return await new Promise<T>((resolve, reject) => {
283
+ const request = run(db.transaction(STORE, mode).objectStore(STORE))
284
+ request.onsuccess = () => resolve(request.result)
285
+ request.onerror = () => reject(request.error)
286
+ })
287
+ } finally {
288
+ db.close()
289
+ }
290
+ }
291
+
292
+ async function putImage(n: number, image: StoredImage): Promise<void> {
293
+ await transact('readwrite', (store) => store.put(image, key(n)))
294
+ }
295
+
296
+ async function getImage(n: number): Promise<StoredImage | null> {
297
+ try {
298
+ return ((await transact('readonly', (store) => store.get(key(n)))) as StoredImage | undefined) ?? null
299
+ } catch {
300
+ return null
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Deletes this app's stored images that no photo in the library has any longer: removed, or gone with a reset.
306
+ * Images added in the last minute are kept, in case their photo is on its way into the state.
307
+ */
308
+ export async function pruneImages(live: () => Set<number>): Promise<void> {
309
+ const prefix = `${getHost().app.slug}/`
310
+ const keys = (await transact('readonly', (store) => store.getAllKeys())).map(String).filter((stored) => stored.startsWith(prefix))
311
+ const keep = live()
312
+ for (const stored of keys) {
313
+ const n = Number(stored.slice(prefix.length))
314
+ if (keep.has(n)) {
315
+ continue
316
+ }
317
+ const image = await getImage(n)
318
+ if (image !== null && Date.now() - image.added > 60_000) {
319
+ await transact('readwrite', (store) => store.delete(stored))
320
+ }
321
+ }
322
+ }
@@ -0,0 +1,153 @@
1
+ import { CodedError } from 'expo'
2
+ import {
3
+ type CapturedPhoto,
4
+ cropToAspect,
5
+ dataUrlInfo,
6
+ getPermission,
7
+ getState,
8
+ type PermissionResponse,
9
+ platform,
10
+ plugin,
11
+ requestPermission,
12
+ showDialog,
13
+ } from 'web-sim/runtime'
14
+ import { type CameraState, feedsOf, INITIAL_CAMERA } from '../../../camera/state.ts'
15
+ import { type LibraryPhoto, libraryAlbums, libraryPhoto, libraryPhotos, photoDataUrl } from '../../appLibrary.ts'
16
+ import { photoThumbnail } from '../../library.ts'
17
+
18
+ type MediaType = 'images' | 'videos' | 'livePhotos'
19
+
20
+ type Options = {
21
+ mediaTypes?: MediaType | MediaType[] | 'All' | 'Images' | 'Videos'
22
+ allowsEditing?: boolean
23
+ aspect?: [number, number]
24
+ quality?: number
25
+ base64?: boolean
26
+ exif?: boolean
27
+ allowsMultipleSelection?: boolean
28
+ selectionLimit?: number
29
+ orderedSelection?: boolean
30
+ cameraType?: 'front' | 'back'
31
+ }
32
+
33
+ function mediaTypes(value: Options['mediaTypes']): MediaType[] {
34
+ if (value === undefined || value === 'Images') {
35
+ return ['images']
36
+ }
37
+ if (value === 'Videos') {
38
+ return ['videos']
39
+ }
40
+ if (value === 'All') {
41
+ return ['images', 'videos']
42
+ }
43
+ return Array.isArray(value) ? value : [value]
44
+ }
45
+
46
+ function libraryPermission(response: PermissionResponse) {
47
+ return { ...response, accessPrivileges: response.granted ? 'all' : 'none' }
48
+ }
49
+
50
+ /**
51
+ * The editing step crops: to a square on iOS, which ignores `aspect`; to `aspect` on Android.
52
+ */
53
+ async function edited(photo: CapturedPhoto, options: Options): Promise<CapturedPhoto> {
54
+ if (!options.allowsEditing || options.allowsMultipleSelection) {
55
+ return photo
56
+ }
57
+ const aspect = platform() === 'ios' ? ([1, 1] as [number, number]) : options.aspect
58
+ return aspect === undefined ? photo : cropToAspect(photo, aspect, options.quality ?? 1)
59
+ }
60
+
61
+ function asset(photo: CapturedPhoto, options: Options, source: { library?: LibraryPhoto; fileName: string }) {
62
+ const { base64, size } = dataUrlInfo(photo.uri)
63
+ const { device } = getState()
64
+ return {
65
+ uri: photo.uri,
66
+ assetId: source.library?.id ?? null,
67
+ width: photo.width,
68
+ height: photo.height,
69
+ type: 'image',
70
+ fileName: source.fileName,
71
+ fileSize: size,
72
+ mimeType: 'image/jpeg',
73
+ exif: options.exif
74
+ ? {
75
+ Make: device.platform === 'ios' ? 'Apple' : 'Google',
76
+ Model: device.label,
77
+ Orientation: 1,
78
+ PixelXDimension: photo.width,
79
+ PixelYDimension: photo.height,
80
+ ...(source.library?.location && {
81
+ GPSLatitude: Math.abs(source.library.location.latitude),
82
+ GPSLatitudeRef: source.library.location.latitude >= 0 ? 'N' : 'S',
83
+ GPSLongitude: Math.abs(source.library.location.longitude),
84
+ GPSLongitudeRef: source.library.location.longitude >= 0 ? 'E' : 'W',
85
+ }),
86
+ }
87
+ : null,
88
+ base64: options.base64 ? base64 : null,
89
+ duration: null,
90
+ pairedVideoAsset: null,
91
+ }
92
+ }
93
+
94
+ /**
95
+ * The image picker on the simulated phone. The library opens the system photo picker over the photos panel's library,
96
+ * which needs no permission, as on iOS 14+ and Android's photo picker. The camera opens the system camera on the
97
+ * camera panel's feeds, which needs the camera permission first, as the module requires.
98
+ */
99
+ export default {
100
+ async launchImageLibraryAsync(options: Options = {}) {
101
+ const multiple = options.allowsMultipleSelection ?? false
102
+ const library = libraryPhotos()
103
+ const result = await showDialog({
104
+ kind: 'photo-picker',
105
+ multiple,
106
+ limit: multiple ? (options.selectionLimit ?? 0) : 1,
107
+ ordered: options.orderedSelection,
108
+ mediaTypes: mediaTypes(options.mediaTypes),
109
+ photos: await Promise.all(library.map(async (photo) => ({ id: photo.id, filename: photo.filename, favorite: photo.favorite, thumbnail: await photoThumbnail(photo) }))),
110
+ albums: libraryAlbums().map(({ id, title, assetIds }) => ({ id, title, assetIds })),
111
+ })
112
+ if (result.button !== 1 || !result.selected?.length) {
113
+ return { canceled: true, assets: null }
114
+ }
115
+ const photos = result.selected.map((id) => libraryPhoto(id)).filter((photo) => photo !== null)
116
+ const assets = await Promise.all(
117
+ photos.map(async (library) => {
118
+ const photo = await edited(await photoDataUrl(library, { quality: options.quality ?? 1 }), options)
119
+ return asset(photo, options, { library, fileName: library.filename })
120
+ }),
121
+ )
122
+ return { canceled: false, assets }
123
+ },
124
+
125
+ async launchCameraAsync(options: Options = {}) {
126
+ if (getPermission('camera').status !== 'granted') {
127
+ throw platform() === 'ios'
128
+ ? new CodedError('ERR_MISSING_CAMERA_PERMISSIONS', 'Missing camera or camera roll permission')
129
+ : new CodedError('ERR_USER_REJECTED_PERMISSIONS', 'User rejected permissions')
130
+ }
131
+ const camera = plugin<CameraState>('camera', INITIAL_CAMERA).get()
132
+ const result = await showDialog({ kind: 'camera', facing: options.cameraType ?? 'back', feeds: feedsOf(camera) })
133
+ if (result.button !== 1 || result.photo === undefined) {
134
+ return { canceled: true, assets: null }
135
+ }
136
+ const photo = await edited(result.photo, options)
137
+ const fileName = platform() === 'ios' ? null : `${crypto.randomUUID()}.jpeg`
138
+ return { canceled: false, assets: [asset(photo, options, { fileName: fileName as string })] }
139
+ },
140
+
141
+ async getCameraPermissionsAsync() {
142
+ return getPermission('camera')
143
+ },
144
+ async requestCameraPermissionsAsync() {
145
+ return requestPermission('camera')
146
+ },
147
+ async getMediaLibraryPermissionsAsync(_writeOnly?: boolean) {
148
+ return libraryPermission(getPermission('photos'))
149
+ },
150
+ async requestMediaLibraryPermissionsAsync(_writeOnly?: boolean) {
151
+ return libraryPermission(await requestPermission('photos'))
152
+ },
153
+ }
@@ -0,0 +1,13 @@
1
+ import { defineOverrides } from '../../../../src/node/overrides/define.ts'
2
+
3
+ export default defineOverrides('expo-image-picker', [
4
+ {
5
+ versions: '>=58 <59',
6
+ note: "the system photo picker over the photos panel's library, and the system camera on the camera panel's feeds",
7
+ // The package's entry point is its TypeScript source; the build is there too, for deep imports.
8
+ files: {
9
+ 'src/ExponentImagePicker.web.ts': './ExponentImagePicker.ts',
10
+ 'build/ExponentImagePicker.web.js': './ExponentImagePicker.ts',
11
+ },
12
+ },
13
+ ])