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

T3NativeControlsModule.swift

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