FileBrowseField.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // Copyright © 2022 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. import SwiftUI
  17. struct FileBrowseField: View {
  18. let titleKey: LocalizedStringKey
  19. @Binding var url: URL?
  20. @Binding var isFileImporterPresented: Bool
  21. let hasClearButton: Bool
  22. let onBrowse: () -> Void
  23. init(_ titleKey: LocalizedStringKey = "Path", url: Binding<URL?>, isFileImporterPresented: Binding<Bool>, hasClearButton: Bool = true, onBrowse: @escaping () -> Void = {}) {
  24. self.titleKey = titleKey
  25. self._url = url
  26. self._isFileImporterPresented = isFileImporterPresented
  27. self.hasClearButton = hasClearButton
  28. self.onBrowse = onBrowse
  29. }
  30. var body: some View {
  31. #if os(macOS)
  32. HStack {
  33. TextField(titleKey, text: .constant(url?.lastPathComponent ?? ""))
  34. .truncationMode(.head)
  35. .disabled(true)
  36. if hasClearButton {
  37. Button("Clear") {
  38. url = nil
  39. }
  40. }
  41. Button("Browse…") {
  42. onBrowse()
  43. isFileImporterPresented.toggle()
  44. }
  45. }
  46. #else
  47. if let path = url?.path {
  48. Text(path)
  49. .lineLimit(1)
  50. .truncationMode(.head)
  51. } else {
  52. Text(titleKey)
  53. .foregroundColor(.secondary)
  54. }
  55. if hasClearButton {
  56. Button {
  57. url = nil
  58. } label: {
  59. Text("Clear")
  60. }
  61. }
  62. Button {
  63. onBrowse()
  64. isFileImporterPresented.toggle()
  65. } label: {
  66. Text("Browse…")
  67. }
  68. #endif
  69. }
  70. }
  71. struct FileBrowseField_Previews: PreviewProvider {
  72. static var previews: some View {
  73. FileBrowseField(url: .constant(URL(fileURLWithPath: "/")), isFileImporterPresented: .constant(false))
  74. }
  75. }