Skip to content

Commit d3f77f3

Browse files
committed
Initial changes for using uniffi bindings
1 parent 828235a commit d3f77f3

File tree

10 files changed

+200
-191
lines changed

10 files changed

+200
-191
lines changed

Sources/LiveViewNative/Coordinators/LiveSessionCoordinator.swift

Lines changed: 57 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -34,71 +34,71 @@ private let logger = Logger(subsystem: "LiveViewNative", category: "LiveSessionC
3434
public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
3535
/// The current state of the live view connection.
3636
@Published public private(set) var state = LiveSessionState.notConnected
37-
37+
3838
/// The current URL this live view is connected to.
3939
public private(set) var url: URL
40-
40+
4141
@Published var navigationPath = [LiveNavigationEntry<R>]()
42-
42+
4343
internal let configuration: LiveSessionConfiguration
44-
44+
4545
@Published private(set) var rootLayout: LiveViewNativeCore.Document?
4646
@Published private(set) var stylesheet: Stylesheet<R>?
47-
47+
4848
// Socket connection
49-
var socket: Socket?
50-
49+
var socket: SwiftPhoenixClient.Socket?
50+
5151
private var domValues: DOMValues!
52-
53-
private var liveReloadSocket: Socket?
54-
private var liveReloadChannel: Channel?
55-
52+
53+
private var liveReloadSocket: SwiftPhoenixClient.Socket?
54+
private var liveReloadChannel: SwiftPhoenixClient.Channel?
55+
5656
private var cancellables = Set<AnyCancellable>()
57-
57+
5858
private var mergedEventSubjects: AnyCancellable?
5959
private var eventSubject = PassthroughSubject<(LiveViewCoordinator<R>, (String, Payload)), Never>()
6060
private var eventHandlers = Set<AnyCancellable>()
61-
61+
6262
/// Delegate for the ``urlSession``.
6363
///
6464
/// This delegate will add the `_format` and other necessary query params to any redirects.
6565
private var urlSessionDelegate: LiveSessionURLSessionDelegate<R>
66-
66+
6767
/// The ``URLSession`` instance to use for all HTTP requests.
6868
///
6969
/// This session is created using the ``LiveSessionConfiguration/urlSessionConfiguration``.
7070
private var urlSession: URLSession
71-
71+
7272
public convenience init(_ host: some LiveViewHost, config: LiveSessionConfiguration = .init(), customRegistryType: R.Type = R.self) {
7373
self.init(host.url, config: config, customRegistryType: customRegistryType)
7474
}
75-
75+
7676
/// Creates a new coordinator with a custom registry.
7777
/// - Parameter url: The URL of the page to establish the connection to.
7878
/// - Parameter config: The configuration for this coordinator.
7979
/// - Parameter customRegistryType: The type of the registry of custom views this coordinator will use when building the SwiftUI view tree from the DOM. This can generally be inferred automatically.
8080
public init(_ url: URL, config: LiveSessionConfiguration = .init(), customRegistryType _: R.Type = R.self) {
8181
self.url = url.appending(path: "").absoluteURL
82-
82+
8383
self.configuration = config
84-
84+
8585
config.urlSessionConfiguration.httpCookieStorage = .shared
8686
self.urlSessionDelegate = .init()
8787
self.urlSession = .init(
8888
configuration: config.urlSessionConfiguration,
8989
delegate: self.urlSessionDelegate,
9090
delegateQueue: nil
9191
)
92-
92+
9393
self.navigationPath = [.init(url: url, coordinator: .init(session: self, url: self.url))]
94-
94+
9595
self.mergedEventSubjects = self.navigationPath.first!.coordinator.eventSubject.compactMap({ [weak self] value in
9696
self.map({ ($0.navigationPath.first!.coordinator, value) })
9797
})
9898
.sink(receiveValue: { [weak self] value in
9999
self?.eventSubject.send(value)
100100
})
101-
101+
102102
$navigationPath.scan(([LiveNavigationEntry<R>](), [LiveNavigationEntry<R>]()), { ($0.1, $1) }).sink { [weak self] prev, next in
103103
guard let self else { return }
104104
let isDisconnected: Bool
@@ -137,14 +137,14 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
137137
}
138138
}.store(in: &cancellables)
139139
}
140-
140+
141141
/// Creates a new coordinator without a custom registry.
142142
/// - Parameter url: The URL of the page to establish the connection to.
143143
/// - Parameter config: The configuration for this coordinator.
144144
public convenience init(_ url: URL, config: LiveSessionConfiguration = .init()) where R == EmptyRegistry {
145145
self.init(url, config: config, customRegistryType: EmptyRegistry.self)
146146
}
147-
147+
148148
/// Connects this coordinator to the LiveView channel.
149149
///
150150
/// You generally do not call this function yourself. It is called automatically when the ``LiveView`` appears.
@@ -159,13 +159,13 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
159159
guard case .notConnected = state else {
160160
return
161161
}
162-
162+
163163
let originalURL = self.navigationPath.last!.url
164-
164+
165165
logger.debug("Connecting to \(originalURL.absoluteString)")
166-
166+
167167
state = .connecting
168-
168+
169169
do {
170170
var request = URLRequest(url: originalURL)
171171
request.httpMethod = httpMethod
@@ -186,7 +186,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
186186
} else {
187187
url = originalURL
188188
}
189-
189+
190190
let doc = try SwiftSoup.parse(html, url.absoluteString, SwiftSoup.Parser.xmlParser().settings(.init(true, true)))
191191
let domValues = try self.extractDOMValues(doc)
192192
// extract the root layout, removing anything within the `<div data-phx-main>`.
@@ -205,23 +205,23 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
205205
}
206206
}
207207
self.rootLayout = try LiveViewNativeCore.Document.parse(doc.outerHtml())
208-
208+
209209
self.domValues = domValues
210-
210+
211211
if socket == nil {
212212
try await self.connectSocket(domValues)
213213
}
214-
214+
215215
self.stylesheet = try await stylesheet
216-
216+
217217
try await navigationPath.last!.coordinator.connect(domValues: domValues, redirect: false)
218218
} catch {
219219
self.state = .connectionFailed(error)
220220
logger.log(level: .error, "\(error.localizedDescription)")
221221
return
222222
}
223223
}
224-
224+
225225
private func disconnect(preserveNavigationPath: Bool = false) async {
226226
for entry in self.navigationPath {
227227
await entry.coordinator.disconnect()
@@ -236,7 +236,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
236236
self.socket = nil
237237
self.state = .notConnected
238238
}
239-
239+
240240
/// Forces the session to disconnect then connect.
241241
///
242242
/// All state will be lost when the reload occurs, as an entirely new LiveView is mounted.
@@ -252,7 +252,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
252252
}
253253
await self.connect(httpMethod: httpMethod, httpBody: httpBody)
254254
}
255-
255+
256256
/// Creates a publisher that can be used to listen for server-sent LiveView events.
257257
///
258258
/// - Parameter event: The event name that is being listened for.
@@ -266,7 +266,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
266266
.filter { $0.1.0 == event }
267267
.map({ ($0.0, $0.1.1) })
268268
}
269-
269+
270270
/// Permanently registers a handler for a server-sent LiveView event.
271271
///
272272
/// - Parameter event: The event name that is being listened for.
@@ -280,7 +280,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
280280
.sink(receiveValue: handler)
281281
.store(in: &eventHandlers)
282282
}
283-
283+
284284
/// Request the dead render with the given `request`.
285285
///
286286
/// Returns the dead render HTML and the HTTP response information (including the final URL after redirects).
@@ -292,15 +292,15 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
292292
if domValues != nil {
293293
request.setValue(domValues.phxCSRFToken, forHTTPHeaderField: "x-csrf-token")
294294
}
295-
295+
296296
let data: Data
297297
let response: URLResponse
298298
do {
299299
(data, response) = try await urlSession.data(for: request)
300300
} catch {
301301
throw LiveConnectionError.initialFetchError(error)
302302
}
303-
303+
304304
guard let response = response as? HTTPURLResponse,
305305
response.statusCode == 200,
306306
let html = String(data: data, encoding: .utf8)
@@ -317,7 +317,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
317317
}
318318
return (html, response)
319319
}
320-
320+
321321
struct DOMValues {
322322
let phxCSRFToken: String
323323
let phxSession: String
@@ -326,17 +326,17 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
326326
let phxID: String
327327
let liveReloadEnabled: Bool
328328
}
329-
329+
330330
private func extractLiveReloadFrame(_ doc: SwiftSoup.Document) throws -> Bool {
331331
!(try doc.select("iframe[src=\"/phoenix/live_reload/frame\"]").isEmpty())
332332
}
333-
333+
334334
private func extractDOMValues(_ doc: SwiftSoup.Document) throws -> DOMValues {
335335
let csrfToken = try doc.select("csrf-token")
336336
guard !csrfToken.isEmpty() else {
337337
throw LiveConnectionError.initialParseError(missingOrInvalid: .csrfToken)
338338
}
339-
339+
340340
let mainDivRes = try doc.select("div[data-phx-main]")
341341
guard !mainDivRes.isEmpty() else {
342342
throw LiveConnectionError.initialParseError(missingOrInvalid: .phxMain)
@@ -357,7 +357,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
357357
guard let self else {
358358
return continuation.resume(throwing: LiveConnectionError.sessionCoordinatorReleased)
359359
}
360-
360+
361361
var wsEndpoint = URLComponents(url: self.url, resolvingAgainstBaseURL: true)!
362362
wsEndpoint.scheme = self.url.scheme == "https" ? "wss" : "ws"
363363
wsEndpoint.path = "/live/websocket"
@@ -371,7 +371,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
371371
]
372372
}
373373
)
374-
374+
375375
// set to `reconnecting` when the socket asks for the delay duration.
376376
socket.reconnectAfter = { [weak self] tries in
377377
Task {
@@ -389,9 +389,9 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
389389
}
390390
}
391391
}
392-
392+
393393
var refs = [String]()
394-
394+
395395
refs.append(socket.onOpen { [weak self, weak socket] in
396396
guard let socket else { return }
397397
guard self != nil else {
@@ -416,20 +416,20 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
416416
}
417417
self.socket?.onClose { logger.debug("[Socket] Closed") }
418418
self.socket?.logger = { message in logger.debug("[Socket] \(message)") }
419-
419+
420420
self.state = .connected
421-
421+
422422
if domValues.liveReloadEnabled {
423423
await self.connectLiveReloadSocket(urlSessionConfiguration: urlSession.configuration)
424424
}
425425
}
426-
426+
427427
private func connectLiveReloadSocket(urlSessionConfiguration: URLSessionConfiguration) async {
428428
if let liveReloadSocket = self.liveReloadSocket {
429429
liveReloadSocket.disconnect()
430430
self.liveReloadSocket = nil
431431
}
432-
432+
433433
logger.debug("[LiveReload] attempting to connect...")
434434

435435
var liveReloadEndpoint = URLComponents(url: self.url, resolvingAgainstBaseURL: true)!
@@ -453,7 +453,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
453453
}
454454
}
455455
}
456-
456+
457457
func redirect(_ redirect: LiveRedirect) async throws {
458458
switch redirect.mode {
459459
case .replaceTop:
@@ -497,7 +497,7 @@ class LiveSessionURLSessionDelegate<R: RootRegistry>: NSObject, URLSessionTaskDe
497497
return request
498498
}
499499
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
500-
500+
501501
var newRequest = request
502502
if !(components?.queryItems?.contains(where: { $0.name == "_format" }) ?? false) {
503503
newRequest.url = url.appending(queryItems: [.init(name: "_format", value: await LiveSessionCoordinator<R>.platform)])
@@ -519,19 +519,19 @@ extension LiveSessionCoordinator {
519519
"target": getTarget()
520520
]
521521
}
522-
522+
523523
private static func getAppVersion() -> String {
524524
let dictionary = Bundle.main.infoDictionary!
525525

526526
return dictionary["CFBundleShortVersionString"] as! String
527527
}
528-
528+
529529
private static func getAppBuild() -> String {
530530
let dictionary = Bundle.main.infoDictionary!
531531

532532
return dictionary["CFBundleVersion"] as! String
533533
}
534-
534+
535535
private static func getBundleID() -> String {
536536
let dictionary = Bundle.main.infoDictionary!
537537

@@ -558,7 +558,7 @@ extension LiveSessionCoordinator {
558558
let majorVersion = operatingSystemVersion.majorVersion
559559
let minorVersion = operatingSystemVersion.minorVersion
560560
let patchVersion = operatingSystemVersion.patchVersion
561-
561+
562562
return "\(majorVersion).\(minorVersion).\(patchVersion)"
563563
#else
564564
return UIDevice.current.systemVersion

0 commit comments

Comments
 (0)