SPB Git

Repository Public

Components.swift 18.0 KB 448 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Design/Components.swift10// Description      : composants de base — verdict de prix, pastilles, états11//                    vides et d'erreur, en-têtes.12// Module           : LouKa13// Repository       : https://git.spboucher.ai/lou-ka-ios-v314// Project Website  : https://www.lou-ka.com15// Created          : 2026-11-2516// Last Modified    : 2026-11-2817//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import SwiftUI9192// MARK: - Verdict de prix9394struct VerdictPill: View {95    let verdict: Verdict?96    var deviation: Double?97    var large = false98    /// fond opaque : lisible par-dessus une photo99    var onPhoto = false100101    var body: some View {102        if let verdict {103            HStack(spacing: 4) {104                Image(systemName: icon(verdict)).font(.system(size: large ? 12 : 10, weight: .bold))105                Text(verdict.label)106                if let deviation, verdict != .marche {107                    Text(Fmt.pct(deviation)).num().opacity(0.85)108                }109            }110            .font(.system(size: large ? 14 : 11.5, weight: .semibold))111            .lineLimit(1)112            .fixedSize()113            .foregroundStyle(Theme.color(for: verdict))114            .padding(.horizontal, large ? 12 : 9)115            .padding(.vertical, large ? 7 : 5)116            .background {117                // étiquette à coins mesurés ; sur une photo : fond opaque, sans effet de verre118                RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous)119                    .fill(onPhoto ? Theme.surface : Theme.softColor(for: verdict))120            }121            .accessibilityElement(children: .ignore)122            .accessibilityLabel("\(verdict.longLabel)\(deviation.map { ", \(Fmt.pct($0))" } ?? "")")123        }124    }125126    private func icon(_ v: Verdict) -> String {127        switch v {128        case .sous: "arrow.down.right"129        case .marche: "equal"130        case .sur: "arrow.up.right"131        }132    }133}134135/// Jauge : position du loyer dans la fourchette de juste valeur.136struct FairValueGauge: View {137    let price: Double138    let fv: Double139    let low: Double140    let high: Double141    let verdict: Verdict?142    /// le repère du loyer vient se poser à sa place à l'apparition143    @State private var settle: Double = 0144145    var body: some View {146        GeometryReader { geo in147            let span = max(high - low, 1)148            let lo = low - span * 0.45, hi = high + span * 0.45149            let x: (Double) -> CGFloat = { v in geo.size.width * CGFloat(min(1, max(0, (v - lo) / (hi - lo)))) }150            let color = Theme.color(for: verdict)151            ZStack(alignment: .topLeading) {152                Capsule().fill(Theme.surface3).frame(width: geo.size.width, height: 9).offset(y: 26)153                // fourchette de juste valeur : un aplat, sans dégradé154                Capsule()155                    .fill(Theme.ink3.opacity(0.38))156                    .frame(width: max(4, x(high) - x(low)), height: 9)157                    .offset(x: x(low), y: 26)158                RoundedRectangle(cornerRadius: 1).fill(Theme.ink3).frame(width: 2, height: 19).offset(x: x(fv) - 1, y: 21)159                Circle().fill(color).frame(width: 22, height: 22)160                    .overlay(Circle().strokeBorder(Theme.surface, lineWidth: 3))161                    .offset(x: (x(fv) + (x(price) - x(fv)) * settle) - 11, y: 19.5)162                    .opacity(0.25 + 0.75 * settle)163                // étiquettes centrées sur leur repère, maintenues dans la largeur de la jauge164                Text("Ce loyer").font(.caption2.weight(.semibold)).foregroundStyle(color)165                    .fixedSize().position(x: min(max(x(price), 26), geo.size.width - 26), y: 7)166                Text(Fmt.money(low)).font(.caption2).num().foregroundStyle(Theme.ink3)167                    .fixedSize().position(x: min(max(x(low), 22), geo.size.width - 22), y: 52)168                Text(Fmt.money(high)).font(.caption2).num().foregroundStyle(Theme.ink3)169                    .fixedSize().position(x: min(max(x(high), 22), geo.size.width - 22), y: 52)170            }171        }172        .frame(height: 60)173        .drawOnAppear($settle, duration: 0.75, delay: 0.1)174        .accessibilityElement(children: .ignore)175        .accessibilityLabel("Loyer de \(Fmt.money(price)), valeur estimée \(Fmt.money(fv)), fourchette de \(Fmt.money(low)) à \(Fmt.money(high))")176    }177}178179// MARK: - Pastilles et boutons180181/// Pastille à bascule (filtres).182struct Chip: View {183    let label: String184    var icon: String?185    /// Nombre d'annonces concernées (compteur du serveur) ; nil : non affiché.186    var count: Int?187    var active = false188    var tint: Color = Theme.brand189    let action: () -> Void190191    var body: some View {192        Button {193            Haptics.select()194            action()195        } label: {196            HStack(spacing: 6) {197                if let icon { Image(systemName: icon).font(.system(size: 12, weight: .semibold)) }198                Text(label).font(.subheadline.weight(.medium))199                if let count { Text(Fmt.int(count)).font(.caption).monospacedDigit().foregroundStyle(active ? tint : Theme.ink3) }200            }201            .padding(.horizontal, 14)202            .frame(minHeight: 44)203            .foregroundStyle(active ? tint : Theme.ink2)204            .background(active ? tint.opacity(0.12) : Color.clear, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))205            .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(active ? tint : Theme.line2, lineWidth: 1))206            .contentShape(Rectangle())207        }208        .buttonStyle(.plain)209        .accessibilityLabel(count.map { "\(label), \(Fmt.plural($0, "annonce", "annonces"))" } ?? label)210        .accessibilityAddTraits(active ? .isSelected : [])211    }212}213214/// Bouton principal plein.215struct PrimaryButtonStyle: ButtonStyle {216    var tint: Color = Theme.brand217    var foreground: Color = Theme.brandInk218    func makeBody(configuration: Configuration) -> some View {219        configuration.label220            .font(.body.weight(.semibold))221            .foregroundStyle(foreground)222            .padding(.horizontal, 22)223            .frame(minHeight: 50)224            .background(configuration.isPressed ? Theme.brandStrong : tint, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))225            .animation(.easeOut(duration: 0.1), value: configuration.isPressed)226    }227}228229struct SoftButtonStyle: ButtonStyle {230    func makeBody(configuration: Configuration) -> some View {231        configuration.label232            .font(.subheadline.weight(.semibold))233            .foregroundStyle(Theme.ink)234            .padding(.horizontal, 16)235            .frame(minHeight: 44)236            .background(configuration.isPressed ? Theme.surface3 : Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))237            .animation(.easeOut(duration: 0.1), value: configuration.isPressed)238    }239}240241/// Bouton rond opaque (sur photo ou carte).242struct GlassIconButton: View {243    let system: String244    var tint: Color = .primary245    var size: CGFloat = 38246    let label: String247    let action: () -> Void248    var body: some View {249        Button(action: action) {250            Image(systemName: system)251                .font(.system(size: size * 0.42, weight: .semibold))252                .foregroundStyle(tint)253                .frame(width: size, height: size)254                .background(Theme.surface, in: Circle())255                .overlay(Circle().strokeBorder(Theme.line2, lineWidth: 1))256                .shadow(color: .black.opacity(0.12), radius: 5, y: 2)257                .contentShape(Circle().inset(by: -4))258        }259        .buttonStyle(.plain)260        .accessibilityLabel(label)261    }262}263264// MARK: - En-têtes et états265266struct SectionHeader<Trailing: View>: View {267    var eyebrow: String?268    let title: String269    var subtitle: String?270    @ViewBuilder var trailing: () -> Trailing271272    init(eyebrow: String? = nil, title: String, subtitle: String? = nil, @ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() }) {273        self.eyebrow = eyebrow274        self.title = title275        self.subtitle = subtitle276        self.trailing = trailing277    }278279    var body: some View {280        // motif commun : filet haut, titre serif, une phrase, lien à droite. Le sur-titre est réservé281        // aux rares cas où il apporte une information (il n'est plus affiché par défaut).282        VStack(alignment: .leading, spacing: 12) {283            Divider().overlay(Theme.line)284            HStack(alignment: .firstTextBaseline) {285                VStack(alignment: .leading, spacing: 5) {286                    Text(title).font(.editorial(23)).foregroundStyle(Theme.ink)287                        .fixedSize(horizontal: false, vertical: true)288                    if let subtitle {289                        Text(subtitle).font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)290                    }291                }292                Spacer(minLength: 12)293                trailing()294            }295        }296        .accessibilityElement(children: .combine)297        .accessibilityAddTraits(.isHeader)298    }299}300301struct EmptyStateView: View {302    var icon: String = "tray"303    /// illustration de porte à la place de l'icône (fermée : aucun résultat ; entrouverte : invitation ; cœur : favoris vides)304    var door: DoorIllustration.Kind?305    let title: String306    var message: String?307    var actionTitle: String?308    var action: (() -> Void)?309310    var body: some View {311        VStack(spacing: 14) {312            if let door {313                DoorIllustration(kind: door).padding(.bottom, 4)314            } else {315                Image(systemName: icon)316                    .font(.system(size: 24, weight: .medium))317                    .foregroundStyle(Theme.ink2)318                    .frame(width: 60, height: 60)319                    .background(Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))320            }321            Text(title).font(.editorial(21)).foregroundStyle(Theme.ink).multilineTextAlignment(.center)322            if let message {323                Text(message).font(.subheadline).foregroundStyle(Theme.ink3).multilineTextAlignment(.center)324            }325            if let actionTitle, let action {326                Button(actionTitle, action: action).buttonStyle(SoftButtonStyle()).padding(.top, 4)327            }328        }329        .padding(32)330        .frame(maxWidth: 420)331        .frame(maxWidth: .infinity)332    }333}334335/// État d'erreur avec nouvelle tentative ; message adapté au hors-ligne.336struct ErrorStateView: View {337    let error: Error338    var retry: (() -> Void)?339    var body: some View {340        let offline = (error as? APIError)?.isOffline ?? false341        EmptyStateView(icon: offline ? "wifi.slash" : "exclamationmark.triangle",342                       title: offline ? "Vous êtes hors ligne" : "Chargement impossible",343                       message: offline ? "Vos favoris et les dernières fiches consultées restent accessibles."344                                        : ((error as? LocalizedError)?.errorDescription ?? "Réessayez dans un instant."),345                       actionTitle: retry == nil ? nil : "Réessayer", action: retry)346    }347}348349/// Bloc fantôme pendant le chargement.350struct Skeleton: View {351    var height: CGFloat = 16352    var radius: CGFloat = 8353    @State private var phase = false354    @Environment(\.accessibilityReduceMotion) private var reduceMotion355    var body: some View {356        RoundedRectangle(cornerRadius: radius, style: .continuous)357            .fill(Theme.surface2)358            .frame(height: height)359            .opacity(phase ? 0.55 : 1)360            .onAppear {361                guard !reduceMotion else { return }362                withAnimation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true)) { phase = true }363            }364            .accessibilityHidden(true)365    }366}367368/// Chiffre clé : grande valeur, libellé discret.369struct StatTile: View {370    let value: String371    let label: String372    var hint: String?373    var body: some View {374        VStack(alignment: .leading, spacing: 4) {375            Text(value).font(.display(26, weight: .semibold)).tracking(-0.5).num().foregroundStyle(Theme.ink)376                .minimumScaleFactor(0.6).lineLimit(1)377            Text(label).font(.footnote.weight(.medium)).foregroundStyle(Theme.ink2)378            if let hint { Text(hint).font(.caption2).foregroundStyle(Theme.ink3) }379        }380        .frame(maxWidth: .infinity, alignment: .leading)381        .accessibilityElement(children: .combine)382    }383}384385/// Ligne « libellé … valeur ».386struct KeyValueRow: View {387    let label: String388    let value: String389    var valueColor: Color = Theme.ink390    var body: some View {391        HStack(alignment: .firstTextBaseline) {392            Text(label).foregroundStyle(Theme.ink2)393            Spacer(minLength: 12)394            Text(value).fontWeight(.semibold).num().foregroundStyle(valueColor).multilineTextAlignment(.trailing)395        }396        .font(.subheadline)397        .padding(.vertical, 9)398        .accessibilityElement(children: .combine)399    }400}401402/// Étoiles d'une note sur 5.403struct Stars: View {404    let rating: Double405    var size: CGFloat = 12406    var body: some View {407        HStack(spacing: 1.5) {408            ForEach(0..<5, id: \.self) { i in409                let v = rating - Double(i)410                Image(systemName: v >= 0.75 ? "star.fill" : v >= 0.25 ? "star.leadinghalf.filled" : "star")411                    .font(.system(size: size))412            }413        }414        .foregroundStyle(Theme.high)415        .accessibilityElement()416        .accessibilityLabel(String(format: "%.1f sur 5", rating))417    }418}419420/// Disposition en flux (pastilles qui passent à la ligne).421struct FlowLayout: Layout {422    var spacing: CGFloat = 8423424    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {425        let maxW = proposal.width ?? .infinity426        var x: CGFloat = 0, y: CGFloat = 0, rowH: CGFloat = 0, widest: CGFloat = 0427        for s in subviews {428            let size = s.sizeThatFits(.unspecified)429            if x + size.width > maxW, x > 0 { x = 0; y += rowH + spacing; rowH = 0 }430            x += size.width + spacing431            rowH = max(rowH, size.height)432            widest = max(widest, x - spacing)433        }434        return CGSize(width: min(widest, maxW), height: y + rowH)435    }436437    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {438        var x = bounds.minX, y = bounds.minY, rowH: CGFloat = 0439        for s in subviews {440            let size = s.sizeThatFits(.unspecified)441            if x + size.width > bounds.maxX, x > bounds.minX { x = bounds.minX; y += rowH + spacing; rowH = 0 }442            s.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size))443            x += size.width + spacing444            rowH = max(rowH, size.height)445        }446    }447}448
Files main
Menu

Theme