oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1import SwiftUI
2#if os(macOS)
3import AppKit
4#elseif os(iOS)
5import UIKit
6import UniformTypeIdentifiers
7#endif
8
9/// The composer (chat.html `.composer`): one field that grows to a few
10/// lines, with Send (an arrow) and, while a turn runs, Stop (a square) in
11/// its end, round and filled like a primary button. Return sends; Shift
12/// Return and Option Return are a new line at the cursor; an input
13/// method's Return finishes its word and sends nothing. Focused, a thin luminous edge outside the field,
14/// teal into violet, drifts round it (a turn every 6 s) over a soft glow;
15/// with Reduce Motion it holds still.
16public struct Composer: View {
17 @Bindable var model: AskModel
18 @FocusState.Binding var focused: Bool
19 @Environment(\.colorScheme) private var scheme
20 @State private var input = ComposerInput()
21
22 public init(model: AskModel, focused: FocusState<Bool>.Binding) {
23 self.model = model
24 _focused = focused
25 }
26
27 private var canSend: Bool { model.turn == nil && !model.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
28
29 public var body: some View {
30 let p = Palette(scheme)
31 let shape = RoundedRectangle(cornerRadius: 10, style: .continuous)
32 HStack(alignment: .bottom, spacing: 0) {
33 TextField(text: $model.text, prompt: Text(BaseText.text("ask.placeholder")).foregroundStyle(p[.placeholder]), axis: .vertical) {
34 Text(BaseText.text("ask.message_label"))
35 }
36 .textFieldStyle(.plain)
37 .font(BaseFont.body(16))
38 .foregroundStyle(p[.frost])
39 .lineLimit(1...7)
40 .focused($focused)
41 .background(ComposerAnchor(input: input, model: model).allowsHitTesting(false).accessibilityHidden(true))
42 .onChange(of: focused, initial: true) { _, now in input.focused = now }
43 // A hardware keyboard's Return (and a Mac keypad's Enter), as
44 // the web's keydown. On a Mac a field's own Return always
45 // submits, Shift or not, so the field never sees one of these.
46 .onKeyPress(keys: ComposerReturn.keys, phases: .down) { press in
47 switch ComposerReturn.action(press.modifiers, composing: input.composing) {
48 case .send: send(); return .handled
49 case .newline: return input.insertNewline() ? .handled : .ignored
50 case .pass: return .ignored
51 }
52 }
53 #if os(iOS)
54 // The iPhone's on-screen keyboard: its Send key.
55 .onSubmit(send)
56 .submitLabel(.send)
57 #endif
58 .padding(.vertical, 11).padding(.leading, 14).padding(.trailing, model.turn != nil || canSend ? 4 : 14)
59 .frame(minHeight: 44)
60 .accessibilityLabel(Text(BaseText.text("ask.message_label")))
61 if model.turn != nil {
62 RoundAction(icon: .stop, label: BaseText.text("ask.stop")) { Task { await model.stop() } }
63 .transition(.scale(scale: 0.6).combined(with: .opacity))
64 } else if canSend {
65 RoundAction(icon: .send, label: BaseText.text("ask.send"), action: send)
66 .disabled(model.sending)
67 .transition(.scale(scale: 0.6).combined(with: .opacity))
68 }
69 }
70 .background(p[.field], in: shape)
71 .overlay { shape.strokeBorder(p[.fieldEdge], lineWidth: 1) }
72 .background { if focused { FocusEdge() } }
73 .animation(.easeOut(duration: 0.16), value: model.turn == nil)
74 .animation(.easeOut(duration: 0.16), value: canSend)
75 }
76
77 private func send() {
78 guard canSend else { return }
79 Task { await model.send() }
80 }
81}
82
83/// What Return does in the composer on a hardware keyboard: Return (with
84/// Command or Control too) sends; Shift or Option makes it a new line;
85/// while an input method is composing it is the input method's, to finish
86/// the word, as `!e.isComposing` in ask.js.
87enum ComposerReturn: Equatable {
88 case send, newline, pass
89
90 /// Return, and Enter on a Mac's keypad (ETX).
91 static let keys: Set<KeyEquivalent> = [.return, KeyEquivalent("\u{3}")]
92
93 static func action(_ modifiers: EventModifiers, composing: Bool) -> ComposerReturn {
94 if composing { return .pass }
95 if !modifiers.isDisjoint(with: [.shift, .option]) { return .newline }
96 return .send
97 }
98}
99
100/// The composer field's text view, which SwiftUI doesn't hand out: the
101/// first responder of the window the anchor is in, while the field has the
102/// keyboard (as it does whenever its key handler runs).
103@MainActor final class ComposerInput {
104 weak var model: AskModel?
105 #if os(macOS)
106 /// Whether the field has the keyboard (its FocusState).
107 var focused = false
108 weak var anchor: NSView?
109 /// A Mac field's editor.
110 var editor: NSTextView? { anchor?.window?.firstResponder as? NSTextView }
111 var composing: Bool { editor?.hasMarkedText() ?? false }
112 /// Where pastes come from (tests give their own).
113 static var pasteboard = NSPasteboard.general
114 private var observers: [NSObjectProtocol] = []
115 /// A menu's Paste (by its key or a click) is being sent.
116 private var pasting = false
117 private var converting = false
118
119 /// Starts watching the field, once its anchor is in a view (never in
120 /// an init: SwiftUI makes a ComposerInput on every pass of a parent's
121 /// body and keeps only the first).
122 func start() {
123 guard observers.isEmpty else { return }
124 let center = NotificationCenter.default
125 // Undo, Redo, text changes and menu actions all post on the main
126 // thread.
127 func watch(_ name: Notification.Name, _ act: @escaping @MainActor (ComposerInput, Notification) -> Void) {
128 observers.append(center.addObserver(forName: name, object: nil, queue: nil) { [weak self] note in
129 nonisolated(unsafe) let note = note
130 MainActor.assumeIsolated { if let self { act(self, note) } }
131 })
132 }
133 watch(.NSUndoManagerDidUndoChange) { $0.undone(by: $1.object as AnyObject?) }
134 watch(.NSUndoManagerDidRedoChange) { $0.undone(by: $1.object as AnyObject?) }
135 watch(NSText.didChangeNotification) { $0.richPaste(in: $1.object as AnyObject?) }
136 watch(NSMenu.willSendActionNotification) { input, note in
137 input.pasting = (note.userInfo?["MenuItem"] as? NSMenuItem)?.action == #selector(NSText.paste(_:))
138 }
139 watch(NSMenu.didSendActionNotification) { input, _ in input.pasting = false }
140 }
141
142 isolated deinit { observers.forEach(NotificationCenter.default.removeObserver) }
143
144 /// Undo and Redo in a Mac field change the field but never tell it,
145 /// so its binding kept the text taken back, and Send sent that. Told
146 /// here as a typed change is, the field updates the model itself
147 /// (setting the model would push the text back into the field and
148 /// lose Redo).
149 func undone(by manager: AnyObject?) {
150 guard focused, let editor, let manager, manager === editor.undoManager, model?.text != editor.string else { return }
151 editor.didChangeText()
152 }
153
154 /// A rich paste (HTML, or RTF without HTML) as Markdown. The Mac field
155 /// pastes the plain text itself and has no hook before it, so this
156 /// follows, inside the Paste menu action (its key or a click): the
157 /// plain text just pasted, ending at the cursor, is put back as one
158 /// edit with the paste (one Undo takes both). Paste and Match Style,
159 /// typing, an input method, dictation, drops and Undo are never a
160 /// Paste, and are left alone.
161 func richPaste(in changed: AnyObject?) {
162 guard pasting, focused, !converting, let editor, changed === editor, !editor.hasMarkedText() else { return }
163 let board = Self.pasteboard
164 guard let rich = board.availableType(from: [.html, .rtf]),
165 let plain = board.string(forType: .string), !plain.isEmpty else { return }
166 let markdown = rich == .html ? board.string(forType: .html).flatMap(PasteMarkdown.fromHTML)
167 : board.data(forType: .rtf).flatMap(PasteMarkdown.fromRTF)
168 guard let markdown else { return }
169 let text = editor.string as NSString, length = (plain as NSString).length
170 let selection = editor.selectedRange()
171 let pasted = NSRange(location: selection.location - length, length: length)
172 guard selection.length == 0, pasted.location >= 0, text.substring(with: pasted) == plain,
173 editor.shouldChangeText(in: pasted, replacementString: markdown) else { return }
174 converting = true
175 defer { converting = false }
176 editor.replaceCharacters(in: pasted, with: markdown)
177 editor.setSelectedRange(NSRange(location: pasted.location + (markdown as NSString).length, length: 0))
178 editor.didChangeText()
179 editor.breakUndoCoalescing()
180 }
181
182 /// A new line in place of the selection, as Option Return in any Mac
183 /// field: one undoable edit, the cursor after it.
184 func insertNewline() -> Bool {
185 guard let editor else { return false }
186 editor.insertNewlineIgnoringFieldEditor(nil)
187 return true
188 }
189 #elseif os(iOS)
190 weak var anchor: UIView?
191 var editor: (UIView & UITextInput)? { anchor?.window.flatMap(Self.firstResponder) }
192 private let paste = ComposerPaste()
193 /// Whether the field has the keyboard; once it has, its text view
194 /// takes rich pastes as Markdown (ComposerPaste).
195 var focused = false {
196 didSet {
197 guard focused else { return }
198 Task { @MainActor [weak self] in
199 guard let self, let view = self.editor as? UITextView, view.pasteDelegate !== self.paste else { return }
200 view.pasteDelegate = self.paste
201 }
202 }
203 }
204 var composing: Bool { editor?.markedTextRange != nil }
205 func insertNewline() -> Bool {
206 guard let editor, let range = editor.selectedTextRange else { return false }
207 editor.replace(range, withText: "\n")
208 return true
209 }
210 private static func firstResponder(in view: UIView) -> (UIView & UITextInput)? {
211 if view.isFirstResponder, let input = view as? UIView & UITextInput { return input }
212 for sub in view.subviews { if let found = firstResponder(in: sub) { return found } }
213 return nil
214 }
215 #else
216 var focused = false
217 var composing: Bool { false }
218 func insertNewline() -> Bool { false }
219 #endif
220}
221
222#if os(iOS)
223/// The iPhone and iPad field's paste: HTML or RTF becomes Markdown, in
224/// place of the selection as any paste; anything else is pasted as is.
225final class ComposerPaste: NSObject, UITextPasteDelegate {
226 func textPasteConfigurationSupporting(_ textPasteConfigurationSupporting: any UITextPasteConfigurationSupporting, transform item: UITextPasteItem) {
227 let provider = item.itemProvider
228 nonisolated(unsafe) let item = item
229 for (type, convert) in [(UTType.html, { (data: Data) in PasteMarkdown.html(data).flatMap(PasteMarkdown.fromHTML) }),
230 (UTType.rtf, PasteMarkdown.fromRTF)] where provider.hasItemConformingToTypeIdentifier(type.identifier) {
231 provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, _ in
232 if let markdown = data.flatMap(convert) { item.setResult(string: markdown) } else { item.setDefaultResult() }
233 }
234 return
235 }
236 item.setDefaultResult()
237 }
238}
239#endif
240
241/// An empty view behind the field, so the composer knows its window.
242#if os(macOS)
243struct ComposerAnchor: NSViewRepresentable {
244 let input: ComposerInput
245 let model: AskModel
246 func makeNSView(context: Context) -> NSView {
247 let view = NSView(); input.anchor = view; input.model = model; input.start(); return view
248 }
249 func updateNSView(_ view: NSView, context: Context) { input.anchor = view; input.model = model }
250}
251#elseif os(iOS)
252struct ComposerAnchor: UIViewRepresentable {
253 let input: ComposerInput
254 let model: AskModel
255 func makeUIView(context: Context) -> UIView {
256 let view = UIView(); view.isUserInteractionEnabled = false; input.anchor = view; input.model = model; return view
257 }
258 func updateUIView(_ view: UIView, context: Context) { input.anchor = view; input.model = model }
259}
260#endif
261
262/// Send and Stop: a 32 pt circle in a 44 pt target.
263struct RoundAction: View {
264 enum Kind { case send, stop }
265 let icon: Kind
266 let label: String
267 let action: () -> Void
268 @Environment(\.colorScheme) private var scheme
269 var body: some View {
270 let p = Palette(scheme)
271 Button(action: action) {
272 ZStack {
273 Circle().fill(p[.btn])
274 switch icon {
275 case .send: Icon(.send, weight: 2.4).frame(width: 18, height: 18)
276 case .stop: RoundedRectangle(cornerRadius: 2 * 18 / 24).frame(width: 11 * 18 / 24, height: 11 * 18 / 24)
277 }
278 }
279 .foregroundStyle(p[.btnInk])
280 .frame(width: 32, height: 32)
281 .frame(width: 44, height: 44)
282 .contentShape(Circle())
283 }
284 .buttonStyle(.plain)
285 .accessibilityLabel(Text(label))
286 .help(Text(label))
287 }
288}
289
290/// The focus edge: a 2 pt ring 3 pt outside the field, a conic gradient
291/// (--edge-a, --edge-hi, --edge-a, --edge-b) turning every 6 s, over a glow
292/// of --edge-glow-a and --edge-glow-b that breathes (2.25 s). The edge
293/// stays at full strength, so it is a real focus indicator.
294struct FocusEdge: View {
295 @Environment(\.colorScheme) private var scheme
296 @Environment(\.accessibilityReduceMotion) private var reduceMotion
297 @Environment(\.skyFrozen) private var frozen
298
299 var body: some View {
300 if reduceMotion || frozen {
301 ring(turn: 0, breath: 0.6)
302 } else {
303 TimelineView(.animation(minimumInterval: 1.0 / 30)) { timeline in
304 let t = timeline.date.timeIntervalSinceReferenceDate
305 ring(turn: t.truncatingRemainder(dividingBy: 6) / 6 * 360,
306 breath: SkyPainter.cubicBezier(SkyPainter.progress(t, period: 2.25, delay: 0, reverse: false), 0.37, 0, 0.63, 1))
307 }
308 }
309 }
310
311 func ring(turn: Double, breath: Double) -> some View {
312 let p = Palette(scheme)
313 let shape = RoundedRectangle(cornerRadius: 13, style: .continuous)
314 let gradient = AngularGradient(stops: [
315 .init(color: p[.edgeA], location: 0), .init(color: p[.edgeHi], location: 0.09), .init(color: p[.edgeA], location: 0.2),
316 .init(color: p[.edgeB], location: 0.5), .init(color: p[.edgeA], location: 1),
317 ], center: .center, angle: .degrees(turn - 90))
318 return ZStack {
319 // A box-shadow: outside the field only, never under it.
320 ZStack {
321 shape.fill(p[.edgeGlowA].opacity(0.55 + 0.35 * breath)).blur(radius: 8 + 3 * breath).padding(3)
322 shape.fill(p[.edgeGlowB].opacity(0.4 + 0.3 * breath)).blur(radius: 14 + 4 * breath).padding(6)
323 }
324 .mask {
325 Rectangle().padding(-40)
326 .overlay { RoundedRectangle(cornerRadius: 10, style: .continuous).padding(3).blendMode(.destinationOut) }
327 .compositingGroup()
328 }
329 shape.strokeBorder(gradient, lineWidth: 2)
330 }
331 .padding(-3)
332 .allowsHitTesting(false)
333 .accessibilityHidden(true)
334 }
335}
336