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

T3NativeControlsModule.swift

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