Skip to content

Commit e6b2b23

Browse files
committed
Add Toggle and conform Bool to FormValue
1 parent 7e4028b commit e6b2b23

File tree

3 files changed

+69
-1
lines changed

3 files changed

+69
-1
lines changed

Sources/LiveViewNative/BuiltinRegistry.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@ struct BuiltinRegistry {
4646
Shape(element: element, context: context, shape: RoundedRectangle(from: element))
4747
case "lvn-link":
4848
Link(element: element, context: context)
49-
49+
case "toggle":
50+
Toggle(element: element, context: context)
5051
case "phx-form":
5152
PhxForm<R>(element: element, context: context)
5253
case "phx-submit-button":

Sources/LiveViewNative/ViewModel.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,3 +206,15 @@ extension String: FormValue {
206206
self = formValue
207207
}
208208
}
209+
210+
extension Bool: FormValue {
211+
public var formValue: String {
212+
self.description
213+
}
214+
215+
public init?(formValue: String) {
216+
guard let value = Bool(formValue)
217+
else { return nil }
218+
self = value
219+
}
220+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
//
2+
// Toggle.swift
3+
//
4+
//
5+
// Created by Carson Katri on 1/17/23.
6+
//
7+
8+
import SwiftUI
9+
10+
struct Toggle<R: CustomRegistry>: View {
11+
@ObservedElement private var element: ElementNode
12+
let context: LiveContext<R>
13+
14+
@FormState(default: false) var value: Bool
15+
16+
init(element: ElementNode, context: LiveContext<R>) {
17+
self.context = context
18+
}
19+
20+
public var body: some View {
21+
SwiftUI.Toggle(isOn: $value) {
22+
context.buildChildren(of: element)
23+
}
24+
.applyToggleStyle(
25+
element.attributeValue(for: "toggle-style").flatMap(ToggleStyle.init) ?? .automatic
26+
)
27+
}
28+
}
29+
30+
fileprivate enum ToggleStyle: String {
31+
case automatic
32+
case button
33+
case `switch`
34+
#if os(macOS)
35+
case checkbox
36+
#endif
37+
}
38+
39+
fileprivate extension View {
40+
@ViewBuilder
41+
func applyToggleStyle(_ style: ToggleStyle) -> some View {
42+
switch style {
43+
case .automatic:
44+
self.toggleStyle(.automatic)
45+
case .button:
46+
self.toggleStyle(.button)
47+
case .`switch`:
48+
self.toggleStyle(.switch)
49+
#if os(macOS)
50+
case .checkbox:
51+
self.toggleStyle(.checkbox)
52+
#endif
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)