Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

T3NativeControlsModule.swift

305 lines12.3 KB

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