// ============================================================================= // SP BOUCHER | SOFTWARE & RESEARCH // ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING // ============================================================================= // // Project : SP GlassKit // File : Sources/SPGlassAI/AI/GlassPromptBar.swift // Module : SPGlassAI // Repository : https://git.spboucher.ai/sp-glasskit // Project Website : https://glass.spboucher.ai // Created : 2026-12-02 // Last Modified : 2026-12-03 // // Author : Simon-Pierre Boucher // Position : Professor of Finance // Institution : Université du Québec en Outaouais (UQO) // Organization : SP Boucher // Website : https://spboucher.ai // Git : https://git.spboucher.ai // // Preferred Contact: contact@spboucher.ai // Development : dev@spboucher.ai // Support : support@spboucher.ai // Security/Admin : admin@spboucher.ai // // Copyright (c) 2026 // Simon-Pierre Boucher // All rights reserved where applicable. This file is governed by the // applicable project license, copyright notices and relevant law. // Existing third-party rights and notices remain unaffected. // // License : MIT // // Do not embed credentials, private keys, access tokens, // certificates or confidential personal information. // // ============================================================================= // END OF SP BOUCHER SOURCE HEADER // ============================================================================= import SwiftUI /// A file, image or other item the host attached to the prompt. The bar only displays it. public struct GlassPromptAttachment: Identifiable, Hashable, Sendable { public let id: String /// Display name (data, shown verbatim). public let name: String public let systemImage: String public init(id: String, name: String, systemImage: String = "paperclip") { self.id = id self.name = name self.systemImage = systemImage } } /// The decisions of ``GlassPromptBar``, separated from the view so that they can be tested. public enum GlassPromptInput { /// What a press of the Return key does. public enum ReturnKeyAction: Equatable, Sendable { /// Send the prompt. case submit /// Insert a line break at the insertion point. case insertNewline /// Consume the key and do nothing (nothing to send, or a response is in progress). case ignore } /// The text that would be sent: without leading and trailing whitespace and line breaks. public static func trimmed(_ text: String) -> String { text.trimmingCharacters(in: .whitespacesAndNewlines) } /// Sending needs non-blank text and no response in progress. public static func canSend(text: String, isResponding: Bool) -> Bool { !isResponding && !trimmed(text).isEmpty } /// Return sends; Shift-Return and Option-Return insert a line break. public static func returnKeyAction(shift: Bool, option: Bool, canSend: Bool) -> ReturnKeyAction { if shift || option { return .insertNewline } return canSend ? .submit : .ignore } /// Inserts a line break in `text`, replacing `range` (the selection) when it is valid and appending otherwise. /// - Returns: the new text and the character offset of the insertion point after the line break. public static func insertingNewline(in text: String, replacing range: Range?) -> (text: String, cursorOffset: Int) { guard let range, range.lowerBound >= text.startIndex, range.upperBound <= text.endIndex else { let result = text + "\n" return (result, result.count) } let prefix = text[..) -> ClosedRange { let lower = max(limit.lowerBound, 1) return lower...max(limit.upperBound, lower) } } /// A glass composer: attachments, a multiline prompt editor, and a row with the attach button, an optional /// accessory and the send or stop button. /// /// ```swift /// GlassPromptBar(text: $draft, isResponding: model.isResponding, attachments: model.attachments) { prompt in /// model.send(prompt) /// } onStop: { /// model.cancel() /// } onAttach: { /// isImporterPresented = true // the host opens its own picker /// } onRemoveAttachment: { attachment in /// model.remove(attachment) /// } accessory: { /// GlassModelPicker(models: models, selection: $modelID) // any small control: a model, a context chip /// } /// ``` /// /// The bar never opens a file and never contacts a model: it reports the user's intent through closures. /// `onSend` receives the trimmed text, after which the bar clears the binding. While `isResponding` is true /// the send button is replaced by a stop button. /// /// Keyboard: Return sends; Shift-Return or Option-Return inserts a line break (hardware keyboards, through /// `onKeyPress`). The software keyboard's Return key submits, as `TextField(axis: .vertical)` does. public struct GlassPromptBar: View { @GlassThemed private var theme @Binding private var text: String private let placeholder: Text private let isResponding: Bool private let attachments: [GlassPromptAttachment] private let lineLimit: ClosedRange private let onSend: @MainActor (String) -> Void private let onStop: @MainActor () -> Void private let onAttach: (@MainActor () -> Void)? private let onRemoveAttachment: (@MainActor (GlassPromptAttachment) -> Void)? private let accessory: Accessory @State private var selection: TextSelection? /// - Parameters: /// - text: the draft. /// - placeholder: prompt shown while the draft is empty; "Message" by default. /// - isResponding: true while a response is in progress: the stop button replaces the send button. /// - attachments: items already attached, shown as chips above the editor. /// - lineLimit: smallest and largest number of visible lines before the editor scrolls. /// - onSend: receives the trimmed text. /// - onStop: called by the stop button (and Escape) while responding. /// - onAttach: shows the attachment button; the host presents its own picker. /// - onRemoveAttachment: shows a remove button on each chip. /// - accessory: small controls placed in the bottom row between the attach and send buttons, such as /// a model picker or a context chip. public init( text: Binding, placeholder: LocalizedStringKey? = nil, isResponding: Bool = false, attachments: [GlassPromptAttachment] = [], lineLimit: ClosedRange = 1...6, onSend: @escaping @MainActor (String) -> Void, onStop: @escaping @MainActor () -> Void = {}, onAttach: (@MainActor () -> Void)? = nil, onRemoveAttachment: (@MainActor (GlassPromptAttachment) -> Void)? = nil, @ViewBuilder accessory: () -> Accessory ) { _text = text self.placeholder = placeholder.map { Text($0) } ?? Text(GlassL10n.string(.message)) self.isResponding = isResponding self.attachments = attachments self.lineLimit = GlassPromptInput.sanitizedLineLimit(lineLimit) self.onSend = onSend self.onStop = onStop self.onAttach = onAttach self.onRemoveAttachment = onRemoveAttachment self.accessory = accessory() } private var canSend: Bool { GlassPromptInput.canSend(text: text, isResponding: isResponding) } public var body: some View { VStack(alignment: .leading, spacing: theme.spacing.xxs) { if !attachments.isEmpty { attachmentChips .padding(.top, theme.spacing.xxs) } editor .padding(.horizontal, theme.spacing.xs) HStack(spacing: theme.spacing.xs) { if let onAttach { Button(action: onAttach) { Image(systemName: "plus") .font(.system(size: 15, weight: .semibold)) .foregroundStyle(theme.color(.textPrimary)) .frame(width: 34, height: 34) .background(theme.color(.textSecondary).opacity(0.14), in: Circle()) .glassMinimumHitTarget() .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityLabel(Text(GlassL10n.string(.attach))) .help(GlassL10n.string(.attach)) } accessory Spacer(minLength: 0) primaryButton } } .padding(.horizontal, theme.spacing.xs) .padding(.vertical, theme.spacing.xxs) .glassSurface(.regular.tinted(.none), in: theme.shape(\.large)) } /// Send, or stop while a response is in progress: a filled disc, so that the main action is unmistakable. @ViewBuilder private var primaryButton: some View { if isResponding { Button(action: onStop) { Image(systemName: "stop.fill") .font(.system(size: 13, weight: .bold)) .foregroundStyle(theme.color(.background)) .frame(width: 34, height: 34) .background(theme.color(.textPrimary), in: Circle()) .glassMinimumHitTarget() .contentShape(Rectangle()) } .buttonStyle(.plain) .keyboardShortcut(.cancelAction) .accessibilityLabel(Text(GlassL10n.string(.stop))) .help(GlassL10n.string(.stop)) } else { Button(action: submit) { Image(systemName: "arrow.up") .font(.system(size: 15, weight: .bold)) .foregroundStyle(canSend ? theme.onColor(.primary) : theme.color(.textSecondary)) .frame(width: 34, height: 34) .background(canSend ? theme.color(.primary) : theme.color(.textSecondary).opacity(0.18), in: Circle()) .glassMinimumHitTarget() .contentShape(Rectangle()) } .buttonStyle(.plain) .disabled(!canSend) .accessibilityLabel(Text(GlassL10n.string(.send))) .help(GlassL10n.string(.send)) } } private var editor: some View { TextField(GlassL10n.string(.message), text: $text, selection: $selection, prompt: placeholder.foregroundStyle(theme.color(.textSecondary)), axis: .vertical) .textFieldStyle(.plain) .lineLimit(lineLimit) .font(theme.font(.body)) .foregroundStyle(theme.color(.textPrimary)) .submitLabel(.send) .onSubmit(submit) .onKeyPress(.return, phases: .down) { press in switch GlassPromptInput.returnKeyAction( shift: press.modifiers.contains(.shift), option: press.modifiers.contains(.option), canSend: canSend ) { case .submit: submit() case .insertNewline: insertNewline() case .ignore: break } return .handled } .padding(.vertical, theme.spacing.xs) .frame(minHeight: theme.metrics.minimumHitTarget) } private var attachmentChips: some View { ScrollView(.horizontal) { HStack(spacing: theme.spacing.xs) { ForEach(attachments) { attachment in HStack(spacing: theme.spacing.xs) { Image(systemName: attachment.systemImage) .font(.system(size: 13, weight: .semibold)) .foregroundStyle(theme.color(.primary)) .frame(width: 28, height: 28) .background(theme.color(.primary).opacity(theme.isDark ? 0.26 : 0.13), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) .accessibilityHidden(true) Text(verbatim: attachment.name) .font(theme.font(.caption).weight(.medium)) .foregroundStyle(theme.color(.textPrimary)) .lineLimit(1) if let onRemoveAttachment { Button { onRemoveAttachment(attachment) } label: { Label(GlassL10n.string(.removeAttachment, attachment.name), systemImage: "xmark") .labelStyle(.iconOnly) .font(.system(size: 9, weight: .bold)) .foregroundStyle(theme.color(.textSecondary)) .frame(width: 20, height: 20) .background(theme.color(.textSecondary).opacity(0.16), in: Circle()) .contentShape(Rectangle()) } .buttonStyle(.plain) } } .padding(.leading, 5) .padding(.trailing, theme.spacing.xs) .padding(.vertical, 5) .background(theme.color(.surface), in: RoundedRectangle(cornerRadius: 12, style: .continuous)) .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(theme.color(.separator), lineWidth: 0.5)) } } .padding(.horizontal, theme.spacing.xxs) } .scrollIndicators(.hidden) .accessibilityElement(children: .contain) .accessibilityLabel(Text(GlassL10n.string(.attachments))) } private func submit() { guard canSend else { return } let prompt = GlassPromptInput.trimmed(text) text = "" selection = nil onSend(prompt) } private func insertNewline() { var range: Range? if let selection, case .selection(let selected) = selection.indices { range = selected } let result = GlassPromptInput.insertingNewline(in: text, replacing: range) text = result.text let cursor = result.text.index(result.text.startIndex, offsetBy: result.cursorOffset, limitedBy: result.text.endIndex) ?? result.text.endIndex selection = TextSelection(insertionPoint: cursor) } } extension GlassPromptBar where Accessory == EmptyView { /// A composer without accessory. public init( text: Binding, placeholder: LocalizedStringKey? = nil, isResponding: Bool = false, attachments: [GlassPromptAttachment] = [], lineLimit: ClosedRange = 1...6, onSend: @escaping @MainActor (String) -> Void, onStop: @escaping @MainActor () -> Void = {}, onAttach: (@MainActor () -> Void)? = nil, onRemoveAttachment: (@MainActor (GlassPromptAttachment) -> Void)? = nil ) { self.init( text: text, placeholder: placeholder, isResponding: isResponding, attachments: attachments, lineLimit: lineLimit, onSend: onSend, onStop: onStop, onAttach: onAttach, onRemoveAttachment: onRemoveAttachment, accessory: { EmptyView() } ) } }