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