@octane-xplat/camera 0.18.0 → 0.20.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 (67) hide show
  1. package/README.md +2 -132
  2. package/package.json +108 -103
  3. package/platforms/android/java/com/octanexplat/camera/CameraPreviewView.java +24 -0
  4. package/platforms/android/java/com/octanexplat/camera/CameraSessionBridge.java +153 -21
  5. package/platforms/ios/src/XplatSwitchingMovieWriter.swift +557 -0
  6. package/src/CameraView.android.tsrx +194 -118
  7. package/src/CameraView.ios.tsrx +129 -76
  8. package/src/CameraView.macos.tsrx +108 -70
  9. package/src/CameraView.tsrx +2 -0
  10. package/src/CameraView.web.tsrx +160 -125
  11. package/src/CameraView.windows.tsrx +141 -92
  12. package/src/camera-host.macos.ts +1059 -0
  13. package/src/camera-permission.mobile.ts +85 -81
  14. package/src/camera-permission.windows.ts +56 -53
  15. package/src/camera-session.ios.ts +89 -61
  16. package/src/camera-session.macos.ts +51 -49
  17. package/src/camera-session.windows.ts +113 -105
  18. package/src/host-movie.web.ts +266 -222
  19. package/src/index.ts +28 -26
  20. package/src/index.web.ts +27 -25
  21. package/src/layout-child.ts +88 -79
  22. package/src/layout-child.web.ts +57 -51
  23. package/src/layout-child.windows.ts +82 -71
  24. package/src/movie-metadata.web.ts +87 -74
  25. package/src/movie-storage.web.ts +142 -135
  26. package/src/movie-writer.ios.ts +170 -0
  27. package/src/photo-lifecycle.macos.ts +60 -0
  28. package/src/photo-sheet.macos.ts +505 -0
  29. package/src/preview-display.ios.ts +69 -0
  30. package/src/preview-pinch.ts +41 -0
  31. package/src/preview-tap.ts +22 -21
  32. package/src/props.ts +118 -68
  33. package/src/recording-haptics.ios.ts +39 -0
  34. package/src/recording-source.web.ts +159 -0
  35. package/src/session-backend.android.ts +552 -410
  36. package/src/session-backend.ios.ts +1500 -1148
  37. package/src/session-backend.linux.ts +886 -860
  38. package/src/session-backend.macos.ts +697 -679
  39. package/src/session-backend.ts +51 -49
  40. package/src/session-backend.web.ts +1181 -867
  41. package/src/session-backend.windows.ts +1556 -1467
  42. package/src/session-core.ts +925 -711
  43. package/src/session.ts +12 -12
  44. package/src/style-merge.ts +43 -43
  45. package/src/synthetic-session.ts +392 -333
  46. package/src/types.ts +384 -239
  47. package/types/generated/.tsrx-typegen-manifest.json +18 -0
  48. package/types/generated/CameraView.d.ts +2 -0
  49. package/types/generated/CameraView.web.d.ts +4 -0
  50. package/types/generated/camera-host.macos.d.ts +33 -0
  51. package/types/generated/index.d.ts +34 -0
  52. package/types/generated/layout-child.web.d.ts +7 -0
  53. package/types/generated/photo-lifecycle.macos.d.ts +12 -0
  54. package/types/generated/photo-sheet.macos.d.ts +36 -0
  55. package/types/generated/props.d.ts +111 -0
  56. package/types/generated/session-backend.d.ts +6 -0
  57. package/types/{session-core.d.ts → generated/session-core.d.ts} +30 -1
  58. package/types/generated/session.d.ts +16 -0
  59. package/types/{synthetic-session.d.ts → generated/synthetic-session.d.ts} +15 -1
  60. package/types/{types.d.ts → generated/types.d.ts} +145 -2
  61. package/LICENSE +0 -21
  62. package/platforms/macos/src/CameraOwnership.swift +0 -22
  63. package/platforms/macos/src/PhotoCaptureLifecycle.swift +0 -34
  64. package/platforms/macos/src/XplatCameraHost.swift +0 -639
  65. package/platforms/macos/src/XplatPhotoCaptureSheet.swift +0 -192
  66. package/types/index.d.ts +0 -48
  67. package/types/props.d.ts +0 -61
@@ -0,0 +1,60 @@
1
+ /** Fences every asynchronous permission, preview and shutter result — the
2
+ * PhotoCaptureLifecycle state machine, now plain JS. */
3
+ export type Phase = 'idle' | 'preparing' | 'preview' | 'capturing' | 'finished'
4
+
5
+ const Phase: Record<Phase, Phase> = {
6
+ idle: 'idle',
7
+ preparing: 'preparing',
8
+ preview: 'preview',
9
+ capturing: 'capturing',
10
+ finished: 'finished',
11
+ }
12
+
13
+ export function createPhotoCaptureLifecycle() {
14
+ let phase: Phase = Phase.idle
15
+ let generation = 0
16
+
17
+ return {
18
+ get phase(): Phase {
19
+ return phase
20
+ },
21
+ prepare(): number | null {
22
+ if (phase !== Phase.idle) {
23
+ return null
24
+ }
25
+
26
+ phase = Phase.preparing
27
+ return generation
28
+ },
29
+ ready(token: number): boolean {
30
+ if (!this.accepts(token) || phase !== Phase.preparing) {
31
+ return false
32
+ }
33
+
34
+ phase = Phase.preview
35
+ return true
36
+ },
37
+ capture(): number | null {
38
+ if (phase !== Phase.preview) {
39
+ return null
40
+ }
41
+
42
+ phase = Phase.capturing
43
+ return generation
44
+ },
45
+ accepts(token: number): boolean {
46
+ return phase !== Phase.finished && token === generation
47
+ },
48
+ finish(): boolean {
49
+ if (phase === Phase.finished) {
50
+ return false
51
+ }
52
+
53
+ phase = Phase.finished
54
+ generation += 1
55
+ return true
56
+ },
57
+ }
58
+ }
59
+
60
+ export type PhotoCaptureLifecycle = ReturnType<typeof createPhotoCaptureLifecycle>
@@ -0,0 +1,505 @@
1
+ import { createCameraHost, type CameraHost } from './camera-host.macos.ts'
2
+
3
+ // TypeScript port of the removed Swift XplatPhotoCaptureSheet, registered under
4
+ // the same ObjC name so the media package's declare-const lookup still binds.
5
+ // App-owned still-photo UI: no microphone input, movie output or Photos writes.
6
+ declare const objc: { import(framework: string): void }
7
+ declare const NSObject: any
8
+ declare const NativeClass: (cls: unknown) => void
9
+ declare const interop: any
10
+
11
+ declare const NSApplication: any
12
+ declare const NSWindow: any
13
+ declare const NSView: any
14
+ declare const NSButton: any
15
+ declare const NSTextField: any
16
+ declare const NSColor: any
17
+ declare const NSImage: any
18
+ declare const NSBitmapImageRep: any
19
+ declare const NSWindowDelegate: any
20
+ declare const NSNotificationCenter: any
21
+ declare const NSOperationQueue: any
22
+ declare const NSFileManager: any
23
+ declare const NSUUID: any
24
+ declare const NSData: any
25
+ declare const NSNumber: any
26
+ declare const NSMutableDictionary: any
27
+
28
+ declare const NSWindowWillCloseNotification: string
29
+ declare const NSImageCompressionFactor: string
30
+
31
+ let importsDone = false
32
+ const ensureImports = () => {
33
+ if (!importsDone) {
34
+ importsDone = true
35
+ objc.import('AppKit')
36
+ objc.import('AVFoundation')
37
+ }
38
+ }
39
+
40
+ import { createPhotoCaptureLifecycle, type PhotoCaptureLifecycle } from './photo-lifecycle.macos.ts'
41
+
42
+ const typed = (object: any, cls: any): any =>
43
+ object == null ? object : Object.setPrototypeOf(object, cls.prototype)
44
+
45
+ // The class definition must stay import-safe where the bridge globals are
46
+ // absent (sandboxed loaders, non-AppKit bundles): fall back to inert bases.
47
+ // Constructing a sheet still requires the real host, which refuses lazily.
48
+ const g = globalThis as Record<string, any>
49
+ const SheetBase: any = g.NSObject ?? class {}
50
+ class XplatPhotoCaptureSheet extends SheetBase {
51
+ static ObjCProtocols: any[] = g.NSWindowDelegate ? [g.NSWindowDelegate] : []
52
+ static ObjCExposedMethods: Record<string, unknown> = {
53
+ permissionStatus: { params: [] as any[], returns: g.interop?.types?.id },
54
+ 'present:reply:': {
55
+ params: [g.interop?.types?.id, g.interop?.types?.id],
56
+ returns: g.interop?.types?.void,
57
+ },
58
+ 'discard:': { params: [g.interop?.types?.id], returns: g.interop?.types?.void },
59
+ dispose: { params: [] as any[], returns: g.interop?.types?.void },
60
+ 'windowShouldClose:': { params: [g.interop?.types?.id], returns: g.interop?.types?.bool },
61
+ // NSButton target/action selectors. Without entries the click never
62
+ // reaches JS — AppKit dispatch needs the registered selector.
63
+ capturePhoto: { params: [] as any[], returns: g.interop?.types?.void },
64
+ cancelPhoto: { params: [] as any[], returns: g.interop?.types?.void },
65
+ }
66
+ static {
67
+ if (typeof g.NativeClass === 'function') {
68
+ // The JSC host's native method enumeration sees enumerable keys only:
69
+ // class methods are non-enumerable, so mark the exposed methods
70
+ // before registering or AppKit dispatch cannot reach them.
71
+ for (const name of Object.keys(this.ObjCExposedMethods)) {
72
+ const descriptor = Object.getOwnPropertyDescriptor(this.prototype, name)
73
+
74
+ if (descriptor && typeof descriptor.value === 'function' && !descriptor.enumerable) {
75
+ Object.defineProperty(this.prototype, name, { ...descriptor, enumerable: true })
76
+ }
77
+ }
78
+
79
+ g.NativeClass(this)
80
+ }
81
+ }
82
+
83
+ // alloc().init() bypasses JS field initializers; create lazily so both
84
+ // construction paths land on a live host and lifecycle.
85
+ private _host: CameraHost | undefined
86
+ private _life: PhotoCaptureLifecycle | undefined
87
+ private get host(): CameraHost {
88
+ return (this._host ??= (ensureImports(), createCameraHost()))
89
+ }
90
+ private get life(): PhotoCaptureLifecycle {
91
+ return (this._life ??= createPhotoCaptureLifecycle())
92
+ }
93
+ private sheet: any
94
+ private parent: any
95
+ private reply: ((result: string | null) => void) | undefined
96
+ private timeout: ReturnType<typeof setTimeout> | undefined
97
+ private closeObserver: any
98
+ private preview: any
99
+ private captureButton: any
100
+ private statusLabel: any
101
+ private options: Record<string, unknown> = {}
102
+ private disposed = false
103
+ private _operationTimeout: number | undefined
104
+ // alloc().init() bypasses JS field initializers, so the deadline must not
105
+ // read a bare field: an uninitialized timeout would fire immediately.
106
+ private get operationTimeout(): number {
107
+ return (this._operationTimeout ??= 15_000)
108
+ }
109
+
110
+ permissionStatus(): string {
111
+ return this.host.permissionStatus('camera')
112
+ }
113
+
114
+ // ObjC callers bind present:reply:; JS callers use the camel alias.
115
+ presentReply(options: any, reply: (result: string | null) => void): void {
116
+ this['present:reply:'](options, reply)
117
+ }
118
+
119
+ ['present:reply:'](options: any, reply: (result: string | null) => void): void {
120
+ const app = NSApplication.sharedApplication
121
+ const parent = app.keyWindow ?? app.mainWindow
122
+
123
+ if (parent == null) {
124
+ reply(null)
125
+ return
126
+ }
127
+
128
+ this.presentOnWindow(parent, options ?? {}, reply)
129
+ }
130
+
131
+ // Explicit host window mirrors the Swift test seam.
132
+ presentOnWindow(
133
+ parent: any,
134
+ options: Record<string, unknown>,
135
+ reply: (result: string | null) => void,
136
+ ): void {
137
+ // saveToGallery is not refused here: the media leaf owns the Photos
138
+ // write after the shot file is delivered.
139
+ if (this.disposed || this.sheet != null || parent.attachedSheet != null) {
140
+ reply(null)
141
+ return
142
+ }
143
+
144
+ this.options = options
145
+ this.reply = reply
146
+ this.parent = parent
147
+
148
+ const frame = (w: number, h: number) => ({
149
+ origin: { x: 0, y: 0 },
150
+ size: { width: w, height: h },
151
+ })
152
+
153
+ const sheet = typed(
154
+ NSWindow.alloc().initWithContentRectStyleMaskBackingDefer(frame(640, 480), 3, 2, false),
155
+ NSWindow,
156
+ )
157
+
158
+ sheet.title = 'Take a photo'
159
+ sheet.delegate = this
160
+
161
+ const content = NSView.alloc().initWithFrame(frame(640, 480))
162
+ const preview = NSView.alloc().initWithFrame({
163
+ origin: { x: 16, y: 80 },
164
+ size: { width: 608, height: 384 },
165
+ })
166
+
167
+ preview.wantsLayer = true
168
+ preview.layer.backgroundColor = NSColor.blackColor.CGColor
169
+ content.addSubview(preview)
170
+
171
+ const status = NSTextField.labelWithString('Choose Capture to start the camera.')
172
+
173
+ status.frame = { origin: { x: 16, y: 48 }, size: { width: 440, height: 22 } }
174
+ content.addSubview(status)
175
+
176
+ const cancel = NSButton.buttonWithTitleTargetAction('Cancel', this, 'cancelPhoto')
177
+
178
+ cancel.keyEquivalent = ''
179
+ cancel.frame = { origin: { x: 432, y: 12 }, size: { width: 92, height: 32 } }
180
+ content.addSubview(cancel)
181
+
182
+ const capture = NSButton.buttonWithTitleTargetAction('Capture', this, 'capturePhoto')
183
+
184
+ capture.keyEquivalent = '\r'
185
+ capture.frame = { origin: { x: 528, y: 12 }, size: { width: 96, height: 32 } }
186
+ content.addSubview(capture)
187
+ sheet.contentView = content
188
+ this.sheet = sheet
189
+ this.preview = preview
190
+ this.statusLabel = status
191
+ this.captureButton = capture
192
+ this.closeObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
193
+ NSWindowWillCloseNotification,
194
+ parent,
195
+ NSOperationQueue.mainQueue,
196
+ () => this.complete(null),
197
+ )
198
+
199
+ parent.beginSheetCompletionHandler(sheet, () => this.complete(null))
200
+ }
201
+
202
+ private deadline(token: number): void {
203
+ if (this.timeout !== undefined) {
204
+ clearTimeout(this.timeout)
205
+ }
206
+
207
+ this.timeout = setTimeout(() => {
208
+ if (!this.disposed && this.life.accepts(token)) {
209
+ this.complete(null)
210
+ }
211
+ }, this.operationTimeout)
212
+ }
213
+
214
+ ['capturePhoto'](): void {
215
+ const prepared = this.life.prepare()
216
+
217
+ if (prepared != null) {
218
+ const token = prepared
219
+
220
+ if (this.captureButton != null) {
221
+ this.captureButton.isEnabled = false
222
+ }
223
+
224
+ if (this.statusLabel != null) {
225
+ this.statusLabel.stringValue = 'Starting camera…'
226
+ }
227
+
228
+ this.deadline(token)
229
+ // Authorization happens only after the user presses Capture.
230
+ this.host.requestPermissionReply('camera', (status: string) => {
231
+ if (this.disposed || !this.life.accepts(token)) {
232
+ return
233
+ }
234
+
235
+ if (status !== 'granted') {
236
+ this.complete(null)
237
+ return
238
+ }
239
+
240
+ const failure = this.host.configure({ photo: true, audio: false })
241
+
242
+ if (this.disposed || !this.life.accepts(token)) {
243
+ return
244
+ }
245
+
246
+ if (failure != null || this.preview == null) {
247
+ this.complete(null)
248
+ return
249
+ }
250
+
251
+ this.host.installObserver((message: string) => {
252
+ let event: any
253
+
254
+ try {
255
+ event = JSON.parse(message)
256
+ } catch {
257
+ return
258
+ }
259
+
260
+ if (!this.life.accepts(token)) {
261
+ return
262
+ }
263
+
264
+ if (event.type === 'previewReady' && event.ready === true && this.life.ready(token)) {
265
+ if (this.timeout !== undefined) {
266
+ clearTimeout(this.timeout)
267
+ this.timeout = undefined
268
+ }
269
+
270
+ this.captureButton.isEnabled = true
271
+ if (this.statusLabel != null) {
272
+ this.statusLabel.stringValue = 'Frame your photo, then choose Capture.'
273
+ }
274
+ } else if (
275
+ event.type === 'interrupted' ||
276
+ (event.type === 'availability' && event.available === false)
277
+ ) {
278
+ this.complete(null)
279
+ }
280
+ })
281
+
282
+ if (this.host.attachPreview(this.preview) != null) {
283
+ this.complete(null)
284
+ }
285
+ })
286
+
287
+ return
288
+ }
289
+
290
+ const token = this.life.capture()
291
+
292
+ if (token == null) {
293
+ return
294
+ }
295
+
296
+ if (this.captureButton != null) {
297
+ this.captureButton.isEnabled = false
298
+ }
299
+
300
+ if (this.statusLabel != null) {
301
+ this.statusLabel.stringValue = 'Taking photo…'
302
+ }
303
+
304
+ this.deadline(token)
305
+
306
+ const failure = this.host.capturePhoto((data: any) => {
307
+ if (this.disposed || !this.life.accepts(token)) {
308
+ return
309
+ }
310
+
311
+ const result = data != null ? this.persist(data) : null
312
+
313
+ this.complete(result)
314
+ })
315
+
316
+ if (failure != null) {
317
+ this.complete(null)
318
+ }
319
+ }
320
+
321
+ private persist(data: any): string | null {
322
+ const source = typed(NSBitmapImageRep.alloc().initWithData(data), NSBitmapImageRep)
323
+
324
+ if (source == null) {
325
+ return null
326
+ }
327
+
328
+ // Option semantics match the Swift NSNumber cast: a non-number falls
329
+ // back to the source size, while an out-of-range number fails below.
330
+ const width =
331
+ typeof this.options.width === 'number' ? this.options.width : Number(source.pixelsWide)
332
+
333
+ const height =
334
+ typeof this.options.height === 'number' ? this.options.height : Number(source.pixelsHigh)
335
+
336
+ if (
337
+ !Number.isFinite(width) ||
338
+ !Number.isFinite(height) ||
339
+ width < 1 ||
340
+ height < 1 ||
341
+ width > 16384 ||
342
+ height > 16384 ||
343
+ width * height > 64_000_000
344
+ ) {
345
+ return null
346
+ }
347
+
348
+ const keepAspectRatio = this.options.keepAspectRatio !== false
349
+ const scale = Math.min(width / source.pixelsWide, height / source.pixelsHigh, 1)
350
+ const size = {
351
+ width: keepAspectRatio ? source.pixelsWide * scale : width,
352
+ height: keepAspectRatio ? source.pixelsHigh * scale : height,
353
+ }
354
+
355
+ // The long NSBitmapImageRep designated initializer is absent from the
356
+ // bridge metadata; resize through NSImage + TIFFRepresentation instead.
357
+ const image = typed(NSImage.alloc().init(), NSImage)
358
+
359
+ if (image == null) {
360
+ return null
361
+ }
362
+
363
+ try {
364
+ image.addRepresentation(source)
365
+ image.size = { width: Math.floor(size.width), height: Math.floor(size.height) }
366
+
367
+ const tiff =
368
+ typeof image.TIFFRepresentation === 'function'
369
+ ? image.TIFFRepresentation()
370
+ : image.TIFFRepresentation
371
+
372
+ const scaled =
373
+ tiff != null ? typed(NSBitmapImageRep.imageRepWithData(tiff), NSBitmapImageRep) : null
374
+
375
+ if (scaled == null) {
376
+ return null
377
+ }
378
+
379
+ const props = NSMutableDictionary.dictionary()
380
+
381
+ props.setObjectForKey(0.9, NSImageCompressionFactor)
382
+
383
+ const jpeg = scaled.representationUsingTypeProperties(g.NSBitmapImageFileTypeJPEG ?? 3, props)
384
+
385
+ if (jpeg == null) {
386
+ return null
387
+ }
388
+
389
+ return this.persistWrite(jpeg)
390
+ } catch {
391
+ return null
392
+ }
393
+ }
394
+
395
+ private persistWrite(jpeg: any): string | null {
396
+ const name = `octane-capture-${NSUUID.UUID().UUIDString}.jpg`
397
+ const url = NSFileManager.defaultManager.temporaryDirectory.URLByAppendingPathComponent(name)
398
+
399
+ try {
400
+ const payload = {
401
+ name,
402
+ uri: String(url.path),
403
+ dataUrl: `data:image/jpeg;base64,${jpeg.base64EncodedStringWithOptions(0)}`,
404
+ }
405
+
406
+ const message = JSON.stringify(payload)
407
+
408
+ if (!jpeg.writeToURLAtomically(url, true)) {
409
+ return null
410
+ }
411
+
412
+ return message
413
+ } catch {
414
+ try {
415
+ NSFileManager.defaultManager.removeItemAtURLError(url, null)
416
+ } catch {
417
+ // Temporary leftovers are reclaimed by the OS.
418
+ }
419
+
420
+ return null
421
+ }
422
+ }
423
+
424
+ ['cancelPhoto'](): void {
425
+ this.complete(null)
426
+ }
427
+
428
+ ['windowShouldClose:'](_sender: any): boolean {
429
+ this.complete(null)
430
+ return false
431
+ }
432
+
433
+ private complete(result: string | null): void {
434
+ if (!this.life.finish()) {
435
+ return
436
+ }
437
+
438
+ const callback = this.reply
439
+
440
+ this.reply = undefined
441
+ this.dispose()
442
+ callback?.(result)
443
+ }
444
+
445
+ discard(path: any): void {
446
+ this['discard:'](path)
447
+ }
448
+
449
+ ['discard:'](path: any): void {
450
+ const value = String(path)
451
+ const manager = NSFileManager.defaultManager
452
+ const tempDir = String(manager.temporaryDirectory.path ?? '')
453
+ const name = value.slice(value.lastIndexOf('/') + 1)
454
+
455
+ if (
456
+ tempDir === '' ||
457
+ !name.startsWith('octane-capture-') ||
458
+ value !== `${tempDir.replace(/\/+$/, '')}/${name}`
459
+ ) {
460
+ return
461
+ }
462
+
463
+ manager.removeItemAtPathError(value, null)
464
+ }
465
+
466
+ dispose(): void {
467
+ if (this.disposed) {
468
+ return
469
+ }
470
+
471
+ this.disposed = true
472
+ if (this.timeout !== undefined) {
473
+ clearTimeout(this.timeout)
474
+ this.timeout = undefined
475
+ }
476
+
477
+ if (this.closeObserver != null) {
478
+ NSNotificationCenter.defaultCenter.removeObserver(this.closeObserver)
479
+ this.closeObserver = undefined
480
+ }
481
+
482
+ this._host?.dispose()
483
+ if (this.sheet != null) {
484
+ this.parent?.endSheet(this.sheet)
485
+ this.sheet.orderOut(null)
486
+ }
487
+
488
+ this.sheet = undefined
489
+ this.preview = undefined
490
+ this.captureButton = undefined
491
+ this.statusLabel = undefined
492
+ // Disposal is also a cancellation, including an external owner teardown.
493
+ if (this.life.finish()) {
494
+ const callback = this.reply
495
+
496
+ this.reply = undefined
497
+ callback?.(null)
498
+ }
499
+ }
500
+ }
501
+
502
+ // Publish under the ObjC name the media package binds dynamically.
503
+ ;(globalThis as Record<string, unknown>).XplatPhotoCaptureSheet = XplatPhotoCaptureSheet
504
+
505
+ export { XplatPhotoCaptureSheet }
@@ -0,0 +1,69 @@
1
+ import { NSObject, interop } from '@octane-xplat/platform/ios'
2
+
3
+ /** `previewing` (iOS 13+) is documented KVO-observable: it flips true when
4
+ * the layer actually renders frames, asynchronously after
5
+ * `startRunning()` returns. Non-empty bounds are the second half of
6
+ * "visible" — a zero-size layer can report previewing without showing
7
+ * anything. */
8
+ let DisplayObserverClass: any
9
+ const displayObserverClass = () => {
10
+ // Register through the Objective-C bridge lazily; the probe/test
11
+ // runtime does not provide the extend hook.
12
+ DisplayObserverClass ??= (NSObject as any).extend(
13
+ {
14
+ 'observeValueForKeyPath:ofObject:change:context:'() {
15
+ ;(this as any).callback?.()
16
+ },
17
+ },
18
+ {
19
+ name: 'XplatCameraPreviewDisplayObserver',
20
+ exposedMethods: {
21
+ 'observeValueForKeyPath:ofObject:change:context:': {
22
+ returns: interop.types.void,
23
+ params: [interop.types.id, interop.types.id, interop.types.id, interop.types.id],
24
+ },
25
+ },
26
+ },
27
+ )
28
+
29
+ return DisplayObserverClass
30
+ }
31
+
32
+ /** Whether the preview layer is displaying a live frame right now. */
33
+ export function previewLayerDisplaying(layer: any): boolean {
34
+ return (
35
+ layer?.previewing === true &&
36
+ (layer.bounds?.size?.width ?? 0) > 0 &&
37
+ (layer.bounds?.size?.height ?? 0) > 0
38
+ )
39
+ }
40
+
41
+ /** Observe display readiness on an AVCaptureVideoPreviewLayer. `change`
42
+ * runs on every readiness transition in either direction — callers own
43
+ * edge detection. Returns the detach, or `undefined` when the runtime
44
+ * predates the iOS 13 `previewing` property and no display signal
45
+ * exists. */
46
+ export function observePreviewDisplay(layer: any, change: () => void): (() => void) | undefined {
47
+ if (
48
+ typeof layer?.addObserverForKeyPathOptionsContext !== 'function' ||
49
+ typeof layer.previewing !== 'boolean'
50
+ ) {
51
+ return undefined
52
+ }
53
+
54
+ const observer = displayObserverClass().new()
55
+
56
+ observer.callback = change
57
+ // New = 1; `bounds` is observed so a layer laid out after previewing
58
+ // started still produces a transition worth re-evaluating.
59
+ for (const key of ['previewing', 'bounds']) {
60
+ layer.addObserverForKeyPathOptionsContext(observer, key, 1, null as any)
61
+ }
62
+
63
+ return () => {
64
+ observer.callback = undefined
65
+ for (const key of ['previewing', 'bounds']) {
66
+ layer.removeObserverForKeyPath(observer, key)
67
+ }
68
+ }
69
+ }
@@ -0,0 +1,41 @@
1
+ import type { CameraPinchEvent } from './types'
2
+
3
+ const PINCH_STATE = ['cancelled', 'began', 'moved', 'ended'] as const
4
+
5
+ /** Attach a notification-only 'pinch' observer to a preview host view and
6
+ * report each event as a `CameraPinchEvent`: NS's cumulative scale plus
7
+ * the focal point normalized into preview space (the same space
8
+ * `observePreviewTap` uses). The recognizer never consumes the gesture —
9
+ * layered recognizers still see the touches. Platforms whose runtime
10
+ * never dispatches 'pinch' simply never fire the callback. */
11
+ export function observePreviewPinch(
12
+ view: any,
13
+ onPinch: ((event: CameraPinchEvent) => void) | undefined,
14
+ ): () => void {
15
+ if (!view || !onPinch || typeof view.on !== 'function') {
16
+ return () => {}
17
+ }
18
+
19
+ const handler = (args: any) => {
20
+ const size = view.getActualSize?.()
21
+ const width = size?.width ?? 0
22
+ const height = size?.height ?? 0
23
+ const fx = typeof args?.getFocusX === 'function' ? args.getFocusX() : NaN
24
+ const fy = typeof args?.getFocusY === 'function' ? args.getFocusY() : NaN
25
+ const hasFocus = width > 0 && height > 0 && Number.isFinite(fx) && Number.isFinite(fy)
26
+
27
+ onPinch({
28
+ scale: typeof args?.scale === 'number' ? args.scale : 1,
29
+ state: PINCH_STATE[args?.state] ?? 'moved',
30
+ focus: hasFocus
31
+ ? {
32
+ x: Math.min(1, Math.max(0, fx / width)),
33
+ y: Math.min(1, Math.max(0, fy / height)),
34
+ }
35
+ : { x: 0.5, y: 0.5 },
36
+ })
37
+ }
38
+
39
+ view.on('pinch', handler)
40
+ return () => view.off?.('pinch', handler)
41
+ }