Branchwell

Voxley / app · voxley.si / Sources / Voxley / RefineWindow.swift

Raw 9.9 KB on 80ae64b931ebad0441b504355b24e4ec60e012a3
1import AppKit
2import SwiftUI
3
4/// The small, static Refine window. It stays where it opens so the person can take their
5/// hands off the shortcut, type, chat with Apple Intelligence, and copy the result.
6@MainActor
7final class RefineWindow: NSObject, NSWindowDelegate {
8 let session = RefineSession()
9 private var window: NSWindow?
10 private var returnApp: NSRunningApplication?
11 private let size = NSSize(width: 480, height: 560)
12
13 var isVisible: Bool { window?.isVisible == true }
14
15 /// Opens the window with a new transcript, or adds to the open conversation.
16 func present(_ text: String, from target: Destination, locale: String) {
17 if isVisible, target.app?.processIdentifier == ProcessInfo.processInfo.processIdentifier {
18 session.receiveSpokenRequest(text)
19 window?.makeKeyAndOrderFront(nil)
20 return
21 }
22 returnApp = target.app?.processIdentifier == ProcessInfo.processInfo.processIdentifier ? returnApp : target.app
23 session.begin(text: text, source: target.name, locale: locale)
24 show(near: target.windowFrame)
25 }
26
27 /// Opens an empty window from the menu, for typing an idea instead of saying it.
28 func openEmpty(locale: String) {
29 if isVisible {
30 window?.makeKeyAndOrderFront(nil)
31 NSApp.activate()
32 return
33 }
34 returnApp = NSWorkspace.shared.frontmostApplication
35 session.begin(text: "", source: "", locale: locale)
36 show(near: nil)
37 }
38
39 func close() { window?.close() }
40
41 /// Copies the draft, closes the window, and brings back the app the person was working in.
42 func copyAndReturn() {
43 session.copy()
44 let app = returnApp
45 window?.close()
46 if let app, app.processIdentifier != ProcessInfo.processInfo.processIdentifier {
47 app.activate()
48 }
49 }
50
51 var returnAppName: String? {
52 guard let returnApp, returnApp.processIdentifier != ProcessInfo.processInfo.processIdentifier else { return nil }
53 return returnApp.localizedName
54 }
55
56 private func show(near anchor: NSRect?) {
57 let window = window ?? makeWindow()
58 let reference = anchor.map { NSPoint(x: $0.midX, y: $0.midY) } ?? NSEvent.mouseLocation
59 if let screen = NSScreen.screens.first(where: { $0.frame.contains(reference) }) ?? NSScreen.main {
60 let visible = screen.visibleFrame
61 let width = min(size.width, visible.width - 24)
62 let height = min(size.height, visible.height - 24)
63 window.setFrame(NSRect(x: visible.midX - width / 2, y: visible.midY - height / 2,
64 width: width, height: height), display: true)
65 }
66 NSApp.activate()
67 window.makeKeyAndOrderFront(nil)
68 }
69
70 private func makeWindow() -> NSWindow {
71 let window = NSWindow(
72 contentRect: NSRect(origin: .zero, size: size),
73 styleMask: [.titled, .closable, .fullSizeContentView],
74 backing: .buffered,
75 defer: false
76 )
77 window.title = "Refine with Voxley"
78 window.titlebarAppearsTransparent = true
79 window.isMovableByWindowBackground = true
80 window.level = .floating
81 window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
82 window.isReleasedWhenClosed = false
83 window.hidesOnDeactivate = false
84 window.delegate = self
85 window.contentView = NSHostingView(rootView: RefineView(
86 session: session,
87 returnAppName: { [weak self] in self?.returnAppName },
88 copyAndReturn: { [weak self] in self?.copyAndReturn() },
89 close: { [weak self] in self?.close() }
90 ))
91 self.window = window
92 return window
93 }
94
95 func windowWillClose(_ notification: Notification) {
96 session.end()
97 }
98}
99
100struct RefineView: View {
101 @Bindable var session: RefineSession
102 let returnAppName: () -> String?
103 let copyAndReturn: () -> Void
104 let close: () -> Void
105 @FocusState private var focus: Field?
106
107 private enum Field { case draft, request }
108
109 var body: some View {
110 VStack(alignment: .leading, spacing: 12) {
111 header
112 draftEditor
113 conversation
114 requestRow
115 actions
116 }
117 .padding(.horizontal, 18)
118 .padding(.top, 34)
119 .padding(.bottom, 16)
120 .frame(minWidth: 380, minHeight: 440)
121 .background(.black)
122 .tint(.voxleyAccent)
123 .onAppear { focus = .draft }
124 .onExitCommand(perform: close)
125 }
126
127 private var header: some View {
128 HStack(spacing: 8) {
129 Image(systemName: "sparkles")
130 .foregroundStyle(Color.voxleyAccent)
131 .accessibilityHidden(true)
132 Text("Refine your idea").font(.headline)
133 Spacer()
134 if !session.sourceName.isEmpty {
135 Text("from \(session.sourceName)")
136 .font(.caption)
137 .foregroundStyle(.secondary)
138 }
139 }
140 }
141
142 private var draftEditor: some View {
143 TextEditor(text: $session.draft)
144 .font(.body)
145 .focused($focus, equals: .draft)
146 .scrollContentBackground(.hidden)
147 .padding(8)
148 .frame(minHeight: 150)
149 .background(.background.opacity(0.55), in: RoundedRectangle(cornerRadius: 10))
150 .overlay {
151 RoundedRectangle(cornerRadius: 10).strokeBorder(.quaternary).allowsHitTesting(false)
152 }
153 .overlay(alignment: .topLeading) {
154 if session.draft.isEmpty {
155 Text("Type or dictate your idea…")
156 .foregroundStyle(.tertiary)
157 .padding(.horizontal, 13).padding(.vertical, 8)
158 .allowsHitTesting(false)
159 }
160 }
161 .disabled(session.isThinking)
162 .accessibilityLabel("Draft")
163 }
164
165 private var conversation: some View {
166 ScrollViewReader { proxy in
167 ScrollView {
168 VStack(alignment: .leading, spacing: 8) {
169 if session.messages.isEmpty {
170 Text("Edit the draft yourself, or press Refine and tell Apple Intelligence what to change. It runs on your Mac.")
171 .font(.callout)
172 .foregroundStyle(.secondary)
173 }
174 ForEach(session.messages) { message in
175 RefineBubble(message: message).id(message.id)
176 }
177 if session.isThinking {
178 HStack(spacing: 6) {
179 ProgressView().controlSize(.small)
180 Text("Apple Intelligence is refining…").font(.callout).foregroundStyle(.secondary)
181 }
182 .id("thinking")
183 }
184 }
185 .frame(maxWidth: .infinity, alignment: .leading)
186 }
187 .frame(minHeight: 70, maxHeight: 150)
188 .onChange(of: session.messages.count) {
189 withAnimation { proxy.scrollTo(session.messages.last?.id, anchor: .bottom) }
190 }
191 }
192 }
193
194 private var requestRow: some View {
195 HStack(spacing: 8) {
196 TextField("Ask for a change, like “make it shorter”", text: $session.request)
197 .textFieldStyle(.roundedBorder)
198 .focused($focus, equals: .request)
199 .onSubmit { session.refine() }
200 .disabled(session.isThinking)
201 Button {
202 session.refine()
203 } label: {
204 Label("Refine", systemImage: "sparkles")
205 }
206 .buttonStyle(.borderedProminent).foregroundStyle(.black)
207 .disabled(!session.canRefine)
208 .help(session.modelReady ? "Refine the draft with Apple Intelligence" : session.modelStatus)
209 }
210 }
211
212 private var actions: some View {
213 HStack {
214 Button("Undo", systemImage: "arrow.uturn.backward") { session.undo() }
215 .disabled(session.previousDrafts.isEmpty || session.isThinking)
216 Spacer()
217 if session.copied {
218 Label("Copied", systemImage: "checkmark")
219 .font(.callout)
220 .foregroundStyle(.secondary)
221 }
222 Button("Copy") { session.copy() }
223 .keyboardShortcut("c", modifiers: [.command, .shift])
224 .disabled(session.draft.isEmpty)
225 Button(returnAppName().map { "Copy and Return to \($0)" } ?? "Copy and Close", action: copyAndReturn)
226 .keyboardShortcut(.return, modifiers: .command)
227 .buttonStyle(.borderedProminent).foregroundStyle(.black)
228 .disabled(session.draft.isEmpty)
229 }
230 }
231}
232
233private struct RefineBubble: View {
234 let message: RefineMessage
235
236 var body: some View {
237 switch message.role {
238 case .person:
239 HStack {
240 Spacer(minLength: 40)
241 Text(message.text)
242 .padding(.horizontal, 10).padding(.vertical, 6)
243 .background(Color.voxleyAccent.opacity(0.22), in: RoundedRectangle(cornerRadius: 10))
244 .textSelection(.enabled)
245 }
246 case .assistant:
247 HStack(alignment: .top, spacing: 6) {
248 Image(systemName: "apple.intelligence")
249 .foregroundStyle(.secondary)
250 .accessibilityLabel("Apple Intelligence")
251 Text(message.text)
252 .padding(.horizontal, 10).padding(.vertical, 6)
253 .background(.quaternary.opacity(0.6), in: RoundedRectangle(cornerRadius: 10))
254 .textSelection(.enabled)
255 Spacer(minLength: 40)
256 }
257 case .note:
258 Label(message.text, systemImage: "info.circle")
259 .font(.callout)
260 .foregroundStyle(.secondary)
261 }
262 }
263}