SPB Git

Repository Public

ChatScreen.swift 29.3 KB 488 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Chat/ChatScreen.swift3// Description: Conversation screen: lazily rendered transcript with smart scrolling, banners, composer, toolbar (model, export, inspector), artefact and Quick Look sheets.4import SwiftUI5import QuickLook6import UniformTypeIdentifiers7import SPChatCore89struct ChatScreen: View {10    let chat: ChatViewModel11    @Bindable var window: WindowModel12    @Environment(AppEnvironment.self) private var env13    @State private var speech = SpeechPlayer()14    @State private var artifactId: String?15    @State private var previewURL: URL?16    @State private var regenerateTarget: Message?17    @State private var forkTarget: Message?18    @State private var forkLabel = ""19    @State private var windowDropTargeted = false2021    var body: some View {22        @Bindable var prefs = env.preferences23        ZStack(alignment: .bottom) {24            VStack(spacing: 0) {25                banners26                if chat.isLoading && chat.isEmpty { ProgressView("Chargement…").frame(maxWidth: .infinity, maxHeight: .infinity) }27                else if let failed = chat.loadFailed, chat.isEmpty { EmptyStateView(systemImage: "exclamationmark.bubble", title: "Conversation indisponible", message: failed).frame(maxHeight: .infinity) }28                else if chat.isEmpty { WelcomeView(chat: chat).frame(maxWidth: .infinity, maxHeight: .infinity).padding(.bottom, 120) }29                else { TranscriptView(chat: chat, actions: actions, bottomInset: composerHeight + 20) }30            }31            // the composer floats above the transcript, docked at the bottom centre32            ComposerView(chat: chat, focusToken: window.composerFocus, pickerToken: window.modelPickerToken, onOpenExplorer: { id in window.explorerModelId = id; window.destination = .library(.models) })33                .padding(.horizontal, 20).padding(.bottom, 14)34                .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { composerHeight = $0 }35        }36        .environment(\.transcriptFontSize, 14 * prefs.textScale)37        .background(DS.C.bg)38        .overlay { if windowDropTargeted { RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(DS.C.accent, lineWidth: 2).padding(6).allowsHitTesting(false).transition(.opacity) } }39        .onDrop(of: [.fileURL, .plainText], isTargeted: $windowDropTargeted) { providers in ComposerDrop.handle(providers, chat: chat) }40        .animation(DS.Motion.fade, value: windowDropTargeted)41        .navigationTitle(chat.title)42        .navigationSubtitle(subtitle)43        .toolbar { toolbar }44        .inspector(isPresented: $prefs.inspectorVisible) { ContextPanel(chat: chat, window: window) }45        .sheet(item: Binding(get: { artifactId.map(IdentifiedString.init) }, set: { artifactId = $0?.value })) { ArtifactSheet(artifactId: $0.value) }46        .sheet(item: $regenerateTarget) { m in47            VStack(spacing: 0) {48                ModelPickerView(selection: m.modelId, title: "Régénérer la réponse avec…") { model in regenerateTarget = nil; chat.regenerate(m, modelId: model.id) }49                Rectangle().fill(DS.C.border).frame(height: 1)50                HStack { Spacer(); Button("Annuler") { regenerateTarget = nil }.keyboardShortcut(.cancelAction) }.padding(10)51            }52            .background(DS.C.bgElev)53        }54        .alert("Nouvelle branche", isPresented: Binding(get: { forkTarget != nil }, set: { if !$0 { forkTarget = nil } })) {55            TextField("Nom de la branche (facultatif)", text: $forkLabel)56            Button("Créer") { if let m = forkTarget { let label = forkLabel; Task { if let id = await chat.fork(at: m, label: label) { window.open(id); env.toasts.show("Branche créée") } } } }57            Button("Annuler", role: .cancel) {}58        } message: { Text("La conversation est copiée jusqu'à ce message dans une nouvelle conversation reliée à celle-ci.") }59        .quickLookPreview($previewURL)60        .focusedSceneValue(\.activeChat, chat)61        .task(id: ObjectIdentifier(chat)) {62            chat.onConversationCreated = { [weak window] id in if window?.currentConversationId == nil { window?.destination = .chat(id) } }63            await chat.loadIfNeeded()64        }65        .onChange(of: env.navigationRequest) { _, req in if let req, req.conversationId == chat.conversationId, let m = req.messageId { chat.scrollTarget = m } }66        .onAppear { if let req = env.navigationRequest, req.conversationId == chat.conversationId, let m = req.messageId { chat.scrollTarget = m } }67        .onDisappear { speech.stop() }68        .onChange(of: env.catalog.loaded) { chat.ensureModel() }69        .onChange(of: env.catalog.models.models.count) { chat.ensureModel() }70        .onReceive(NotificationCenter.default.publisher(for: .spchatExport)) { note in71            guard NSApp.keyWindow?.isMainWindow == true || NSApp.windows.filter(\.isVisible).count == 1 else { return }72            switch note.object as? String { case "markdown": export(.markdown); case "pdf": export(.pdf); case "json": export(.json(tree: false)); default: break }73        }74    }7576    @State private var composerHeight: CGFloat = 967778    private var subtitle: String {79        guard !chat.isEmpty else { return "" }80        let cost = chat.totalCost81        return "\(chat.displayed.count) messages" + (cost > 0 ? " · \(Format.usd(cost))" : "")82    }8384    private var actions: MessageActions {85        MessageActions(86            regenerate: { m, model in chat.regenerate(m, modelId: model) },87            edit: { m, text in chat.edit(m, text: text) },88            showVersion: { m in Task { await chat.showVersion(m) } },89            fork: { m in forkLabel = ""; forkTarget = m },90            decideTools: { m, approve, deny in chat.decideToolCalls(on: m, approve: approve, deny: deny) },91            speak: { m in speech.toggle(m, env: env) },92            openArtifact: { artifactId = $0 },93            openAttachment: { id, name in Task { do { previewURL = try await env.files.exportedFile(attachmentId: id, filename: name) } catch { env.toasts.error(error) } } },94            lens: { m in window.openLens(messageId: m.id, preferences: env.preferences) },95            followUp: { text in chat.sendFollowUp(text) },96            regenerateWithPicker: { m in regenerateTarget = m })97    }9899    @ViewBuilder private var banners: some View {100        VStack(spacing: 6) {101            if chat.isFromCache { Banner(kind: .info, text: "Hors ligne : cette conversation est affichée depuis le cache local.", actionTitle: "Réessayer") { Task { await chat.reload(attach: true) } } }102            if let w = chat.warning { Banner(kind: .warning, text: w, onDismiss: { chat.warning = nil }) }103            if let e = chat.errorBanner { Banner(kind: .error, text: e, onDismiss: { chat.errorBanner = nil }).accessibilityIdentifier("chat-error") }104        }105        .padding(.horizontal, 20).padding(.top, chat.isFromCache || chat.warning != nil || chat.errorBanner != nil ? 10 : 0)106        .frame(maxWidth: Metrics.transcriptMaxWidth + 40)107    }108109    @ToolbarContentBuilder private var toolbar: some ToolbarContent {110        ToolbarItemGroup(placement: .primaryAction) {111            Menu {112                Button("Markdown…") { export(.markdown) }113                Button("PDF…") { export(.pdf) }114                Button("JSON…") { export(.json(tree: false)) }115                Button("JSON avec toutes les versions…") { export(.json(tree: true)) }116                Divider()117                Button("Copier toute la conversation") { if let d = chat.detail { Pasteboard.copy(ConversationExporter.markdown(d)); env.toasts.show("Conversation copiée") } }118            } label: { Label("Exporter", systemImage: "square.and.arrow.up") }119                .disabled(chat.detail == nil).help("Exporter la conversation").accessibilityIdentifier("export-menu")120            Menu {121                ForEach(PanelTab.allCases) { tab in122                    Button { toggle(tab) } label: { Label(tab.title, systemImage: tab.systemImage) }123                }124            } label: { Label("Panneau", systemImage: env.preferences.inspectorVisible ? window.panelTab.systemImage : "sidebar.trailing") } primaryAction: { env.preferences.inspectorVisible.toggle() }125                .help("Panneau contextuel : contexte, chronologie, Lens, branches (⌥⌘I)").accessibilityIdentifier("panel-menu")126        }127    }128129    private func toggle(_ tab: PanelTab) {130        if env.preferences.inspectorVisible, window.panelTab == tab { env.preferences.inspectorVisible = false } else { window.showPanel(tab, preferences: env.preferences) }131    }132133    enum ExportFormat { case markdown, pdf, json(tree: Bool) }134135    func export(_ format: ExportFormat) {136        guard let detail = chat.detail else { return }137        let base = ConversationExporter.fileName(title: detail.conversation.title)138        switch format {139        case .markdown: SavePanel.save(Data(ConversationExporter.markdown(detail).utf8), name: base + ".md", type: UTType(filenameExtension: "md") ?? .plainText, env: env)140        case .json(let tree): SavePanel.save(ConversationExporter.json(detail, includeInactiveBranches: tree), name: base + ".json", type: .json, env: env)141        case .pdf:142            let doc = RichText.document(for: detail) { env.catalog.displayName(forModel: $0) }143            SavePanel.save(RichText.pdf(doc), name: base + ".pdf", type: .pdf, env: env)144        }145    }146}147148struct IdentifiedString: Identifiable { let value: String; var id: String { value } }149150enum SavePanel {151    /// Native save panel; the sandbox grants access to the chosen location only.152    static func save(_ data: Data, name: String, type: UTType, env: AppEnvironment) {153        let panel = NSSavePanel()154        panel.nameFieldStringValue = name; panel.allowedContentTypes = [type]; panel.canCreateDirectories = true155        let write: (NSApplication.ModalResponse) -> Void = { response in156            guard response == .OK, let url = panel.url else { return }157            do { try data.write(to: url, options: .atomic); env.toasts.show("Enregistré : \(url.lastPathComponent)") } catch { env.toasts.show("Enregistrement impossible : \(error.localizedDescription)", isError: true) }158        }159        if let w = NSApp.keyWindow { panel.beginSheetModal(for: w, completionHandler: write) } else { write(panel.runModal()) }160    }161}162163// MARK: - Transcript164165struct TranscriptView: View {166    let chat: ChatViewModel167    let actions: MessageActions168    /// Room left under the last message for the floating composer.169    var bottomInset: CGFloat = 16170    @Environment(AppEnvironment.self) private var env171    @Environment(\.accessibilityReduceMotion) private var reduceMotion172    @State private var position = ScrollPosition(edge: .bottom)173    @State private var atBottom = true174    @State private var highlighted: String?175176    var body: some View {177        let lastId = chat.live == nil ? chat.messages.last?.id : nil178        ScrollView {179            // lazy stack: rows far from the viewport are not built, long conversations stay light180            LazyVStack(alignment: .leading, spacing: 22) {181                ForEach(chat.messages) { m in182                    MessageRow(message: m, versions: chat.versions(of: m), isBusy: chat.isStreaming, showReasoning: env.preferences.showReasoning, highlighted: highlighted == m.id, isLast: m.id == lastId, actions: actions)183                        .equatable().id(m.id)184                        .transition(reduceMotion ? .opacity : .opacity.combined(with: .offset(y: 8)))185                }186                if let live = chat.live {187                    MessageRow(message: live, versions: [live], isBusy: true, showReasoning: env.preferences.showReasoning, highlighted: false, actions: actions).equatable().id("live")188                        .transition(reduceMotion ? .opacity : .opacity.combined(with: .offset(y: 8)))189                } else if chat.phase == .sending || chat.phase == .reconnecting {190                    HStack(spacing: 8) {191                        ModelMark(chat.modelIdentity, size: 16, breathing: true)192                        Text(chat.phase == .reconnecting ? "Reconnexion au serveur…" : "Envoi…").font(DS.F.caption).foregroundStyle(DS.C.muted)193                    }194                    .id("pending").transition(.opacity)195                }196                Color.clear.frame(height: 4).id("bottom")197            }198            .scrollTargetLayout()199            .frame(maxWidth: Metrics.transcriptMaxWidth, alignment: .leading)200            .padding(.horizontal, 24).padding(.top, 18).padding(.bottom, bottomInset)201            .frame(maxWidth: .infinity)202            // Conversation Flow: a new message rises 8 pt and fades in; streaming itself never animates layout203            .animation(DS.Motion.resolve(DS.Motion.snappy, reduceMotion: reduceMotion), value: chat.messages.count)204        }205        .scrollPosition($position)206        .defaultScrollAnchor(.bottom)207        .onScrollGeometryChange(for: Bool.self) { g in g.contentOffset.y + g.containerSize.height >= g.contentSize.height - 80 } action: { _, now in atBottom = now }208        // follow the answer only while the reader is at the bottom: scrolling up to read is never interrupted209        .onChange(of: chat.live) { if atBottom { position.scrollTo(edge: .bottom) } }210        .onChange(of: chat.messages.count) { _, _ in if atBottom || chat.messages.last?.role == .user { position.scrollTo(edge: .bottom) } }211        .onChange(of: chat.scrollTarget) { _, target in jump(to: target) }212        .onAppear {213            if let t = chat.scrollTarget { jump(to: t) } else if let saved = chat.savedScrollId, chat.messages.contains(where: { $0.id == saved }) { position.scrollTo(id: saved, anchor: .top) }214        }215        .onDisappear { chat.savedScrollId = atBottom ? nil : position.viewID(type: String.self) }216        .overlay(alignment: .bottom) {217            if !atBottom {218                Button { withAnimation(DS.Motion.resolve(DS.Motion.snappy, reduceMotion: reduceMotion)) { position.scrollTo(edge: .bottom) } } label: {219                    Label(chat.isStreaming ? "Suivre la réponse" : "Aller au dernier message", systemImage: "arrow.down").font(DS.F.caption).foregroundStyle(DS.C.text2).padding(.horizontal, 11).padding(.vertical, 6)220                }221                .buttonStyle(.plain).floatSurface(radius: 14)222                .padding(.bottom, bottomInset + 4).transition(.opacity.combined(with: .offset(y: 6))).accessibilityIdentifier("jump-to-bottom")223            }224        }225        .animation(DS.Motion.fade, value: atBottom)226        .accessibilityIdentifier("transcript")227    }228229    private func jump(to target: String?) {230        guard let target, chat.messages.contains(where: { $0.id == target }) else { return }231        if reduceMotion { position.scrollTo(id: target, anchor: .center) } else { withAnimation(DS.Motion.snappy) { position.scrollTo(id: target, anchor: .center) } }232        highlighted = target; chat.scrollTarget = nil233        Task { try? await Task.sleep(for: .seconds(2.2)); if highlighted == target { withAnimation(DS.Motion.fade) { highlighted = nil } } }234    }235}236237// MARK: - Welcome (empty conversation)238239struct WelcomeView: View {240    let chat: ChatViewModel241    @Environment(AppEnvironment.self) private var env242    private let ideas: [(String, String, String)] = [243        ("lightbulb", "Expliquer", "Explique-moi simplement "), ("doc.text", "Résumer", "Résume ce document en cinq points : "),244        ("chevron.left.forwardslash.chevron.right", "Coder", "Écris une fonction qui "), ("function", "Calculer", "Démontre pas à pas que "),245    ]246    var body: some View {247        VStack(spacing: 16) {248            BrandMark(size: 52)249            Text("Que veux-tu explorer ?").font(DS.F.display).tracking(-0.5).foregroundStyle(DS.C.text)250            modelLine251            HStack(spacing: 8) {252                ForEach(ideas, id: \.1) { icon, title, text in253                    Button { chat.draft = text } label: { Label(title, systemImage: icon) }.buttonStyle(ChipStyle(prominent: true))254                }255            }256            .padding(.top, 4)257            if !env.catalog.presets.isEmpty {258                HStack(spacing: 6) {259                    Text("Profil").font(DS.F.caption).foregroundStyle(DS.C.muted)260                    ForEach(env.catalog.presets.prefix(5)) { p in261                        Button(p.name) { chat.settings.presetId = chat.settings.presetId == p.id ? nil : p.id }262                            .buttonStyle(ChipStyle(selected: chat.settings.presetId == p.id)).help(p.description ?? p.name)263                    }264                }265            }266        }267        .padding(30).accessibilityIdentifier("welcome")268    }269    @ViewBuilder private var modelLine: some View {270        if let p = env.catalog.preset(chat.settings.presetId) { Text("Profil « \(p.name) »").font(DS.F.uiRegular).foregroundStyle(DS.C.text2) }271        else if chat.settings.routingMode != .manual { Text("Routage \(chat.settings.routingMode.label.lowercased()) parmi les modèles vérifiés").font(DS.F.uiRegular).foregroundStyle(DS.C.text2) }272        else if let m = chat.currentModel {273            HStack(spacing: 8) { ModelChip(identity: ModelIdentity(m), markSize: 16, font: DS.F.uiRegular, showCatalogNotice: true); Text("· " + m.creatorName).font(DS.F.uiRegular).foregroundStyle(DS.C.muted) }274        } else { Text("Choisis un modèle dans le compositeur").font(DS.F.uiRegular).foregroundStyle(DS.C.text2) }275    }276}277278/// The SP Chat mark, drawn natively (same geometry as the app icon).279struct BrandMark: View {280    var size: CGFloat = 48281    var body: some View {282        ZStack {283            RoundedRectangle(cornerRadius: size * 0.225, style: .continuous).fill(LinearGradient(colors: [Palette.iris, Palette.irisDeep], startPoint: .topLeading, endPoint: .bottomTrailing))284            BubbleGlyph().fill(.white).padding(size * 0.2)285        }286        .frame(width: size, height: size).shadow(color: Palette.irisDeep.opacity(0.35), radius: size * 0.15, y: size * 0.06)287        .accessibilityHidden(true)288    }289}290291/// Speech bubble with a spark: the brand glyph.292nonisolated struct BubbleGlyph: Shape {293    func path(in r: CGRect) -> Path {294        var p = Path()295        let body = CGRect(x: r.minX, y: r.minY, width: r.width, height: r.height * 0.8)296        p.addRoundedRect(in: body, cornerSize: CGSize(width: r.width * 0.26, height: r.width * 0.26), style: .continuous)297        p.move(to: CGPoint(x: r.minX + r.width * 0.2, y: body.maxY - 1))298        p.addLine(to: CGPoint(x: r.minX + r.width * 0.16, y: r.maxY))299        p.addLine(to: CGPoint(x: r.minX + r.width * 0.46, y: body.maxY - 1))300        p.closeSubpath()301        // four-point spark, cut out of the bubble302        let c = CGPoint(x: body.midX, y: body.midY); let R = r.width * 0.26, q = r.width * 0.07303        var s = Path()304        s.move(to: CGPoint(x: c.x, y: c.y - R)); s.addQuadCurve(to: CGPoint(x: c.x + R, y: c.y), control: CGPoint(x: c.x + q, y: c.y - q))305        s.addQuadCurve(to: CGPoint(x: c.x, y: c.y + R), control: CGPoint(x: c.x + q, y: c.y + q)); s.addQuadCurve(to: CGPoint(x: c.x - R, y: c.y), control: CGPoint(x: c.x - q, y: c.y + q))306        s.addQuadCurve(to: CGPoint(x: c.x, y: c.y - R), control: CGPoint(x: c.x - q, y: c.y - q)); s.closeSubpath()307        return p.subtracting(s)308    }309}310311// MARK: - Artefacts312313/// Source of an artefact with native preview where one exists (SVG). HTML / React / Mermaid are shown as highlighted314/// source and can be opened in the default browser: the app embeds no web engine.315struct ArtifactSheet: View {316    let artifactId: String317    @Environment(AppEnvironment.self) private var env318    @Environment(\.dismiss) private var dismiss319    @State private var artifact: Artifact?320    @State private var error: String?321322    var body: some View {323        VStack(spacing: 0) {324            HStack {325                VStack(alignment: .leading) { Text(artifact?.title ?? "Artefact").font(.headline); Text([artifact?.type, artifact.map { "version \($0.version)" }].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(.secondary) }326                Spacer()327                if let a = artifact, let content = a.content {328                    Button("Copier") { Pasteboard.copy(content); env.toasts.show("Artefact copié") }329                    Button("Enregistrer…") { SavePanel.save(Data(content.utf8), name: "\(a.title).\(Self.ext(a))", type: UTType(filenameExtension: Self.ext(a)) ?? .plainText, env: env) }330                    if ["html", "svg", "react", "mermaid"].contains(a.type) { Button("Ouvrir dans le navigateur") { openInBrowser(a, content) }.help(a.type == "html" || a.type == "svg" ? "Ouvre le fichier dans le navigateur par défaut" : "Enregistre la source et l'ouvre avec l'application par défaut") }331                }332                Button("Fermer") { dismiss() }.keyboardShortcut(.cancelAction)333            }334            .padding(14)335            Divider()336            if let a = artifact, let content = a.content {337                ScrollView {338                    VStack(alignment: .leading, spacing: 14) {339                        ArtifactPreview(artifact: a, content: content)340                        CodeBlockView(language: a.language ?? a.type, code: content)341                    }342                    .padding(16)343                }344            } else if let error { EmptyStateView(systemImage: "exclamationmark.triangle", title: "Artefact indisponible", message: error) }345            else { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }346        }347        .frame(minWidth: 620, idealWidth: 760, minHeight: 440, idealHeight: 600)348        .task { do { artifact = try await env.api.artifact(artifactId) } catch { self.error = (error as? LocalizedError)?.errorDescription ?? "Chargement impossible" } }349    }350351    static func ext(_ a: Artifact) -> String { ["html": "html", "svg": "svg", "mermaid": "mmd", "react": a.language == "jsx" ? "jsx" : "tsx", "python": "py", "typescript": "ts", "markdown": "md"][a.type] ?? "txt" }352353    private func openInBrowser(_ a: Artifact, _ content: String) {354        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("SPChat-artefacts", isDirectory: true)355        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)356        let url = dir.appendingPathComponent("\(a.id).\(Self.ext(a))")357        do { try Data(content.utf8).write(to: url, options: .atomic); NSWorkspace.shared.open(url) } catch { env.toasts.error(error) }358    }359}360361/// Native preview of an artefact where one exists: Markdown, LaTeX, tables (CSV / TSV), JSON (outline), SVG.362/// HTML, React and Mermaid keep the documented policy — highlighted source + « Ouvrir dans le navigateur » — because363/// the app embeds no web engine.364struct ArtifactPreview: View {365    let artifact: Artifact366    let content: String367    private var kind: String { (artifact.language ?? artifact.type).lowercased() }368369    var body: some View {370        switch true {371        case artifact.type == "svg":372            if let img = NSImage(data: Data(content.utf8)) { Image(nsImage: img).resizable().aspectRatio(contentMode: .fit).frame(maxHeight: 320).frame(maxWidth: .infinity).card() }373        case artifact.type == "markdown" || kind == "md" || kind == "markdown": MarkdownView(text: content).card()374        case kind == "json" || artifact.type == "json":375            if let value = JSONValue.parse(Data(content.utf8)) {376                VStack(alignment: .leading, spacing: 6) { SectionCaption(text: "Structure"); JSONOutlineView(value: value) }.card()377            }378        case kind == "csv" || kind == "tsv":379            if let table = DelimitedTable(content, separator: kind == "tsv" ? "\t" : ",") { DelimitedTableView(table: table).card() }380        case kind == "latex" || kind == "tex" || artifact.type == "latex" || artifact.type == "math":381            MarkdownView(text: content.contains("$") || content.contains("\\[") || content.contains("\\begin{document}") ? content : "$$\n\(content)\n$$").card()382        case ["html", "react", "mermaid"].contains(artifact.type):383            Label("Aperçu vivant non disponible dans l'app : SP Chat n'embarque aucun moteur web. La source est ci-dessous ; « Ouvrir dans le navigateur » l'affiche hors de l'app.", systemImage: "info.circle")384                .font(DS.F.caption).foregroundStyle(DS.C.text2).fixedSize(horizontal: false, vertical: true)385        default: EmptyView()386        }387    }388}389390/// Collapsible outline of a JSON document (objects and arrays expand; scalars are typed and selectable).391struct JSONOutlineView: View {392    let value: JSONValue393    var key: String?394    var depth = 0395    @State private var expanded: Bool396397    init(value: JSONValue, key: String? = nil, depth: Int = 0) { self.value = value; self.key = key; self.depth = depth; _expanded = State(initialValue: depth < 2) }398399    private var children: [(String, JSONValue)]? {400        switch value {401        case .object(let o): o.sorted { $0.key < $1.key }.map { ($0.key, $0.value) }402        case .array(let a): a.enumerated().map { ("[\($0.offset)]", $0.element) }403        default: nil404        }405    }406407    var body: some View {408        if let children {409            VStack(alignment: .leading, spacing: 2) {410                Button { expanded.toggle() } label: {411                    HStack(spacing: 5) {412                        Image(systemName: "chevron.right").font(.system(size: 8, weight: .bold)).foregroundStyle(DS.C.muted).rotationEffect(.degrees(expanded ? 90 : 0)).frame(width: 10)413                        if let key { Text(key).font(DS.F.mono(12, weight: .medium)).foregroundStyle(DS.C.text) }414                        Text({ if case .array = value { "tableau · \(children.count)" } else { "objet · \(children.count)" } }()).font(.system(size: 10.5)).foregroundStyle(DS.C.muted)415                    }416                    .contentShape(Rectangle())417                }418                .buttonStyle(.plain).accessibilityLabel("\(key ?? "racine"), \(children.count) éléments")419                if expanded {420                    // large collections are windowed: the first 200 entries are listed, the count says the rest421                    LazyVStack(alignment: .leading, spacing: 2) {422                        ForEach(Array(children.prefix(200).enumerated()), id: \.offset) { _, c in JSONOutlineView(value: c.1, key: c.0, depth: depth + 1) }423                        if children.count > 200 { Text("… \(children.count - 200) autres éléments (voir la source)").font(.system(size: 10.5)).foregroundStyle(DS.C.muted) }424                    }425                    .padding(.leading, 15).overlay(alignment: .leading) { Rectangle().fill(DS.C.border).frame(width: 1).padding(.leading, 4) }426                }427            }428        } else {429            HStack(alignment: .firstTextBaseline, spacing: 6) {430                Spacer().frame(width: 10)431                if let key { Text(key).font(DS.F.mono(12, weight: .medium)).foregroundStyle(DS.C.text) }432                Text(scalar.text).font(DS.F.mono(12)).foregroundStyle(scalar.color).textSelection(.enabled).lineLimit(4)433            }434        }435    }436437    private var scalar: (text: String, color: Color) {438        switch value {439        case .string(let s): ("\"\(s)\"", DS.C.text2)440        case .number: (value.jsonString(), DS.C.accent)441        case .bool(let b): (b ? "true" : "false", DS.C.ok)442        default: ("null", DS.C.muted)443        }444    }445}446447/// CSV / TSV parsed for display (quoted fields supported); capped so that a huge file stays light.448struct DelimitedTable {449    let header: [String]450    let rows: [[String]]451    let truncated: Bool452453    init?(_ text: String, separator: Character, maxRows: Int = 200) {454        var rows: [[String]] = []; var field = ""; var row: [String] = []; var quoted = false; var truncated = false455        var it = text.makeIterator()456        while let ch = it.next() {457            if quoted {458                if ch == "\"" { quoted = false } else { field.append(ch) }459            } else if ch == "\"" { quoted = true }460            else if ch == separator { row.append(field); field = "" }461            else if ch == "\n" || ch == "\r\n" { row.append(field); field = ""; if !(row.count == 1 && row[0].isEmpty) { rows.append(row) }; row = []; if rows.count > maxRows { truncated = true; break } }462            else if ch != "\r" { field.append(ch) }463        }464        if !truncated, !field.isEmpty || !row.isEmpty { row.append(field); rows.append(row) }465        guard rows.count >= 2, let first = rows.first, first.count >= 2 else { return nil }466        header = first; self.rows = Array(rows.dropFirst()); self.truncated = truncated467    }468}469470struct DelimitedTableView: View {471    let table: DelimitedTable472    var body: some View {473        VStack(alignment: .leading, spacing: 6) {474            ScrollView(.horizontal) {475                Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 5) {476                    GridRow { ForEach(Array(table.header.enumerated()), id: \.offset) { _, h in Text(h).font(.system(size: 12, weight: .semibold)).foregroundStyle(DS.C.text) } }477                    Rectangle().fill(DS.C.border).frame(height: 1).gridCellUnsizedAxes(.horizontal)478                    ForEach(Array(table.rows.enumerated()), id: \.offset) { _, r in479                        GridRow { ForEach(0..<table.header.count, id: \.self) { c in Text(c < r.count ? r[c] : "").font(.system(size: 12).monospacedDigit()).foregroundStyle(DS.C.text2).textSelection(.enabled).lineLimit(2) } }480                    }481                }482            }483            if table.truncated { Text("Aperçu limité aux \(table.rows.count) premières lignes.").font(.system(size: 10.5)).foregroundStyle(DS.C.muted) }484        }485        .accessibilityLabel("Tableau de \(table.rows.count) lignes")486    }487}488
Files main
Menu

Theme