import SwiftUI #if os(macOS) import AppKit #elseif os(iOS) import UIKit import UniformTypeIdentifiers #endif /// The composer (chat.html `.composer`): one field that grows to a few /// lines, with Send (an arrow) and, while a turn runs, Stop (a square) in /// its end, round and filled like a primary button. Return sends; Shift /// Return and Option Return are a new line at the cursor; an input /// method's Return finishes its word and sends nothing. Focused, a thin luminous edge outside the field, /// teal into violet, drifts round it (a turn every 6 s) over a soft glow; /// with Reduce Motion it holds still. public struct Composer: View { @Bindable var model: AskModel @FocusState.Binding var focused: Bool @Environment(\.colorScheme) private var scheme @State private var input = ComposerInput() public init(model: AskModel, focused: FocusState.Binding) { self.model = model _focused = focused } private var canSend: Bool { model.turn == nil && !model.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } public var body: some View { let p = Palette(scheme) let shape = RoundedRectangle(cornerRadius: 10, style: .continuous) HStack(alignment: .bottom, spacing: 0) { TextField(text: $model.text, prompt: Text(BaseText.text("ask.placeholder")).foregroundStyle(p[.placeholder]), axis: .vertical) { Text(BaseText.text("ask.message_label")) } .textFieldStyle(.plain) .font(BaseFont.body(16)) .foregroundStyle(p[.frost]) .lineLimit(1...7) .focused($focused) .background(ComposerAnchor(input: input, model: model).allowsHitTesting(false).accessibilityHidden(true)) .onChange(of: focused, initial: true) { _, now in input.focused = now } // A hardware keyboard's Return (and a Mac keypad's Enter), as // the web's keydown. On a Mac a field's own Return always // submits, Shift or not, so the field never sees one of these. .onKeyPress(keys: ComposerReturn.keys, phases: .down) { press in switch ComposerReturn.action(press.modifiers, composing: input.composing) { case .send: send(); return .handled case .newline: return input.insertNewline() ? .handled : .ignored case .pass: return .ignored } } #if os(iOS) // The iPhone's on-screen keyboard: its Send key. .onSubmit(send) .submitLabel(.send) #endif .padding(.vertical, 11).padding(.leading, 14).padding(.trailing, model.turn != nil || canSend ? 4 : 14) .frame(minHeight: 44) .accessibilityLabel(Text(BaseText.text("ask.message_label"))) if model.turn != nil { RoundAction(icon: .stop, label: BaseText.text("ask.stop")) { Task { await model.stop() } } .transition(.scale(scale: 0.6).combined(with: .opacity)) } else if canSend { RoundAction(icon: .send, label: BaseText.text("ask.send"), action: send) .disabled(model.sending) .transition(.scale(scale: 0.6).combined(with: .opacity)) } } .background(p[.field], in: shape) .overlay { shape.strokeBorder(p[.fieldEdge], lineWidth: 1) } .background { if focused { FocusEdge() } } .animation(.easeOut(duration: 0.16), value: model.turn == nil) .animation(.easeOut(duration: 0.16), value: canSend) } private func send() { guard canSend else { return } Task { await model.send() } } } /// What Return does in the composer on a hardware keyboard: Return (with /// Command or Control too) sends; Shift or Option makes it a new line; /// while an input method is composing it is the input method's, to finish /// the word, as `!e.isComposing` in ask.js. enum ComposerReturn: Equatable { case send, newline, pass /// Return, and Enter on a Mac's keypad (ETX). static let keys: Set = [.return, KeyEquivalent("\u{3}")] static func action(_ modifiers: EventModifiers, composing: Bool) -> ComposerReturn { if composing { return .pass } if !modifiers.isDisjoint(with: [.shift, .option]) { return .newline } return .send } } /// The composer field's text view, which SwiftUI doesn't hand out: the /// first responder of the window the anchor is in, while the field has the /// keyboard (as it does whenever its key handler runs). @MainActor final class ComposerInput { weak var model: AskModel? #if os(macOS) /// Whether the field has the keyboard (its FocusState). var focused = false weak var anchor: NSView? /// A Mac field's editor. var editor: NSTextView? { anchor?.window?.firstResponder as? NSTextView } var composing: Bool { editor?.hasMarkedText() ?? false } /// Where pastes come from (tests give their own). static var pasteboard = NSPasteboard.general private var observers: [NSObjectProtocol] = [] /// A menu's Paste (by its key or a click) is being sent. private var pasting = false private var converting = false /// Starts watching the field, once its anchor is in a view (never in /// an init: SwiftUI makes a ComposerInput on every pass of a parent's /// body and keeps only the first). func start() { guard observers.isEmpty else { return } let center = NotificationCenter.default // Undo, Redo, text changes and menu actions all post on the main // thread. func watch(_ name: Notification.Name, _ act: @escaping @MainActor (ComposerInput, Notification) -> Void) { observers.append(center.addObserver(forName: name, object: nil, queue: nil) { [weak self] note in nonisolated(unsafe) let note = note MainActor.assumeIsolated { if let self { act(self, note) } } }) } watch(.NSUndoManagerDidUndoChange) { $0.undone(by: $1.object as AnyObject?) } watch(.NSUndoManagerDidRedoChange) { $0.undone(by: $1.object as AnyObject?) } watch(NSText.didChangeNotification) { $0.richPaste(in: $1.object as AnyObject?) } watch(NSMenu.willSendActionNotification) { input, note in input.pasting = (note.userInfo?["MenuItem"] as? NSMenuItem)?.action == #selector(NSText.paste(_:)) } watch(NSMenu.didSendActionNotification) { input, _ in input.pasting = false } } isolated deinit { observers.forEach(NotificationCenter.default.removeObserver) } /// Undo and Redo in a Mac field change the field but never tell it, /// so its binding kept the text taken back, and Send sent that. Told /// here as a typed change is, the field updates the model itself /// (setting the model would push the text back into the field and /// lose Redo). func undone(by manager: AnyObject?) { guard focused, let editor, let manager, manager === editor.undoManager, model?.text != editor.string else { return } editor.didChangeText() } /// A rich paste (HTML, or RTF without HTML) as Markdown. The Mac field /// pastes the plain text itself and has no hook before it, so this /// follows, inside the Paste menu action (its key or a click): the /// plain text just pasted, ending at the cursor, is put back as one /// edit with the paste (one Undo takes both). Paste and Match Style, /// typing, an input method, dictation, drops and Undo are never a /// Paste, and are left alone. func richPaste(in changed: AnyObject?) { guard pasting, focused, !converting, let editor, changed === editor, !editor.hasMarkedText() else { return } let board = Self.pasteboard guard let rich = board.availableType(from: [.html, .rtf]), let plain = board.string(forType: .string), !plain.isEmpty else { return } let markdown = rich == .html ? board.string(forType: .html).flatMap(PasteMarkdown.fromHTML) : board.data(forType: .rtf).flatMap(PasteMarkdown.fromRTF) guard let markdown else { return } let text = editor.string as NSString, length = (plain as NSString).length let selection = editor.selectedRange() let pasted = NSRange(location: selection.location - length, length: length) guard selection.length == 0, pasted.location >= 0, text.substring(with: pasted) == plain, editor.shouldChangeText(in: pasted, replacementString: markdown) else { return } converting = true defer { converting = false } editor.replaceCharacters(in: pasted, with: markdown) editor.setSelectedRange(NSRange(location: pasted.location + (markdown as NSString).length, length: 0)) editor.didChangeText() editor.breakUndoCoalescing() } /// A new line in place of the selection, as Option Return in any Mac /// field: one undoable edit, the cursor after it. func insertNewline() -> Bool { guard let editor else { return false } editor.insertNewlineIgnoringFieldEditor(nil) return true } #elseif os(iOS) weak var anchor: UIView? var editor: (UIView & UITextInput)? { anchor?.window.flatMap(Self.firstResponder) } private let paste = ComposerPaste() /// Whether the field has the keyboard; once it has, its text view /// takes rich pastes as Markdown (ComposerPaste). var focused = false { didSet { guard focused else { return } Task { @MainActor [weak self] in guard let self, let view = self.editor as? UITextView, view.pasteDelegate !== self.paste else { return } view.pasteDelegate = self.paste } } } var composing: Bool { editor?.markedTextRange != nil } func insertNewline() -> Bool { guard let editor, let range = editor.selectedTextRange else { return false } editor.replace(range, withText: "\n") return true } private static func firstResponder(in view: UIView) -> (UIView & UITextInput)? { if view.isFirstResponder, let input = view as? UIView & UITextInput { return input } for sub in view.subviews { if let found = firstResponder(in: sub) { return found } } return nil } #else var focused = false var composing: Bool { false } func insertNewline() -> Bool { false } #endif } #if os(iOS) /// The iPhone and iPad field's paste: HTML or RTF becomes Markdown, in /// place of the selection as any paste; anything else is pasted as is. final class ComposerPaste: NSObject, UITextPasteDelegate { func textPasteConfigurationSupporting(_ textPasteConfigurationSupporting: any UITextPasteConfigurationSupporting, transform item: UITextPasteItem) { let provider = item.itemProvider nonisolated(unsafe) let item = item for (type, convert) in [(UTType.html, { (data: Data) in PasteMarkdown.html(data).flatMap(PasteMarkdown.fromHTML) }), (UTType.rtf, PasteMarkdown.fromRTF)] where provider.hasItemConformingToTypeIdentifier(type.identifier) { provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, _ in if let markdown = data.flatMap(convert) { item.setResult(string: markdown) } else { item.setDefaultResult() } } return } item.setDefaultResult() } } #endif /// An empty view behind the field, so the composer knows its window. #if os(macOS) struct ComposerAnchor: NSViewRepresentable { let input: ComposerInput let model: AskModel func makeNSView(context: Context) -> NSView { let view = NSView(); input.anchor = view; input.model = model; input.start(); return view } func updateNSView(_ view: NSView, context: Context) { input.anchor = view; input.model = model } } #elseif os(iOS) struct ComposerAnchor: UIViewRepresentable { let input: ComposerInput let model: AskModel func makeUIView(context: Context) -> UIView { let view = UIView(); view.isUserInteractionEnabled = false; input.anchor = view; input.model = model; return view } func updateUIView(_ view: UIView, context: Context) { input.anchor = view; input.model = model } } #endif /// Send and Stop: a 32 pt circle in a 44 pt target. struct RoundAction: View { enum Kind { case send, stop } let icon: Kind let label: String let action: () -> Void @Environment(\.colorScheme) private var scheme var body: some View { let p = Palette(scheme) Button(action: action) { ZStack { Circle().fill(p[.btn]) switch icon { case .send: Icon(.send, weight: 2.4).frame(width: 18, height: 18) case .stop: RoundedRectangle(cornerRadius: 2 * 18 / 24).frame(width: 11 * 18 / 24, height: 11 * 18 / 24) } } .foregroundStyle(p[.btnInk]) .frame(width: 32, height: 32) .frame(width: 44, height: 44) .contentShape(Circle()) } .buttonStyle(.plain) .accessibilityLabel(Text(label)) .help(Text(label)) } } /// The focus edge: a 2 pt ring 3 pt outside the field, a conic gradient /// (--edge-a, --edge-hi, --edge-a, --edge-b) turning every 6 s, over a glow /// of --edge-glow-a and --edge-glow-b that breathes (2.25 s). The edge /// stays at full strength, so it is a real focus indicator. struct FocusEdge: View { @Environment(\.colorScheme) private var scheme @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.skyFrozen) private var frozen var body: some View { if reduceMotion || frozen { ring(turn: 0, breath: 0.6) } else { TimelineView(.animation(minimumInterval: 1.0 / 30)) { timeline in let t = timeline.date.timeIntervalSinceReferenceDate ring(turn: t.truncatingRemainder(dividingBy: 6) / 6 * 360, breath: SkyPainter.cubicBezier(SkyPainter.progress(t, period: 2.25, delay: 0, reverse: false), 0.37, 0, 0.63, 1)) } } } func ring(turn: Double, breath: Double) -> some View { let p = Palette(scheme) let shape = RoundedRectangle(cornerRadius: 13, style: .continuous) let gradient = AngularGradient(stops: [ .init(color: p[.edgeA], location: 0), .init(color: p[.edgeHi], location: 0.09), .init(color: p[.edgeA], location: 0.2), .init(color: p[.edgeB], location: 0.5), .init(color: p[.edgeA], location: 1), ], center: .center, angle: .degrees(turn - 90)) return ZStack { // A box-shadow: outside the field only, never under it. ZStack { shape.fill(p[.edgeGlowA].opacity(0.55 + 0.35 * breath)).blur(radius: 8 + 3 * breath).padding(3) shape.fill(p[.edgeGlowB].opacity(0.4 + 0.3 * breath)).blur(radius: 14 + 4 * breath).padding(6) } .mask { Rectangle().padding(-40) .overlay { RoundedRectangle(cornerRadius: 10, style: .continuous).padding(3).blendMode(.destinationOut) } .compositingGroup() } shape.strokeBorder(gradient, lineWidth: 2) } .padding(-3) .allowsHitTesting(false) .accessibilityHidden(true) } }