Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassAI/AI/GlassPromptBar.swift8// Module : SPGlassAI9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0313//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import SPGlassCore43import SPGlassTokens44import SPGlassThemes45import SPGlassEffects4647/// A file, image or other item the host attached to the prompt. The bar only displays it.48public struct GlassPromptAttachment: Identifiable, Hashable, Sendable {49 public let id: String50 /// Display name (data, shown verbatim).51 public let name: String52 public let systemImage: String5354 public init(id: String, name: String, systemImage: String = "paperclip") {55 self.id = id56 self.name = name57 self.systemImage = systemImage58 }59}6061/// The decisions of ``GlassPromptBar``, separated from the view so that they can be tested.62public enum GlassPromptInput {63 /// What a press of the Return key does.64 public enum ReturnKeyAction: Equatable, Sendable {65 /// Send the prompt.66 case submit67 /// Insert a line break at the insertion point.68 case insertNewline69 /// Consume the key and do nothing (nothing to send, or a response is in progress).70 case ignore71 }7273 /// The text that would be sent: without leading and trailing whitespace and line breaks.74 public static func trimmed(_ text: String) -> String {75 text.trimmingCharacters(in: .whitespacesAndNewlines)76 }7778 /// Sending needs non-blank text and no response in progress.79 public static func canSend(text: String, isResponding: Bool) -> Bool {80 !isResponding && !trimmed(text).isEmpty81 }8283 /// Return sends; Shift-Return and Option-Return insert a line break.84 public static func returnKeyAction(shift: Bool, option: Bool, canSend: Bool) -> ReturnKeyAction {85 if shift || option { return .insertNewline }86 return canSend ? .submit : .ignore87 }8889 /// Inserts a line break in `text`, replacing `range` (the selection) when it is valid and appending otherwise.90 /// - Returns: the new text and the character offset of the insertion point after the line break.91 public static func insertingNewline(in text: String, replacing range: Range<String.Index>?) -> (text: String, cursorOffset: Int) {92 guard let range, range.lowerBound >= text.startIndex, range.upperBound <= text.endIndex else {93 let result = text + "\n"94 return (result, result.count)95 }96 let prefix = text[..<range.lowerBound]97 return (prefix + "\n" + text[range.upperBound...], prefix.count + 1)98 }99100 /// A usable line limit: at least one line, and an upper bound that is not below the lower bound.101 public static func sanitizedLineLimit(_ limit: ClosedRange<Int>) -> ClosedRange<Int> {102 let lower = max(limit.lowerBound, 1)103 return lower...max(limit.upperBound, lower)104 }105}106107/// A glass composer: attachments, a multiline prompt editor, and a row with the attach button, an optional108/// accessory and the send or stop button.109///110/// ```swift111/// GlassPromptBar(text: $draft, isResponding: model.isResponding, attachments: model.attachments) { prompt in112/// model.send(prompt)113/// } onStop: {114/// model.cancel()115/// } onAttach: {116/// isImporterPresented = true // the host opens its own picker117/// } onRemoveAttachment: { attachment in118/// model.remove(attachment)119/// } accessory: {120/// GlassModelPicker(models: models, selection: $modelID) // any small control: a model, a context chip121/// }122/// ```123///124/// The bar never opens a file and never contacts a model: it reports the user's intent through closures.125/// `onSend` receives the trimmed text, after which the bar clears the binding. While `isResponding` is true126/// the send button is replaced by a stop button.127///128/// Keyboard: Return sends; Shift-Return or Option-Return inserts a line break (hardware keyboards, through129/// `onKeyPress`). The software keyboard's Return key submits, as `TextField(axis: .vertical)` does.130public struct GlassPromptBar<Accessory: View>: View {131 @GlassThemed private var theme132 @Binding private var text: String133 private let placeholder: Text134 private let isResponding: Bool135 private let attachments: [GlassPromptAttachment]136 private let lineLimit: ClosedRange<Int>137 private let onSend: @MainActor (String) -> Void138 private let onStop: @MainActor () -> Void139 private let onAttach: (@MainActor () -> Void)?140 private let onRemoveAttachment: (@MainActor (GlassPromptAttachment) -> Void)?141 private let accessory: Accessory142 @State private var selection: TextSelection?143144 /// - Parameters:145 /// - text: the draft.146 /// - placeholder: prompt shown while the draft is empty; "Message" by default.147 /// - isResponding: true while a response is in progress: the stop button replaces the send button.148 /// - attachments: items already attached, shown as chips above the editor.149 /// - lineLimit: smallest and largest number of visible lines before the editor scrolls.150 /// - onSend: receives the trimmed text.151 /// - onStop: called by the stop button (and Escape) while responding.152 /// - onAttach: shows the attachment button; the host presents its own picker.153 /// - onRemoveAttachment: shows a remove button on each chip.154 /// - accessory: small controls placed in the bottom row between the attach and send buttons, such as155 /// a model picker or a context chip.156 public init(157 text: Binding<String>,158 placeholder: LocalizedStringKey? = nil,159 isResponding: Bool = false,160 attachments: [GlassPromptAttachment] = [],161 lineLimit: ClosedRange<Int> = 1...6,162 onSend: @escaping @MainActor (String) -> Void,163 onStop: @escaping @MainActor () -> Void = {},164 onAttach: (@MainActor () -> Void)? = nil,165 onRemoveAttachment: (@MainActor (GlassPromptAttachment) -> Void)? = nil,166 @ViewBuilder accessory: () -> Accessory167 ) {168 _text = text169 self.placeholder = placeholder.map { Text($0) } ?? Text(GlassL10n.string(.message))170 self.isResponding = isResponding171 self.attachments = attachments172 self.lineLimit = GlassPromptInput.sanitizedLineLimit(lineLimit)173 self.onSend = onSend174 self.onStop = onStop175 self.onAttach = onAttach176 self.onRemoveAttachment = onRemoveAttachment177 self.accessory = accessory()178 }179180 private var canSend: Bool {181 GlassPromptInput.canSend(text: text, isResponding: isResponding)182 }183184 public var body: some View {185 VStack(alignment: .leading, spacing: theme.spacing.xxs) {186 if !attachments.isEmpty {187 attachmentChips188 .padding(.top, theme.spacing.xxs)189 }190 editor191 .padding(.horizontal, theme.spacing.xs)192 HStack(spacing: theme.spacing.xs) {193 if let onAttach {194 Button(action: onAttach) {195 Image(systemName: "plus")196 .font(.system(size: 15, weight: .semibold))197 .foregroundStyle(theme.color(.textPrimary))198 .frame(width: 34, height: 34)199 .background(theme.color(.textSecondary).opacity(0.14), in: Circle())200 .glassMinimumHitTarget()201 .contentShape(Rectangle())202 }203 .buttonStyle(.plain)204 .accessibilityLabel(Text(GlassL10n.string(.attach)))205 .help(GlassL10n.string(.attach))206 }207 accessory208 Spacer(minLength: 0)209 primaryButton210 }211 }212 .padding(.horizontal, theme.spacing.xs)213 .padding(.vertical, theme.spacing.xxs)214 .glassSurface(.regular.tinted(.none), in: theme.shape(\.large))215 }216217 /// Send, or stop while a response is in progress: a filled disc, so that the main action is unmistakable.218 @ViewBuilder219 private var primaryButton: some View {220 if isResponding {221 Button(action: onStop) {222 Image(systemName: "stop.fill")223 .font(.system(size: 13, weight: .bold))224 .foregroundStyle(theme.color(.background))225 .frame(width: 34, height: 34)226 .background(theme.color(.textPrimary), in: Circle())227 .glassMinimumHitTarget()228 .contentShape(Rectangle())229 }230 .buttonStyle(.plain)231 .keyboardShortcut(.cancelAction)232 .accessibilityLabel(Text(GlassL10n.string(.stop)))233 .help(GlassL10n.string(.stop))234 } else {235 Button(action: submit) {236 Image(systemName: "arrow.up")237 .font(.system(size: 15, weight: .bold))238 .foregroundStyle(canSend ? theme.onColor(.primary) : theme.color(.textSecondary))239 .frame(width: 34, height: 34)240 .background(canSend ? theme.color(.primary) : theme.color(.textSecondary).opacity(0.18), in: Circle())241 .glassMinimumHitTarget()242 .contentShape(Rectangle())243 }244 .buttonStyle(.plain)245 .disabled(!canSend)246 .accessibilityLabel(Text(GlassL10n.string(.send)))247 .help(GlassL10n.string(.send))248 }249 }250251 private var editor: some View {252 TextField(GlassL10n.string(.message), text: $text, selection: $selection, prompt: placeholder.foregroundStyle(theme.color(.textSecondary)), axis: .vertical)253 .textFieldStyle(.plain)254 .lineLimit(lineLimit)255 .font(theme.font(.body))256 .foregroundStyle(theme.color(.textPrimary))257 .submitLabel(.send)258 .onSubmit(submit)259 .onKeyPress(.return, phases: .down) { press in260 switch GlassPromptInput.returnKeyAction(261 shift: press.modifiers.contains(.shift),262 option: press.modifiers.contains(.option),263 canSend: canSend264 ) {265 case .submit: submit()266 case .insertNewline: insertNewline()267 case .ignore: break268 }269 return .handled270 }271 .padding(.vertical, theme.spacing.xs)272 .frame(minHeight: theme.metrics.minimumHitTarget)273 }274275 private var attachmentChips: some View {276 ScrollView(.horizontal) {277 HStack(spacing: theme.spacing.xs) {278 ForEach(attachments) { attachment in279 HStack(spacing: theme.spacing.xs) {280 Image(systemName: attachment.systemImage)281 .font(.system(size: 13, weight: .semibold))282 .foregroundStyle(theme.color(.primary))283 .frame(width: 28, height: 28)284 .background(theme.color(.primary).opacity(theme.isDark ? 0.26 : 0.13), in: RoundedRectangle(cornerRadius: 8, style: .continuous))285 .accessibilityHidden(true)286 Text(verbatim: attachment.name)287 .font(theme.font(.caption).weight(.medium))288 .foregroundStyle(theme.color(.textPrimary))289 .lineLimit(1)290 if let onRemoveAttachment {291 Button {292 onRemoveAttachment(attachment)293 } label: {294 Label(GlassL10n.string(.removeAttachment, attachment.name), systemImage: "xmark")295 .labelStyle(.iconOnly)296 .font(.system(size: 9, weight: .bold))297 .foregroundStyle(theme.color(.textSecondary))298 .frame(width: 20, height: 20)299 .background(theme.color(.textSecondary).opacity(0.16), in: Circle())300 .contentShape(Rectangle())301 }302 .buttonStyle(.plain)303 }304 }305 .padding(.leading, 5)306 .padding(.trailing, theme.spacing.xs)307 .padding(.vertical, 5)308 .background(theme.color(.surface), in: RoundedRectangle(cornerRadius: 12, style: .continuous))309 .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(theme.color(.separator), lineWidth: 0.5))310 }311 }312 .padding(.horizontal, theme.spacing.xxs)313 }314 .scrollIndicators(.hidden)315 .accessibilityElement(children: .contain)316 .accessibilityLabel(Text(GlassL10n.string(.attachments)))317 }318319 private func submit() {320 guard canSend else { return }321 let prompt = GlassPromptInput.trimmed(text)322 text = ""323 selection = nil324 onSend(prompt)325 }326327 private func insertNewline() {328 var range: Range<String.Index>?329 if let selection, case .selection(let selected) = selection.indices {330 range = selected331 }332 let result = GlassPromptInput.insertingNewline(in: text, replacing: range)333 text = result.text334 let cursor = result.text.index(result.text.startIndex, offsetBy: result.cursorOffset, limitedBy: result.text.endIndex) ?? result.text.endIndex335 selection = TextSelection(insertionPoint: cursor)336 }337}338339extension GlassPromptBar where Accessory == EmptyView {340 /// A composer without accessory.341 public init(342 text: Binding<String>,343 placeholder: LocalizedStringKey? = nil,344 isResponding: Bool = false,345 attachments: [GlassPromptAttachment] = [],346 lineLimit: ClosedRange<Int> = 1...6,347 onSend: @escaping @MainActor (String) -> Void,348 onStop: @escaping @MainActor () -> Void = {},349 onAttach: (@MainActor () -> Void)? = nil,350 onRemoveAttachment: (@MainActor (GlassPromptAttachment) -> Void)? = nil351 ) {352 self.init(353 text: text,354 placeholder: placeholder,355 isResponding: isResponding,356 attachments: attachments,357 lineLimit: lineLimit,358 onSend: onSend,359 onStop: onStop,360 onAttach: onAttach,361 onRemoveAttachment: onRemoveAttachment,362 accessory: { EmptyView() }363 )364 }365}366