forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditableText.swift
More file actions
55 lines (49 loc) · 1.49 KB
/
EditableText.swift
File metadata and controls
55 lines (49 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import SwiftUI
import Perception
struct EditableText: View {
let title: String
let initialText: String
let onCommit: (String) -> Bool
@State private var text: String
@State private var lastCommittedText: String
@State private var isReverting: Bool = false
init(_ title: String, text: String, onCommit: @escaping (String) -> Bool) {
self.title = title
self.initialText = text
self._text = State(initialValue: text)
self._lastCommittedText = State(initialValue: text)
self.onCommit = onCommit
}
var body: some View {
TextField(title, text: $text, onEditingChanged: { editing in
if !editing {
commit()
}
})
.onSubmit {
commit()
}
.onChange(of: initialText) { newValue in
if text != newValue {
text = newValue
}
if lastCommittedText != newValue {
lastCommittedText = newValue
}
}
}
private func commit() {
guard !isReverting else { return }
guard text != lastCommittedText else { return }
if onCommit(text) {
lastCommittedText = text
} else {
isReverting = true
// Async revert to ensure textField updates even during focus change
DispatchQueue.main.async {
text = lastCommittedText
isReverting = false
}
}
}
}