SPB Git

Repository Public MIT

GlassTimeline.swift 12.2 KB 290 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassData/Data/GlassTimeline.swift8// Module           : SPGlassData9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import SwiftUI43import SPGlassCore44import SPGlassTokens45import SPGlassThemes46import SPGlassEffects47import SPGlassComponents4849/// One dated event of a ``GlassTimeline``.50public struct GlassTimelineEvent: Identifiable, Hashable, Sendable {51    /// Stable identifier, unique in the timeline.52    public let id: String53    public let date: Date54    /// What happened. Data: displayed as is.55    public let title: String56    /// Optional second line.57    public let detail: String?58    /// Optional SF Symbol drawn in the event's marker instead of a dot.59    public let systemImage: String?60    /// Colour of the marker. It decorates the event; the title carries the meaning.61    public let tone: GlassBadgeTone6263    public init(id: String, date: Date, title: String, detail: String? = nil, systemImage: String? = nil, tone: GlassBadgeTone = .accent) {64        self.id = id65        self.date = date66        self.title = title67        self.detail = detail68        self.systemImage = systemImage69        self.tone = tone70    }71}7273/// Chronological direction of a ``GlassTimeline``.74public enum GlassTimelineOrder: String, CaseIterable, Sendable {75    /// Oldest first.76    case ascending77    /// Most recent first.78    case descending79}8081/// The events of one calendar day.82public struct GlassTimelineDay: Identifiable, Equatable, Sendable {83    /// Start of the day in the calendar used for grouping.84    public let day: Date85    /// The day's events, in timeline order.86    public let events: [GlassTimelineEvent]8788    public var id: Date { day }89}9091/// Ordering, grouping and titling rules of ``GlassTimeline``, independent of any view.92public enum GlassTimelineLogic {93    /// Events in chronological order. The sort is stable: events with the same date keep their original94    /// order, in both directions.95    public static func sorted(_ events: [GlassTimelineEvent], order: GlassTimelineOrder = .ascending) -> [GlassTimelineEvent] {96        events.enumerated().sorted { lhs, rhs in97            if lhs.element.date == rhs.element.date { return lhs.offset < rhs.offset }98            return order == .ascending ? lhs.element.date < rhs.element.date : lhs.element.date > rhs.element.date99        }.map(\.element)100    }101102    /// Events sorted and grouped by calendar day. The day of an event is decided by `calendar` and its time103    /// zone, so the same instant can fall on different days for different calendars, and days that are 23 or104    /// 25 hours long because of daylight saving time are still one group each.105    public static func groups(106        _ events: [GlassTimelineEvent],107        order: GlassTimelineOrder = .ascending,108        calendar: Calendar = .current109    ) -> [GlassTimelineDay] {110        var days: [GlassTimelineDay] = []111        var currentDay: Date?112        var current: [GlassTimelineEvent] = []113        for event in sorted(events, order: order) {114            let day = calendar.startOfDay(for: event.date)115            if let open = currentDay, open != day {116                days.append(GlassTimelineDay(day: open, events: current))117                current = []118            }119            currentDay = day120            current.append(event)121        }122        if let open = currentDay {123            days.append(GlassTimelineDay(day: open, events: current))124        }125        return days126    }127128    /// The header of a day: the complete date in the given locale, calendar and the calendar's time zone129    /// ("Monday, March 9, 2026", "lundi 9 mars 2026").130    public static func dayTitle(_ day: Date, calendar: Calendar = .current, locale: Locale = .current) -> String {131        day.formatted(Date.FormatStyle(date: .complete, time: .omitted, locale: locale, calendar: calendar, timeZone: calendar.timeZone))132    }133134    /// The time of an event in the given locale and the calendar's time zone ("9:41 AM", "09:41").135    public static func timeText(_ date: Date, calendar: Calendar = .current, locale: Locale = .current) -> String {136        date.formatted(Date.FormatStyle(date: .omitted, time: .shortened, locale: locale, calendar: calendar, timeZone: calendar.timeZone))137    }138}139140/// Dated events in chronological order, grouped under localised day headers.141///142/// ```swift143/// ScrollView {144///     GlassTimeline(events, order: .descending)145/// }146/// ```147///148/// Grouping and formatting use the calendar, time zone and locale of the environment. Each event shows its149/// time in a leading column, a marker on a rail (a tinted tile with the event's symbol, or a ring) and its150/// title and detail; at accessibility text sizes the time moves above the title. The timeline is a lazy151/// stack without its own scroll view or surface, so it can live inside a card or a page that scrolls. The152/// rail is decorative and hidden from assistive technologies; each event is one accessibility element and153/// each day title is a header.154public struct GlassTimeline: View {155    @GlassThemed private var theme156    @Environment(\.calendar) private var environmentCalendar157    @Environment(\.timeZone) private var timeZone158    @Environment(\.locale) private var locale159    @Environment(\.dynamicTypeSize) private var dynamicTypeSize160    @ScaledMetric(relativeTo: .caption) private var timeColumnWidth: CGFloat = 60161    private let events: [GlassTimelineEvent]162    private let order: GlassTimelineOrder163    private let emptyTitle: Text164165    /// - Parameters:166    ///   - events: the events, in any order.167    ///   - order: oldest first or most recent first.168    ///   - emptyTitle: text of the empty state. Defaults to the localised "No events".169    public init(_ events: [GlassTimelineEvent], order: GlassTimelineOrder = .ascending, emptyTitle: LocalizedStringKey? = nil) {170        self.events = events171        self.order = order172        self.emptyTitle = emptyTitle.map { Text($0) } ?? Text(GlassL10n.string(.noEvents))173    }174175    /// The environment's calendar in the environment's time zone.176    private var calendar: Calendar {177        var calendar = environmentCalendar178        calendar.timeZone = timeZone179        return calendar180    }181182    public var body: some View {183        if events.isEmpty {184            ContentUnavailableView {185                Label { emptyTitle } icon: { Image(systemName: "calendar") }186            }187        } else {188            LazyVStack(alignment: .leading, spacing: theme.spacing.md) {189                ForEach(GlassTimelineLogic.groups(events, order: order, calendar: calendar)) { day in190                    Section {191                        VStack(alignment: .leading, spacing: 0) {192                            ForEach(Array(day.events.enumerated()), id: \.element.id) { index, event in193                                row(event, isLast: index == day.events.count - 1)194                            }195                        }196                    } header: {197                        dayHeader(day.day)198                    }199                }200            }201            .accessibilityElement(children: .contain)202            .accessibilityLabel(Text(GlassL10n.string(.timeline)))203        }204    }205206    private static var markerSize: CGFloat { 28 }207208    private func dayHeader(_ day: Date) -> some View {209        HStack(alignment: .center, spacing: theme.spacing.sm) {210            Text(verbatim: GlassTimelineLogic.dayTitle(day, calendar: calendar, locale: locale))211                .font(.system(.caption, weight: .semibold))212                .textCase(.uppercase)213                .tracking(0.6)214                .foregroundStyle(theme.color(.textSecondary))215                .fixedSize(horizontal: false, vertical: true)216                .layoutPriority(1)217                .accessibilityAddTraits(.isHeader)218            Rectangle()219                .fill(theme.color(.separator).opacity(0.7))220                .frame(minWidth: 12)221                .frame(height: 1)222                .accessibilityHidden(true)223        }224        .padding(.bottom, theme.spacing.xxs)225    }226227    private func row(_ event: GlassTimelineEvent, isLast: Bool) -> some View {228        let stacksTime = dynamicTypeSize.isAccessibilitySize229        let time = GlassTimelineLogic.timeText(event.date, calendar: calendar, locale: locale)230        return HStack(alignment: .top, spacing: theme.spacing.sm) {231            if !stacksTime {232                Text(verbatim: time)233                    .font(theme.font(.caption).monospacedDigit())234                    .foregroundStyle(theme.color(.textSecondary))235                    .lineLimit(1)236                    .minimumScaleFactor(0.8)237                    .frame(width: timeColumnWidth, height: Self.markerSize, alignment: .trailing)238                    .accessibilityHidden(true)239            }240            VStack(spacing: theme.spacing.xxs) {241                marker(event)242                if !isLast {243                    Capsule()244                        .fill(theme.color(.separator))245                        .frame(width: 2)246                        .frame(maxHeight: .infinity)247                }248            }249            .frame(width: Self.markerSize)250            .padding(.bottom, isLast ? 0 : theme.spacing.xxs)251            .accessibilityHidden(true)252253            VStack(alignment: .leading, spacing: 2) {254                if stacksTime {255                    Text(verbatim: time)256                        .font(theme.font(.caption))257                        .foregroundStyle(theme.color(.textSecondary))258                }259                Text(verbatim: event.title)260                    .font(theme.font(.body).weight(.medium))261                    .foregroundStyle(theme.color(.textPrimary))262                    .frame(minHeight: stacksTime ? nil : Self.markerSize, alignment: .leading)263                if let detail = event.detail, !detail.isEmpty {264                    Text(verbatim: detail)265                        .font(theme.font(.callout))266                        .foregroundStyle(theme.color(.textSecondary))267                }268            }269            .padding(.bottom, isLast ? 0 : theme.spacing.md)270            .frame(maxWidth: .infinity, alignment: .leading)271            .accessibilityElement(children: .combine)272            .accessibilityLabel(Text(verbatim: [time, event.title, event.detail ?? ""].filter { !$0.isEmpty }.joined(separator: ", ")))273        }274        .fixedSize(horizontal: false, vertical: true)275    }276277    @ViewBuilder278    private func marker(_ event: GlassTimelineEvent) -> some View {279        if let systemImage = event.systemImage {280            GlassIconTile(systemImage: systemImage, tone: event.tone, size: Self.markerSize)281        } else {282            let color = event.tone.colorToken.map { theme.color($0) } ?? theme.color(.textSecondary)283            Circle()284                .strokeBorder(color, lineWidth: 2.5)285                .frame(width: 12, height: 12)286                .frame(width: Self.markerSize, height: Self.markerSize)287        }288    }289}290
Files main
Menu

Theme