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

T3NativeControlsModule.swift

241 lines8.9 KB

1import ExpoModulesCore
2import Security
3import UIKit
4​
5// Expo Modules 2.0: plain members marked @JS are bound by the macro, while the
6// views and main-queue presenters stay in definition(). Both are merged.
7@ExpoModule("T3NativeControls")
8public final class T3NativeControlsModule: Module {
9 private let presentationSources = T3PresentationSources()
10 private var videoPresentation: T3NativeVideoPresentation?
11 private var filePresentation: T3NativeFilePresentation?
12​
13 public func definition() -> ModuleDefinition {
14 Constants {
15 if #available(iOS 26.0, *) {
16 return [
17 "supportsWorkspaceColumns": NSClassFromString("RNSSplitHostComponentView") != nil,
18 ]
19 }
20 return ["supportsWorkspaceColumns": false]
21 }
22 View(T3LayoutMetricsView.self) {
23 ViewName("LayoutMetrics")
24 Events("onMetricsChange")
25 }
26​
27 AsyncFunction("presentVideo") { (url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) in
28 try self.presentVideo(
29 url: url,
30 title: title,
31 sourceIdentifier: sourceIdentifier,
32 identifier: identifier,
33 promise: promise
34 )
35 }.runOnQueue(.main)
36​
37 AsyncFunction("presentFile") { (url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) in
38 try self.presentFile(url: url, title: title, sourceIdentifier: sourceIdentifier,
39 identifier: identifier, promise: promise)
40 }.runOnQueue(.main)
41​
42 OnDestroy {
43 let presentation = self.videoPresentation
44 let file = self.filePresentation
45 DispatchQueue.main.async {
46 presentation?.dismiss()
47 file?.dismiss()
48 }
49 }
50​
51 View(T3PresentationSourceView.self) {
52 ViewName("PresentationSource")
53 Prop("identifier") { (view: T3PresentationSourceView, identifier: String) in
54 view.sources = self.presentationSources
55 view.identifier = identifier
56 }
57 }
58​
59 View(T3FrostedCutoutView.self) {
60 ViewName("FrostedCutout")
61 Prop("cutoutTop") { (view: T3FrostedCutoutView, value: Double) in view.cutoutTop = CGFloat(value) }
62 Prop("cutoutWidth") { (view: T3FrostedCutoutView, value: Double) in view.cutoutWidth = CGFloat(value) }
63 Prop("cutoutHeight") { (view: T3FrostedCutoutView, value: Double) in view.cutoutHeight = CGFloat(value) }
64 Prop("cutoutRadius") { (view: T3FrostedCutoutView, value: Double) in view.cutoutRadius = CGFloat(value) }
65 Prop("appearance") { (view: T3FrostedCutoutView, value: String) in view.appearance = value }
66 }
67​
68 View(T3ContextSheetSizeView.self) {
69 ViewName("ContextSheetSize")
70 Prop("contentHeight") { (view: T3ContextSheetSizeView, height: Double) in
71 view.contentHeight = CGFloat(height)
72 }
73 }
74​
75 AsyncFunction("shareFileFromSource") { (url: URL, title: String, identifier: String, promise: Promise) in
76 try self.shareFile(url: url, title: title, sourceIdentifier: identifier, promise: promise)
77 }.runOnQueue(.main)
78 }
79​
80 // UIKit presenters are main-actor isolated rather than run on the JS thread
81 // the macro would otherwise pick.
82 @JS
83 @MainActor
84 func dismissVideo(identifier: String) async {
85 dismissVideoPresentation(identifier: identifier)
86 }
87​
88 @JS
89 @MainActor
90 func dismissFile(identifier: String) async {
91 dismissFilePresentation(identifier: identifier)
92 }
93​
94 // Rotates the interface without Simulator menu UI scripting, which CI
95 // runners cannot perform (osascript is denied Accessibility access there).
96 @JS
97 @MainActor
98 func applyShowcaseOrientation(orientation: String) async {
99 let mask: UIInterfaceOrientationMask = orientation == "landscape" ? .landscapeRight : .portrait
100 for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
101 windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { error in
102 NSLog("T3NativeControls applyShowcaseOrientation(\(orientation)) failed: \(error)")
103 }
104 for window in windowScene.windows {
105 window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
106 }
107 }
108 }
109​
110 // The geometry request above can fail transiently (for example before the
111 // scene is foreground-active), so callers poll this until it settles.
112 // Screen bounds — not the scene's interface orientation — decide the
113 // answer because they match the captured framebuffer: with iPadOS
114 // windowing active, a floating landscape window still reports a portrait
115 // screen, and screenshots would come out portrait.
116 @JS
117 @MainActor
118 func getInterfaceOrientation() async -> String {
119 guard
120 let windowScene = UIApplication.shared.connectedScenes
121 .compactMap({ $0 as? UIWindowScene })
122 .first
123 else {
124 return "unknown"
125 }
126 let bounds = windowScene.screen.coordinateSpace.bounds
127 return bounds.width > bounds.height ? "landscape" : "portrait"
128 }
129​
130 private func launchArgument(_ flag: String) -> String? {
131 let arguments = ProcessInfo.processInfo.arguments
132 guard
133 let flagIndex = arguments.firstIndex(of: flag),
134 arguments.indices.contains(flagIndex + 1)
135 else {
136 return nil
137 }
138 return arguments[flagIndex + 1]
139 }
140​
141 @JS
142 func getShowcasePairingUrl() -> String? {
143 launchArgument("--showcasePairingUrl")
144 }
145​
146 @JS
147 func getShowcaseScene() -> String? {
148 let scenePath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseScene"
149 if let storedScene = try? String(contentsOfFile: scenePath, encoding: .utf8)
150 .trimmingCharacters(in: .whitespacesAndNewlines), !storedScene.isEmpty {
151 return storedScene
152 }
153 return launchArgument("--showcaseScene")
154 }
155​
156 // The palette is fixed for the whole capture, so it only ever arrives as a
157 // launch argument — unlike the scene, which the runner rewrites in place.
158 @JS
159 func getShowcaseTheme() -> String? {
160 launchArgument("--showcaseTheme")
161 }
162​
163 @JS
164 func getShowcaseOrientation() -> String? {
165 launchArgument("--showcaseOrientation")
166 }
167​
168 @JS
169 func prepareShowcaseCapture() {
170 for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
171 SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
172 }
173 }
174​
175 @JS(.concurrent)
176 func markShowcaseReady(scene: String) async {
177 let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
178 try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
179 }
180​
181 private func presentVideo(url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) throws {
182 let isPlayableURL = url.isFileURL
183 ? FileManager.default.isReadableFile(atPath: url.path)
184 : (["https", "http"].contains(url.scheme?.lowercased() ?? "") && url.host != nil)
185 guard videoPresentation == nil, filePresentation == nil,
186 let presenter = appContext?.utilities?.currentViewController(),
187 isPlayableURL
188 else {
189 throw NSError(
190 domain: "T3NativeVideo",
191 code: 2,
192 userInfo: [NSLocalizedDescriptionKey: "The video preview is no longer available."]
193 )
194 }
195 let presentation = T3NativeVideoPresentation(identifier: identifier, url: url, title: title) { [weak self] error in
196 self?.videoPresentation = nil
197 if let error { promise.reject(error) } else { promise.resolve(nil) }
198 }
199 videoPresentation = presentation
200 presentation.present(from: presenter, sources: presentationSources, sourceIdentifier: sourceIdentifier)
201 }
202​
203 private func dismissVideoPresentation(identifier: String) {
204 if videoPresentation?.identifier == identifier { videoPresentation?.dismiss() }
205 }
206​
207 private func presentFile(url: URL, title: String, sourceIdentifier: String,
208 identifier: String, promise: Promise) throws {
209 guard filePresentation == nil, videoPresentation == nil,
210 let presenter = appContext?.utilities?.currentViewController()
211 else { throw URLError(.cannotLoadFromNetwork) }
212 let file = T3NativeFilePresentation(identifier: identifier, sources: presentationSources,
213 sourceIdentifier: sourceIdentifier) { [weak self] error in
214 self?.filePresentation = nil
215 if let error { promise.reject(error) } else { promise.resolve(nil) }
216 }
217 filePresentation = file
218 file.present(url: url, title: title, from: presenter)
219 }
220​
221 private func dismissFilePresentation(identifier: String) {
222 if filePresentation?.identifier == identifier { filePresentation?.dismiss() }
223 }
224​
225 private func shareFile(url: URL, title: String, sourceIdentifier: String, promise: Promise) throws {
226 guard let presenter = appContext?.utilities?.currentViewController() else {
227 throw NSError(
228 domain: "T3NativePresentation",
229 code: 2,
230 userInfo: [NSLocalizedDescriptionKey: "The presenting screen is no longer open."]
231 )
232 }
233 try presentFileShare(
234 url: url,
235 title: title,
236 source: presentationSources.view(for: sourceIdentifier),
237 presenter: presenter,
238 promise: promise
239 )
240 }