Skip to content

Fix live_patch handling #1552

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: 0.4
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/elixir.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ env:
jobs:
build:
name: Build and test
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Elixir
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed
- Views will now update properly when the server changes the value of a form field (#1483)
- Fixed float parsing for stylesheet rules

## [0.3.1] 2024-10-02

Expand Down
6 changes: 3 additions & 3 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions Sources/LiveViewNative/Coordinators/LiveNavigationEntry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,20 @@ import SwiftUI
public struct LiveNavigationEntry<R: RootRegistry>: Hashable {
public let url: URL
public let coordinator: LiveViewCoordinator<R>

let mode: LiveRedirect.Mode

let navigationTransition: Any?
let pendingView: (any View)?

public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.url == rhs.url && lhs.coordinator === rhs.coordinator
&& lhs.mode == rhs.mode
}

public func hash(into hasher: inout Hasher) {
hasher.combine(url)
hasher.combine(ObjectIdentifier(coordinator))
hasher.combine(mode)
}
}
99 changes: 69 additions & 30 deletions Sources/LiveViewNative/Coordinators/LiveSessionCoordinator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
try? LiveViewNativeCore.storeSessionCookie("\(cookie.name)=\(cookie.value)", self.url.absoluteString)
}

self.navigationPath = [.init(url: url, coordinator: .init(session: self, url: self.url), navigationTransition: nil, pendingView: nil)]
self.navigationPath = [.init(url: url, coordinator: .init(session: self, url: self.url), mode: .replaceTop, navigationTransition: nil, pendingView: nil)]

self.mergedEventSubjects = self.navigationPath.first!.coordinator.eventSubject.compactMap({ [weak self] value in
self.map({ ($0.navigationPath.first!.coordinator, value) })
Expand All @@ -112,37 +112,76 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
$navigationPath.scan(([LiveNavigationEntry<R>](), [LiveNavigationEntry<R>]()), { ($0.1, $1) }).sink { [weak self] prev, next in
guard let self else { return }
Task {
try await prev.last?.coordinator.disconnect()
if prev.count > next.count {
let targetEntry = self.liveSocket!.getEntries()[next.count - 1]
next.last?.coordinator.join(
try await self.liveSocket!.traverseTo(targetEntry.id,
.some([
"_format": .str(string: LiveSessionParameters.platform),
"_interface": .object(object: LiveSessionParameters.platformParams)
]),
nil)
)
// backward navigation

// if the coordinator is connected, the mode was a `patch`, and the new entry has the same coordinator
// send a `live_patch` event and keep the same coordinator.
if case .patch = prev.last!.mode,
case .connected = prev.last?.coordinator.state,
next.last?.coordinator === prev.last?.coordinator
{
_ = try await prev.last?.coordinator.doPushEvent(
"live_patch",
payload: .jsonPayload(json: .object(object: [
"url": .str(string: next.last!.url.absoluteString)
]))
)
next.last!.coordinator.url = next.last!.url
next.last!.coordinator.objectWillChange.send()
if next.count <= 1 { // if we navigated back to the root page, trigger an update on the session too
self.objectWillChange.send()
}
return
} else {
try await prev.last?.coordinator.disconnect()
let targetEntry = self.liveSocket!.getEntries()[next.count - 1]
next.last?.coordinator.join(
try await self.liveSocket!.traverseTo(
targetEntry.id,
.some([
"_format": .str(string: LiveSessionParameters.platform),
"_interface": .object(object: LiveSessionParameters.platformParams)
]),
nil
)
)
}
} else if next.count > prev.count && prev.count > 0 {
// forward navigation (from `redirect` or `<NavigationLink>`)
next.last?.coordinator.join(
try await self.liveSocket!.navigate(next.last!.url.absoluteString,
.some([
"_format": .str(string: LiveSessionParameters.platform),
"_interface": .object(object: LiveSessionParameters.platformParams)
]),
NavOptions(action: .push))
)
} else if next.count == prev.count {
guard let liveChannel =
try await self.liveSocket?.navigate(next.last!.url.absoluteString,
switch next.last!.mode {
case .patch:
next.last?.coordinator.url = next.last!.url
return
case .replaceTop:
try await prev.last?.coordinator.disconnect()
next.last?.coordinator.join(
try await self.liveSocket!.navigate(next.last!.url.absoluteString,
.some([
"_format": .str(string: LiveSessionParameters.platform),
"_interface": .object(object: LiveSessionParameters.platformParams)
]),
NavOptions(action: .replace))
else { return }
next.last?.coordinator.join(liveChannel)
]),
NavOptions(action: .push))
)
}
} else if next.count == prev.count {
switch next.last!.mode {
case .patch:
next.last?.coordinator.url = next.last!.url
return
case .replaceTop:
try await prev.last?.coordinator.disconnect()
guard let liveChannel = try await self.liveSocket?.navigate(
next.last!.url.absoluteString,
.some([
"_format": .str(string: LiveSessionParameters.platform),
"_interface": .object(object: LiveSessionParameters.platformParams)
]),
NavOptions(action: .replace)
)
else { return }
next.last?.coordinator.join(liveChannel)
}
}
}
}.store(in: &cancellables)
Expand Down Expand Up @@ -318,7 +357,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
if case .user(user: "assets_change") = event.event {
Task { @MainActor in
await self.disconnect()
self.navigationPath = [.init(url: self.url, coordinator: .init(session: self, url: self.url), navigationTransition: nil, pendingView: nil)]
self.navigationPath = [.init(url: self.url, coordinator: .init(session: self, url: self.url), mode: .replaceTop, navigationTransition: nil, pendingView: nil)]
await self.connect()
self.lastReloadTime = Date()
}
Expand Down Expand Up @@ -374,7 +413,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
await self.disconnect()
if let url {
self.url = url
self.navigationPath = [.init(url: self.url, coordinator: self.navigationPath.first!.coordinator, navigationTransition: nil, pendingView: nil)]
self.navigationPath = [.init(url: self.url, coordinator: self.navigationPath.first!.coordinator, mode: .replaceTop, navigationTransition: nil, pendingView: nil)]
}
await self.connect(httpMethod: httpMethod, httpBody: httpBody, additionalHeaders: headers)
// do {
Expand Down Expand Up @@ -440,7 +479,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
switch redirect.mode {
case .replaceTop:
let coordinator = LiveViewCoordinator(session: self, url: redirect.to)
let entry = LiveNavigationEntry(url: redirect.to, coordinator: coordinator, navigationTransition: navigationTransition, pendingView: pendingView)
let entry = LiveNavigationEntry(url: redirect.to, coordinator: coordinator, mode: redirect.mode, navigationTransition: navigationTransition, pendingView: pendingView)
switch redirect.kind {
case .push:
navigationPath.append(entry)
Expand All @@ -458,7 +497,7 @@ public class LiveSessionCoordinator<R: RootRegistry>: ObservableObject {
// patch is like `replaceTop`, but it does not disconnect.
let coordinator = navigationPath.last!.coordinator
coordinator.url = redirect.to
let entry = LiveNavigationEntry(url: redirect.to, coordinator: coordinator, navigationTransition: navigationTransition, pendingView: pendingView)
let entry = LiveNavigationEntry(url: redirect.to, coordinator: coordinator, mode: redirect.mode, navigationTransition: navigationTransition, pendingView: pendingView)
switch redirect.kind {
case .push:
navigationPath.append(entry)
Expand Down
2 changes: 1 addition & 1 deletion Sources/LiveViewNative/Live/LiveView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ struct PhxMain<R: RootRegistry>: View {
@EnvironmentObject private var session: LiveSessionCoordinator<R>

var body: some View {
NavStackEntryView(.init(url: context.coordinator.url, coordinator: context.coordinator, navigationTransition: nil, pendingView: nil))
NavStackEntryView(.init(url: context.coordinator.url, coordinator: context.coordinator, mode: .replaceTop, navigationTransition: nil, pendingView: nil))
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ struct NavigationLink<Root: RootRegistry>: View {
value: LiveNavigationEntry(
url: url,
coordinator: LiveViewCoordinator(session: $liveElement.context.coordinator.session, url: url),
mode: .replaceTop,
navigationTransition: nil, // FIXME: navigationTransition
pendingView: pendingView
)
Expand Down
24 changes: 11 additions & 13 deletions lib/live_view_native/swiftui/rules_parser/tokens.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,32 +21,30 @@ defmodule LiveViewNative.SwiftUI.RulesParser.Tokens do

def nil_(), do: replace(string("nil"), nil)

def minus(), do: string("-")

def underscored_integer() do
integer(min: 1)
def digits() do
ascii_char([?0..?9])
|> repeat(
choice([
ascii_char([?0..?9]),
ignore(string("_"))
|> ascii_char([?0..?9])
ignore(string("_")) |> ascii_char([?0..?9])
])
|> reduce({List, :to_string, []})
)
|> reduce({Enum, :join, [""]})
|> reduce({List, :to_string, []})
end

def minus(), do: string("-")

def frac() do
concat(string("."), digits())
end

def integer() do
optional(minus())
|> concat(underscored_integer())
|> concat(digits())
|> reduce({Enum, :join, [""]})
|> map({String, :to_integer, []})
end

def frac() do
concat(string("."), underscored_integer())
end

def float() do
integer()
|> concat(frac())
Expand Down
4 changes: 2 additions & 2 deletions test/live_view_native/swiftui/rules_parser_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ defmodule LiveViewNative.SwiftUI.RulesParserTest do

assert parse(input) == output

input = "background(Color.blue.opacity(0.2).blendMode(.multiply).mix(with: .orange).opacity(0.7))"
output = {:background, [], [{:., [], [{:., [], [{:., [], [{:., [], [{:., [], [:Color, :blue]}, {:opacity, [], [0.2]}]}, {:blendMode, [], [{:., [], [nil, :multiply]}]}]}, {:mix, [], [{:with, {:., [], [nil, :orange]}}]}]}, {:opacity, [], [0.7]}]}]}
input = "background(Color.blue.opacity(0.02).blendMode(.multiply).mix(with: .orange).opacity(0.7))"
output = {:background, [], [{:., [], [{:., [], [{:., [], [{:., [], [{:., [], [:Color, :blue]}, {:opacity, [], [0.02]}]}, {:blendMode, [], [{:., [], [nil, :multiply]}]}]}, {:mix, [], [{:with, {:., [], [nil, :orange]}}]}]}, {:opacity, [], [0.7]}]}]}

assert parse(input) == output
end
Expand Down
Loading