import AppKit import EquipoKit import SwiftUI import Observation @MainActor @Observable final class MacComposerDraft { var text = "" } /// The composer's text view: Return sends, Shift-Return starts a new line, /// and an input method's marked text is never sent half typed. final class ComposerEditor: NSTextView { var onSubmit: (() -> Void)? var placeholder = "" var onAttachments: ((NSPasteboard) -> Bool)? override func paste(_ sender: Any?) { if onAttachments?(NSPasteboard.general) != true { super.paste(sender) } } private func accepts(_ board: NSPasteboard) -> Bool { board.availableType(from: [.fileURL, .png, .tiff] + NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) }) != nil } override func draggingEntered(_ sender: any NSDraggingInfo) -> NSDragOperation { return accepts(sender.draggingPasteboard) ? .copy : super.draggingEntered(sender) } override func draggingUpdated(_ sender: any NSDraggingInfo) -> NSDragOperation { return accepts(sender.draggingPasteboard) ? .copy : super.draggingUpdated(sender) } override func prepareForDragOperation(_ sender: any NSDraggingInfo) -> Bool { return accepts(sender.draggingPasteboard) || super.prepareForDragOperation(sender) } override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool { guard accepts(sender.draggingPasteboard) else { return super.performDragOperation(sender) } return onAttachments?(sender.draggingPasteboard) == true } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) if string.isEmpty { var attributes = typingAttributes attributes[.foregroundColor] = NSColor.webPlaceholder (placeholder as NSString).draw(in: NSRect(x: 18, y: 0, width: max(0, bounds.width - 36), height: 24), withAttributes: attributes) } } override func didChangeText() { super.didChangeText(); needsDisplay = true } override func keyDown(with event: NSEvent) { if (event.keyCode == 36 || event.keyCode == 76) && !event.modifierFlags.contains(.shift) && !hasMarkedText() { onSubmit?() } else { super.keyDown(with: event) } } } final class ComposerPill: NSView { override var isFlipped: Bool { true } override func draw(_ dirtyRect: NSRect) { let path = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), xRadius: 10, yRadius: 10) NSColor.webSurface2.setFill(); path.fill() let focused = window?.firstResponder is ComposerEditor && window?.isKeyWindow == true (focused ? NSColor.webAccent : NSColor.webBorder).setStroke() path.lineWidth = focused ? 2 : 1; path.stroke() } } /// The conversation's composer: attachments above a pill that grows to /// six lines, then scrolls, with a 44-point send target centred on its last /// line. final class MacComposer: NSView, NSTextViewDelegate { override var isFlipped: Bool { true } let editor = ComposerEditor() let send = ActionButton("", style: .send, symbol: "arrow.up") {} let attachmentButton = ActionButton("", style: .attachment, symbol: "plus") {} let pill = ComposerPill() let textScroll = NSScrollView() var onSend: ((String) -> Void)? var onTextChange: ((String) -> Void)? var onHeightChange: (() -> Void)? private(set) var desiredHeight: CGFloat = 44 private var updating = false private var draft: AttachmentDraft? private var attachmentHost: NSHostingView? private var attachmentHeight: CGFloat = 0 func attach(_ draft: AttachmentDraft) { self.draft = draft attachmentButton.isHidden = false let host = NSHostingView(rootView: AnyView(AttachmentDraftStrip(draft: draft).fixedSize(horizontal: false, vertical: true) .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { [weak self] height in Task { @MainActor in guard let self, self.attachmentHeight != height else { return } self.attachmentHeight = height; self.refresh() } })) attachmentHost = host; addSubview(host) editor.registerForDraggedTypes([.fileURL, .png, .tiff] + NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) }) editor.onAttachments = { [weak self] pasteboard in self?.acceptAttachments(pasteboard) ?? false } observeDraft() } @discardableResult func acceptAttachments(_ pasteboard: NSPasteboard) -> Bool { guard let draft else { return false } if let promises = pasteboard.readObjects(forClasses: [NSFilePromiseReceiver.self]) as? [NSFilePromiseReceiver], !promises.isEmpty { receive(promises, into: draft) return true } if let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty { for url in urls { Task { await draft.add(url: url) } } return true } for type in [NSPasteboard.PasteboardType.png, .tiff] { if let data = pasteboard.data(forType: type) { Task { await draft.add(data: data, name: type == .png ? "image.png" : "image.tiff") } return true } } return false } private func observeDraft() { withObservationTracking { _ = draft?.items; _ = draft?.notice } onChange: { [weak self] in Task { @MainActor in self?.refresh(); self?.observeDraft() } } refresh() } init() { super.init(frame: .zero) addSubview(pill) addSubview(attachmentButton) attachmentButton.isHidden = true attachmentButton.toolTip = EquipoStrings.text("chat.attach.add") attachmentButton.setAccessibilityLabel(EquipoStrings.text("chat.attach.add")) attachmentButton.actionBlock = { [weak self] in self?.chooseFiles() } pill.addSubview(textScroll); pill.addSubview(send) textScroll.documentView = editor textScroll.drawsBackground = false textScroll.hasVerticalScroller = false textScroll.borderType = .noBorder editor.isRichText = false; editor.drawsBackground = false editor.allowsUndo = true editor.font = .systemFont(ofSize: 14) editor.textColor = .webText editor.insertionPointColor = .webText editor.textContainerInset = NSSize(width: 18, height: 0) editor.textContainer?.lineFragmentPadding = 0 editor.isVerticallyResizable = true editor.isHorizontallyResizable = false editor.textContainer?.widthTracksTextView = true editor.delegate = self let paragraph = NSMutableParagraphStyle() paragraph.minimumLineHeight = 24; paragraph.maximumLineHeight = 24 editor.defaultParagraphStyle = paragraph editor.typingAttributes = [.font: NSFont.systemFont(ofSize: 14), .paragraphStyle: paragraph, .foregroundColor: NSColor.webText, .baselineOffset: 3] editor.placeholder = EquipoStrings.text("conversation.placeholder") editor.setAccessibilityLabel(EquipoStrings.text("conversation.placeholder")) send.toolTip = EquipoStrings.text("composer.send") send.setAccessibilityLabel(EquipoStrings.text("composer.send")) send.actionBlock = { [weak self] in self?.submit() } editor.onSubmit = { [weak self] in self?.submit() } refresh() } required init?(coder: NSCoder) { fatalError() } var text: String { editor.string } private var canSend: Bool { draft?.canSend(text: editor.string) ?? !editor.string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } func textDidChange(_ notification: Notification) { onTextChange?(editor.string); refresh() } func textDidBeginEditing(_ notification: Notification) { pill.needsDisplay = true } func textDidEndEditing(_ notification: Notification) { pill.needsDisplay = true } func chooseFiles() { guard let draft, let window else { return } let panel = Self.makeAttachmentPanel() panel.beginSheetModal(for: window) { response in guard response == .OK else { return } for url in panel.urls { Task { await draft.add(url: url) } } } } static func makeAttachmentPanel() -> NSOpenPanel { let panel = NSOpenPanel() panel.canChooseFiles = true panel.canChooseDirectories = false panel.allowsMultipleSelection = true return panel } func setText(_ text: String) { editor.string = text; editor.needsDisplay = true; onTextChange?(text); refresh() } func submit() { let value = editor.string.trimmingCharacters(in: .whitespacesAndNewlines) guard canSend else { return } editor.string = ""; editor.needsDisplay = true; onTextChange?("") refresh(); onSend?(value) window?.makeFirstResponder(editor) } func refresh() { send.isHidden = !canSend needsLayout = true layoutSubtreeIfNeeded() } override func layout() { super.layout() guard !updating, bounds.width > 80 else { return } updating = true let attachmentSpaceX: CGFloat = draft == nil ? 0 : 52 let pillWidth = bounds.width - attachmentSpaceX let editorWidth = pillWidth - 44 editor.frame.size.width = editorWidth editor.textContainer?.containerSize = NSSize(width: max(1, editorWidth - 36), height: .greatestFiniteMagnitude) editor.layoutManager?.ensureLayout(for: editor.textContainer!) let used = editor.layoutManager?.usedRect(for: editor.textContainer!).height ?? 24 let contentHeight = max(24, ceil(used)) let height = min(164, contentHeight + 20) attachmentHost?.frame = NSRect(x: 0, y: 0, width: bounds.width, height: attachmentHeight) let attachmentSpace = attachmentHeight > 0 ? attachmentHeight + 8 : 0 attachmentButton.frame = NSRect(x: 0, y: attachmentSpace + height - 44, width: 44, height: 44) pill.frame = NSRect(x: attachmentSpaceX, y: attachmentSpace, width: pillWidth, height: height) textScroll.frame = NSRect(x: 0, y: 10, width: editorWidth, height: height - 20) editor.frame.size = NSSize(width: editorWidth, height: contentHeight) textScroll.hasVerticalScroller = contentHeight > 144 send.frame = NSRect(x: pillWidth - 44, y: height - 44, width: 44, height: 44) let changed = desiredHeight != height + attachmentSpace desiredHeight = height + attachmentSpace updating = false if changed { onHeightChange?() } } }