From 120b3778e097adcd21fc040fc2a7573ea13d5bb7 Mon Sep 17 00:00:00 2001 From: Gui Rambo Date: Mon, 18 Jul 2022 15:14:19 -0300 Subject: [PATCH] Abstracted common field behavior into an EphemeralTextField type --- VirtualBuddy.xcodeproj/project.pbxproj | 18 +- .../EphemeralTextField.swift | 159 ++++++++++++++++++ .../NumericPropertyControl.swift | 3 +- .../NumericValueField.swift | 84 +++++++++ .../SharedFocusEnvironment.swift | 0 .../Building Blocks/NumericValueField.swift | 131 --------------- 6 files changed, 259 insertions(+), 136 deletions(-) create mode 100644 VirtualUI/Source/Building Blocks/Configuration Controls/EphemeralTextField.swift rename VirtualUI/Source/Building Blocks/{ => Configuration Controls}/NumericPropertyControl.swift (98%) create mode 100644 VirtualUI/Source/Building Blocks/Configuration Controls/NumericValueField.swift rename VirtualUI/Source/Building Blocks/{ => Configuration Controls}/SharedFocusEnvironment.swift (100%) delete mode 100644 VirtualUI/Source/Building Blocks/NumericValueField.swift diff --git a/VirtualBuddy.xcodeproj/project.pbxproj b/VirtualBuddy.xcodeproj/project.pbxproj index 1b98dcf..1040ad6 100644 --- a/VirtualBuddy.xcodeproj/project.pbxproj +++ b/VirtualBuddy.xcodeproj/project.pbxproj @@ -9,6 +9,7 @@ /* Begin PBXBuildFile section */ F417255B2884D79C004FF8A7 /* FixSwiftUIMaterialInPreviews.m in Sources */ = {isa = PBXBuildFile; fileRef = F417255A2884D79C004FF8A7 /* FixSwiftUIMaterialInPreviews.m */; }; F422586D2885CC9F009420AE /* SharedFocusEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = F422586C2885CC9F009420AE /* SharedFocusEnvironment.swift */; }; + F42258702885D537009420AE /* EphemeralTextField.swift in Sources */ = {isa = PBXBuildFile; fileRef = F422586F2885D537009420AE /* EphemeralTextField.swift */; }; F4471004286D0C1200F030EB /* NSAlert+Confirmation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4471003286D0C1200F030EB /* NSAlert+Confirmation.swift */; }; F465C3AE284F93A5006E9ED4 /* VBAPIClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = F465C3AD284F93A5006E9ED4 /* VBAPIClient.swift */; }; F465C3B0284F9660006E9ED4 /* VBRestoreImagesResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = F465C3AF284F9660006E9ED4 /* VBRestoreImagesResponse.swift */; }; @@ -151,6 +152,7 @@ /* Begin PBXFileReference section */ F417255A2884D79C004FF8A7 /* FixSwiftUIMaterialInPreviews.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FixSwiftUIMaterialInPreviews.m; sourceTree = ""; }; F422586C2885CC9F009420AE /* SharedFocusEnvironment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedFocusEnvironment.swift; sourceTree = ""; }; + F422586F2885D537009420AE /* EphemeralTextField.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EphemeralTextField.swift; sourceTree = ""; }; F4471003286D0C1200F030EB /* NSAlert+Confirmation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSAlert+Confirmation.swift"; sourceTree = ""; }; F465C3AD284F93A5006E9ED4 /* VBAPIClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VBAPIClient.swift; sourceTree = ""; }; F465C3AF284F9660006E9ED4 /* VBRestoreImagesResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VBRestoreImagesResponse.swift; sourceTree = ""; }; @@ -274,6 +276,17 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + F422586E2885D518009420AE /* Configuration Controls */ = { + isa = PBXGroup; + children = ( + F422586C2885CC9F009420AE /* SharedFocusEnvironment.swift */, + F498AD112884C36A006F1C00 /* NumericValueField.swift */, + F498AD172884C593006F1C00 /* NumericPropertyControl.swift */, + F422586F2885D537009420AE /* EphemeralTextField.swift */, + ); + path = "Configuration Controls"; + sourceTree = ""; + }; F465C3AC284F939C006E9ED4 /* Restore Images */ = { isa = PBXGroup; children = ( @@ -324,12 +337,10 @@ F498AD0F2884C35A006F1C00 /* Building Blocks */ = { isa = PBXGroup; children = ( + F422586E2885D518009420AE /* Configuration Controls */, F417255A2884D79C004FF8A7 /* FixSwiftUIMaterialInPreviews.m */, F498AD132884C36A006F1C00 /* ControlGroupChrome.swift */, - F498AD112884C36A006F1C00 /* NumericValueField.swift */, - F498AD172884C593006F1C00 /* NumericPropertyControl.swift */, F498AD192884C5FF006F1C00 /* SliderConversion.swift */, - F422586C2885CC9F009420AE /* SharedFocusEnvironment.swift */, ); path = "Building Blocks"; sourceTree = ""; @@ -896,6 +907,7 @@ F498AD162884C36A006F1C00 /* ControlGroupChrome.swift in Sources */, F498AD1A2884C5FF006F1C00 /* SliderConversion.swift in Sources */, F422586D2885CC9F009420AE /* SharedFocusEnvironment.swift in Sources */, + F42258702885D537009420AE /* EphemeralTextField.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/VirtualUI/Source/Building Blocks/Configuration Controls/EphemeralTextField.swift b/VirtualUI/Source/Building Blocks/Configuration Controls/EphemeralTextField.swift new file mode 100644 index 0000000..e41f722 --- /dev/null +++ b/VirtualUI/Source/Building Blocks/Configuration Controls/EphemeralTextField.swift @@ -0,0 +1,159 @@ +// +// EphemeralTextField.swift +// VirtualUI +// +// Created by Guilherme Rambo on 18/07/22. +// + +import SwiftUI + +private struct EphemeralTextFieldContentWidthKey: PreferenceKey { + static var defaultValue: CGFloat = 0 + + static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { + value = nextValue() + } +} + +struct EphemeralTextField: View where StaticContent: View, EditableContent: View, Value: Equatable { + + @Binding var value: Value + var staticContent: (Value) -> StaticContent + var editableContent: (Binding) -> EditableContent + var clamp: (Value) -> Value + var validate: (Value) -> Bool + + init(_ value: Binding, + @ViewBuilder staticContent: @escaping (Value) -> StaticContent, + @ViewBuilder editableContent: @escaping (Binding) -> EditableContent, + clamp: @escaping (Value) -> Value = { $0 }, + validate: @escaping (Value) -> Bool = { _ in true }) + { + self._value = value + self._internalValue = .init(wrappedValue: value.wrappedValue) + self.staticContent = staticContent + self.editableContent = editableContent + self.clamp = clamp + self.validate = validate + } + + @State private var internalValue: Value + + @Environment(\.unfocusActiveField) + private var unfocus + + @FocusState + private var isFocused: Bool + + @State private var isInEditMode = false + + @State private var contentWidth: CGFloat = 40 + + var body: some View { + ZStack { + staticContent(internalValue) + .contentShape(Rectangle()) + .onTapGesture { isInEditMode = true } + .onHover { isHovered = $0 } + .opacity(isInEditMode ? 0 : 1) + .background { + GeometryReader { proxy in + Color.clear + .preference(key: EphemeralTextFieldContentWidthKey.self, value: proxy.size.width) + } + } + .onPreferenceChange(EphemeralTextFieldContentWidthKey.self) { newValue in + contentWidth = newValue + } + + if isInEditMode { + editableContent($internalValue) + .focused($isFocused) + .textFieldStyle(.plain) + .frame(width: contentWidth, alignment: .trailing) + .onChange(of: value) { newValue in + // Unfocus when changing the value externally. + isFocused = false + internalValue = newValue + } + .onSubmit { + guard validate(internalValue) else { return } + + /// Update the external value with the edited value on submit, + /// limiting to the allowed range. + value = clamp(internalValue) + internalValue = clamp(internalValue) + + isFocused = false + } + .onExitCommand { + /// Unfocus the field when pressing the escape key. + isFocused = false + + /// Ugly hack alert! + DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { + /// Restore initial value when cancelling out of the field. + internalValue = value + } + } + .onReceive(unfocus) { + isFocused = false + } + .onChange(of: isFocused) { newValue in + if !newValue { isInEditMode = false } + } + } + } + .monospacedDigit() + .padding(.vertical, 4) + .padding(.horizontal, 8) + .background(hoverBackground) + .padding(.vertical, -4) + .padding(.horizontal, -8) + .onChange(of: isInEditMode) { newValue in + if newValue { + internalValue = value + isFocused = true + } + } + .onChange(of: value) { newValue in + internalValue = newValue + } + } + + @State private var isHovered = false + + @ViewBuilder + private var hoverBackground: some View { + RoundedRectangle(cornerRadius: 6, style: .continuous) + .foregroundColor(.white.opacity(0.07)) + .opacity(isHovered || isInEditMode ? 1 : 0) + .animation(.easeOut(duration: 0.24), value: isHovered) + } +} + +#if DEBUG + +struct EphemeralTextField_Previews: PreviewProvider { + static var previews: some View { + _Template() + } + + struct _Template: View { + @State var text = "Hello, World" + + var body: some View { + VStack { + EphemeralTextField($text) { value in + Text(value) + } editableContent: { value in + TextField("", text: value) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding() + } + } +} + +#endif diff --git a/VirtualUI/Source/Building Blocks/NumericPropertyControl.swift b/VirtualUI/Source/Building Blocks/Configuration Controls/NumericPropertyControl.swift similarity index 98% rename from VirtualUI/Source/Building Blocks/NumericPropertyControl.swift rename to VirtualUI/Source/Building Blocks/Configuration Controls/NumericPropertyControl.swift index 2915d0d..adde50b 100644 --- a/VirtualUI/Source/Building Blocks/NumericPropertyControl.swift +++ b/VirtualUI/Source/Building Blocks/Configuration Controls/NumericPropertyControl.swift @@ -30,7 +30,7 @@ struct NumericPropertyControl: View { VStack(alignment: .leading, spacing: spacing) { HStack { PropertyControlLabel(label) - + Spacer() NumericValueField( @@ -42,7 +42,6 @@ struct NumericPropertyControl: View { .textFieldStyle(.plain) .multilineTextAlignment(.trailing) .monospacedDigit() - .frame(minWidth: 30) } if !hideSlider { diff --git a/VirtualUI/Source/Building Blocks/Configuration Controls/NumericValueField.swift b/VirtualUI/Source/Building Blocks/Configuration Controls/NumericValueField.swift new file mode 100644 index 0000000..5a40d77 --- /dev/null +++ b/VirtualUI/Source/Building Blocks/Configuration Controls/NumericValueField.swift @@ -0,0 +1,84 @@ +import SwiftUI +import Combine +import VirtualCore + +struct NumericValueField: View { + + var label: String + @Binding var value: Value + var range: ClosedRange + var formatter: F + + @Environment(\.unfocusActiveField) + private var unfocus + + init(label: String, value: Binding, range: ClosedRange, formatter: F) { + self.label = label + self._value = value + self.range = range + self.formatter = formatter + } + + @FocusState + private var isFocused: Bool + + @State private var isInEditMode = false + + var body: some View { + EphemeralTextField($value) { currentValue in + Text(formatter.string(for: currentValue) ?? "") + } editableContent: { binding in + TextField(label, value: binding, formatter: formatter) + } clamp: { $0.limited(to: range) } + .multilineTextAlignment(.trailing) + } +} + +extension BinaryInteger { + func limited(to range: ClosedRange) -> Self { + Swift.min(range.upperBound, Swift.max(range.lowerBound, self)) + } +} + +#if DEBUG + +struct NumericValueField_Previews: PreviewProvider { + static var previews: some View { + _Template() + } + + struct _Template: View { + @State var value = 1 + + @Environment(\.unfocusActiveField) + private var unfocusActiveField + + private let formatter: NumberFormatter = { + let f = NumberFormatter() + f.numberStyle = .decimal + f.maximumFractionDigits = 0 + f.minimumFractionDigits = 0 + f.hasThousandSeparators = false + return f + }() + + var body: some View { + VStack { + NumericValueField( + label: "Test", + value: $value, + range: 1...10, + formatter: formatter + ) + + Button("Unfocus") { + unfocusActiveField.send() + } + .controlSize(.small) + } + .padding() + } + } +} + +#endif diff --git a/VirtualUI/Source/Building Blocks/SharedFocusEnvironment.swift b/VirtualUI/Source/Building Blocks/Configuration Controls/SharedFocusEnvironment.swift similarity index 100% rename from VirtualUI/Source/Building Blocks/SharedFocusEnvironment.swift rename to VirtualUI/Source/Building Blocks/Configuration Controls/SharedFocusEnvironment.swift diff --git a/VirtualUI/Source/Building Blocks/NumericValueField.swift b/VirtualUI/Source/Building Blocks/NumericValueField.swift deleted file mode 100644 index b899475..0000000 --- a/VirtualUI/Source/Building Blocks/NumericValueField.swift +++ /dev/null @@ -1,131 +0,0 @@ -import SwiftUI -import Combine -import VirtualCore - -struct NumericValueField: View { - - var label: String - @Binding var value: Value - var range: ClosedRange - var formatter: F - - @State private var internalValue: Value - - @Environment(\.unfocusActiveField) - private var unfocus - - init(label: String, value: Binding, range: ClosedRange, formatter: F) { - self.label = label - self._value = value - self.range = range - self.formatter = formatter - self._internalValue = .init(initialValue: value.wrappedValue) - } - - @FocusState - private var isFocused: Bool - - @State private var isInEditMode = false - - var body: some View { - Group { - if isInEditMode { - editableBody - .onChange(of: isFocused) { newValue in - if !newValue { isInEditMode = false } - } - } else { - Text(formatter.string(for: value) ?? "") - .frame(maxWidth: .infinity, alignment: .trailing) - .contentShape(Rectangle()) - .onTapGesture { isInEditMode = true } - } - } - .multilineTextAlignment(.trailing) - .monospacedDigit() - .onChange(of: isInEditMode) { newValue in - if newValue { isFocused = true } - } - .onChange(of: value) { newValue in - internalValue = newValue - } - } - - private var editableBody: some View { - TextField(label, value: $internalValue, formatter: formatter) - .focused($isFocused) - .textFieldStyle(.plain) - .onChange(of: value) { newValue in - // Unfocus when changing the value externally. - isFocused = false - internalValue = newValue - } - .onSubmit { - /// Update the external value with the edited value on submit, - /// limiting to the allowed range. - value = internalValue.limited(to: range) - internalValue = internalValue.limited(to: range) - - isFocused = false - } - .onExitCommand { - /// Unfocus the field when pressing the escape key. - isFocused = false - /// Restore initial value when cancelling out of the field. - internalValue = value - } - .onReceive(unfocus) { - isFocused = false - } - } - -} - -extension BinaryInteger { - func limited(to range: ClosedRange) -> Self { - Swift.min(range.upperBound, Swift.max(range.lowerBound, self)) - } -} - -#if DEBUG - -struct NumericValueField_Previews: PreviewProvider { - static var previews: some View { - _Template() - } - - struct _Template: View { - @State var value = 1 - - @Environment(\.unfocusActiveField) - private var unfocusActiveField - - private let formatter: NumberFormatter = { - let f = NumberFormatter() - f.numberStyle = .decimal - f.maximumFractionDigits = 0 - f.minimumFractionDigits = 0 - f.hasThousandSeparators = false - return f - }() - - var body: some View { - VStack { - NumericValueField( - label: "Test", - value: $value, - range: 1...10, - formatter: formatter - ) - - Button("Unfocus") { - unfocusActiveField.send() - } - .controlSize(.small) - } - .padding() - } - } -} - -#endif