Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassForms/Forms/GlassTextArea.swift8// Module : SPGlassForms9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0213//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/// Character counting and limiting for multiline text. Pure.48public enum GlassTextLimit {49 /// Number of user-perceived characters: an emoji, a flag or a letter with combining marks counts as one.50 public static func count(_ text: String) -> Int {51 text.count52 }5354 /// `text` cut to at most `limit` characters, never in the middle of a composed character.55 /// A `nil` limit returns the text unchanged; a limit below zero is treated as zero.56 public static func clamp(_ text: String, to limit: Int?) -> String {57 guard let limit else { return text }58 let bound = max(limit, 0)59 return text.count > bound ? String(text.prefix(bound)) : text60 }6162 /// Characters still available, or `nil` without a limit.63 public static func remaining(_ text: String, limit: Int?) -> Int? {64 limit.map { max($0, 0) - text.count }65 }6667 /// The visible counter: "12/280" with a limit, "12" without, with digits of the given locale.68 public static func counter(_ text: String, limit: Int?, locale: Locale = .current) -> String {69 let count = text.count.formatted(.number.locale(locale))70 guard let limit else { return count }71 return "\(count)/\(max(limit, 0).formatted(.number.locale(locale)))"72 }7374 /// What VoiceOver reads for the counter: "12 of 280 characters" or "12 characters".75 public static func accessibilityCounter(_ text: String, limit: Int?) -> String {76 if let limit {77 return GlassL10n.string(.charactersOfLimit, text.count, max(limit, 0))78 }79 return GlassL10n.string(.charactersCount, text.count)80 }81}8283/// A multiline editor with a label, a placeholder, an optional character limit and a counter.84///85/// ```swift86/// GlassTextArea("Notes", text: $notes, placeholder: "Anything the team should know", limit: 280)87/// ```88///89/// The limit counts user-perceived characters and never cuts an emoji in two. The placeholder is visible only90/// while the editor is empty and is read by VoiceOver as the value of the empty editor.91public struct GlassTextArea: View {92 @GlassThemed private var theme93 @FocusState private var isFocused: Bool94 @ScaledMetric private var minHeight: CGFloat95 private let label: Text?96 @Binding private var text: String97 private let placeholder: String?98 private let helper: Text?99 private let limit: Int?100 private let showsCounter: Bool101 private let errorMessage: String?102103 /// - Parameters:104 /// - label: label shown above the editor and read by VoiceOver.105 /// - text: the value.106 /// - placeholder: text shown while the editor is empty, already localised.107 /// - helper: explanation shown under the editor when there is no error.108 /// - limit: largest number of characters; further input is dropped.109 /// - showsCounter: shows the character count. `nil` shows it when there is a limit.110 /// - minHeight: smallest height at the default text size; it grows with Dynamic Type.111 /// - errorMessage: error decided by the host.112 public init(113 _ label: LocalizedStringKey,114 text: Binding<String>,115 placeholder: String? = nil,116 helper: LocalizedStringKey? = nil,117 limit: Int? = nil,118 showsCounter: Bool? = nil,119 minHeight: CGFloat = 96,120 errorMessage: String? = nil121 ) {122 self.label = Text(label)123 self._text = text124 self.placeholder = placeholder125 self.helper = helper.map { Text($0) }126 self.limit = limit127 self.showsCounter = showsCounter ?? (limit != nil)128 self._minHeight = ScaledMetric(wrappedValue: minHeight, relativeTo: .body)129 self.errorMessage = errorMessage130 }131132 public var body: some View {133 GlassFieldScaffold(label: label, isRequired: false, helper: helper, error: errorMessage) {134 editor135 } accessory: {136 if showsCounter {137 Text(verbatim: GlassTextLimit.counter(text, limit: limit))138 .font(theme.font(.caption).monospacedDigit())139 .foregroundStyle(theme.color(isAtLimit ? .warning : .textSecondary))140 .accessibilityLabel(Text(verbatim: GlassTextLimit.accessibilityCounter(text, limit: limit)))141 }142 }143 }144145 private var isAtLimit: Bool {146 GlassTextLimit.remaining(text, limit: limit).map { $0 <= 0 } ?? false147 }148149 private var editor: some View {150 TextEditor(text: $text)151 .font(theme.font(.body))152 .foregroundStyle(theme.color(.textPrimary))153 .scrollContentBackground(.hidden)154 .focused($isFocused)155 .frame(minHeight: minHeight)156 .accessibilityLabel(label ?? Text(verbatim: ""))157 .accessibilityValue(text.isEmpty ? Text(verbatim: placeholder ?? "") : Text(verbatim: text))158 .overlay(alignment: .topLeading) {159 if text.isEmpty, let placeholder {160 Text(verbatim: placeholder)161 .font(theme.font(.body))162 .foregroundStyle(theme.color(.textSecondary))163 .padding(GlassTextAreaMetrics.placeholderInsets)164 .allowsHitTesting(false)165 .accessibilityHidden(true)166 }167 }168 .padding(.horizontal, theme.spacing.xs)169 .padding(.vertical, theme.spacing.xxs)170 .background(theme.color(.surface), in: theme.glassFieldShape)171 .glassFieldRing(isFocused: isFocused, status: errorMessage != nil ? .error : .normal, in: theme.glassFieldShape)172 .onChange(of: text) { _, newValue in173 let clamped = GlassTextLimit.clamp(newValue, to: limit)174 if clamped != newValue { text = clamped }175 }176 }177}178179/// Insets that line the placeholder up with the first line of the system text editor.180enum GlassTextAreaMetrics {181 static var placeholderInsets: EdgeInsets {182 #if os(macOS)183 EdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5)184 #else185 EdgeInsets(top: 8, leading: 5, bottom: 8, trailing: 5)186 #endif187 }188}189