Branchwell

Jotley / app / macOS / Views / CustomTooltip+ThemedTextField.swift

1import SwiftUI
2import AppKit
3
4// MARK: - Custom Themed TextField
5
6// Center single-line text within larger controls without changing note-title layout.
7final class ThemedTextFieldCell: NSTextFieldCell {
8 override func drawingRect(forBounds rect: NSRect) -> NSRect {
9 var drawing = super.drawingRect(forBounds: rect)
10 if usesSingleLineMode {
11 let activeFont = font ?? NSFont.systemFont(ofSize: NSFont.systemFontSize)
12 let height = min(drawing.height, ceil(activeFont.ascender - activeFont.descender + activeFont.leading))
13 drawing.origin.y += (drawing.height - height) / 2
14 drawing.size.height = height
15 }
16 return drawing
17 }
18
19 override func edit(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, event: NSEvent?) {
20 super.edit(withFrame: drawingRect(forBounds: rect), in: controlView, editor: textObj, delegate: delegate, event: event)
21 }
22
23 override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) {
24 super.select(withFrame: drawingRect(forBounds: rect), in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength)
25 }
26}
27
28// Custom NSTextField that properly sets cursor color
29class ThemedNSTextField: NSTextField {
30 var cursorColor: NSColor = .controlAccentColor
31 var minimumHeight: CGFloat = 0
32 var maxDisplayLines: Int = 1 {
33 didSet {
34 configureLineWrapping()
35 invalidateIntrinsicContentSize()
36 }
37 }
38
39 override func becomeFirstResponder() -> Bool {
40 let result = super.becomeFirstResponder()
41 if result {
42 updateFieldEditorColors()
43 }
44 return result
45 }
46
47 override var acceptsFirstResponder: Bool {
48 return true
49 }
50
51 override func layout() {
52 super.layout()
53
54 guard maxDisplayLines > 1 else { return }
55 let width = bounds.width
56 if width > 0, abs(preferredMaxLayoutWidth - width) > 0.5 {
57 preferredMaxLayoutWidth = width
58 invalidateIntrinsicContentSize()
59 }
60 }
61
62 override var intrinsicContentSize: NSSize {
63 var size = super.intrinsicContentSize
64 guard maxDisplayLines > 1 else {
65 size.height = max(size.height, minimumHeight)
66 return size
67 }
68
69 let activeFont = font ?? NSFont.systemFont(ofSize: NSFont.systemFontSize)
70 let lineHeight = ceil(activeFont.ascender - activeFont.descender + activeFont.leading)
71 let maxHeight = lineHeight * CGFloat(maxDisplayLines)
72 let textToMeasure = (stringValue.isEmpty ? (placeholderString ?? "") : stringValue) as NSString
73 let measuredWidth = bounds.width > 0 ? bounds.width : 800
74 let measuredRect = textToMeasure.boundingRect(
75 with: NSSize(width: measuredWidth, height: .greatestFiniteMagnitude),
76 options: [.usesLineFragmentOrigin, .usesFontLeading],
77 attributes: [.font: activeFont]
78 )
79 let measuredHeight = max(lineHeight, ceil(measuredRect.height))
80
81 size.height = min(measuredHeight, maxHeight) + 2
82 return size
83 }
84
85 func updateFieldEditorColors() {
86 if let fieldEditor = self.currentEditor() as? NSTextView {
87 fieldEditor.insertionPointColor = cursorColor
88 fieldEditor.selectedTextAttributes = [
89 .backgroundColor: cursorColor.withAlphaComponent(0.3),
90 .foregroundColor: NSColor.white
91 ]
92 }
93 }
94
95 func configureLineWrapping() {
96 let lines = max(1, maxDisplayLines)
97 let isMultiline = lines > 1
98 maximumNumberOfLines = lines
99
100 if let cell = cell as? NSTextFieldCell {
101 cell.usesSingleLineMode = !isMultiline
102 cell.wraps = isMultiline
103 cell.isScrollable = !isMultiline
104 cell.lineBreakMode = isMultiline ? .byWordWrapping : .byTruncatingTail
105 cell.truncatesLastVisibleLine = isMultiline
106 }
107
108 lineBreakMode = isMultiline ? .byWordWrapping : .byTruncatingTail
109 }
110}
111
112// SwiftUI wrapper for themed text field
113struct ThemedTextField: NSViewRepresentable {
114 @Binding var text: String
115 var placeholder: String
116 var font: NSFont?
117 var textColor: NSColor?
118 var onCommit: (() -> Void)?
119 var maxLines: Int = 1
120 var minimumHeight: CGFloat = 0
121 var allowsEditing = true
122
123 @ObservedObject private var themeManager = ThemeManager.shared
124
125 func makeNSView(context: Context) -> ThemedNSTextField {
126 let textField = ThemedNSTextField()
127 if minimumHeight > 0 {
128 textField.cell = ThemedTextFieldCell(textCell: "")
129 }
130 textField.isEditable = allowsEditing
131 textField.isSelectable = allowsEditing
132 textField.minimumHeight = minimumHeight
133 textField.delegate = context.coordinator
134 textField.isBordered = false
135 textField.backgroundColor = .clear
136 textField.focusRingType = .none
137 textField.placeholderString = placeholder
138 textField.stringValue = text
139
140 if let font = font {
141 textField.font = font
142 }
143 if let textColor = textColor {
144 textField.textColor = textColor
145 }
146
147 // Set cursor color
148 textField.cursorColor = NSColor(themeManager.currentThemeColor.color)
149 textField.maxDisplayLines = max(1, maxLines)
150 textField.configureLineWrapping()
151
152 return textField
153 }
154
155 func updateNSView(_ nsView: ThemedNSTextField, context: Context) {
156 if nsView.stringValue != text {
157 nsView.stringValue = text
158 }
159 nsView.minimumHeight = minimumHeight
160 nsView.placeholderString = placeholder
161 nsView.cursorColor = NSColor(themeManager.currentThemeColor.color)
162
163 if let font = font {
164 nsView.font = font
165 }
166 if let textColor = textColor {
167 nsView.textColor = textColor
168 }
169 nsView.maxDisplayLines = max(1, maxLines)
170 nsView.configureLineWrapping()
171
172 // Update colors if currently editing
173 if nsView.currentEditor() != nil {
174 nsView.updateFieldEditorColors()
175 }
176 }
177
178 func makeCoordinator() -> Coordinator {
179 Coordinator(self)
180 }
181
182 class Coordinator: NSObject, NSTextFieldDelegate {
183 var parent: ThemedTextField
184 // Suppress the end-editing onCommit when Enter already fired one.
185 // resignFirstResponder triggers controlTextDidEndEditing, so without
186 // this flag text fields can receive two onCommit calls
187 // for a single Return press and create duplicate notes.
188 private var didFireOnCommitFromReturnKey = false
189
190 init(_ parent: ThemedTextField) {
191 self.parent = parent
192 }
193
194 func controlTextDidChange(_ obj: Notification) {
195 guard let textField = obj.object as? NSTextField else { return }
196 parent.text = textField.stringValue
197 if let themedField = textField as? ThemedNSTextField {
198 themedField.invalidateIntrinsicContentSize()
199 }
200 }
201
202 func controlTextDidBeginEditing(_ obj: Notification) {
203 guard let textField = obj.object as? ThemedNSTextField else { return }
204 textField.updateFieldEditorColors()
205 }
206
207 func controlTextDidEndEditing(_ obj: Notification) {
208 if didFireOnCommitFromReturnKey {
209 didFireOnCommitFromReturnKey = false
210 return
211 }
212 parent.onCommit?()
213 }
214
215 func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
216 if commandSelector == #selector(NSResponder.insertNewline(_:)) {
217 didFireOnCommitFromReturnKey = true
218 parent.onCommit?()
219 control.window?.makeFirstResponder(nil)
220 return true
221 }
222 return false
223 }
224 }
225}