Skip to content

Commit

Permalink
EnumView; extract resettable
Browse files Browse the repository at this point in the history
  • Loading branch information
eagleoflqj committed Nov 11, 2024
1 parent f02a0e5 commit 905e60c
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 7 deletions.
8 changes: 1 addition & 7 deletions src/config/BooleanView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,6 @@ struct BooleanView: View {
var body: some View {
Toggle(isOn: $viewModel.value) {
Text(description)
}.contextMenu {
Button {
viewModel.reset()
} label: {
Text("Reset")
}
}
}.resettable(viewModel)
}
}
32 changes: 32 additions & 0 deletions src/config/EnumView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import SwiftUI
import SwiftUtil

struct EnumView: View {
let description: String
@ObservedObject private var viewModel: OptionViewModel<String>
let options: [(String, String)]

init(data: [String: Any], onUpdate: @escaping (String) -> Void) {
description = data["Description"] as! String
let original = data["Enum"] as! [String: String]
let translation = data["EnumI18n"] as? [String: String] ?? original
options = original.reduce(into: [(String, String)]()) { result, pair in
result.append((pair.value, translation[pair.key] ?? pair.value))
}
viewModel = OptionViewModel(
value: data["Value"] as! String,
defaultValue: data["DefaultValue"] as! String,
onUpdate: { value in
onUpdate(value)
}
)
}

var body: some View {
Picker(description, selection: $viewModel.value) {
ForEach(options, id: \.0) { pair in
Text(pair.1).tag(pair.0)
}
}.resettable(viewModel)
}
}
14 changes: 14 additions & 0 deletions src/config/option.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,24 @@ class OptionViewModel<T>: ObservableObject {
}
}

extension View {
func resettable<T>(_ viewModel: OptionViewModel<T>) -> some View {
self.contextMenu {
Button {
viewModel.reset()
} label: {
Text("Reset")
}
}
}
}

func toOptionView(_ data: [String: Any], onUpdate: @escaping (Encodable) -> Void) -> any View {
switch data["Type"] as! String {
case "Boolean":
return BooleanView(data: data, onUpdate: onUpdate)
case "Enum":
return EnumView(data: data, onUpdate: onUpdate)
default:
return UnknownView()
}
Expand Down

0 comments on commit 905e60c

Please sign in to comment.