Skip to content

Commit 2dd279f

Browse files
authored
Query encode + characters in form events (#1449)
* Query encode `+` characters in form events * Use `replacing` instead of `replacingOccurrences` * Update CHANGELOG.md * Revise changelog wording * Add PR link * Encode each query item
1 parent cb8c1fa commit 2dd279f

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1414
## Changed
1515

1616
## Fixed
17+
- `+` characters are properly encoded as `%2B` in form events (#1449)
1718

1819
## [0.3.0] 2024-08-21
1920

Sources/LiveViewNative/ViewModel.swift

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ public class FormModel: ObservableObject, CustomDebugStringConvertible {
9393

9494
/// Create a URL encoded body from the data in the form.
9595
public func buildFormQuery() throws -> String {
96-
return try buildFormURLComponents().query!
96+
return try buildFormURLComponents().formEncodedQuery!
9797
}
9898

9999
private func sendChangeEventForFormElement(_ value: any FormValue, for name: String, _ sendEvent: ((Any) async throws -> ())?) -> (() async throws -> Void)? {
@@ -113,7 +113,7 @@ public class FormModel: ObservableObject, CustomDebugStringConvertible {
113113
.init(name: "_target", value: name)
114114
]
115115

116-
try await event(components.query!)
116+
try await event(components.formEncodedQuery!)
117117
}
118118
}
119119

@@ -124,7 +124,7 @@ public class FormModel: ObservableObject, CustomDebugStringConvertible {
124124
var components = try self.buildFormURLComponents()
125125
components.queryItems?.append(.init(name: "_target", value: name))
126126

127-
try await event(components.query!)
127+
try await event(components.formEncodedQuery!)
128128
}
129129
}
130130

@@ -206,3 +206,16 @@ public class FormModel: ObservableObject, CustomDebugStringConvertible {
206206
}
207207

208208
}
209+
210+
private extension URLComponents {
211+
var formEncodedQuery: String? {
212+
var components = self
213+
components.queryItems = components.queryItems?.map({
214+
.init(
215+
name: $0.name,
216+
value: $0.value.flatMap({ $0.addingPercentEncoding(withAllowedCharacters: .alphanumerics) })
217+
)
218+
})
219+
return components.query!
220+
}
221+
}

0 commit comments

Comments
 (0)