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

T3NativeControlsModule.swift

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