SPB Git

Repository Public

AIPanelView.swift 27.1 KB 551 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : KeyboardUI/AIPanelView.swift10// Description      : The ✦ SP AI panel. Shows exactly what would be11//                    transmitted, lets the user pick one transformation and12//                    send it explicitly, then previews the editable result with13//                    Insert / Replace (when still safe) / Copy / Regenerate.14//                    Explains why it is unavailable instead of failing15//                    silently.16// Module           : KeyboardUI17// Repository       : https://git.spboucher.ai/sp-keyboard18// Created          : 2026-12-0119// Last Modified    : 2026-12-0120//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import UIKit94import AIEngine95import ThemeEngine9697/// Why SP AI cannot run right now; the rest of the keyboard keeps working.98enum AIUnavailability: Equatable {99    case noFullAccess100    case noKey101    case keychainUnavailable(String)102    case noModel103104    var message: String {105        switch self {106        case .noFullAccess:107            "SP AI a besoin du réseau. Activez « Autoriser l'accès complet » pour SP Keyboard dans Réglages → Général → Clavier → Claviers. Le reste du clavier fonctionne sans cet accès."108        case .noKey:109            "Aucune clé Anthropic n'est configurée. Ouvrez l'app SP Keyboard → SP AI pour ajouter votre clé."110        case .keychainUnavailable(let code):111            "Le trousseau partagé est inaccessible (\(code)). La clé n'est jamais lue ailleurs : ouvrez l'app SP Keyboard → Diagnostics."112        case .noModel:113            "Aucun modèle n'est choisi. Ouvrez l'app SP Keyboard → SP AI, testez la connexion puis choisissez un modèle."114        }115    }116}117118struct AIChip: Equatable {119    var title: String120    var action: AIAction121}122123@MainActor124protocol AIPanelDelegate: AnyObject {125    func aiPanelDidClose(_ panel: AIPanelView)126    func aiPanelDidTapPaste(_ panel: AIPanelView)127    func aiPanelDidTapEditSource(_ panel: AIPanelView)128    func aiPanelDidTapPrompt(_ panel: AIPanelView)129    func aiPanel(_ panel: AIPanelView, didSend action: AIAction)130    func aiPanelDidCancel(_ panel: AIPanelView)131    func aiPanelDidTapInsert(_ panel: AIPanelView)132    func aiPanelDidTapReplace(_ panel: AIPanelView)133    func aiPanelDidTapCopy(_ panel: AIPanelView)134    func aiPanelDidTapRegenerate(_ panel: AIPanelView)135    func aiPanelDidTapEditResult(_ panel: AIPanelView)136    func aiPanelDidTapBack(_ panel: AIPanelView)137}138139final class AIPanelView: UIView {140    weak var delegate: AIPanelDelegate?141142    private let star = AIGlyphButton()143    private let titleLabel = UILabel()144    private let modelLabel = UILabel()145    private let closeButton = UIButton(type: .system)146    private let captionLabel = UILabel()147    private let textBox = UITextView()148    private let messageLabel = UILabel()149    private let noticeLabel = UILabel()150    private let spinner = UIActivityIndicatorView(style: .medium)151    private let chipScrollA = UIScrollView()152    private let chipScrollB = UIScrollView()153    private let chipStackA = UIStackView()154    private let chipStackB = UIStackView()155    private var chipButtons: [(button: UIButton, chip: AIChip)] = []156    private let primaryRow = UIStackView()157    private let secondaryRow = UIStackView()158159    private var theme: Theme = BuiltInThemes.default160    private var state: AISessionState = .idle161    private var unavailability: AIUnavailability?162    private var canReplace = false163    private(set) var selectedAction: AIAction = .correct164    private var customPrompt = ""165    private var favorites: [AIFavoritePrompt] = []166    private var defaultTone: AITone = .professional167168    override init(frame: CGRect) {169        super.init(frame: frame)170        star.isUserInteractionEnabled = false171        addSubview(star)172        titleLabel.text = "SP AI"173        titleLabel.font = .systemFont(ofSize: 15, weight: .bold)174        addSubview(titleLabel)175        modelLabel.font = .systemFont(ofSize: 11, weight: .medium)176        modelLabel.textAlignment = .right177        modelLabel.lineBreakMode = .byTruncatingMiddle178        addSubview(modelLabel)179        closeButton.setTitle("ABC", for: .normal)180        closeButton.accessibilityLabel = "Fermer SP AI et revenir aux lettres"181        closeButton.accessibilityIdentifier = "ai.close"182        closeButton.addAction(UIAction { [weak self] _ in self.map { $0.delegate?.aiPanelDidClose($0) } }, for: .touchUpInside)183        addSubview(closeButton)184        captionLabel.font = .systemFont(ofSize: 11, weight: .semibold)185        addSubview(captionLabel)186        textBox.isEditable = false187        textBox.isSelectable = false188        textBox.font = .systemFont(ofSize: 14)189        textBox.backgroundColor = .clear190        textBox.textContainerInset = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 6)191        textBox.layer.cornerRadius = 9192        textBox.layer.borderWidth = 1193        textBox.accessibilityIdentifier = "ai.text"194        addSubview(textBox)195        messageLabel.font = .systemFont(ofSize: 14)196        messageLabel.numberOfLines = 0197        messageLabel.textAlignment = .center198        messageLabel.adjustsFontSizeToFitWidth = true199        messageLabel.minimumScaleFactor = 0.8200        addSubview(messageLabel)201        noticeLabel.font = .systemFont(ofSize: 10.5)202        noticeLabel.numberOfLines = 2203        noticeLabel.textAlignment = .center204        noticeLabel.adjustsFontSizeToFitWidth = true205        noticeLabel.minimumScaleFactor = 0.8206        noticeLabel.text = "Le texte ci-dessus sera transmis à Anthropic à l'envoi. L'usage de l'API peut être facturé à votre clé."207        addSubview(noticeLabel)208        spinner.hidesWhenStopped = true209        addSubview(spinner)210        for (scroll, stack) in [(chipScrollA, chipStackA), (chipScrollB, chipStackB)] {211            scroll.showsHorizontalScrollIndicator = false212            stack.axis = .horizontal213            stack.spacing = 6214            scroll.addSubview(stack)215            addSubview(scroll)216        }217        for row in [primaryRow, secondaryRow] {218            row.axis = .horizontal219            row.spacing = 6220            row.distribution = .fillEqually221            addSubview(row)222        }223        rebuildChips()224    }225226    @available(*, unavailable)227    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }228229    // MARK: Inputs230231    func apply(theme: Theme) {232        self.theme = theme233        star.apply(theme: theme)234        let text = theme.suggestionText235        titleLabel.textColor = text.uiColor236        modelLabel.textColor = text.opacity(0.65).uiColor237        captionLabel.textColor = text.opacity(0.75).uiColor238        textBox.textColor = text.uiColor239        textBox.layer.borderColor = text.opacity(0.3).cgColor240        messageLabel.textColor = text.uiColor241        noticeLabel.textColor = text.opacity(0.7).uiColor242        spinner.color = text.uiColor243        closeButton.restyle(theme: theme)244        refreshChipStyles()245        render()246    }247248    func configure(settings: AISettings) {249        modelLabel.text = settings.selectedModel?.displayName ?? ""250        if favorites != settings.favorites || defaultTone != settings.defaultTone {251            favorites = settings.favorites252            defaultTone = settings.defaultTone253            rebuildChips()254        }255    }256257    func update(state: AISessionState, unavailability: AIUnavailability?, canReplace: Bool) {258        self.state = state259        self.unavailability = unavailability260        self.canReplace = canReplace261        render()262    }263264    /// Text typed in the prompt strip. Selects the custom action unless "reply" is selected (then it guides the reply).265    func setCustomPrompt(_ text: String) {266        customPrompt = text.trimmingCharacters(in: .whitespacesAndNewlines)267        if case .reply = selectedAction {268            selectedAction = .reply(guidance: customPrompt)269        } else if !customPrompt.isEmpty {270            selectedAction = .custom(customPrompt)271        }272        refreshChipStyles()273    }274275    var currentCustomPrompt: String { customPrompt }276277    // MARK: Chips278279    private func rebuildChips() {280        chipButtons.removeAll()281        chipStackA.arrangedSubviews.forEach { $0.removeFromSuperview() }282        chipStackB.arrangedSubviews.forEach { $0.removeFromSuperview() }283        let first: [AIChip] = [284            AIChip(title: "Corriger", action: .correct), AIChip(title: "Reformuler", action: .rephrase),285            AIChip(title: "Raccourcir", action: .shorten), AIChip(title: "Développer", action: .expand),286            AIChip(title: "Répondre", action: .reply(guidance: "")),287            AIChip(title: "→ FR", action: .translate(.french)), AIChip(title: "→ EN", action: .translate(.english)), AIChip(title: "→ ES", action: .translate(.spanish)),288        ]289        let toneNames: [AITone: String] = [.professional: "Professionnel", .friendly: "Amical", .direct: "Direct", .warm: "Chaleureux", .academic: "Universitaire", .humorous: "Humoristique"]290        let tones = [defaultTone] + AITone.allCases.filter { $0 != defaultTone }291        var second: [AIChip] = tones.map { AIChip(title: toneNames[$0] ?? $0.rawValue, action: .tone($0)) }292        second += favorites.map { AIChip(title: "★ " + $0.title, action: .custom($0.prompt)) }293        for (chips, stack) in [(first, chipStackA), (second, chipStackB)] {294            for chip in chips {295                let button = UIButton(type: .system)296                button.setTitle(chip.title, for: .normal)297                button.titleLabel?.font = .systemFont(ofSize: 13.5, weight: .semibold)298                button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 11, bottom: 0, right: 11)299                button.layer.cornerRadius = 15300                button.layer.borderWidth = 1301                button.accessibilityIdentifier = "ai.chip.\(chip.action.identifier)"302                button.addAction(UIAction { [weak self] _ in self?.select(chip) }, for: .touchUpInside)303                stack.addArrangedSubview(button)304                chipButtons.append((button, chip))305            }306        }307        let prompt = UIButton(type: .system)308        prompt.setTitle("Prompt…", for: .normal)309        prompt.setImage(UIImage(systemName: "pencil", withConfiguration: UIImage.SymbolConfiguration(pointSize: 12, weight: .semibold)), for: .normal)310        prompt.titleLabel?.font = .systemFont(ofSize: 13.5, weight: .semibold)311        prompt.contentEdgeInsets = UIEdgeInsets(top: 0, left: 11, bottom: 0, right: 11)312        prompt.layer.cornerRadius = 15313        prompt.layer.borderWidth = 1314        prompt.accessibilityIdentifier = "ai.chip.prompt"315        prompt.addAction(UIAction { [weak self] _ in self.map { $0.delegate?.aiPanelDidTapPrompt($0) } }, for: .touchUpInside)316        chipStackB.insertArrangedSubview(prompt, at: 0)317        chipButtons.append((prompt, AIChip(title: "Prompt…", action: .custom(""))))318        refreshChipStyles()319        setNeedsLayout()320    }321322    private func select(_ chip: AIChip) {323        if case .reply = chip.action {324            selectedAction = .reply(guidance: customPrompt)325        } else {326            selectedAction = chip.action327        }328        refreshChipStyles()329    }330331    private func isSelected(_ chip: AIChip) -> Bool {332        switch (chip.action, selectedAction) {333        case (.reply, .reply): return true334        case (.custom(let a), .custom(let b)): return chip.title == "Prompt…" ? (b == customPrompt && !b.isEmpty && !favorites.contains { $0.prompt == b }) : a == b335        default: return chip.action == selectedAction336        }337    }338339    private func refreshChipStyles() {340        let accent = theme.accentKey341        for (button, chip) in chipButtons {342            let selected = isSelected(chip)343            button.backgroundColor = selected ? accent.fill.average.opacity(1).uiColor : theme.suggestionText.opacity(0.10).uiColor344            let color = selected ? accent.text.uiColor : theme.suggestionText.uiColor345            button.setTitleColor(color, for: .normal)346            button.tintColor = color347            button.layer.borderColor = (selected ? accent.border : theme.suggestionText.opacity(0.28)).cgColor348            button.accessibilityTraits = selected ? [.button, .selected] : .button349        }350    }351352    // MARK: Rendering353354    private func button(_ title: String, symbol: String? = nil, accent: Bool = false, enabled: Bool = true, id: String, action: @escaping (AIPanelView) -> Void) -> UIButton {355        let button = UIButton.pill(title: title, symbol: symbol, theme: theme, accent: accent)356        button.isEnabled = enabled357        button.alpha = enabled ? 1 : 0.45358        button.accessibilityIdentifier = id359        button.addAction(UIAction { [weak self] _ in self.map(action) }, for: .touchUpInside)360        return button361    }362363    /// Compact icon-only button for the header row.364    private func iconButton(_ symbol: String, label: String, id: String, action: @escaping (AIPanelView) -> Void) -> UIButton {365        let button = button("", symbol: symbol, id: id, action: action)366        button.setTitle(nil, for: .normal)367        button.accessibilityLabel = label368        return button369    }370371    private func setRows(primary: [UIButton], secondary: [UIButton] = []) {372        for (row, buttons) in [(primaryRow, primary), (secondaryRow, secondary)] {373            row.arrangedSubviews.forEach { $0.removeFromSuperview() }374            buttons.forEach(row.addArrangedSubview)375            row.isHidden = buttons.isEmpty376        }377    }378379    private enum Mode { case message, source, busy, result }380    private var mode: Mode = .message381382    private func render() {383        spinner.stopAnimating()384        if let unavailability {385            mode = .message386            messageLabel.text = unavailability.message387            setRows(primary: [button("Retour au clavier", id: "ai.back") { $0.delegate?.aiPanelDidClose($0) }])388            applyVisibility()389            return390        }391        switch state {392        case .idle, .applied:393            mode = .message394            messageLabel.text = "Sélectionnez du texte ou écrivez quelque chose, puis rouvrez SP AI. Vous pouvez aussi coller ou saisir un texte ici."395            setRows(primary: [button("Coller", symbol: "doc.on.clipboard", id: "ai.paste") { $0.delegate?.aiPanelDidTapPaste($0) },396                              button("Saisir", symbol: "keyboard", id: "ai.type") { $0.delegate?.aiPanelDidTapEditSource($0) }])397        case .sourcePreview(let source):398            mode = .source399            captionLabel.text = Self.caption(for: source)400            textBox.text = source.text401            setRows(primary: [button("Envoyer à Claude", symbol: "paperplane.fill", accent: true, id: "ai.send") { $0.delegate?.aiPanel($0, didSend: $0.selectedAction) }],402                    secondary: [iconButton("doc.on.clipboard", label: "Coller un autre texte", id: "ai.paste") { $0.delegate?.aiPanelDidTapPaste($0) },403                                iconButton("pencil", label: "Modifier le texte", id: "ai.editsource") { $0.delegate?.aiPanelDidTapEditSource($0) }])404        case .submitting:405            mode = .busy406            messageLabel.text = "Claude traite le texte…\nAnnuler arrête l'attente ici, pas forcément le traitement déjà lancé chez Anthropic."407            spinner.startAnimating()408            setRows(primary: [button("Annuler", symbol: "xmark", id: "ai.cancel") { $0.delegate?.aiPanelDidCancel($0) }])409        case .resultPreview(_, _, let result):410            mode = .result411            captionLabel.text = "RÉSULTAT — VÉRIFIEZ AVANT D'INSÉRER"412            textBox.text = result.text413            setRows(primary: [button("Insérer", symbol: "text.insert", accent: true, id: "ai.insert") { $0.delegate?.aiPanelDidTapInsert($0) },414                              button("Remplacer", symbol: "arrow.triangle.2.circlepath", enabled: canReplace, id: "ai.replace") { $0.delegate?.aiPanelDidTapReplace($0) },415                              button("Copier", symbol: "doc.on.doc", id: "ai.copy") { $0.delegate?.aiPanelDidTapCopy($0) }],416                    secondary: [button("Retour", symbol: "chevron.left", id: "ai.back") { $0.delegate?.aiPanelDidTapBack($0) },417                                button("Modifier", symbol: "pencil", id: "ai.editresult") { $0.delegate?.aiPanelDidTapEditResult($0) },418                                button("Régénérer", symbol: "arrow.clockwise", id: "ai.regenerate") { $0.delegate?.aiPanelDidTapRegenerate($0) }])419        case .cancelled:420            mode = .message421            messageLabel.text = "Requête annulée. Rien n'a été inséré."422            setRows(primary: [button("Retour", symbol: "chevron.left", id: "ai.back") { $0.delegate?.aiPanelDidTapBack($0) }])423        case .offline:424            mode = .message425            messageLabel.text = "Réseau indisponible. Le clavier et les suggestions fonctionnent toujours hors ligne."426            setRows(primary: [button("Retour", symbol: "chevron.left", id: "ai.back") { $0.delegate?.aiPanelDidTapBack($0) },427                              button("Réessayer", symbol: "arrow.clockwise", id: "ai.retry") { $0.delegate?.aiPanelDidTapRegenerate($0) }])428        case .failed(let source, let error):429            mode = .message430            messageLabel.text = Self.describe(error)431            var buttons = [button("Retour", symbol: "chevron.left", id: "ai.back") { panel in432                if source == nil { panel.delegate?.aiPanelDidClose(panel) } else { panel.delegate?.aiPanelDidTapBack(panel) }433            }]434            if Self.canRetry(error), source != nil {435                buttons.append(button("Réessayer", symbol: "arrow.clockwise", id: "ai.retry") { $0.delegate?.aiPanelDidTapRegenerate($0) })436            }437            setRows(primary: buttons)438        }439        applyVisibility()440    }441442    private func applyVisibility() {443        let showsText = mode == .source || mode == .result444        captionLabel.isHidden = !showsText445        textBox.isHidden = !showsText446        messageLabel.isHidden = showsText447        chipScrollA.isHidden = mode != .source448        chipScrollB.isHidden = mode != .source449        noticeLabel.isHidden = mode != .source450        modelLabel.isHidden = mode == .source451        setNeedsLayout()452    }453454    static func caption(for source: AISource) -> String {455        let count = "\(source.text.count) caractères"456        switch source.origin {457        case .selection: return "TEXTE SÉLECTIONNÉ — \(count)"458        case .contextBeforeCursor: return "TEXTE AVANT LE CURSEUR — \(count)"459        case .provided: return "TEXTE FOURNI — \(count)"460        }461    }462463    static func canRetry(_ error: AIError) -> Bool {464        switch error {465        case .rateLimited, .overloaded, .server, .offline, .timeout, .outcomeUnknown, .truncated, .emptyOutput, .malformedResponse: true466        default: false467        }468    }469470    /// Plain-language explanation of a failure. Never includes the key or the user's text.471    static func describe(_ error: AIError) -> String {472        switch error {473        case .missingKey: return AIUnavailability.noKey.message474        case .keychain(let failure): return AIUnavailability.keychainUnavailable(failure.diagnosticCode).message475        case .noModelSelected: return AIUnavailability.noModel.message476        case .emptySource: return "Il n'y a aucun texte à transformer. Sélectionnez, collez ou saisissez un texte."477        case .sourceTooLong(let limit): return "Le texte dépasse \(limit) caractères. Réduisez la sélection."478        case .invalidKey: return "Anthropic a refusé la clé (401). Vérifiez-la dans l'app SP Keyboard → SP AI."479        case .forbidden: return "Cette clé n'a pas l'autorisation requise (403)."480        case .modelUnavailable: return "Ce modèle n'est pas disponible pour cette clé (404). Choisissez-en un autre dans l'app."481        case .badRequest(let message): return "Requête refusée par l'API (400). \(message)"482        case .rateLimited(let seconds):483            return seconds.map { "Limite de débit atteinte (429). Réessayez dans environ \($0) s." } ?? "Limite de débit atteinte (429). Réessayez dans un instant."484        case .overloaded: return "Le service d'Anthropic est surchargé (529). Réessayez dans un instant."485        case .server(let status): return "Erreur du service d'Anthropic (\(status)). Réessayez plus tard."486        case .offline: return "Réseau indisponible."487        case .timeout: return "Délai dépassé sans réponse. La requête a pu être traitée et facturée ; réessayer peut la facturer de nouveau."488        case .outcomeUnknown: return "La connexion a été interrompue avant la réponse. La requête a pu être traitée et facturée ; réessayer peut la facturer de nouveau."489        case .blockedRedirect: return "Redirection inattendue refusée : la requête ne va que vers api.anthropic.com."490        case .malformedResponse: return "Réponse illisible reçue du réseau (portail captif ou proxy ?)."491        case .refused: return "Claude a décliné cette demande."492        case .truncated: return "La réponse dépasse le budget de tokens. Augmentez-le dans l'app ou raccourcissez le texte."493        case .emptyOutput: return "Claude n'a renvoyé aucun texte."494        case .cancelled: return "Requête annulée."495        case .busy: return "Une requête est déjà en cours."496        }497    }498499    // MARK: Layout500501    override func layoutSubviews() {502        super.layoutSubviews()503        let width = bounds.width, pad: CGFloat = 8504        star.frame = CGRect(x: 2, y: 0, width: 36, height: 34)505        titleLabel.frame = CGRect(x: 38, y: 0, width: 60, height: 34)506        closeButton.frame = CGRect(x: width - 62, y: 3, width: 56, height: 28)507        modelLabel.frame = CGRect(x: 100, y: 0, width: closeButton.frame.minX - 108, height: 34)508        let buttonHeight: CGFloat = bounds.height < 220 ? 32 : 36509        var bottom = bounds.height - 6510        if !primaryRow.isHidden {511            primaryRow.frame = CGRect(x: pad, y: bottom - buttonHeight, width: width - pad * 2, height: buttonHeight)512            bottom = primaryRow.frame.minY - 5513        }514        let compact = bounds.height < 200515        var top: CGFloat = 36516        switch mode {517        case .message, .busy:518            secondaryRow.frame = .zero519            spinner.center = CGPoint(x: width / 2, y: top + 12)520            let offset: CGFloat = mode == .busy ? 26 : 0521            messageLabel.frame = CGRect(x: 16, y: top + offset, width: width - 32, height: max(0, bottom - top - offset))522        case .source:523            captionLabel.frame = CGRect(x: pad + 2, y: top, width: width - 2 * pad, height: 14)524            // Paste / edit live in the header, where they get a full-height touch target.525            secondaryRow.frame = CGRect(x: closeButton.frame.minX - 100, y: 3, width: 94, height: 28)526            top += 17527            let chipHeight: CGFloat = 30528            let noticeHeight: CGFloat = compact ? 0 : 26529            noticeLabel.isHidden = compact530            let chipsBlock = chipHeight * 2 + 10531            let boxHeight = max(30, bottom - top - chipsBlock - noticeHeight - 4)532            textBox.frame = CGRect(x: pad, y: top, width: width - pad * 2, height: boxHeight)533            top = textBox.frame.maxY + 4534            chipScrollA.frame = CGRect(x: 0, y: top, width: width, height: chipHeight)535            chipScrollB.frame = CGRect(x: 0, y: top + chipHeight + 5, width: width, height: chipHeight)536            for (scroll, stack) in [(chipScrollA, chipStackA), (chipScrollB, chipStackB)] {537                let size = stack.systemLayoutSizeFitting(CGSize(width: UIView.layoutFittingCompressedSize.width, height: chipHeight))538                stack.frame = CGRect(x: pad, y: 0, width: size.width, height: chipHeight)539                scroll.contentSize = CGSize(width: size.width + pad * 2, height: chipHeight)540            }541            noticeLabel.frame = CGRect(x: pad, y: chipScrollB.frame.maxY + 2, width: width - pad * 2, height: noticeHeight)542        case .result:543            captionLabel.frame = CGRect(x: pad + 2, y: top, width: width - 2 * pad, height: 14)544            top += 17545            secondaryRow.frame = CGRect(x: pad, y: bottom - 30, width: width - pad * 2, height: 30)546            bottom = secondaryRow.frame.minY - 5547            textBox.frame = CGRect(x: pad, y: top, width: width - pad * 2, height: max(30, bottom - top))548        }549    }550}551
Files main
Menu

Theme