Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraUI/Sources/Chat/Composer.swift10// Module : Chat11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import PhotosUI90import UniformTypeIdentifiers91import AstraCore92import AstraDesign93import AstraPersistence9495/// The prompt composer: multi-line text that grows with its content, attachments with previews, dictation, a model chip96/// and one send / stop button whose state always matches what a tap will do.97struct Composer: View {98 @Binding var text: String99 @Binding var drafts: [AttachmentDraft]100 let isGenerating: Bool101 let model: ModelInfo?102 let modelRef: ModelRef103 let modelName: String104 let contextFraction: Double105 let onSend: () -> Void106 let onStop: () -> Void107 let onPickModel: () -> Void108 let onError: (String) -> Void109110 @FocusState private var focused: Bool111 @State private var photoItems: [PhotosPickerItem] = []112 @State private var showFiles = false113 @State private var showPhotos = false114 @State private var dictation = Dictation()115 @Environment(\.accessibilityReduceMotion) private var reduceMotion116117 private var canSend: Bool { !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !drafts.isEmpty }118119 var body: some View {120 VStack(alignment: .leading, spacing: 8) {121 if !drafts.isEmpty { draftStrip }122 if dictation.isRecording { dictationBar }123 HStack(alignment: .bottom, spacing: 4) {124 attachMenu125 TextField("Message", text: $text, axis: .vertical)126 .lineLimit(1...8)127 .font(AstraFont.body)128 .focused($focused)129 .padding(.vertical, 11)130 .accessibilityIdentifier("composer-field")131 .onChange(of: dictation.transcript) { _, new in if dictation.isRecording || !new.isEmpty { text = dictation.prefix + new } }132 if text.isEmpty, !isGenerating, dictation.isAvailable {133 IconButton(dictation.isRecording ? "mic.fill" : "mic", label: dictation.isRecording ? "Stop dictation" : "Dictate",134 tint: dictation.isRecording ? AstraColor.danger : AstraColor.textSecondary) { toggleDictation() }135 }136 sendButton137 }138 .padding(.leading, 2).padding(.trailing, 4)139 .background(AstraColor.surface, in: RoundedRectangle(cornerRadius: 24, style: .continuous))140 .overlay(RoundedRectangle(cornerRadius: 24, style: .continuous).strokeBorder(focused ? AstraColor.violet.opacity(0.55) : AstraColor.stroke, lineWidth: 1))141 .animation(AstraMotion.resolve(AstraMotion.quick, reduceMotion: reduceMotion), value: focused)142143 HStack(spacing: 8) {144 Button(action: onPickModel) {145 HStack(spacing: 6) {146 ProviderLogo(ref: modelRef, vendor: model?.vendor, size: 20)147 Text(modelName).font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(1)148 Image(systemName: "chevron.up.chevron.down").font(.system(size: 9, weight: .bold)).foregroundStyle(AstraColor.textTertiary)149 }150 .padding(.horizontal, 10).frame(minHeight: 36)151 .background(AstraColor.surfaceRaised, in: Capsule())152 .contentShape(Rectangle())153 }154 .buttonStyle(.plain)155 .accessibilityLabel("Model: \(modelName)").accessibilityHint("Opens the model picker")156 .accessibilityIdentifier("composer-model")157 if modelRef.provider.isLocal { AstraBadge("On device", symbol: "lock.fill", tone: .success) }158 Spacer(minLength: 0)159 ContextMeter(fraction: contextFraction)160 }161 }162 .padding(.horizontal, AstraSpace.md).padding(.top, 8).padding(.bottom, 6)163 .photosPicker(isPresented: $showPhotos, selection: $photoItems, maxSelectionCount: 4, matching: .images, preferredItemEncoding: .compatible)164 .onChange(of: photoItems) { _, items in165 guard !items.isEmpty else { return }166 Task { await importPhotos(items); photoItems = [] }167 }168 .fileImporter(isPresented: $showFiles, allowedContentTypes: [.pdf, .plainText, .text, .image, .json, .commaSeparatedText, .sourceCode, .xml, .data], allowsMultipleSelection: true) { result in169 guard case .success(let urls) = result else { return }170 Task { await importFiles(urls) }171 }172 .onDisappear { dictation.stop() }173 }174175 private var attachMenu: some View {176 Menu {177 Button { showPhotos = true } label: { Label("Photo library", systemImage: "photo.on.rectangle") }178 Button { showFiles = true } label: { Label("Files", systemImage: "folder") }179 Button { pasteImage() } label: { Label("Paste", systemImage: "doc.on.clipboard") }180 } label: {181 Image(systemName: "plus").font(.system(size: 17, weight: .semibold)).foregroundStyle(AstraColor.textSecondary)182 .frame(width: AstraSpace.hit, height: AstraSpace.hit).contentShape(Rectangle())183 }184 .accessibilityLabel("Add attachment")185 .disabled(isGenerating)186 }187188 private var sendButton: some View {189 Button {190 if isGenerating { AstraHaptics.tap(); onStop() }191 else { dictation.stop(); AstraHaptics.send(); onSend() }192 } label: {193 Image(systemName: isGenerating ? "stop.fill" : "arrow.up")194 .font(.system(size: 15, weight: .bold))195 .foregroundStyle(AstraColor.onAccent)196 .frame(width: 34, height: 34)197 .background(isGenerating ? AnyShapeStyle(AstraColor.dangerFill) : (canSend ? AnyShapeStyle(AstraColor.accentFill) : AnyShapeStyle(AstraColor.strokeStrong)), in: Circle())198 .contentTransition(.symbolEffect(.replace))199 .frame(width: AstraSpace.hit, height: AstraSpace.hit).contentShape(Rectangle())200 }201 .buttonStyle(.plain)202 .disabled(!isGenerating && !canSend)203 .accessibilityLabel(isGenerating ? "Stop generating" : "Send")204 .accessibilityIdentifier(isGenerating ? "composer-stop" : "composer-send")205 }206207 private var draftStrip: some View {208 ScrollView(.horizontal, showsIndicators: false) {209 HStack(spacing: 8) {210 ForEach(Array(drafts.enumerated()), id: \.offset) { index, draft in211 ZStack(alignment: .topTrailing) {212 Group {213 if draft.kind == .image, let image = ImageLoader.thumbnail(data: draft.data, maxPixel: 240) {214 image.resizable().scaledToFill().frame(width: 64, height: 64)215 } else {216 VStack(spacing: 4) {217 Image(systemName: draft.kind == .pdf ? "doc.richtext" : "doc.text").foregroundStyle(AstraColor.cyan)218 Text(draft.filename).font(AstraFont.micro).foregroundStyle(AstraColor.textSecondary).lineLimit(2).multilineTextAlignment(.center)219 }220 .padding(6).frame(width: 96, height: 64)221 }222 }223 .background(AstraColor.surfaceRaised)224 .clipShape(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))225 .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))226 Button { drafts.remove(at: index) } label: {227 Image(systemName: "xmark.circle.fill").font(.system(size: 18)).symbolRenderingMode(.palette)228 .foregroundStyle(AstraColor.onAccent, AstraColor.textTertiary)229 .frame(width: 32, height: 32).contentShape(Rectangle())230 }231 .buttonStyle(.plain).offset(x: 8, y: -8)232 .accessibilityLabel("Remove \(draft.filename)")233 }234 .accessibilityElement(children: .contain)235 }236 }237 .padding(.top, 8).padding(.trailing, 8)238 }239 }240241 private var dictationBar: some View {242 HStack(spacing: 8) {243 Image(systemName: "waveform").symbolEffect(.variableColor.iterative, isActive: !reduceMotion).foregroundStyle(AstraColor.danger)244 Text(dictation.onDevice ? "Listening. Speech is recognised on this device." : "Listening. Speech is sent to Apple for recognition.")245 .font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)246 Spacer()247 Button("Done") { dictation.stop() }.font(AstraFont.captionEmphasis).frame(minHeight: 36)248 }249 .padding(.horizontal, 4)250 }251252 private func toggleDictation() {253 if dictation.isRecording { dictation.stop(); return }254 Task {255 if let problem = await dictation.start(prefix: text) { onError(problem) }256 }257 }258259 private func importPhotos(_ items: [PhotosPickerItem]) async {260 for item in items {261 guard drafts.count < 6 else { onError("A message can carry up to 6 attachments."); return }262 guard let data = try? await item.loadTransferable(type: Data.self) else { onError("That photo could not be loaded."); continue }263 do { drafts.append(try AttachmentImporter.draft(data: data, name: "photo", type: .image)) }264 catch { onError(error.localizedDescription) }265 }266 }267268 private func importFiles(_ urls: [URL]) async {269 for url in urls {270 guard drafts.count < 6 else { onError("A message can carry up to 6 attachments."); return }271 do { drafts.append(try await AttachmentImporter.draft(fromFile: url)) }272 catch { onError(error.localizedDescription) }273 }274 }275276 private func pasteImage() {277 #if canImport(UIKit)278 if let image = UIPasteboard.general.image, let data = image.jpegData(compressionQuality: 0.9),279 let draft = try? AttachmentImporter.draft(data: data, name: "pasted", type: .image) { drafts.append(draft); return }280 #endif281 if let s = Pasteboard.string, !s.isEmpty { text += s } else { onError("There is nothing to paste.") }282 }283}284285/// How full the context window is, as an estimate. A ring, plus a spoken value for VoiceOver.286struct ContextMeter: View {287 let fraction: Double288 var body: some View {289 let tone: Color = fraction > 0.9 ? AstraColor.danger : fraction > 0.7 ? AstraColor.warning : AstraColor.cyan290 HStack(spacing: 5) {291 ZStack {292 Circle().stroke(AstraColor.stroke, lineWidth: 2.5)293 Circle().trim(from: 0, to: max(0.02, min(1, fraction))).stroke(tone, style: StrokeStyle(lineWidth: 2.5, lineCap: .round)).rotationEffect(.degrees(-90))294 }295 .frame(width: 14, height: 14)296 Text("\(Int((fraction * 100).rounded()))%").font(AstraFont.micro.monospacedDigit()).foregroundStyle(AstraColor.textTertiary)297 }298 .accessibilityElement(children: .ignore)299 .accessibilityLabel("Context window")300 .accessibilityValue("About \(Int((fraction * 100).rounded())) percent used, estimated")301 }302}303