SPB Git

Repository Public

ModelIdentity.swift 14.6 KB 259 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Components/ModelIdentity.swift3// Description: Model identity of Visual System V2: bundled maker logos (ModelMark), route badge, ModelChip with Model Morphing, capability glyphs, and the Lumen presence line.4import SwiftUI5import SPChatCore67// MARK: - Logo registry89/// The bundled logo registry (LogoRegistry.json + Assets.xcassets/Logos, generated by Scripts/sync-logos.py from the10/// canonical registry shared with the web and iOS apps). No image is ever fetched at runtime and no logo is drawn:11/// a maker without an entry gets a neutral monogram.12final class LogoRegistry: Sendable {13    static let shared = LogoRegistry()14    struct MakerEntry: Decodable, Sendable { let name: String; let color: Bool }15    private struct File: Decodable { let source: String?; let license: String?; let makers: [String: MakerEntry]; let aliases: [String: String] }16    let makers: [String: MakerEntry]17    let aliases: [String: String]18    let source: String19    let license: String2021    init(bundle: Bundle = .main) {22        if let url = bundle.url(forResource: "LogoRegistry", withExtension: "json"), let data = try? Data(contentsOf: url), let f = try? JSONDecoder().decode(File.self, from: data) {23            makers = f.makers; aliases = f.aliases; source = f.source ?? ""; license = f.license ?? ""24        } else { makers = [:]; aliases = [:]; source = ""; license = "" }25    }2627    /// Registry slug for a logo / creator / vendor value, or nil when no artwork is bundled.28    func slug(_ value: String?) -> String? {29        guard let v = value?.lowercased(), !v.isEmpty else { return nil }30        if makers[v] != nil { return v }31        if let a = aliases[v], makers[a] != nil { return a }32        return nil33    }34    func hasColor(_ slug: String) -> Bool { makers[slug]?.color == true }35    func name(_ slug: String) -> String? { makers[slug]?.name }36}3738/// What the interface shows wherever a model is named: maker logo, exact name, route.39struct ModelIdentity: Equatable {40    var id: String41    var name: String42    var logo: String?43    var creatorName: String44    var route: String45    var isCatalogOnly: Bool46    var isKnown: Bool4748    init(_ m: AIModel, short: Bool = false) {49        id = m.id; name = short ? m.shortName : m.displayName; logo = m.logo ?? LogoRegistry.shared.slug(m.creator); creatorName = m.creatorName; route = m.route; isCatalogOnly = m.isCatalogOnly; isKnown = true50    }51    /// A model id that is not (or no longer) in the catalogue: the id itself is shown, the maker comes from the id.52    init(unknownId id: String) {53        let creator = Maker.slug(forModelId: id)54        self.id = id; name = id.hasPrefix("or:") ? String(id.dropFirst(3)) : (id.hasPrefix("local:") ? String(id.dropFirst(6)) : id); logo = LogoRegistry.shared.slug(creator)55        creatorName = LogoRegistry.shared.slug(creator).flatMap { LogoRegistry.shared.name($0) } ?? Maker.name(creator); route = Maker.route(forModelId: id); isCatalogOnly = false; isKnown = false56    }57    var isOpenRouter: Bool { route == "openrouter" }58    var isLocal: Bool { route == "local" }59    var accessibilityText: String { "\(name), \(creatorName)" + (isOpenRouter ? ", via OpenRouter" : "") + (isLocal ? ", inférence locale MacLustr" : "") + (isCatalogOnly ? ", non testé par le banc" : "") }60}6162// MARK: - ModelMark6364/// Maker logo: bundled template image tinted with the text colour (colour variant only in hero contexts), or a65/// neutral monogram. Sizes 14 / 18 / 24 / 40.66struct ModelMark: View {67    let logo: String?68    let name: String69    var size: CGFloat = 1870    var colored = false71    /// Streaming Presence: the mark of the model that is generating breathes (opacity 0.6 ↔ 1).72    var breathing = false73    @Environment(\.accessibilityReduceMotion) private var reduceMotion74    @State private var dim = false7576    init(logo: String?, name: String, size: CGFloat = 18, colored: Bool = false, breathing: Bool = false) { self.logo = logo; self.name = name; self.size = size; self.colored = colored; self.breathing = breathing }77    init(_ identity: ModelIdentity, size: CGFloat = 18, colored: Bool = false, breathing: Bool = false) { self.init(logo: identity.logo, name: identity.creatorName, size: size, colored: colored, breathing: breathing) }78    init(_ model: AIModel, size: CGFloat = 18, colored: Bool = false, breathing: Bool = false) { self.init(ModelIdentity(model), size: size, colored: colored, breathing: breathing) }7980    var body: some View {81        Group {82            if let slug = LogoRegistry.shared.slug(logo) {83                if colored, LogoRegistry.shared.hasColor(slug) { Image("Logos/\(slug)-color").resizable().renderingMode(.original).interpolation(.high).scaledToFit() }84                else { Image("Logos/\(slug)").resizable().renderingMode(.template).interpolation(.high).scaledToFit().foregroundStyle(DS.C.text) }85            } else {86                RoundedRectangle(cornerRadius: size * 0.26, style: .continuous).fill(DS.C.surface2)87                    .overlay(RoundedRectangle(cornerRadius: size * 0.26, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))88                    .overlay(Text(monogram).font(.system(size: size * 0.52, weight: .semibold, design: .rounded)).foregroundStyle(DS.C.text2))89            }90        }91        .frame(width: size, height: size)92        .opacity(breathing && !reduceMotion && dim ? 0.55 : 1)93        .onChange(of: breathing, initial: true) { _, on in94            if on, !reduceMotion { withAnimation(.easeInOut(duration: 1.1).repeatForever(autoreverses: true)) { dim = true } } else { withAnimation(DS.Motion.fade) { dim = false } }95        }96        .accessibilityHidden(true)97    }98    private var monogram: String { String(name.trimmingCharacters(in: .punctuationCharacters.union(.whitespaces)).prefix(1)).uppercased().ifEmpty("?") }99}100101private extension String { func ifEmpty(_ other: String) -> String { isEmpty ? other : self } }102103/// Route badge: micro uppercase text in a hairline capsule. Shown only when the route is not direct.104struct RouteBadge: View {105    let route: String106    var body: some View {107        if route != "direct" {108            Text(route == "openrouter" ? "OPENROUTER" : route == "local" ? "LOCAL" : route.uppercased())109                .font(.system(size: 9, weight: .semibold)).tracking(0.5).foregroundStyle(DS.C.muted)110                .padding(.horizontal, 5).padding(.vertical, 1.5)111                .overlay(Capsule().strokeBorder(DS.C.border, lineWidth: 1))112                .fixedSize().accessibilityLabel(route == "local" ? "inférence locale MacLustr" : route == "openrouter" ? "via OpenRouter" : "route \(route)")113                .help(route == "local" ? "Requête exécutée par MacLustr AI, ton service d'inférence local (0 $)" : route == "openrouter" ? "Requête exécutée par OpenRouter" : "Route \(route)")114        }115    }116}117118/// « Catalogue OpenRouter · non testé par le banc » — said wherever a catalogue-only model is described.119struct CatalogNotice: View {120    var compact = true121    /// Route of the model: the local route has its own wording (it is not an OpenRouter catalogue entry).122    var route: String = "openrouter"123    var body: some View {124        Text(route == "local" ? (compact ? "non testé par le banc" : "MacLustr AI (local) · non testé par le banc") : (compact ? "catalogue · non testé" : "Catalogue OpenRouter · non testé par le banc"))125            .font(.system(size: 10.5, weight: .medium)).foregroundStyle(DS.C.muted).lineLimit(1)126            .help(route == "local" ? "Modèle servi par MacLustr AI, ton service d'inférence local. Il n'a pas été vérifié par le banc d'essai de SP Chat." : "Modèle listé par le catalogue OpenRouter. Il n'a pas été vérifié par le banc d'essai local de SP Chat.")127    }128}129130// MARK: - ModelChip131132/// `[logo] Exact name [OPENROUTER]`. Changing the identity morphs in place (Model Morphing): the logo cross-scales,133/// the name slides up with a content transition; the frame animates with `spring-smooth`.134struct ModelChip: View {135    let identity: ModelIdentity136    var markSize: CGFloat = 16137    var font: Font = DS.F.ui138    var showRoute = true139    var showCatalogNotice = false140    var breathing = false141    @Environment(\.accessibilityReduceMotion) private var reduceMotion142143    var body: some View {144        HStack(spacing: 6) {145            ModelMark(identity, size: markSize, breathing: breathing)146                .id(identity.logo ?? identity.creatorName)147                .transition(reduceMotion ? .opacity : .scale(scale: 0.6).combined(with: .opacity))148            Text(identity.name).font(font).foregroundStyle(DS.C.text).lineLimit(1)149                .id(identity.id)150                .transition(reduceMotion ? .opacity : .asymmetric(insertion: .offset(y: 6).combined(with: .opacity), removal: .offset(y: -6).combined(with: .opacity)))151            if showRoute { RouteBadge(route: identity.route) }152            if showCatalogNotice, identity.isCatalogOnly { CatalogNotice(route: identity.route) }153        }154        .animation(DS.Motion.resolve(DS.Motion.smooth, reduceMotion: reduceMotion), value: identity)155        .accessibilityElement(children: .ignore).accessibilityLabel("Modèle \(identity.accessibilityText)")156    }157}158159/// Capability glyphs of a model (verified flags or catalogue facts), muted, with a tooltip each.160struct CapabilityGlyphs: View {161    let model: AIModel162    var limit = 5163    private static let order = ["vision", "reasoning", "tools", "audioInput", "imageGeneration", "structuredOutput"]164    var body: some View {165        HStack(spacing: 5) {166            ForEach(Self.order.filter { model.has($0) }.prefix(limit), id: \.self) { c in167                Image(systemName: ModelFacet.capabilitySymbol(c)).help(ModelFacet.capabilityLabel(c)).accessibilityLabel(ModelFacet.capabilityLabel(c))168            }169        }170        .font(.system(size: 10.5)).foregroundStyle(DS.C.muted)171    }172}173174extension AIModel {175    /// Name for plain-text menus, with the route when it is not direct (« Gemini 4 Neon · OpenRouter », « Qwen3 · local »).176    var menuTitle: String { isOpenRouter ? "\(shortName) · OpenRouter" : isLocal ? "\(shortName) · local" : shortName }177    /// « 1,0 M · 3 $ / 15 $ » — context window and list price per million tokens (as published; see `pricingNotes`).178    var factsLine: String {179        var parts: [String] = []180        if let c = contextWindow { parts.append(Format.tokens(c)) }181        if isLocal { parts.append("local · 0 $") } else if hasVariablePrice { parts.append("prix variable") } else if isFree { parts.append("gratuit") } else if let i = inputPrice, let o = outputPrice { parts.append("\(Format.price(i)) / \(Format.price(o)) $ par M") }182        return parts.joined(separator: " · ")183    }184}185186extension Format {187    /// Price per million tokens without trailing zeros (« 0,15 », « 3 », « 12,5 »).188    static func price(_ v: Double) -> String {189        let f = NumberFormatter(); f.locale = Locale(identifier: "fr_CA"); f.minimumFractionDigits = 0; f.maximumFractionDigits = v < 0.1 ? 3 : 2; f.numberStyle = .decimal190        return f.string(from: NSNumber(value: v)) ?? String(v)191    }192}193194// MARK: - Compatibility shims (V1 call sites)195196/// V1 showed a coloured provider dot; V2 shows the maker logo. Kept as a thin wrapper so that every call site renders a logo.197struct ProviderDot: View {198    let provider: String?199    var size: CGFloat = 7200    var body: some View { ModelMark(logo: provider, name: Provider.label(provider), size: max(size * 1.9, 13)) }201}202203/// Model name with its maker logo, resolved from the catalogue by id.204struct ModelBadge: View {205    let name: String206    let provider: String?207    var modelId: String?208    @Environment(AppEnvironment.self) private var env209    init(name: String, provider: String?, modelId: String? = nil) { self.name = name; self.provider = provider; self.modelId = modelId }210    var body: some View {211        if let modelId { ModelChip(identity: env.catalog.identity(for: modelId), markSize: 14, font: DS.F.caption) }212        else {213            HStack(spacing: 5) { ModelMark(logo: provider, name: Provider.label(provider), size: 14); Text(name).font(DS.F.caption).foregroundStyle(DS.C.text).lineLimit(1) }214                .accessibilityElement(children: .combine).accessibilityLabel("Modèle \(name), \(Provider.label(provider))")215        }216    }217}218219// MARK: - Lumen (Streaming Presence)220221/// The presence light: a soft iris glow travelling along a hairline while a model generates (≈ 2.4 s loop). The222/// `TimelineView` only exists while `active` is true, so nothing ticks when idle. Reduce Motion: a static iris hairline.223struct LumenLine: View {224    var active: Bool225    var cornerInset: CGFloat = DS.R.float226    @Environment(\.accessibilityReduceMotion) private var reduceMotion227    @Environment(\.colorScheme) private var scheme228229    var body: some View {230        ZStack {231            if active {232                if reduceMotion { Capsule().fill(DS.C.accent.opacity(0.8)).frame(height: 1.5).padding(.horizontal, cornerInset) }233                else {234                    TimelineView(.animation) { context in235                        let t = context.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 2.4) / 2.4236                        Canvas { ctx, size in237                            let w = size.width - cornerInset * 2238                            guard w > 20 else { return }239                            let span = max(w * 0.34, 90)240                            let x = cornerInset - span + (w + span) * t241                            let rect = CGRect(x: x, y: size.height / 2 - 1, width: span, height: 2)242                            ctx.clip(to: Path(CGRect(x: cornerInset, y: 0, width: w, height: size.height)))243                            let gradient = Gradient(stops: [.init(color: DS.C.accent.opacity(0), location: 0), .init(color: DS.C.accent, location: 0.35), .init(color: DS.C.lumenHi, location: 0.5),244                                                            .init(color: DS.C.accent, location: 0.65), .init(color: DS.C.accent.opacity(0), location: 1)])245                            ctx.addFilter(.blur(radius: 1.2))246                            ctx.opacity = scheme == .dark ? 0.9 : 0.75247                            ctx.fill(Path(roundedRect: rect, cornerRadius: 1), with: .linearGradient(gradient, startPoint: CGPoint(x: rect.minX, y: 0), endPoint: CGPoint(x: rect.maxX, y: 0)))248                        }249                    }250                    .frame(height: 6)251                    .background(Capsule().fill(DS.C.accent.opacity(0.22)).frame(height: 1).padding(.horizontal, cornerInset))252                }253            }254        }255        .frame(height: 6).allowsHitTesting(false).accessibilityHidden(true)256        .transition(.opacity).animation(DS.Motion.fade, value: active)257    }258}259
Files main
Menu

Theme