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 AsyncFunction("presentFiles") { (urls: [URL], titles: [String], selectedIndex: Int, sourceIdentifiers: [String], identifier: String, promise: Promise) in
70 guard !urls.isEmpty, urls.count == titles.count, urls.count == sourceIdentifiers.count,
71 urls.indices.contains(selectedIndex)
72 else {
73 throw URLError(.badURL)
74 }
75 let file = try self.makeFilePresentation(sourceIdentifiers: sourceIdentifiers, identifier: identifier,
76 promise: promise)
77 guard let presenter = self.appContext?.utilities?.currentViewController() else {
78 file.dismiss()
79 return
80 }
81 file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter)
82 }.runOnQueue(.main)
83
84 OnDestroy {
85 let presentation = self.videoPresentation
86 let file = self.filePresentation
87 DispatchQueue.main.async {
88 presentation?.dismiss()
89 file?.dismiss()
90 }
91 }
92
93 View(T3PresentationSourceView.self) {
94 ViewName("PresentationSource")
95 Prop("identifier") { (view: T3PresentationSourceView, identifier: String) in
96 view.sources = self.presentationSources
97 view.identifier = identifier
98 }
99 }
100
101 View(T3FrostedCutoutView.self) {
102 ViewName("FrostedCutout")
103 Prop("cutoutTop") { (view: T3FrostedCutoutView, value: Double) in view.cutoutTop = CGFloat(value) }
104 Prop("cutoutWidth") { (view: T3FrostedCutoutView, value: Double) in view.cutoutWidth = CGFloat(value) }
105 Prop("cutoutHeight") { (view: T3FrostedCutoutView, value: Double) in view.cutoutHeight = CGFloat(value) }
106 Prop("cutoutRadius") { (view: T3FrostedCutoutView, value: Double) in view.cutoutRadius = CGFloat(value) }
107 Prop("appearance") { (view: T3FrostedCutoutView, value: String) in view.appearance = value }
108 }
109
110 View(T3ContextSheetSizeView.self) {
111 ViewName("ContextSheetSize")
112 Prop("contentHeight") { (view: T3ContextSheetSizeView, height: Double) in
113 view.contentHeight = CGFloat(height)
114 }
115 }
116
117 AsyncFunction("shareFileFromSource") { (url: URL, title: String, identifier: String, promise: Promise) in
118 try self.shareFile(url: url, title: title, sourceIdentifier: identifier, promise: promise)
119 }.runOnQueue(.main)
120 }
121
122 // UIKit presenters are main-actor isolated rather than run on the JS thread
123 // the macro would otherwise pick.
124 @JS
125 @MainActor
126 func dismissVideo(identifier: String) async {
127 dismissVideoPresentation(identifier: identifier)
128 }
129
130 // expo-video activates the session for inline playback but never deactivates
131 // it. Any other category or mode means another feature (recording) owns it.
132 @JS
133 @MainActor
134 func releaseVideoAudioSession() async {
135 // The fullscreen presentation releases the session in its own teardown.
136 guard videoPresentation == nil else { return }
137 let session = AVAudioSession.sharedInstance()
138 guard session.category == .playback, session.mode == .moviePlayback else { return }
139 try? session.setActive(false, options: [.notifyOthersOnDeactivation])
140 }
141
142 @JS
143 @MainActor
144 func dismissFile(identifier: String) async {
145 dismissFilePresentation(identifier: identifier)
146 }
147
148 // Rotates the interface without Simulator menu UI scripting, which CI
149 // runners cannot perform (osascript is denied Accessibility access there).
150 @JS
151 @MainActor
152 func applyShowcaseOrientation(orientation: String) async {
153 let mask: UIInterfaceOrientationMask = orientation == "landscape" ? .landscapeRight : .portrait
154 for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
155 windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { error in
156 NSLog("T3NativeControls applyShowcaseOrientation(\(orientation)) failed: \(error)")
157 }
158 for window in windowScene.windows {
159 window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
160 }
161 }
162 }
163
164 // Geometry requests can fail before foreground activation; callers retry until bounds match.
165 // Use screen bounds because iPadOS floating-window orientation can differ from the captured framebuffer.
166 @JS
167 @MainActor
168 func getInterfaceOrientation() async -> String {
169 guard
170 let windowScene = UIApplication.shared.connectedScenes
171 .compactMap({ $0 as? UIWindowScene })
172 .first
173 else {
174 return "unknown"
175 }
176 let bounds = windowScene.screen.coordinateSpace.bounds
177 return bounds.width > bounds.height ? "landscape" : "portrait"
178 }
179
180 @JS
181 @MainActor
182 func isProtectedDataAvailable() async -> Bool {
183 UIApplication.shared.isProtectedDataAvailable
184 }
185
186 private func launchArgument(_ flag: String) -> String? {
187 let arguments = ProcessInfo.processInfo.arguments
188 guard
189 let flagIndex = arguments.firstIndex(of: flag),
190 arguments.indices.contains(flagIndex + 1)
191 else {
192 return nil
193 }
194 return arguments[flagIndex + 1]
195 }
196
197 @JS
198 func getShowcasePairingUrl() -> String? {
199 launchArgument("--showcasePairingUrl")
200 }
201
202 @JS
203 func getShowcaseScene() -> String? {
204 let scenePath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseScene"
205 if let storedScene = try? String(contentsOfFile: scenePath, encoding: .utf8)
206 .trimmingCharacters(in: .whitespacesAndNewlines), !storedScene.isEmpty {
207 return storedScene
208 }
209 return launchArgument("--showcaseScene")
210 }
211
212 // The palette is fixed for the whole capture, so it only ever arrives as a
213 // launch argument — unlike the scene, which the runner rewrites in place.
214 @JS
215 func getShowcaseTheme() -> String? {
216 launchArgument("--showcaseTheme")
217 }
218
219 @JS
220 func getShowcaseOrientation() -> String? {
221 launchArgument("--showcaseOrientation")
222 }
223
224 @JS
225 func prepareShowcaseCapture() {
226 for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
227 SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
228 }
229 }
230
231 @JS(.concurrent)
232 func markShowcaseReady(scene: String) async {
233 let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
234 try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
235 }
236
237 private func presentVideo(url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) throws {
238 let isPlayableURL = url.isFileURL
239 ? FileManager.default.isReadableFile(atPath: url.path)
240 : (["https", "http"].contains(url.scheme?.lowercased() ?? "") && url.host != nil)
241 guard videoPresentation == nil, filePresentation == nil,
242 let presenter = appContext?.utilities?.currentViewController(),
243 isPlayableURL
244 else {
245 throw NSError(
246 domain: "T3NativeVideo",
247 code: 2,
248 userInfo: [NSLocalizedDescriptionKey: "The video preview is no longer available."]
249 )
250 }
251 let presentation = T3NativeVideoPresentation(
252 identifier: identifier, url: url, title: title,
253 onPlaybackChange: { [weak self] isPlaying in
254 self?.sendEvent("videoPlaybackChange", ["identifier": identifier, "isPlaying": isPlaying])
255 },
256 completion: { [weak self] error in
257 self?.videoPresentation = nil
258 if let error { promise.reject(error) } else { promise.resolve(nil) }
259 }
260 )
261 videoPresentation = presentation
262 presentation.present(from: presenter, sources: presentationSources, sourceIdentifier: sourceIdentifier)
263 }
264
265 private func dismissVideoPresentation(identifier: String) {
266 if videoPresentation?.identifier == identifier { videoPresentation?.dismiss() }
267 }
268
269 private func makeFilePresentation(sourceIdentifiers: [String], identifier: String,
270 promise: Promise) throws -> T3NativeFilePresentation {
271 guard filePresentation == nil, videoPresentation == nil,
272 appContext?.utilities?.currentViewController() != nil
273 else { throw URLError(.cannotLoadFromNetwork) }
274 let file = T3NativeFilePresentation(identifier: identifier, sources: presentationSources,
275 sourceIdentifiers: sourceIdentifiers) { [weak self] error in
276 self?.filePresentation = nil
277 if let error { promise.reject(error) } else { promise.resolve(nil) }
278 }
279 filePresentation = file
280 return file
281 }
282
283 private func presentFile(url: URL, title: String, sourceIdentifier: String,
284 identifier: String, promise: Promise) throws {
285 let file = try makeFilePresentation(sourceIdentifiers: [sourceIdentifier], identifier: identifier, promise: promise)
286 guard let presenter = appContext?.utilities?.currentViewController() else { file.dismiss(); return }
287 file.present(url: url, title: title, from: presenter)
288 }
289
290 private func dismissFilePresentation(identifier: String) {
291 if filePresentation?.identifier == identifier { filePresentation?.dismiss() }
292 }
293
294 private func shareFile(url: URL, title: String, sourceIdentifier: String, promise: Promise) throws {
295 guard let presenter = appContext?.utilities?.currentViewController() else {
296 throw NSError(
297 domain: "T3NativePresentation",
298 code: 2,
299 userInfo: [NSLocalizedDescriptionKey: "The presenting screen is no longer open."]
300 )
301 }
302 try presentFileShare(
303 url: url,
304 title: title,
305 source: presentationSources.view(for: sourceIdentifier),
306 presenter: presenter,
307 promise: promise
308 )
309 }
310}