Open History to see the last commit
1import AVFoundation
2import ExpoModulesCore
3import Security
4import UIKit
5
6// Expo Modules 2.0: plain members marked @JS are bound by the macro, while the
7// views and main-queue presenters stay in definition(). Both are merged.
8@ExpoModule("T3NativeControls")
9public final class T3NativeControlsModule: Module {
10 private let presentationSources = T3PresentationSources()
11 private var videoPresentation: T3NativeVideoPresentation?
12 private var filePresentation: T3NativeFilePresentation?
13
14 public func definition() -> ModuleDefinition {
15 Constants {
16 if #available(iOS 26.0, *) {
17 return [
18 "supportsWorkspaceColumns": NSClassFromString("RNSSplitHostComponentView") != nil,
19 ]
20 }
21 return ["supportsWorkspaceColumns": false]
22 }
23 View(T3LayoutMetricsView.self) {
24 ViewName("LayoutMetrics")
25 Events("onMetricsChange")
26 }
27
28 AsyncFunction("presentVideo") { (url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) in
29 try self.presentVideo(
30 url: url,
31 title: title,
32 sourceIdentifier: sourceIdentifier,
33 identifier: identifier,
34 promise: promise
35 )
36 }.runOnQueue(.main)
37
38 AsyncFunction("presentFile") { (url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) in
39 try self.presentFile(url: url, title: title, sourceIdentifier: sourceIdentifier,
40 identifier: identifier, promise: promise)
41 }.runOnQueue(.main)
42
43 AsyncFunction("presentFiles") { (urls: [URL], titles: [String], selectedIndex: Int, identifier: String, promise: Promise) in
44 guard !urls.isEmpty, urls.count == titles.count, urls.indices.contains(selectedIndex) else {
45 throw URLError(.badURL)
46 }
47 let file = try self.makeFilePresentation(sourceIdentifier: "", identifier: identifier, promise: promise)
48 guard let presenter = self.appContext?.utilities?.currentViewController() else {
49 file.dismiss()
50 return
51 }
52 file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter)
53 }.runOnQueue(.main)
54
55 OnDestroy {
56 let presentation = self.videoPresentation
57 let file = self.filePresentation
58 DispatchQueue.main.async {
59 presentation?.dismiss()
60 file?.dismiss()
61 }
62 }
63
64 View(T3PresentationSourceView.self) {
65 ViewName("PresentationSource")
66 Prop("identifier") { (view: T3PresentationSourceView, identifier: String) in
67 view.sources = self.presentationSources
68 view.identifier = identifier
69 }
70 }
71
72 View(T3FrostedCutoutView.self) {
73 ViewName("FrostedCutout")
74 Prop("cutoutTop") { (view: T3FrostedCutoutView, value: Double) in view.cutoutTop = CGFloat(value) }
75 Prop("cutoutWidth") { (view: T3FrostedCutoutView, value: Double) in view.cutoutWidth = CGFloat(value) }
76 Prop("cutoutHeight") { (view: T3FrostedCutoutView, value: Double) in view.cutoutHeight = CGFloat(value) }
77 Prop("cutoutRadius") { (view: T3FrostedCutoutView, value: Double) in view.cutoutRadius = CGFloat(value) }
78 Prop("appearance") { (view: T3FrostedCutoutView, value: String) in view.appearance = value }
79 }
80
81 View(T3ContextSheetSizeView.self) {
82 ViewName("ContextSheetSize")
83 Prop("contentHeight") { (view: T3ContextSheetSizeView, height: Double) in
84 view.contentHeight = CGFloat(height)
85 }
86 }
87
88 AsyncFunction("shareFileFromSource") { (url: URL, title: String, identifier: String, promise: Promise) in
89 try self.shareFile(url: url, title: title, sourceIdentifier: identifier, promise: promise)
90 }.runOnQueue(.main)
91 }
92
93 // UIKit presenters are main-actor isolated rather than run on the JS thread
94 // the macro would otherwise pick.
95 @JS
96 @MainActor
97 func dismissVideo(identifier: String) async {
98 dismissVideoPresentation(identifier: identifier)
99 }
100
101 // expo-video activates the session for inline playback but never deactivates
102 // it. Any other category or mode means another feature (recording) owns it.
103 @JS
104 @MainActor
105 func releaseVideoAudioSession() async {
106 // The fullscreen presentation releases the session in its own teardown.
107 guard videoPresentation == nil else { return }
108 let session = AVAudioSession.sharedInstance()
109 guard session.category == .playback, session.mode == .moviePlayback else { return }
110 try? session.setActive(false, options: [.notifyOthersOnDeactivation])
111 }
112
113 @JS
114 @MainActor
115 func dismissFile(identifier: String) async {
116 dismissFilePresentation(identifier: identifier)
117 }
118
119 // Rotates the interface without Simulator menu UI scripting, which CI
120 // runners cannot perform (osascript is denied Accessibility access there).
121 @JS
122 @MainActor
123 func applyShowcaseOrientation(orientation: String) async {
124 let mask: UIInterfaceOrientationMask = orientation == "landscape" ? .landscapeRight : .portrait
125 for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
126 windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { error in
127 NSLog("T3NativeControls applyShowcaseOrientation(\(orientation)) failed: \(error)")
128 }
129 for window in windowScene.windows {
130 window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
131 }
132 }
133 }
134
135 // The geometry request above can fail transiently (for example before the
136 // scene is foreground-active), so callers poll this until it settles.
137 // Screen bounds — not the scene's interface orientation — decide the
138 // answer because they match the captured framebuffer: with iPadOS
139 // windowing active, a floating landscape window still reports a portrait
140 // screen, and screenshots would come out portrait.
141 @JS
142 @MainActor
143 func getInterfaceOrientation() async -> String {
144 guard
145 let windowScene = UIApplication.shared.connectedScenes
146 .compactMap({ $0 as? UIWindowScene })
147 .first
148 else {
149 return "unknown"
150 }
151 let bounds = windowScene.screen.coordinateSpace.bounds
152 return bounds.width > bounds.height ? "landscape" : "portrait"
153 }
154
155 private func launchArgument(_ flag: String) -> String? {
156 let arguments = ProcessInfo.processInfo.arguments
157 guard
158 let flagIndex = arguments.firstIndex(of: flag),
159 arguments.indices.contains(flagIndex + 1)
160 else {
161 return nil
162 }
163 return arguments[flagIndex + 1]
164 }
165
166 @JS
167 func getShowcasePairingUrl() -> String? {
168 launchArgument("--showcasePairingUrl")
169 }
170
171 @JS
172 func getShowcaseScene() -> String? {
173 let scenePath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseScene"
174 if let storedScene = try? String(contentsOfFile: scenePath, encoding: .utf8)
175 .trimmingCharacters(in: .whitespacesAndNewlines), !storedScene.isEmpty {
176 return storedScene
177 }
178 return launchArgument("--showcaseScene")
179 }
180
181 // The palette is fixed for the whole capture, so it only ever arrives as a
182 // launch argument — unlike the scene, which the runner rewrites in place.
183 @JS
184 func getShowcaseTheme() -> String? {
185 launchArgument("--showcaseTheme")
186 }
187
188 @JS
189 func getShowcaseOrientation() -> String? {
190 launchArgument("--showcaseOrientation")
191 }
192
193 @JS
194 func prepareShowcaseCapture() {
195 for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
196 SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
197 }
198 }
199
200 @JS(.concurrent)
201 func markShowcaseReady(scene: String) async {
202 let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
203 try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
204 }
205
206 private func presentVideo(url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) throws {
207 let isPlayableURL = url.isFileURL
208 ? FileManager.default.isReadableFile(atPath: url.path)
209 : (["https", "http"].contains(url.scheme?.lowercased() ?? "") && url.host != nil)
210 guard videoPresentation == nil, filePresentation == nil,
211 let presenter = appContext?.utilities?.currentViewController(),
212 isPlayableURL
213 else {
214 throw NSError(
215 domain: "T3NativeVideo",
216 code: 2,
217 userInfo: [NSLocalizedDescriptionKey: "The video preview is no longer available."]
218 )
219 }
220 let presentation = T3NativeVideoPresentation(identifier: identifier, url: url, title: title) { [weak self] error in
221 self?.videoPresentation = nil
222 if let error { promise.reject(error) } else { promise.resolve(nil) }
223 }
224 videoPresentation = presentation
225 presentation.present(from: presenter, sources: presentationSources, sourceIdentifier: sourceIdentifier)
226 }
227
228 private func dismissVideoPresentation(identifier: String) {
229 if videoPresentation?.identifier == identifier { videoPresentation?.dismiss() }
230 }
231
232 private func makeFilePresentation(sourceIdentifier: String, identifier: String,
233 promise: Promise) throws -> T3NativeFilePresentation {
234 guard filePresentation == nil, videoPresentation == nil,
235 appContext?.utilities?.currentViewController() != nil
236 else { throw URLError(.cannotLoadFromNetwork) }
237 let file = T3NativeFilePresentation(identifier: identifier, sources: presentationSources,
238 sourceIdentifier: sourceIdentifier) { [weak self] error in
239 self?.filePresentation = nil
240 if let error { promise.reject(error) } else { promise.resolve(nil) }
241 }
242 filePresentation = file
243 return file
244 }
245
246 private func presentFile(url: URL, title: String, sourceIdentifier: String,
247 identifier: String, promise: Promise) throws {
248 let file = try makeFilePresentation(sourceIdentifier: sourceIdentifier, identifier: identifier, promise: promise)
249 guard let presenter = appContext?.utilities?.currentViewController() else { file.dismiss(); return }
250 file.present(url: url, title: title, from: presenter)
251 }
252
253 private func dismissFilePresentation(identifier: String) {
254 if filePresentation?.identifier == identifier { filePresentation?.dismiss() }
255 }
256
257 private func shareFile(url: URL, title: String, sourceIdentifier: String, promise: Promise) throws {
258 guard let presenter = appContext?.utilities?.currentViewController() else {
259 throw NSError(
260 domain: "T3NativePresentation",
261 code: 2,
262 userInfo: [NSLocalizedDescriptionKey: "The presenting screen is no longer open."]
263 )
264 }
265 try presentFileShare(
266 url: url,
267 title: title,
268 source: presentationSources.view(for: sourceIdentifier),
269 presenter: presenter,
270 promise: promise
271 )
272 }
273}