Skip to content

Commit e9799a2

Browse files
authored
Restore navigation path after live reloading (#1264)
* Restore navigation path after live reloading * Reconnect at last connected route * Preserve stale documents on reconnects
1 parent d7fd610 commit e9799a2

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

Sources/LiveViewNative/Coordinators/LiveSessionCoordinator.swift

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -135,14 +135,16 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
135135
return
136136
}
137137

138-
logger.debug("Connecting to \(self.url.absoluteString)")
138+
let url = self.navigationPath.last!.url
139+
140+
logger.debug("Connecting to \(url.absoluteString)")
139141

140142
state = .connecting
141143

142144
do {
143-
let html = try await fetchDOM(url: self.url)
145+
let html = try await fetchDOM(url: url)
144146

145-
let doc = try SwiftSoup.parse(html, self.url.absoluteString, SwiftSoup.Parser.xmlParser().settings(.init(true, true)))
147+
let doc = try SwiftSoup.parse(html, url.absoluteString, SwiftSoup.Parser.xmlParser().settings(.init(true, true)))
146148
let domValues = try self.extractDOMValues(doc)
147149
// extract the root layout, removing anything within the `<div data-phx-main>`.
148150
let mainDiv = try doc.select("div[data-phx-main]")[0]
@@ -158,20 +160,24 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
158160
try await self.connectSocket(domValues)
159161
}
160162

161-
try await navigationPath.first!.coordinator.connect(domValues: domValues, redirect: false)
163+
try await navigationPath.last!.coordinator.connect(domValues: domValues, redirect: false)
162164
} catch {
163165
self.state = .connectionFailed(error)
164166
logger.log(level: .error, "\(error.localizedDescription)")
165167
return
166168
}
167169
}
168170

169-
private func disconnect() async {
171+
private func disconnect(preserveNavigationPath: Bool = false) async {
170172
for entry in self.navigationPath {
171173
await entry.coordinator.disconnect()
172-
entry.coordinator.document = nil
174+
if !preserveNavigationPath {
175+
entry.coordinator.document = nil
176+
}
177+
}
178+
if !preserveNavigationPath {
179+
self.navigationPath = [self.navigationPath.first!]
173180
}
174-
self.navigationPath = [self.navigationPath.first!]
175181
self.socket?.disconnect()
176182
self.socket = nil
177183
self.state = .notConnected
@@ -183,7 +189,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
183189
///
184190
/// This can be used to force the LiveView to reset, for example after an unrecoverable error occurs.
185191
public func reconnect() async {
186-
await self.disconnect()
192+
await self.disconnect(preserveNavigationPath: true)
187193
await self.connect()
188194
}
189195

0 commit comments

Comments
 (0)