oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1import AppKit
2import EquipoKit
3import SwiftUI
4import Observation
5
6@MainActor @Observable final class MacComposerDraft { var text = "" }
7
8/// The composer's text view: Return sends, Shift-Return starts a new line,
9/// and an input method's marked text is never sent half typed.
10final class ComposerEditor: NSTextView {
11 var onSubmit: (() -> Void)?
12 var placeholder = ""
13 var onAttachments: ((NSPasteboard) -> Bool)?
14 override func paste(_ sender: Any?) {
15 if onAttachments?(NSPasteboard.general) != true { super.paste(sender) }
16 }
17 private func accepts(_ board: NSPasteboard) -> Bool {
18 board.availableType(from: [.fileURL, .png, .tiff] + NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) }) != nil
19 }
20 override func draggingEntered(_ sender: any NSDraggingInfo) -> NSDragOperation {
21 return accepts(sender.draggingPasteboard) ? .copy : super.draggingEntered(sender)
22 }
23 override func draggingUpdated(_ sender: any NSDraggingInfo) -> NSDragOperation {
24 return accepts(sender.draggingPasteboard) ? .copy : super.draggingUpdated(sender)
25 }
26 override func prepareForDragOperation(_ sender: any NSDraggingInfo) -> Bool {
27 return accepts(sender.draggingPasteboard) || super.prepareForDragOperation(sender)
28 }
29 override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool {
30 guard accepts(sender.draggingPasteboard) else { return super.performDragOperation(sender) }
31 return onAttachments?(sender.draggingPasteboard) == true
32 }
33 override func draw(_ dirtyRect: NSRect) {
34 super.draw(dirtyRect)
35 if string.isEmpty {
36 var attributes = typingAttributes
37 attributes[.foregroundColor] = NSColor.webPlaceholder
38 (placeholder as NSString).draw(in: NSRect(x: 18, y: 0, width: max(0, bounds.width - 36), height: 24), withAttributes: attributes)
39 }
40 }
41 override func didChangeText() { super.didChangeText(); needsDisplay = true }
42 override func keyDown(with event: NSEvent) {
43 if (event.keyCode == 36 || event.keyCode == 76) && !event.modifierFlags.contains(.shift) && !hasMarkedText() {
44 onSubmit?()
45 } else { super.keyDown(with: event) }
46 }
47}
48
49final class ComposerPill: NSView {
50 override var isFlipped: Bool { true }
51 override func draw(_ dirtyRect: NSRect) {
52 let path = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), xRadius: 10, yRadius: 10)
53 NSColor.webSurface2.setFill(); path.fill()
54 let focused = window?.firstResponder is ComposerEditor && window?.isKeyWindow == true
55 (focused ? NSColor.webAccent : NSColor.webBorder).setStroke()
56 path.lineWidth = focused ? 2 : 1; path.stroke()
57 }
58}
59
60/// The conversation's composer: attachments above a pill that grows to
61/// six lines, then scrolls, with a 44-point send target centred on its last
62/// line.
63final class MacComposer: NSView, NSTextViewDelegate {
64 override var isFlipped: Bool { true }
65 let editor = ComposerEditor()
66 let send = ActionButton("", style: .send, symbol: "arrow.up") {}
67 let attachmentButton = ActionButton("", style: .attachment, symbol: "plus") {}
68 let pill = ComposerPill()
69 let textScroll = NSScrollView()
70 var onSend: ((String) -> Void)?
71 var onTextChange: ((String) -> Void)?
72 var onHeightChange: (() -> Void)?
73 private(set) var desiredHeight: CGFloat = 44
74 private var updating = false
75 private var draft: AttachmentDraft?
76 private var attachmentHost: NSHostingView<AnyView>?
77 private var attachmentHeight: CGFloat = 0
78
79 func attach(_ draft: AttachmentDraft) {
80 self.draft = draft
81 attachmentButton.isHidden = false
82 let host = NSHostingView(rootView: AnyView(AttachmentDraftStrip(draft: draft).fixedSize(horizontal: false, vertical: true)
83 .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { [weak self] height in
84 Task { @MainActor in
85 guard let self, self.attachmentHeight != height else { return }
86 self.attachmentHeight = height; self.refresh()
87 }
88 }))
89 attachmentHost = host; addSubview(host)
90 editor.registerForDraggedTypes([.fileURL, .png, .tiff] + NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) })
91 editor.onAttachments = { [weak self] pasteboard in self?.acceptAttachments(pasteboard) ?? false }
92 observeDraft()
93 }
94
95 @discardableResult func acceptAttachments(_ pasteboard: NSPasteboard) -> Bool {
96 guard let draft else { return false }
97 if let promises = pasteboard.readObjects(forClasses: [NSFilePromiseReceiver.self]) as? [NSFilePromiseReceiver], !promises.isEmpty {
98 receive(promises, into: draft)
99 return true
100 }
101 if let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty {
102 for url in urls { Task { await draft.add(url: url) } }
103 return true
104 }
105 for type in [NSPasteboard.PasteboardType.png, .tiff] {
106 if let data = pasteboard.data(forType: type) {
107 Task { await draft.add(data: data, name: type == .png ? "image.png" : "image.tiff") }
108 return true
109 }
110 }
111 return false
112 }
113
114 private func observeDraft() {
115 withObservationTracking {
116 _ = draft?.items; _ = draft?.notice
117 } onChange: { [weak self] in
118 Task { @MainActor in self?.refresh(); self?.observeDraft() }
119 }
120 refresh()
121 }
122
123 init() {
124 super.init(frame: .zero)
125 addSubview(pill)
126 addSubview(attachmentButton)
127 attachmentButton.isHidden = true
128 attachmentButton.toolTip = EquipoStrings.text("chat.attach.add")
129 attachmentButton.setAccessibilityLabel(EquipoStrings.text("chat.attach.add"))
130 attachmentButton.actionBlock = { [weak self] in self?.chooseFiles() }
131 pill.addSubview(textScroll); pill.addSubview(send)
132 textScroll.documentView = editor
133 textScroll.drawsBackground = false
134 textScroll.hasVerticalScroller = false
135 textScroll.borderType = .noBorder
136 editor.isRichText = false; editor.drawsBackground = false
137 editor.allowsUndo = true
138 editor.font = .systemFont(ofSize: 14)
139 editor.textColor = .webText
140 editor.insertionPointColor = .webText
141 editor.textContainerInset = NSSize(width: 18, height: 0)
142 editor.textContainer?.lineFragmentPadding = 0
143 editor.isVerticallyResizable = true
144 editor.isHorizontallyResizable = false
145 editor.textContainer?.widthTracksTextView = true
146 editor.delegate = self
147 let paragraph = NSMutableParagraphStyle()
148 paragraph.minimumLineHeight = 24; paragraph.maximumLineHeight = 24
149 editor.defaultParagraphStyle = paragraph
150 editor.typingAttributes = [.font: NSFont.systemFont(ofSize: 14), .paragraphStyle: paragraph, .foregroundColor: NSColor.webText, .baselineOffset: 3]
151 editor.placeholder = EquipoStrings.text("conversation.placeholder")
152 editor.setAccessibilityLabel(EquipoStrings.text("conversation.placeholder"))
153 send.toolTip = EquipoStrings.text("composer.send")
154 send.setAccessibilityLabel(EquipoStrings.text("composer.send"))
155 send.actionBlock = { [weak self] in self?.submit() }
156 editor.onSubmit = { [weak self] in self?.submit() }
157 refresh()
158 }
159 required init?(coder: NSCoder) { fatalError() }
160
161 var text: String { editor.string }
162 private var canSend: Bool { draft?.canSend(text: editor.string) ?? !editor.string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
163
164 func textDidChange(_ notification: Notification) { onTextChange?(editor.string); refresh() }
165 func textDidBeginEditing(_ notification: Notification) { pill.needsDisplay = true }
166 func textDidEndEditing(_ notification: Notification) { pill.needsDisplay = true }
167
168 func chooseFiles() {
169 guard let draft, let window else { return }
170 let panel = Self.makeAttachmentPanel()
171 panel.beginSheetModal(for: window) { response in
172 guard response == .OK else { return }
173 for url in panel.urls { Task { await draft.add(url: url) } }
174 }
175 }
176
177 static func makeAttachmentPanel() -> NSOpenPanel {
178 let panel = NSOpenPanel()
179 panel.canChooseFiles = true
180 panel.canChooseDirectories = false
181 panel.allowsMultipleSelection = true
182 return panel
183 }
184
185 func setText(_ text: String) { editor.string = text; editor.needsDisplay = true; onTextChange?(text); refresh() }
186
187 func submit() {
188 let value = editor.string.trimmingCharacters(in: .whitespacesAndNewlines)
189 guard canSend else { return }
190 editor.string = ""; editor.needsDisplay = true; onTextChange?("")
191 refresh(); onSend?(value)
192 window?.makeFirstResponder(editor)
193 }
194
195 func refresh() {
196 send.isHidden = !canSend
197 needsLayout = true
198 layoutSubtreeIfNeeded()
199 }
200
201 override func layout() {
202 super.layout()
203 guard !updating, bounds.width > 80 else { return }
204 updating = true
205 let attachmentSpaceX: CGFloat = draft == nil ? 0 : 52
206 let pillWidth = bounds.width - attachmentSpaceX
207 let editorWidth = pillWidth - 44
208 editor.frame.size.width = editorWidth
209 editor.textContainer?.containerSize = NSSize(width: max(1, editorWidth - 36), height: .greatestFiniteMagnitude)
210 editor.layoutManager?.ensureLayout(for: editor.textContainer!)
211 let used = editor.layoutManager?.usedRect(for: editor.textContainer!).height ?? 24
212 let contentHeight = max(24, ceil(used))
213 let height = min(164, contentHeight + 20)
214 attachmentHost?.frame = NSRect(x: 0, y: 0, width: bounds.width, height: attachmentHeight)
215 let attachmentSpace = attachmentHeight > 0 ? attachmentHeight + 8 : 0
216 attachmentButton.frame = NSRect(x: 0, y: attachmentSpace + height - 44, width: 44, height: 44)
217 pill.frame = NSRect(x: attachmentSpaceX, y: attachmentSpace, width: pillWidth, height: height)
218 textScroll.frame = NSRect(x: 0, y: 10, width: editorWidth, height: height - 20)
219 editor.frame.size = NSSize(width: editorWidth, height: contentHeight)
220 textScroll.hasVerticalScroller = contentHeight > 144
221 send.frame = NSRect(x: pillWidth - 44, y: height - 44, width: 44, height: 44)
222 let changed = desiredHeight != height + attachmentSpace
223 desiredHeight = height + attachmentSpace
224 updating = false
225 if changed { onHeightChange?() }
226 }
227}
228