Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Chat/Composer.swift3// Description: The message composer: multi-line input, attachments, prompt templates, dictation, send / stop.4import SwiftUI5import PhotosUI6import UniformTypeIdentifiers7import LocalChatCore89struct Composer: View {10 @Environment(AppModel.self) private var app11 @Bindable var controller: ChatController12 let speech: SpeechController13 @FocusState private var focused: Bool14 @State private var importingFile = false15 @State private var photoItems: [PhotosPickerItem] = []16 @State private var showPhotoPicker = false17 @State private var templateToFill: PromptTemplate?1819 var body: some View {20 VStack(spacing: 8) {21 if !controller.pendingAttachments.isEmpty {22 ScrollView(.horizontal, showsIndicators: false) {23 HStack(spacing: 6) {24 ForEach(controller.pendingAttachments) { item in25 HStack(spacing: 6) {26 Image(systemName: item.kind == .image ? "photo" : "doc.text").foregroundStyle(item.warning == nil ? DS.C.accent : DS.C.warn)27 Text(item.fileName).font(DS.F.caption).lineLimit(1)28 Button { controller.pendingAttachments.removeAll { $0.id == item.id } } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(DS.C.muted) }29 .buttonStyle(.plain).accessibilityLabel("Remove \(item.fileName)")30 }31 .padding(.horizontal, 9).padding(.vertical, 6).background(DS.C.surface2, in: Capsule())32 .help(item.warning ?? "\(ByteFormat.string(Int64(item.data.count)))")33 }34 }35 }36 if let warning = controller.pendingAttachments.compactMap(\.warning).first { InlineNotice(.warning, warning) }37 if controller.pendingAttachments.contains(where: { $0.kind == .image }), controller.model?.capabilities.contains(.vision) != true {38 InlineNotice(.warning, "The current model cannot see images. Pick a vision model to analyze them.")39 }40 }41 HStack(alignment: .bottom, spacing: 8) {42 Menu {43 Button("Attach files…", systemImage: "doc") { importingFile = true }44 Button("Attach photos…", systemImage: "photo.on.rectangle") { showPhotoPicker = true }45 if let paste = Pasteboard.string, !paste.isEmpty { Button("Paste as attachment", systemImage: "doc.on.clipboard") { controller.attach(data: Data(paste.utf8), fileName: "Pasted text.txt") } }46 Divider()47 Menu("Prompt templates", systemImage: "text.quote") {48 ForEach(app.templates.filter { $0.kind == .user }) { template in49 Button(template.name, systemImage: template.symbol) { apply(template) }50 }51 }52 Menu("System prompt", systemImage: "person.text.rectangle") {53 ForEach(app.templates.filter { $0.kind == .system }) { template in54 Button(template.name) { controller.update { $0.systemPrompt = template.body } }55 }56 }57 } label: {58 Image(systemName: "plus").font(.system(size: 15, weight: .semibold)).frame(width: 34, height: 34).background(DS.C.surface2, in: Circle()).contentShape(Circle())59 }60 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().foregroundStyle(DS.C.text2).accessibilityLabel("Attach or insert")6162 TextField("Message \(controller.model?.name ?? "a local model")…", text: $controller.draft, axis: .vertical)63 .textFieldStyle(.plain).font(.system(size: DS.transcriptSize)).lineLimit(1...10).focused($focused)64 .padding(.vertical, 8)65 .onSubmit { if app.preferences.sendWithReturn && Platform.isMac { controller.send() } }66 .accessibilityIdentifier("composer-field")67 #if os(macOS)68 .onKeyPress(.return, phases: .down) { press in69 // Return sends, Shift-Return inserts a new line (when "send with Return" is on)70 guard app.preferences.sendWithReturn, !press.modifiers.contains(.shift) else { return .ignored }71 controller.send(); return .handled72 }73 #endif7475 if speech.isAvailable {76 Button { speech.toggleDictation { text in controller.draft = text } } label: {77 Image(systemName: speech.isListening ? "waveform.circle.fill" : "mic").font(.system(size: 16, weight: .medium))78 .foregroundStyle(speech.isListening ? DS.C.danger : DS.C.text2).frame(width: 34, height: 34)79 .symbolEffect(.pulse, isActive: speech.isListening)80 }81 .buttonStyle(.plain).accessibilityLabel(speech.isListening ? "Stop dictation" : "Dictate").help("Dictate (on-device when the system supports it)")82 }8384 Button { controller.isGenerating ? controller.stop() : controller.send() } label: {85 Image(systemName: controller.isGenerating ? "stop.fill" : "arrow.up").font(.system(size: 14, weight: .bold)).foregroundStyle(.white)86 .frame(width: 34, height: 34)87 .background(controller.isGenerating ? AnyShapeStyle(DS.C.danger) : AnyShapeStyle(DS.G.accent), in: Circle())88 .contentTransition(.symbolEffect(.replace))89 }90 .buttonStyle(.plain).disabled(!controller.isGenerating && !controller.canSend).opacity(!controller.isGenerating && !controller.canSend ? 0.4 : 1)91 .keyboardShortcut(controller.isGenerating ? KeyEquivalent(".") : .return, modifiers: .command)92 .accessibilityLabel(controller.isGenerating ? "Stop generating" : "Send").accessibilityIdentifier(controller.isGenerating ? "stop-button" : "send-button")93 }94 .padding(.horizontal, 8).padding(.vertical, 6)95 .background(DS.C.surface, in: RoundedRectangle(cornerRadius: 24, style: .continuous))96 .overlay(RoundedRectangle(cornerRadius: 24, style: .continuous).strokeBorder(focused ? AnyShapeStyle(DS.G.aurora) : AnyShapeStyle(DS.C.borderStrong), lineWidth: focused ? 1.5 : 1))97 .shadow(color: .black.opacity(0.08), radius: 12, y: 4)98 .animation(DS.M.fade, value: focused)99 if let error = speech.errorText { Text(error).font(DS.F.micro).foregroundStyle(DS.C.warn) }100 }101 .padding(.horizontal, DS.S.lg).padding(.top, 8).padding(.bottom, 12)102 .frame(maxWidth: DS.S.column + 2 * DS.S.lg).frame(maxWidth: .infinity)103 .fileImporter(isPresented: $importingFile, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in104 if case .success(let urls) = result { for url in urls { controller.attach(url: url) } }105 }106 .photosPicker(isPresented: $showPhotoPicker, selection: $photoItems, maxSelectionCount: 4, matching: .images)107 .onChange(of: photoItems) { _, items in108 guard !items.isEmpty else { return }109 photoItems = []110 Task {111 for (index, item) in items.enumerated() {112 if let data = try? await item.loadTransferable(type: Data.self) { controller.attach(data: data, fileName: "Photo \(index + 1).jpg") }113 }114 }115 }116 .sheet(item: $templateToFill) { template in117 TemplateFillSheet(template: template) { controller.draft = $0; focused = true }118 }119 .onAppear { if Platform.isMac { focused = true } }120 }121122 private func apply(_ template: PromptTemplate) {123 if template.variables.isEmpty { controller.draft = template.body } else { templateToFill = template }124 }125}126127struct TemplateFillSheet: View {128 let template: PromptTemplate129 let onInsert: (String) -> Void130 @State private var values: [String: String] = [:]131 @Environment(\.dismiss) private var dismiss132 var body: some View {133 VStack(alignment: .leading, spacing: 12) {134 SectionHeader(template.name, subtitle: "Fill in the template's variables.", symbol: template.symbol)135 ForEach(template.variables, id: \.self) { name in136 VStack(alignment: .leading, spacing: 4) {137 Text(name).font(DS.F.caption).foregroundStyle(DS.C.muted)138 TextField(name, text: Binding(get: { values[name] ?? "" }, set: { values[name] = $0 }), axis: .vertical).textFieldStyle(.roundedBorder).lineLimit(1...6)139 }140 }141 HStack {142 Spacer()143 Button("Cancel") { dismiss() }.buttonStyle(.lcSecondaryCompact).keyboardShortcut(.cancelAction)144 Button("Insert") { onInsert(template.rendered(values)); dismiss() }.buttonStyle(.lcPrimaryCompact).keyboardShortcut(.defaultAction)145 }146 }147 .padding(DS.S.lg).frame(minWidth: 320, idealWidth: 480).screenBackground()148 #if os(iOS)149 .presentationDetents([.medium, .large])150 #endif151 }152}153