@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,269 @@
1
+ import { CodedError } from 'expo'
2
+ import { type Ref, useEffect, useImperativeHandle, useMemo, useRef, useState, useSyncExternalStore } from 'react'
3
+ import { StyleSheet, View } from 'react-native'
4
+ // @ts-expect-error react-native-web's element factory has no types.
5
+ import createElement from 'react-native-web/dist/exports/createElement'
6
+ import { capturePhoto, dataUrlInfo, drawCameraFrame, getHost, getState, plugin, subscribe } from 'web-sim/runtime'
7
+ import { type CameraState, feedOf, INITIAL_CAMERA, type Scan } from '../../state.ts'
8
+
9
+ type Facing = 'front' | 'back'
10
+
11
+ type PictureOptions = {
12
+ quality?: number
13
+ base64?: boolean
14
+ exif?: boolean
15
+ additionalExif?: Record<string, unknown>
16
+ id?: number
17
+ onPictureSaved?: (picture: unknown) => void
18
+ }
19
+
20
+ type BarcodeEvent = {
21
+ type: string
22
+ data: string
23
+ raw: string
24
+ cornerPoints: { x: number; y: number }[]
25
+ bounds: { origin: { x: number; y: number }; size: { width: number; height: number } }
26
+ }
27
+
28
+ type Props = {
29
+ facing?: Facing
30
+ zoom?: number
31
+ mirror?: boolean
32
+ animateShutter?: boolean
33
+ active?: boolean
34
+ enableTorch?: boolean
35
+ flashMode?: 'off' | 'on' | 'auto'
36
+ barcodeScannerEnabled?: boolean
37
+ barcodeScannerSettings?: { barcodeTypes?: string[] }
38
+ onBarcodeScanned?: (event: { nativeEvent: BarcodeEvent }) => void
39
+ pointerEvents?: string
40
+ style?: unknown
41
+ children?: unknown
42
+ ref?: Ref<unknown>
43
+ onCameraReady?: () => void
44
+ onPictureSaved?: (event: { nativeEvent: { data: unknown; id: number } }) => void
45
+ }
46
+
47
+ const PICTURE_SIZES = ['640x480', '1280x720', '1920x1080', '3024x4032']
48
+
49
+ const Canvas = (props: Record<string, unknown>) => createElement('canvas', props)
50
+
51
+ const camera = () => plugin<CameraState>('camera', INITIAL_CAMERA)
52
+
53
+ /**
54
+ * A barcode in the middle of the preview, in the module's event shape. The corner points come in each platform's
55
+ * order: iOS from the bottom left, Android from the top left.
56
+ */
57
+ function barcodeEvent(scan: Scan, width: number, height: number): BarcodeEvent {
58
+ const size = Math.min(width, height) * 0.4
59
+ const x = (width - size) / 2
60
+ const y = (height - size) / 2
61
+ const [tl, tr, br, bl] = [
62
+ { x, y },
63
+ { x: x + size, y },
64
+ { x: x + size, y: y + size },
65
+ { x, y: y + size },
66
+ ]
67
+ return {
68
+ type: scan.type,
69
+ data: scan.data,
70
+ raw: scan.data,
71
+ cornerPoints: getState().device.platform === 'ios' ? [bl, br, tl, tr] : [tl, tr, br, bl],
72
+ bounds: { origin: { x, y }, size: { width: size, height: size } },
73
+ }
74
+ }
75
+
76
+ /**
77
+ * The camera preview on the simulated phone: the camera panel's feed in place of `getUserMedia`, black until the
78
+ * camera permission is granted, as the device shows it. Pictures are the current frame. The torch, flash and
79
+ * scanner the app sets show in the panel; barcodes the panel scans reach `onBarcodeScanned`.
80
+ */
81
+ export default function ExponentCamera({ facing = 'back', zoom = 0, mirror = false, animateShutter = true, active = true, ref, ...props }: Props) {
82
+ const canvas = useRef<HTMLCanvasElement | null>(null)
83
+ const [paused, setPaused] = useState(false)
84
+ const [shutter, setShutter] = useState(0)
85
+ const granted = useSyncExternalStore(subscribe, () => getHost().getPermission('camera') === 'granted')
86
+ const running = granted && active && !paused
87
+ const state = camera().use()
88
+ const image = facing === 'back' ? state.backImage : state.frontImage
89
+ // eslint-disable-next-line react-hooks/exhaustive-deps
90
+ const feed = useMemo(() => feedOf(state, facing), [state[facing], image, state.code, facing])
91
+ const torch = running && (props.enableTorch ?? false)
92
+ const scanning = running && (props.barcodeScannerEnabled ?? false)
93
+ const scanned = useRef(props.onBarcodeScanned)
94
+ scanned.current = props.onBarcodeScanned
95
+ const barcodeTypes = props.barcodeScannerSettings?.barcodeTypes
96
+
97
+ // What the app's camera is doing, for the panel. Cleared when the preview goes, or the app's page with it.
98
+ useEffect(() => {
99
+ camera().set({ preview: running ? facing : null, scanning, torch, flash: props.flashMode ?? 'off' })
100
+ }, [running, facing, scanning, torch, props.flashMode])
101
+ useEffect(() => {
102
+ const clear = () => camera().set({ preview: null, scanning: false, torch: false })
103
+ window.addEventListener('pagehide', clear)
104
+ return () => {
105
+ window.removeEventListener('pagehide', clear)
106
+ clear()
107
+ }
108
+ }, [])
109
+
110
+ // Barcodes: the panel's scans, and the QR scene's code while it is in view.
111
+ useEffect(() => {
112
+ if (!scanning) {
113
+ return
114
+ }
115
+ const report = (scan: Scan): boolean => {
116
+ if (barcodeTypes !== undefined && barcodeTypes.length > 0 && !barcodeTypes.includes(scan.type)) {
117
+ return false
118
+ }
119
+ const element = canvas.current
120
+ scanned.current?.({ nativeEvent: barcodeEvent(scan, element?.clientWidth ?? 0, element?.clientHeight ?? 0) })
121
+ return true
122
+ }
123
+ const off = camera().on('scan', (payload) => {
124
+ if (report(payload as Scan)) {
125
+ camera().emit('scanned', payload)
126
+ }
127
+ })
128
+ const timer = setInterval(() => {
129
+ const current = camera().get()
130
+ if (current.autoScan && current[facing] === 'qr') {
131
+ report({ data: current.code, type: 'qr' })
132
+ }
133
+ }, 1000)
134
+ return () => {
135
+ off()
136
+ clearInterval(timer)
137
+ }
138
+ }, [scanning, facing, barcodeTypes?.join(',')])
139
+
140
+ const { onCameraReady } = props
141
+ useEffect(() => {
142
+ if (granted) {
143
+ onCameraReady?.()
144
+ }
145
+ // Ready once the camera starts.
146
+ // eslint-disable-next-line react-hooks/exhaustive-deps
147
+ }, [granted])
148
+
149
+ useEffect(() => {
150
+ const element = canvas.current
151
+ if (element === null) {
152
+ return
153
+ }
154
+ if (!granted) {
155
+ const ctx = element.getContext('2d')!
156
+ ctx.fillStyle = '#000'
157
+ ctx.fillRect(0, 0, element.width, element.height)
158
+ return
159
+ }
160
+ if (!running) {
161
+ return
162
+ }
163
+ let frame = 0
164
+ const draw = () => {
165
+ const ratio = Math.min(window.devicePixelRatio || 1, 2)
166
+ const width = Math.round(element.clientWidth * ratio)
167
+ const height = Math.round(element.clientHeight * ratio)
168
+ if (width > 0 && height > 0) {
169
+ if (element.width !== width || element.height !== height) {
170
+ element.width = width
171
+ element.height = height
172
+ }
173
+ drawCameraFrame(element.getContext('2d')!, width, height, performance.now() / 1000, feed, { zoom, torch })
174
+ }
175
+ frame = requestAnimationFrame(draw)
176
+ }
177
+ draw()
178
+ return () => cancelAnimationFrame(frame)
179
+ }, [granted, running, feed, zoom, torch])
180
+
181
+ useImperativeHandle(
182
+ ref,
183
+ () => ({
184
+ async getAvailablePictureSizes() {
185
+ return PICTURE_SIZES
186
+ },
187
+ async takePicture(options: PictureOptions = {}) {
188
+ if (!granted) {
189
+ throw new CodedError('ERR_CAMERA_NOT_READY', 'Camera is not ready yet. Wait for `onCameraReady` callback.')
190
+ }
191
+ if (animateShutter) {
192
+ setShutter((count) => count + 1)
193
+ }
194
+ const { device, orientation } = getState()
195
+ const photo = capturePhoto({ facing, feed: feedOf(camera().get(), facing), orientation, mirror, quality: options.quality ?? 1, zoom, torch })
196
+ const picture = {
197
+ uri: photo.uri,
198
+ width: photo.width,
199
+ height: photo.height,
200
+ format: 'jpg',
201
+ ...(options.base64 && { base64: dataUrlInfo(photo.uri).base64 }),
202
+ ...(options.exif && {
203
+ exif: {
204
+ Make: device.platform === 'ios' ? 'Apple' : 'Google',
205
+ Model: device.label,
206
+ Orientation: 1,
207
+ PixelXDimension: photo.width,
208
+ PixelYDimension: photo.height,
209
+ LensFacing: facing,
210
+ DateTimeOriginal: new Date().toISOString().slice(0, 19).replace('T', ' ').replace(/-/g, ':'),
211
+ ...options.additionalExif,
212
+ },
213
+ }),
214
+ }
215
+ props.onPictureSaved?.({ nativeEvent: { data: picture, id: options.id ?? -1 } })
216
+ return picture
217
+ },
218
+ async resumePreview() {
219
+ setPaused(false)
220
+ },
221
+ async pausePreview() {
222
+ setPaused(true)
223
+ },
224
+ async record() {
225
+ console.warn('Recording is not supported in web-sim.')
226
+ return { uri: '' }
227
+ },
228
+ async stopRecording() {},
229
+ async toggleRecording() {},
230
+ async launchModernScanner() {},
231
+ async getAvailableLenses() {
232
+ return facing === 'back' ? ['Back Camera', 'Back Ultra Wide Camera'] : ['Front Camera']
233
+ },
234
+ }),
235
+ [granted, facing, mirror, zoom, torch, animateShutter, props.onPictureSaved],
236
+ )
237
+
238
+ return (
239
+ <View style={[styles.wrapper, props.style as object]}>
240
+ <Canvas
241
+ ref={canvas}
242
+ style={{
243
+ position: 'absolute', top: 0, left: 0,
244
+ width: '100%',
245
+ height: '100%',
246
+ backgroundColor: '#000',
247
+ pointerEvents: props.pointerEvents,
248
+ transform: facing === 'front' ? [{ scaleX: -1 }] : undefined,
249
+ }}
250
+ />
251
+ {shutter > 0 && <Shutter key={shutter} />}
252
+ {props.children as never}
253
+ </View>
254
+ )
255
+ }
256
+
257
+ /** The preview blinks black as a picture is taken. */
258
+ function Shutter() {
259
+ const [visible, setVisible] = useState(true)
260
+ useEffect(() => {
261
+ const timer = setTimeout(() => setVisible(false), 120)
262
+ return () => clearTimeout(timer)
263
+ }, [])
264
+ return visible ? <View style={[StyleSheet.absoluteFill, { backgroundColor: '#000' }]} pointerEvents="none" /> : null
265
+ }
266
+
267
+ const styles = StyleSheet.create({
268
+ wrapper: { flex: 1, alignItems: 'stretch', overflow: 'hidden' },
269
+ })
@@ -0,0 +1,56 @@
1
+ import { getPermission, requestPermission } from 'web-sim/runtime'
2
+ // @ts-expect-error The package's web manager, for what the simulator leaves as it is (scanning images by URL).
3
+ import original from 'web-sim:original'
4
+
5
+ type Camera = {
6
+ takePicture(options: unknown): Promise<unknown>
7
+ pausePreview(): Promise<void>
8
+ resumePreview(): Promise<void>
9
+ getAvailablePictureSizes(ratio?: string): Promise<string[]>
10
+ }
11
+
12
+ /**
13
+ * The camera manager on the simulated phone: both cameras are there, and the permissions are the simulator's.
14
+ */
15
+ export default {
16
+ ...original,
17
+ isModernBarcodeScannerAvailable: false,
18
+ isDocumentScannerAvailable: false,
19
+ toggleRecordingAsyncAvailable: false,
20
+ async isAvailableAsync() {
21
+ return true
22
+ },
23
+ async getAvailableCameraTypesAsync() {
24
+ return ['front', 'back']
25
+ },
26
+ async takePicture(options: unknown, camera: Camera) {
27
+ return camera.takePicture(options)
28
+ },
29
+ async pausePreview(camera: Camera) {
30
+ return camera.pausePreview()
31
+ },
32
+ async resumePreview(camera: Camera) {
33
+ return camera.resumePreview()
34
+ },
35
+ async getAvailablePictureSizes(ratio: string | undefined, camera: Camera) {
36
+ return camera.getAvailablePictureSizes(ratio)
37
+ },
38
+ async getPermissionsAsync() {
39
+ return getPermission('camera')
40
+ },
41
+ async requestPermissionsAsync() {
42
+ return requestPermission('camera')
43
+ },
44
+ async getCameraPermissionsAsync() {
45
+ return getPermission('camera')
46
+ },
47
+ async requestCameraPermissionsAsync() {
48
+ return requestPermission('camera')
49
+ },
50
+ async getMicrophonePermissionsAsync() {
51
+ return getPermission('microphone')
52
+ },
53
+ async requestMicrophonePermissionsAsync() {
54
+ return requestPermission('microphone')
55
+ },
56
+ }
@@ -0,0 +1,12 @@
1
+ import { defineOverrides } from '../../../../src/node/overrides/define.ts'
2
+
3
+ export default defineOverrides('expo-camera', [
4
+ {
5
+ versions: '>=58 <59',
6
+ note: "the camera panel's feeds instead of getUserMedia; its barcodes reach the scanner; torch and flash show in the panel",
7
+ files: {
8
+ 'build/ExpoCamera.web.js': './ExpoCamera.tsx',
9
+ 'build/ExpoCameraManager.web.js': './ExpoCameraManager.ts',
10
+ },
11
+ },
12
+ ])
@@ -0,0 +1,9 @@
1
+ import { definePlugin } from '../../src/node/plugins.ts'
2
+
3
+ export default definePlugin({
4
+ name: 'camera',
5
+ // The system camera that expo-image-picker opens sees the same feeds.
6
+ packages: ['expo-camera', 'expo-image-picker'],
7
+ overrides: './overrides',
8
+ shell: './shell.tsx',
9
+ })
@@ -0,0 +1,107 @@
1
+ import { CameraIcon } from '@phosphor-icons/react'
2
+ import { useEffect, useRef } from 'react'
3
+ import { CAMERA_SCENES, downscaleImage, drawCameraFrame, type CameraFacing, type CameraFeed } from 'web-sim/runtime'
4
+ import { Button, defineShellPlugin, Field, FileButton, readDataUrl, Row, Select, TextField, Toggle } from 'web-sim/shell'
5
+ import { BARCODE_TYPES, type BarcodeType, type CameraState, feedOf, type FeedChoice, INITIAL_CAMERA, type Scan } from './state.ts'
6
+
7
+ /** A small live view of a feed, as the camera sees it. */
8
+ function FeedPreview({ feed, mirror }: { feed: CameraFeed; mirror: boolean }) {
9
+ const canvas = useRef<HTMLCanvasElement>(null)
10
+ useEffect(() => {
11
+ const element = canvas.current
12
+ if (element === null) {
13
+ return
14
+ }
15
+ let frame = 0
16
+ const draw = () => {
17
+ const ratio = Math.min(window.devicePixelRatio || 1, 2)
18
+ element.width = Math.round(element.clientWidth * ratio)
19
+ element.height = Math.round(element.clientHeight * ratio)
20
+ if (element.width > 0) {
21
+ drawCameraFrame(element.getContext('2d')!, element.width, element.height, performance.now() / 1000, feed)
22
+ }
23
+ frame = requestAnimationFrame(draw)
24
+ }
25
+ draw()
26
+ return () => cancelAnimationFrame(frame)
27
+ }, [feed])
28
+ return <canvas ref={canvas} style={{ width: 72, height: 96, flex: 'none', borderRadius: 6, background: '#000', transform: mirror ? 'scaleX(-1)' : undefined }} />
29
+ }
30
+
31
+ function FeedField({ facing, state, set }: { facing: CameraFacing; state: CameraState; set: (patch: Partial<CameraState>) => void }) {
32
+ const image = facing === 'back' ? state.backImage : state.frontImage
33
+ const imageKey = facing === 'back' ? 'backImage' : 'frontImage'
34
+ const label = facing === 'back' ? 'Back camera' : 'Front camera'
35
+ const options = [
36
+ ...Object.entries(CAMERA_SCENES).map(([value, title]) => ({ value: value as FeedChoice, label: title })),
37
+ ...(image !== null ? [{ value: 'image' as const, label: 'Uploaded image' }] : []),
38
+ ]
39
+ const upload = async (files: File[]) => {
40
+ const photo = await downscaleImage(await readDataUrl(files[0]), 1280)
41
+ set({ [facing]: 'image', [imageKey]: photo.uri })
42
+ }
43
+ return (
44
+ <Field label={label}>
45
+ <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
46
+ <FeedPreview feed={feedOf(state, facing)} mirror={facing === 'front'} />
47
+ <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 6 }}>
48
+ <Select label={label} value={state[facing]} options={options} onChange={(choice) => set({ [facing]: choice })} />
49
+ <FileButton accept="image/*" title={`Upload an image for the ${label.toLowerCase()}`} onFiles={upload}>
50
+ Upload
51
+ </FileButton>
52
+ </div>
53
+ </div>
54
+ </Field>
55
+ )
56
+ }
57
+
58
+ export default defineShellPlugin<CameraState>({
59
+ id: 'camera',
60
+ title: 'Camera',
61
+ icon: CameraIcon,
62
+ initialState: INITIAL_CAMERA,
63
+ actions: {
64
+ /**
65
+ * Shows a barcode to the camera: a mounted `CameraView` that scans reports it. Without `data`, the panel's code.
66
+ * Returns whether a camera read it.
67
+ */
68
+ scan: (context, args) => {
69
+ const state = context.state()
70
+ const scan: Scan = { data: state.code, type: state.codeType, ...(args as Partial<Scan> | undefined) }
71
+ context.set({ code: scan.data, codeType: scan.type as BarcodeType })
72
+ let read = 0
73
+ // The app's side answers at once, while the event is delivered.
74
+ const off = context.on('scanned', () => {
75
+ read += 1
76
+ })
77
+ context.emit('scan', scan)
78
+ off()
79
+ return { scanned: read > 0 }
80
+ },
81
+ },
82
+ Panel: ({ state, set, run }) => {
83
+ const on = (value: boolean) => (value ? 'On' : 'Off')
84
+ return (
85
+ <>
86
+ <FeedField facing="back" state={state} set={set} />
87
+ <FeedField facing="front" state={state} set={set} />
88
+ <Field label="Barcode">
89
+ <TextField label="Barcode data" value={state.code} onChange={(code) => set({ code })} />
90
+ <Row>
91
+ <div style={{ flex: 1 }}>
92
+ <Select label="Barcode type" value={state.codeType} options={BARCODE_TYPES.map((type) => ({ value: type, label: type }))} onChange={(codeType) => set({ codeType })} />
93
+ </div>
94
+ <Button disabled={!state.scanning} onClick={() => run('scan')} title="Show this barcode to the scanning camera">
95
+ Scan
96
+ </Button>
97
+ </Row>
98
+ </Field>
99
+ <Toggle label="Auto-scan QR scene" checked={state.autoScan} onChange={(autoScan) => set({ autoScan })} />
100
+ <Field label="Preview" value={state.preview === null ? 'Off' : state.preview === 'back' ? 'Back' : 'Front'} />
101
+ <Field label="Scanner" value={on(state.scanning)} />
102
+ <Field label="Torch" value={on(state.torch)} />
103
+ <Field label="Flash" value={state.flash[0].toUpperCase() + state.flash.slice(1)} />
104
+ </>
105
+ )
106
+ },
107
+ })
@@ -0,0 +1,61 @@
1
+ import type { CameraFacing, CameraFeed, CameraScene } from '../../src/runtime/media.ts'
2
+
3
+ export type FeedChoice = CameraScene | 'image'
4
+
5
+ /**
6
+ * What each camera sees, set in the panel; the barcode the panel scans; and, as output, what the app's camera is
7
+ * doing. Shared by the panel, `expo-camera` and the system camera.
8
+ */
9
+ export type CameraState = {
10
+ back: FeedChoice
11
+ front: FeedChoice
12
+ /** Uploaded images, as JPEG data URLs no larger than 1280px. */
13
+ backImage: string | null
14
+ frontImage: string | null
15
+ /** The barcode the QR scene shows and the panel scans. */
16
+ code: string
17
+ codeType: BarcodeType
18
+ /** A scanning camera looking at the QR scene reads its code by itself, about once a second. */
19
+ autoScan: boolean
20
+ /** The camera the app's preview shows, or null when none is open. */
21
+ preview: CameraFacing | null
22
+ /** Whether the open preview scans barcodes. */
23
+ scanning: boolean
24
+ torch: boolean
25
+ flash: 'off' | 'on' | 'auto'
26
+ }
27
+
28
+ export const BARCODE_TYPES = ['qr', 'ean13', 'ean8', 'upc_a', 'upc_e', 'code128', 'code39', 'code93', 'codabar', 'itf14', 'pdf417', 'aztec', 'datamatrix'] as const
29
+
30
+ export type BarcodeType = (typeof BARCODE_TYPES)[number]
31
+
32
+ export const INITIAL_CAMERA: CameraState = {
33
+ back: 'park',
34
+ front: 'selfie',
35
+ backImage: null,
36
+ frontImage: null,
37
+ code: 'https://example.com/menu',
38
+ codeType: 'qr',
39
+ autoScan: true,
40
+ preview: null,
41
+ scanning: false,
42
+ torch: false,
43
+ flash: 'off',
44
+ }
45
+
46
+ /** What a camera sees. An image feed with no image is the black of a covered lens. */
47
+ export function feedOf(state: CameraState, facing: CameraFacing): CameraFeed {
48
+ const choice = state[facing]
49
+ if (choice === 'image') {
50
+ const image = facing === 'back' ? state.backImage : state.frontImage
51
+ return image === null ? { scene: 'dark' } : { image }
52
+ }
53
+ return choice === 'qr' ? { scene: 'qr', code: state.code } : { scene: choice }
54
+ }
55
+
56
+ export function feedsOf(state: CameraState): Record<CameraFacing, CameraFeed> {
57
+ return { back: feedOf(state, 'back'), front: feedOf(state, 'front') }
58
+ }
59
+
60
+ /** A barcode as the panel or CLI scans it. */
61
+ export type Scan = { data: string; type: string }
@@ -0,0 +1,138 @@
1
+ import { NativeModule, registerWebModule } from 'expo'
2
+ import { app, platform, plugin, showDialog } from 'web-sim/runtime'
3
+ import { type ClipboardState, contentChanged, contentTypes, imageSize, INITIAL_CLIPBOARD, isUrl, toDataUri, write } from '../../state.ts'
4
+
5
+ /**
6
+ * `ExpoClipboard` over the phone's own pasteboard, kept in the clipboard plugin's state: the app copies and pastes
7
+ * there, never to the computer's clipboard, and the panel shows it. The change event fires on every change to it,
8
+ * the panel's edits included. On iOS, with "Ask before pasting" on, reading what came from outside the app asks first.
9
+ */
10
+ export const clipboardEventName = 'onClipboardChanged'
11
+
12
+ type ContentType = ReturnType<typeof contentTypes>[number]
13
+
14
+ const clipboard = () => plugin<ClipboardState>('clipboard', INITIAL_CLIPBOARD)
15
+
16
+ function htmlToText(html: string): string {
17
+ return new DOMParser().parseFromString(html, 'text/html').body.textContent ?? ''
18
+ }
19
+
20
+ /** iOS's paste prompt, when it applies. Resolves whether the app may read the pasteboard. */
21
+ async function mayPaste(): Promise<boolean> {
22
+ const state = clipboard().get()
23
+ if (platform() !== 'ios' || !state.pastePrompt || state.source === 'app' || state.pasteAllowed || contentTypes(state).length === 0) {
24
+ return true
25
+ }
26
+ const { button } = await showDialog({
27
+ kind: 'alert',
28
+ title: `“${app().name}” would like to paste`,
29
+ message: 'Do you want to allow this?',
30
+ buttons: [{ text: 'Don’t Allow Paste', style: 'cancel' }, { text: 'Allow Paste' }],
31
+ })
32
+ if (button !== 1) {
33
+ return false
34
+ }
35
+ // Allowed for these contents, until the next change.
36
+ if (clipboard().get().changeCount === state.changeCount) {
37
+ clipboard().set({ pasteAllowed: true })
38
+ }
39
+ return true
40
+ }
41
+
42
+ /** The image in the format asked for, through a canvas when it is stored in another. */
43
+ async function convert(data: string, format: string | undefined, quality: number | undefined): Promise<string> {
44
+ const mime = format === 'jpeg' ? 'image/jpeg' : 'image/png'
45
+ if (data.startsWith(`data:${mime}`)) {
46
+ return data
47
+ }
48
+ const image = new Image()
49
+ image.src = data
50
+ await image.decode()
51
+ const canvas = document.createElement('canvas')
52
+ canvas.width = image.naturalWidth
53
+ canvas.height = image.naturalHeight
54
+ canvas.getContext('2d')!.drawImage(image, 0, 0)
55
+ return canvas.toDataURL(mime, quality)
56
+ }
57
+
58
+ class ExpoClipboard extends NativeModule<{ onClipboardChanged: (event: { contentTypes: ContentType[] }) => void }> {
59
+ private stop: (() => void) | null = null
60
+
61
+ startObserving() {
62
+ this.stop ??= clipboard().watch((next, previous) => {
63
+ if (contentChanged(next, previous)) {
64
+ this.emit(clipboardEventName, { contentTypes: contentTypes(next) })
65
+ }
66
+ })
67
+ }
68
+
69
+ stopObserving() {
70
+ this.stop?.()
71
+ this.stop = null
72
+ }
73
+
74
+ async getStringAsync(options: { preferredFormat?: string } = {}) {
75
+ if (!(await mayPaste())) {
76
+ return ''
77
+ }
78
+ const state = clipboard().get()
79
+ if (options.preferredFormat === 'html' && state.html !== null) {
80
+ return state.html
81
+ }
82
+ return state.text ?? state.url ?? ''
83
+ }
84
+
85
+ async setStringAsync(text: string, options: { inputFormat?: string } = {}) {
86
+ const state = clipboard().get()
87
+ clipboard().set(options.inputFormat === 'html' ? write(state, { text: htmlToText(text), html: text }, 'app') : write(state, { text }, 'app'))
88
+ return true
89
+ }
90
+
91
+ async hasStringAsync() {
92
+ const state = clipboard().get()
93
+ return (state.text !== null && state.text !== '') || state.url !== null
94
+ }
95
+
96
+ async getImageAsync(options: { format?: string; jpegQuality?: number } = {}) {
97
+ if (!(await mayPaste())) {
98
+ return null
99
+ }
100
+ const { image } = clipboard().get()
101
+ if (image === null) {
102
+ return null
103
+ }
104
+ return { data: await convert(image.data, options.format, options.jpegQuality), size: { width: image.width, height: image.height } }
105
+ }
106
+
107
+ async setImageAsync(base64: string) {
108
+ const data = toDataUri(base64)
109
+ const size = await imageSize(data)
110
+ clipboard().set(write(clipboard().get(), { image: { data, ...size } }, 'app'))
111
+ }
112
+
113
+ async hasImageAsync() {
114
+ return clipboard().get().image !== null
115
+ }
116
+ }
117
+
118
+ // iOS only, as on the device: a URL item, or text that is a URL.
119
+ class ExpoClipboardIos extends ExpoClipboard {
120
+ async getUrlAsync() {
121
+ if (!(await mayPaste())) {
122
+ return null
123
+ }
124
+ const { url, text } = clipboard().get()
125
+ return url ?? (isUrl(text) ? text : null)
126
+ }
127
+
128
+ async setUrlAsync(url: string) {
129
+ clipboard().set(write(clipboard().get(), { url, text: url }, 'app'))
130
+ }
131
+
132
+ async hasUrlAsync() {
133
+ const { url, text } = clipboard().get()
134
+ return url !== null || isUrl(text)
135
+ }
136
+ }
137
+
138
+ export default registerWebModule(platform() === 'ios' ? ExpoClipboardIos : ExpoClipboard, 'ExpoClipboard')
@@ -0,0 +1,9 @@
1
+ import { defineOverrides } from '../../../../src/node/overrides/define.ts'
2
+
3
+ export default defineOverrides('expo-clipboard', [
4
+ {
5
+ versions: '>=58 <59',
6
+ note: "the phone's own pasteboard in the clipboard panel, with the change listener (which throws on the web build), iOS's URL methods and its paste prompt",
7
+ files: { 'build/ExpoClipboard.web.js': './ExpoClipboard.ts' },
8
+ },
9
+ ])
@@ -0,0 +1,8 @@
1
+ import { definePlugin } from '../../src/node/plugins.ts'
2
+
3
+ export default definePlugin({
4
+ name: 'clipboard',
5
+ packages: ['expo-clipboard'],
6
+ overrides: './overrides',
7
+ shell: './shell.tsx',
8
+ })