Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Chat/Panels/ContextPanel.swift3// Description: Contextual panel of a conversation (Contexte · Chronologie · Lens · Branches): tab header, cross-faded content, and the small building blocks shared by the four tabs.4import SwiftUI5import SPChatCore67/// State of the four tabs. Owned by the panel (not by a tab view) so that switching tab never loses a running lens8/// or the replay position.9@Observable final class PanelStores {10 let inspector = ContextInspectorModel()11 let timeline = TimelineModel()12 let lens = LensModel()13 let branches = BranchesModel()14}1516/// Right contextual panel. One panel at a time: the frame stays, the content cross-fades (DESIGN-SYSTEM-V2 « Panels »).17/// Mounted by the conversation screen: `.inspector(isPresented:) { ContextPanel(chat: chat, window: window) }`.18struct ContextPanel: View {19 let chat: ChatViewModel20 @Bindable var window: WindowModel21 @State private var stores: PanelStores2223 init(chat: ChatViewModel, window: WindowModel) { self.init(chat: chat, window: window, stores: PanelStores()) }24 /// Tests and previews inject pre-loaded stores.25 init(chat: ChatViewModel, window: WindowModel, stores: PanelStores) { self.chat = chat; self.window = window; _stores = State(initialValue: stores) }2627 var body: some View {28 VStack(spacing: 0) {29 PanelTabBar(selection: $window.panelTab)30 Hairline()31 ZStack {32 switch window.panelTab {33 case .inspector: ContextInspectorPanel(chat: chat, model: stores.inspector).transition(.opacity)34 case .timeline: TimelinePanel(chat: chat, window: window, model: stores.timeline).transition(.opacity)35 case .lens: LensPanel(chat: chat, window: window, model: stores.lens).transition(.opacity)36 case .branches: BranchesPanel(chat: chat, window: window, model: stores.branches).transition(.opacity)37 }38 }39 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)40 .animation(DS.Motion.fade, value: window.panelTab)41 }42 .frame(minWidth: 280)43 .background(DS.C.bgElev)44 .inspectorColumnWidth(min: 280, ideal: 320, max: 460)45 .accessibilityIdentifier("context-panel")46 }47}4849/// Segmented header: four glyphs, the selected one unfolds its title. The pill slides between segments.50struct PanelTabBar: View {51 @Binding var selection: PanelTab52 @Namespace private var pill53 @Environment(\.accessibilityReduceMotion) private var reduceMotion5455 var body: some View {56 HStack(spacing: 2) {57 ForEach(PanelTab.allCases) { tab in58 let selected = tab == selection59 Button { withAnimation(DS.Motion.resolve(DS.Motion.snappy, reduceMotion: reduceMotion)) { selection = tab } } label: {60 HStack(spacing: 5) {61 Image(systemName: tab.systemImage).font(.system(size: 12, weight: .medium)).frame(width: 16)62 if selected { Text(tab.title).font(DS.F.ui).lineLimit(1).fixedSize().transition(.opacity) }63 }64 .foregroundStyle(selected ? DS.C.text : DS.C.muted)65 .padding(.horizontal, selected ? 10 : 8).frame(height: 26)66 .frame(maxWidth: selected ? .infinity : nil)67 .background { if selected { RoundedRectangle(cornerRadius: 7, style: .continuous).fill(DS.C.surface).overlay(RoundedRectangle(cornerRadius: 7, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1)).matchedGeometryEffect(id: "pill", in: pill) } }68 .contentShape(Rectangle())69 }70 .buttonStyle(.plain).help(tab.title)71 .accessibilityLabel(tab.title).accessibilityAddTraits(selected ? [.isSelected, .isButton] : .isButton)72 .accessibilityIdentifier("panel-tab-\(tab.rawValue)")73 }74 }75 .padding(3)76 .background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))77 .padding(.horizontal, DS.S.l).padding(.vertical, DS.S.m)78 }79}8081// MARK: - Shared building blocks8283struct Hairline: View { var body: some View { Rectangle().fill(DS.C.border).frame(height: 1).accessibilityHidden(true) } }8485/// A titled block of a panel. Blocks are separated by hairlines, never by cards.86struct PanelSection<Content: View, Trailing: View>: View {87 let title: String88 @ViewBuilder var trailing: () -> Trailing89 @ViewBuilder var content: () -> Content90 init(_ title: String, @ViewBuilder trailing: @escaping () -> Trailing, @ViewBuilder content: @escaping () -> Content) { self.title = title; self.trailing = trailing; self.content = content }91 var body: some View {92 VStack(alignment: .leading, spacing: DS.S.m) {93 HStack(alignment: .firstTextBaseline, spacing: DS.S.s) { SectionCaption(text: title); trailing() }94 content()95 }96 .padding(.horizontal, DS.S.xl).padding(.vertical, DS.S.l)97 .frame(maxWidth: .infinity, alignment: .leading)98 .overlay(alignment: .bottom) { Hairline() }99 }100}101extension PanelSection where Trailing == EmptyView {102 init(_ title: String, @ViewBuilder content: @escaping () -> Content) { self.init(title, trailing: { EmptyView() }, content: content) }103}104105/// « Label ……… value » row with tabular digits.106struct PanelRow: View {107 let label: String108 let value: String109 var valueColor: Color = DS.C.text110 var body: some View {111 HStack(alignment: .firstTextBaseline, spacing: DS.S.m) {112 Text(label).font(DS.F.uiRegular).foregroundStyle(DS.C.text2).lineLimit(1)113 Spacer(minLength: DS.S.m)114 Text(value).font(DS.F.ui.monospacedDigit()).foregroundStyle(valueColor).lineLimit(1).minimumScaleFactor(0.8).multilineTextAlignment(.trailing).textSelection(.enabled)115 }116 .accessibilityElement(children: .combine)117 }118}119120/// The server's own words about where a figure comes from.121struct SourceNote: View {122 let text: String?123 var body: some View {124 if let text, !text.isEmpty { Text(text).font(.system(size: 10.5)).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true).frame(maxWidth: .infinity, alignment: .leading) }125 }126}127128/// Quiet empty / unavailable state of a tab.129struct PanelPlaceholder: View {130 let systemImage: String131 let title: String132 var message: String?133 var actionTitle: String?134 var action: (() -> Void)?135 var body: some View {136 VStack(spacing: DS.S.m) {137 Image(systemName: systemImage).font(.system(size: 22, weight: .light)).foregroundStyle(DS.C.muted)138 Text(title).font(DS.F.ui).foregroundStyle(DS.C.text2)139 if let message { Text(message).font(DS.F.caption).foregroundStyle(DS.C.muted).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true) }140 if let actionTitle, let action { Button(actionTitle, action: action).buttonStyle(ChipStyle()).padding(.top, DS.S.xs) }141 }142 .padding(.horizontal, DS.S.xxxl).padding(.vertical, 40).frame(maxWidth: .infinity, maxHeight: .infinity)143 .accessibilityElement(children: .combine)144 }145}146147/// Thin line shown at the top of a tab while its data is (re)loaded — content stays in place.148struct PanelLoadingLine: View {149 let active: Bool150 var body: some View { LumenLine(active: active, cornerInset: 0).frame(height: 2).frame(maxWidth: .infinity).clipped() }151}152153/// Wrapping row of chips.154struct FlowLayout: Layout {155 var spacing: CGFloat = 6156 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {157 let rows = arrange(subviews, width: proposal.width ?? .infinity)158 return CGSize(width: proposal.width ?? rows.map(\.width).max() ?? 0, height: rows.last.map { $0.y + $0.height } ?? 0)159 }160 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {161 for row in arrange(subviews, width: bounds.width) {162 for item in row.items { subviews[item.index].place(at: CGPoint(x: bounds.minX + item.x, y: bounds.minY + row.y), proposal: ProposedViewSize(item.size)) }163 }164 }165 private struct Row { var y: CGFloat; var height: CGFloat; var width: CGFloat; var items: [(index: Int, x: CGFloat, size: CGSize)] }166 private func arrange(_ subviews: Subviews, width: CGFloat) -> [Row] {167 var rows: [Row] = []; var current = Row(y: 0, height: 0, width: 0, items: [])168 for (i, v) in subviews.enumerated() {169 let ideal = v.sizeThatFits(.unspecified); let size = CGSize(width: min(ideal.width, width), height: ideal.height)170 let x = current.items.isEmpty ? 0 : current.width + spacing171 if !current.items.isEmpty, x + size.width > width {172 rows.append(current); current = Row(y: current.y + current.height + spacing, height: size.height, width: size.width, items: [(i, 0, size)])173 } else {174 current.items.append((i, x, size)); current.width = x + size.width; current.height = max(current.height, size.height)175 }176 }177 if !current.items.isEmpty { rows.append(current) }178 return rows179 }180}181182/// Formatting of the panel's figures (French grouping, tabular).183enum PanelFormat {184 private static let locale = Locale(identifier: "fr_CA")185 static func int(_ n: Int?) -> String { n.map { $0.formatted(.number.locale(locale)) } ?? "—" }186 /// `p` is already a percentage (0…100).187 static func percent(_ p: Double?) -> String {188 guard let p else { return "—" }189 return (p / 100).formatted(.percent.precision(.fractionLength(p < 10 ? 1 : 0)).locale(locale))190 }191 static func time(_ d: Date?) -> String { d.map { $0.formatted(.dateTime.hour().minute().second().locale(locale)) } ?? "—" }192 static func day(_ d: Date) -> String { d.formatted(.dateTime.day().month(.abbreviated).year().locale(locale)) }193 static func dateTime(_ d: Date?) -> String { d.map { $0.formatted(.dateTime.day().month(.abbreviated).hour().minute().locale(locale)) } ?? "—" }194 /// « facturé » when the provider reported the amount, « estimé » otherwise.195 static func costBasis(exact: Bool) -> String { exact ? "facturé" : "estimé" }196 /// One line of plain text out of a Markdown preview (line breaks and emphasis markers removed; the words are untouched).197 static func plain(_ s: String) -> String {198 var t = s.split(whereSeparator: \.isNewline).joined(separator: " ")199 for marker in ["**", "__", "`"] { t = t.replacingOccurrences(of: marker, with: "") }200 return t.trimmingCharacters(in: .whitespaces)201 }202 static func messages(_ n: Int) -> String { n == 1 ? "1 message" : "\(int(n)) messages" }203}204