Code
Examples
One example per component. Every example is compiled with the package and laid out by the test suite in each theme, so the code shown here builds.
CaptureNavigation
GlassBreadcrumb
Typed path with truncation, an overflow menu and keyboard navigation.
import SwiftUI
import SPGlassKit
public struct GlassBreadcrumbExample: GlassExample {
public static let componentID = "glass-breadcrumb"
private static let fullPath: [GlassBreadcrumbItem<Int>] = [
GlassBreadcrumbItem(id: 0, title: "Home", systemImage: "house"),
GlassBreadcrumbItem(id: 1, title: "Projects"),
GlassBreadcrumbItem(id: 2, title: "2026"),
GlassBreadcrumbItem(id: 3, title: "Client workshop — été"),
GlassBreadcrumbItem(id: 4, title: "Photos"),
GlassBreadcrumbItem(id: 5, title: "Selected 📷"),
]
@State private var depth = 6
public init() {}
private var path: [GlassBreadcrumbItem<Int>] { Array(Self.fullPath.prefix(depth)) }
public var body: some View {
VStack(alignment: .leading, spacing: 24) {
GlassBreadcrumb(path) { id in depth = id + 1 }
GlassBreadcrumb(path, maxVisibleItems: 2) { id in depth = id + 1 }
GlassBreadcrumb(Array(Self.fullPath.prefix(1))) { _ in }
Text("Current: \(path.last?.title ?? "—")")
.font(.callout)
.foregroundStyle(.secondary)
Button("Go deeper") { depth = min(depth + 1, Self.fullPath.count) }
.disabled(depth == Self.fullPath.count)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
}
}
#Preview("GlassBreadcrumb") { GlassBreadcrumbExample().glassTheme(.emerald) }
GlassNavigationBar
NavigationStack with a title, toolbar actions and the system back button.
import SwiftUI
import SPGlassKit
public struct GlassNavigationBarExample: GlassExample {
public static let componentID = "glass-navigation-bar"
@State private var notes = ["Quarterly review", "Trip to Lisbon", "A much longer note title that has to wrap or truncate gracefully"]
@State private var isFlagged = false
public init() {}
public var body: some View {
GlassNavigationBar(
"Notes",
subtitle: "\(notes.count) notes",
titleDisplay: .large,
leading: [
GlassToolbarAction(id: "sort", title: "Sort", systemImage: "arrow.up.arrow.down") { notes.sort() },
],
trailing: [
GlassToolbarAction(id: "new", title: "New note", systemImage: "square.and.pencil", shortcut: KeyboardShortcut("n"), priority: .high) {
notes.append("Untitled \(notes.count + 1)")
},
GlassToolbarAction(id: "shuffle", title: "Shuffle", systemImage: "shuffle") { notes.shuffle() },
GlassToolbarAction(id: "clear", title: "Delete all", systemImage: "trash", role: .destructive, isEnabled: !notes.isEmpty, priority: .low) {
notes.removeAll()
},
]
) {
List(notes, id: \.self) { note in
NavigationLink(note, value: note)
}
.overlay {
if notes.isEmpty { ContentUnavailableView("No notes", systemImage: "note.text") }
}
.navigationDestination(for: String.self) { note in
ScrollView {
Text(verbatim: note)
.font(.title3)
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
}
.glassNavigationBar(
"Note",
titleDisplay: .inline,
trailing: [
GlassToolbarAction(id: "flag", title: isFlagged ? "Remove flag" : "Flag", systemImage: isFlagged ? "flag.fill" : "flag") {
isFlagged.toggle()
},
]
)
}
}
}
}
#Preview("GlassNavigationBar") { GlassNavigationBarExample().glassTheme(.ocean) }
GlassSidebar
NavigationSplitView sidebar with sections, selection, search and adaptive collapse.
import SwiftUI
import SPGlassKit
public struct GlassSidebarExample: GlassExample {
public static let componentID = "glass-sidebar"
@State private var selection: String? = "inbox"
@State private var columnVisibility: NavigationSplitViewVisibility = .automatic
public init() {}
private let sections: [GlassSidebarSection<String>] = [
GlassSidebarSection(id: "mailboxes", title: "Mailboxes", items: [
GlassSidebarItem(id: "inbox", title: "Inbox", systemImage: "tray", badge: 12, keywords: ["unread"]),
GlassSidebarItem(id: "drafts", title: "Drafts", systemImage: "doc", badge: 2),
GlassSidebarItem(id: "sent", title: "Sent", systemImage: "paperplane"),
GlassSidebarItem(id: "archive", title: "Archive", systemImage: "archivebox"),
]),
GlassSidebarSection(id: "labels", title: "Labels", items: [
GlassSidebarItem(id: "travel", title: "Voyages et séjours", systemImage: "airplane", keywords: ["travel", "trips"]),
GlassSidebarItem(id: "receipts", title: "Reçus", systemImage: "receipt", keywords: ["receipts"]),
GlassSidebarItem(id: "long", title: "A label with a deliberately long name to check wrapping", systemImage: "tag"),
]),
]
public var body: some View {
GlassSidebar("Mail", sections: sections, selection: $selection, columnVisibility: $columnVisibility, searchPrompt: "Search mailboxes") { id in
if let id {
VStack(spacing: 12) {
Text(verbatim: title(of: id)).font(.title2)
Button(columnVisibility == .detailOnly ? "Show sidebar" : "Hide sidebar") {
columnVisibility = columnVisibility == .detailOnly ? .all : .detailOnly
}
}
.padding()
.navigationTitle(Text(verbatim: title(of: id)))
} else {
ContentUnavailableView("Select a mailbox", systemImage: "sidebar.left")
}
}
}
private func title(of id: String) -> String {
sections.flatMap(\.items).first { $0.id == id }?.title ?? id
}
}
#Preview("GlassSidebar") { GlassSidebarExample() }
GlassTabBar
Typed wrapper around the system TabView with badges, dynamic tabs, per-tab navigation state and deep links.
import SwiftUI
import SPGlassKit
public struct GlassTabBarExample: GlassExample {
public static let componentID = "glass-tab-bar"
enum DemoTab: String, Hashable, Sendable {
case today, library, inbox, search
}
enum DemoRoute: Hashable, Sendable {
case album(String)
case track(String)
}
@State private var state = GlassTabNavigationState<DemoTab, DemoRoute>(selection: .today)
@State private var unread = 3
@State private var showsInbox = true
/// Deep links of the demo: `glasskit-demo://library/<album>/<track>`.
static let router = GlassTabRouter<DemoTab, DemoRoute>(
schemes: ["glasskit-demo"],
tabs: ["today": .today, "library": .library, "inbox": .inbox, "search": .search]
) { tab, components, _ in
switch (tab, components.count) {
case (_, 0): []
case (.library, 1): [.album(components[0])]
case (.library, 2): [.album(components[0]), .track(components[1])]
default: nil
}
}
public init() {}
private var tabs: [GlassTabItem<DemoTab>] {
var tabs = [
GlassTabItem(id: DemoTab.today, title: "Today", systemImage: "sun.max"),
GlassTabItem(id: DemoTab.library, title: "Library", systemImage: "square.stack"),
]
if showsInbox {
tabs.append(GlassTabItem(id: .inbox, title: "Inbox", systemImage: "tray", badge: .count(unread)))
}
tabs.append(GlassTabItem(id: .search, title: "Search", systemImage: "magnifyingglass", isSearch: true))
return tabs
}
public var body: some View {
GlassTabBar(tabs: tabs, state: $state, minimizeBehavior: .onScrollDown) { tab in
root(tab)
} destination: { route in
switch route {
case .album(let name):
List(1...12, id: \.self) { number in
NavigationLink("Track \(number)", value: DemoRoute.track("\(name) · \(number)"))
}
.navigationTitle(name)
case .track(let name):
Text(verbatim: name).font(.title2).navigationTitle("Now playing")
}
}
.onOpenURL { url in
if let destination = Self.router.destination(for: url) { state.open(destination) }
}
.onChange(of: showsInbox) {
state.reconcile(with: tabs.map(\.id), fallback: .today)
}
}
@ViewBuilder
private func root(_ tab: DemoTab) -> some View {
switch tab {
case .today:
List {
Section("Deep links") {
Button("Open “Aurora” in Library") {
state.open(GlassTabDestination(tab: .library, path: [.album("Aurora")]))
}
Button("Open track 4 of “Tides”") {
if let url = URL(string: "glasskit-demo://library/Tides/4"),
let destination = Self.router.destination(for: url) {
state.open(destination)
}
}
}
Section("Dynamic tabs") {
Toggle("Show the Inbox tab", isOn: $showsInbox)
Stepper("Unread: \(unread)", value: $unread, in: 0...99)
}
}
.navigationTitle("Today")
case .library:
List(["Aurora", "Tides", "Quiet Hours", "Granite"], id: \.self) { album in
NavigationLink(album, value: DemoRoute.album(album))
}
.navigationTitle("Library")
case .inbox:
List(0..<unread, id: \.self) { index in
Text("Sample message \(index + 1)")
}
.overlay {
if unread == 0 { ContentUnavailableView("No messages", systemImage: "tray") }
}
.navigationTitle("Inbox")
case .search:
Text("Search results appear here.")
.foregroundStyle(.secondary)
.navigationTitle("Search")
}
}
}
#Preview("GlassTabBar") { GlassTabBarExample() }
GlassToolbar
Groups of toolbar actions with system placements, overflow and keyboard shortcuts.
import SwiftUI
import SPGlassKit
public struct GlassToolbarExample: GlassExample {
public static let componentID = "glass-toolbar"
@State private var log = ["Nothing yet"]
@State private var isPinned = false
public init() {}
private func record(_ entry: String) {
log.insert(entry, at: 0)
}
private var groups: [GlassToolbarGroup] {
[
GlassToolbarGroup(id: "document", placement: .trailing, capacity: 3, actions: [
GlassToolbarAction(id: "share", title: "Share", systemImage: "square.and.arrow.up", shortcut: KeyboardShortcut("s", modifiers: [.command, .shift]), priority: .high) { record("Shared") },
GlassToolbarAction(id: "pin", title: isPinned ? "Unpin" : "Pin", systemImage: isPinned ? "pin.fill" : "pin") {
isPinned.toggle()
record(isPinned ? "Pinned" : "Unpinned")
},
GlassToolbarAction(id: "duplicate", title: "Duplicate", systemImage: "plus.square.on.square", shortcut: KeyboardShortcut("d")) { record("Duplicated") },
GlassToolbarAction(id: "archive", title: "Archive", systemImage: "archivebox", isEnabled: log.count > 1, priority: .low) { record("Archived") },
GlassToolbarAction(id: "delete", title: "Delete", systemImage: "trash", role: .destructive, priority: .low) { log = ["Nothing yet"] },
]),
GlassToolbarGroup(id: "export", placement: .secondary, actions: [
GlassToolbarAction(id: "pdf", title: "Export as PDF", systemImage: "doc.richtext") { record("Exported as PDF") },
GlassToolbarAction(id: "print", title: "Print", systemImage: "printer", shortcut: KeyboardShortcut("p")) { record("Printed") },
]),
GlassToolbarGroup(id: "format", placement: .bottom, actions: [
GlassToolbarAction(id: "bold", title: "Bold", systemImage: "bold", shortcut: KeyboardShortcut("b")) { record("Bold") },
GlassToolbarAction(id: "italic", title: "Italic", systemImage: "italic", shortcut: KeyboardShortcut("i")) { record("Italic") },
]),
]
}
public var body: some View {
NavigationStack {
List(Array(log.enumerated()), id: \.offset) { _, entry in
Text(verbatim: entry)
}
.navigationTitle("Document")
.glassToolbar(groups)
}
}
}
#Preview("GlassToolbar") { GlassToolbarExample() }
Buttons
GlassButton
Button using the system glass styles, with destructive role, loading and disabled states.
import SwiftUI
import SPGlassKit
public struct GlassButtonExample: GlassExample {
public static let componentID = "glass-button"
@State private var isSaving = false
@State private var saveCount = 0
public init() {}
public var body: some View {
VStack(spacing: 16) {
GlassButton("Save changes", systemImage: "checkmark", variant: .prominent, isLoading: isSaving) {
isSaving = true
saveCount += 1
}
GlassButton("Duplicate", systemImage: "plus.square.on.square") { saveCount += 1 }
GlassButton("Delete draft", systemImage: "trash", role: .destructive) { saveCount = 0 }
GlassButton("Unavailable", size: .small) {}
.disabled(true)
GlassButton(variant: .regular, size: .large) {
isSaving = false
} label: {
VStack {
Text("Reset")
Text("Saved \(saveCount) times").font(.caption)
}
}
}
.padding()
}
}
#Preview("GlassButton") { GlassButtonExample().glassTheme(.aurora) }
GlassButtonGroup
Related glass buttons rendered in one glass container so that they blend consistently.
import SwiftUI
import SPGlassKit
public struct GlassButtonGroupExample: GlassExample {
public static let componentID = "glass-button-group"
@State private var styles: Set<String> = []
public init() {}
public var body: some View {
VStack(spacing: 24) {
GlassButtonGroup(accessibilityLabel: "Text style") {
ForEach(["bold", "italic", "underline"], id: \.self) { style in
GlassIconButton(
systemImage: style,
label: Text(style.capitalized),
variant: styles.contains(style) ? .prominent : .regular
) {
styles.formSymmetricDifference([style])
}
}
}
GlassButtonGroup(axis: .vertical, spacing: .sm, accessibilityLabel: "Zoom") {
GlassIconButton(systemImage: "plus", accessibilityLabel: "Zoom in") {}
GlassIconButton(systemImage: "minus", accessibilityLabel: "Zoom out") {}
}
}
.padding()
}
}
#Preview("GlassButtonGroup") { GlassButtonGroupExample() }
GlassFloatingButton
Floating action placed inside the safe area, clear of the keyboard.
import SwiftUI
import SPGlassKit
public struct GlassFloatingButtonExample: GlassExample {
public static let componentID = "glass-floating-button"
@State private var notes = ["Groceries", "Reading list", "Trip ideas"]
@State private var isExtended = true
public init() {}
public var body: some View {
List {
Toggle("Show title", isOn: $isExtended)
ForEach(notes, id: \.self) { Text($0) }
}
.frame(minHeight: 280)
.glassFloatingButton("New note", systemImage: "plus", position: .bottomTrailing, isExtended: isExtended) {
notes.append("Note \(notes.count + 1)")
}
}
}
#Preview("GlassFloatingButton") { GlassFloatingButtonExample() }
GlassIconButton
Symbol-only glass button with a mandatory accessibility label and a full-size hit target.
import SwiftUI
import SPGlassKit
public struct GlassIconButtonExample: GlassExample {
public static let componentID = "glass-icon-button"
@State private var isFavourite = false
public init() {}
public var body: some View {
HStack(spacing: 16) {
GlassIconButton(systemImage: "square.and.arrow.up", accessibilityLabel: "Share") {}
GlassIconButton(
systemImage: isFavourite ? "star.fill" : "star",
accessibilityLabel: isFavourite ? "Remove from favourites" : "Add to favourites",
variant: .prominent
) { isFavourite.toggle() }
GlassIconButton(systemImage: "trash", accessibilityLabel: "Delete", role: .destructive, size: .small) {}
GlassIconButton(systemImage: "ellipsis", accessibilityLabel: "More", size: .large) {}
}
.padding()
}
}
#Preview("GlassIconButton") { GlassIconButtonExample() }
GlassSplitButton
Primary action with a separate menu of secondary actions.
import SwiftUI
import SPGlassKit
public struct GlassSplitButtonExample: GlassExample {
public static let componentID = "glass-split-button"
@State private var lastAction = "Nothing sent yet"
public init() {}
public var body: some View {
VStack(spacing: 16) {
GlassSplitButton("Send", systemImage: "paperplane", variant: .prominent) {
lastAction = "Sent now"
} menu: {
Button("Send later…", systemImage: "clock") { lastAction = "Scheduled" }
Button("Save as draft", systemImage: "tray") { lastAction = "Saved as draft" }
}
Text(lastAction).font(.callout).foregroundStyle(.secondary)
}
.padding()
}
}
#Preview("GlassSplitButton") { GlassSplitButtonExample() }
Forms
GlassOTPField
One logical one-time-code field with paste, AutoFill and a segmented display.
import SwiftUI
import SPGlassKit
public struct GlassOTPFieldExample: GlassExample {
public static let componentID = "glass-otp-field"
/// The demo accepts this fictitious code only.
private static let expected = "246810"
@State private var code = ""
@State private var shortCode = ""
@State private var status = "Enter the 6-digit demo code 246810."
@State private var rejected = false
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
GlassOTPField(code: $code, hasError: rejected) { entered in
rejected = entered != Self.expected
status = rejected ? "That code is not valid. Try again." : "Code accepted."
}
.onChange(of: code) { _, newValue in
if newValue.count < 6 { rejected = false }
}
Label(status, systemImage: rejected ? "xmark.octagon" : "info.circle")
.font(.callout)
.foregroundStyle(.secondary)
HStack {
Button("Simulate paste “246 810”") { code = GlassOTPSanitizer.sanitize("246 810", length: 6) }
Button("Clear") { code = "" }
}
Text("Four digits").font(.headline)
GlassOTPField(code: $shortCode, length: 4, label: "PIN")
Text("Disabled").font(.headline)
GlassOTPField(code: .constant("12"), length: 4)
.disabled(true)
}
.padding()
}
}
}
#Preview("GlassOTPField") { GlassOTPFieldExample() }
GlassSearchField
Search with suggestions, cancellation and a cancellable debounce for asynchronous queries.
import SwiftUI
import SPGlassKit
public struct GlassSearchFieldExample: GlassExample {
public static let componentID = "glass-search-field"
private static let catalogue = ["Café crème", "Cafetière italienne", "Thé vert", "Théière en fonte", "Chocolat chaud", "Citronnade", "Eau pétillante", "Jus d’orange"]
private static let recent = [
GlassSearchSuggestion(title: "café", systemImage: "clock"),
GlassSearchSuggestion(title: "thé", systemImage: "clock"),
GlassSearchSuggestion(title: "Hot drinks", systemImage: "cup.and.saucer", completion: "chaud"),
]
@State private var query = ""
@State private var inlineQuery = ""
@State private var results = GlassSearchFieldExample.catalogue
@State private var debouncer = GlassSearchDebouncer(delay: .milliseconds(250))
public init() {}
/// A stand-in for a remote search: it only filters a local list after a short pause.
private static func search(_ query: String) async throws -> [String] {
try await Task.sleep(for: .milliseconds(150))
let needle = query.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)
return needle.isEmpty ? catalogue : catalogue.filter { $0.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil).contains(needle) }
}
public var body: some View {
NavigationStack {
List {
Section("Inline field") {
GlassSearchField(text: $inlineQuery, prompt: "Filter this section")
.listRowSeparator(.hidden)
ForEach(Self.catalogue.filter { inlineQuery.isEmpty || $0.localizedStandardContains(inlineQuery) }, id: \.self) { item in
Text(verbatim: item)
}
}
Section {
ForEach(results, id: \.self) { item in
Text(verbatim: item)
}
if results.isEmpty {
Text("No results").foregroundStyle(.secondary)
}
} header: {
HStack {
Text("Debounced results")
if debouncer.isPending { ProgressView().controlSize(.small) }
}
}
}
.navigationTitle("Drinks")
.glassSearchable(text: $query, prompt: "Search drinks", suggestions: query.isEmpty ? Self.recent : [])
.onChange(of: query) { _, newValue in
debouncer.submit(newValue, search: Self.search) { results = $0 }
}
.onDisappear { debouncer.cancel() }
}
}
}
#Preview("GlassSearchField") { GlassSearchFieldExample() }
GlassSecureField
Secure field with optional explicit reveal; its content is never logged.
import SwiftUI
import SPGlassKit
public struct GlassSecureFieldExample: GlassExample {
public static let componentID = "glass-secure-field"
@State private var current = ""
@State private var new = ""
@State private var pin = ""
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
GlassSecureField("Current password", text: $current, validation: GlassFieldValidation(.required()))
GlassSecureField(
"New password",
text: $new,
prompt: "At least 12 characters",
helper: "Use a phrase you can remember.",
content: .newPassword,
allowsReveal: true,
validation: GlassFieldValidation(.required(), .minLength(12)),
validateOn: .always
)
GlassSecureField("Device PIN", text: $pin, allowsReveal: true, errorMessage: pin.isEmpty ? nil : "Demo: this PIN is always rejected.")
// Only the length is ever displayed: the example never prints the secret.
Text("New password length: \(new.count)")
.font(.callout)
.foregroundStyle(.secondary)
}
.padding()
}
}
}
#Preview("GlassSecureField") { GlassSecureFieldExample() }
GlassTextArea
Multiline editor with an accessible placeholder, optional limit and counter.
import SwiftUI
import SPGlassKit
public struct GlassTextAreaExample: GlassExample {
public static let componentID = "glass-text-area"
@State private var notes = ""
@State private var bio = "Hiking 🥾, bread 🍞 and old maps 🗺️."
@State private var feedback = "Too short"
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
GlassTextArea("Notes", text: $notes, placeholder: "Anything the team should know before the visit", helper: "Visible to your team only.")
GlassTextArea("Short bio", text: $bio, limit: 40)
GlassTextArea(
"Feedback",
text: $feedback,
showsCounter: true,
minHeight: 72,
errorMessage: feedback.count < 20 ? "Please write at least 20 characters." : nil
)
GlassTextArea("Archived comment", text: .constant("This comment can no longer be edited."))
.disabled(true)
}
.padding()
}
}
}
#Preview("GlassTextArea") { GlassTextAreaExample().glassTheme(.solar) }
GlassTextField
Text field with label, validation message, focus handling and keyboard configuration.
import SwiftUI
import SPGlassKit
public struct GlassTextFieldExample: GlassExample {
public static let componentID = "glass-text-field"
@State private var name = ""
@State private var email = ""
@State private var handle = "taken"
@State private var locked = "Read-only value"
@FocusState private var emailFocused: Bool
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
GlassTextField(
"Full name",
text: $name,
prompt: "Ada Lovelace",
validation: GlassFieldValidation(.required(), .minLength(2)),
input: .name
)
.onSubmit { emailFocused = true }
GlassTextField(
"Email",
text: $email,
prompt: "name@example.com",
helper: "Used only for the receipt.",
systemImage: "envelope",
validation: GlassFieldValidation(.required(), .custom(message: "Enter an address such as name@example.com") { $0.contains("@") && $0.contains(".") }),
input: .email,
focus: $emailFocused
)
GlassTextField(
"Username",
text: $handle,
validation: GlassFieldValidation(.maxLength(12)),
validateOn: .always,
errorMessage: handle == "taken" ? "This username is already taken." : nil,
input: .username
)
GlassTextField("Account", text: $locked)
.disabled(true)
Button("Focus the email field") { emailFocused = true }
}
.padding()
}
}
}
#Preview("GlassTextField") { GlassTextFieldExample().glassTheme(.aurora) }
Selection
GlassPicker
Generic picker over Hashable options, as a menu or a wheel depending on the platform.
import SwiftUI
import SPGlassKit
public struct GlassPickerExample: GlassExample {
public static let componentID = "glass-picker"
struct Plan: Hashable {
let name: String
let symbol: String
}
private static let plans = [
Plan(name: "Starter", symbol: "leaf"),
Plan(name: "Team", symbol: "person.3"),
Plan(name: "Enterprise with a long name", symbol: "building.2"),
]
@State private var plan = GlassPickerExample.plans[0]
@State private var currency = "CAD"
@State private var hour = 9
@State private var priority = "Normal"
public init() {}
public var body: some View {
Form {
GlassPicker("Plan", selection: $plan, options: Self.plans) { plan in
Label(plan.name, systemImage: plan.symbol)
}
GlassPicker("Currency", selection: $currency, options: ["CAD", "EUR", "JPY", "USD"])
GlassPicker("Reminder hour", selection: $hour, options: Array(6...22), presentation: .wheel) { hour in
"\(hour.formatted(.number.precision(.integerLength(2)))):00"
}
GlassPicker("Priority", selection: $priority, options: ["Low", "Normal", "High"], presentation: .inline)
GlassPicker("Region", selection: .constant("Canada"), options: ["Canada"])
.disabled(true)
}
}
}
#Preview("GlassPicker") { GlassPickerExample() }
GlassSegmentedControl
Segmented picker with labels that adapt to the available width.
import SwiftUI
import SPGlassKit
public struct GlassSegmentedControlExample: GlassExample {
public static let componentID = "glass-segmented-control"
enum Mode: String, CaseIterable, Hashable {
case list, grid, map
var title: String { rawValue.capitalized }
}
@State private var mode = Mode.list
@State private var period = "Week"
@State private var long = "Everything that happened"
@State private var weekday = "Mon"
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 24) {
GlassSegmentedControl("View", selection: $mode, options: Mode.allCases, title: \.title)
Text("Showing: \(mode.title)").font(.callout).foregroundStyle(.secondary)
GlassSegmentedControl("Period", selection: $period, options: ["Day", "Week", "Month", "Year"]) { $0 }
Text("Titles too long for the width fall back to a menu").font(.headline)
GlassSegmentedControl("Scope", selection: $long, options: ["Everything that happened", "Only what I was mentioned in", "Nothing at all, thank you"]) { $0 }
Text("More than five options: a menu").font(.headline)
GlassSegmentedControl("Day", selection: $weekday, options: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]) { $0 }
GlassSegmentedControl("Locked", selection: .constant("On"), options: ["Off", "On"]) { $0 }
.disabled(true)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
}
}
}
#Preview("GlassSegmentedControl") { GlassSegmentedControlExample() }
GlassSlider
System slider with bounds, step, a readable value and VoiceOver adjustment.
import SwiftUI
import SPGlassKit
public struct GlassSliderExample: GlassExample {
public static let componentID = "glass-slider"
@State private var brightness = 0.6
@State private var temperature = 21.0
@State private var budget = 1500.0
@State private var locked = 0.3
@State private var isDragging = false
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 24) {
GlassSlider("Brightness", value: $brightness, format: .percent.precision(.fractionLength(0)))
GlassSlider("Temperature", value: $temperature, in: 16...28, step: 0.5, showsBoundLabels: true) { value in
Measurement(value: value, unit: UnitTemperature.celsius)
.formatted(.measurement(width: .abbreviated, usage: .asProvided, numberFormatStyle: .number.precision(.fractionLength(1))))
}
GlassSlider(
"Monthly budget",
value: $budget,
in: 0...5000,
step: 250,
format: .currency(code: "CAD").precision(.fractionLength(0)),
showsBoundLabels: true,
showsTicks: true,
onEditingChanged: { isDragging = $0 }
)
Text(isDragging ? "Adjusting…" : "Released")
.font(.caption)
.foregroundStyle(.secondary)
GlassSlider("Locked by policy", value: $locked)
.disabled(true)
}
.padding()
}
}
}
#Preview("GlassSlider") { GlassSliderExample().glassTheme(.ocean) }
GlassStepper
System stepper with bounds, increments and a formatted value.
import SwiftUI
import SPGlassKit
public struct GlassStepperExample: GlassExample {
public static let componentID = "glass-stepper"
@State private var guests = 2
@State private var dose = 0.5
@State private var zoom = 1.0
@State private var fixed = 3
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
GlassStepper("Guests", value: $guests, in: 1...12)
GlassStepper("Dose", value: $dose, in: 0...2.5, step: 0.25) { value in
Measurement(value: value, unit: UnitMass.milligrams)
.formatted(.measurement(width: .abbreviated, usage: .asProvided, numberFormatStyle: .number.precision(.fractionLength(2))))
}
// The upper bound 4 is not on a step from 0.5 by 0.75: the last press stops at the bound.
GlassStepper("Zoom", value: $zoom, in: 0.5...4, step: 0.75) { value in
value.formatted(.percent.precision(.fractionLength(0)))
}
GlassStepper("Seats (fixed by your plan)", value: $fixed, in: 1...5)
.disabled(true)
}
.padding()
}
}
}
#Preview("GlassStepper") { GlassStepperExample().glassTheme(.crystal) }
GlassToggle
System toggle with title, description and disabled state.
import SwiftUI
import SPGlassKit
public struct GlassToggleExample: GlassExample {
public static let componentID = "glass-toggle"
@State private var notifications = true
@State private var summary = false
@State private var analytics = false
@State private var terms = false
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
GlassToggle("Notifications", isOn: $notifications)
GlassToggle(
"Weekly summary",
description: "A digest every Monday morning with the activity of the previous week, sent to the address of your account.",
systemImage: "envelope",
isOn: $summary
)
GlassToggle("Share usage statistics", description: "Managed by your organisation.", isOn: $analytics)
.disabled(true)
GlassToggle("I accept the terms", appearance: .checkbox, isOn: $terms)
}
.padding()
}
}
}
#Preview("GlassToggle") { GlassToggleExample().glassTheme(.emerald) }
Containers
GlassAccordion
Disclosure sections with controlled expansion and Reduce Motion support.
import SwiftUI
import SPGlassKit
public struct GlassAccordionExample: GlassExample {
public static let componentID = "glass-accordion"
private struct Question: Identifiable {
let id: String
let title: String
let answer: String
}
private let questions = [
Question(id: "delivery", title: "How long does delivery take?", answer: "Two to four working days for this sample shop."),
Question(id: "returns", title: "Can I return an item?", answer: "Yes, within 30 days, in its original packaging."),
Question(id: "unicode", title: "Les accents et les émojis passent-ils ? 🎉", answer: "Oui : « é », « ñ », « 日本語 » et le texte de droite à gauche (مرحبا) s'affichent sans casser la mise en page."),
]
@State private var expanded: Set<String> = ["delivery"]
@State private var singleMode = true
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
Toggle("One section at a time", isOn: $singleMode)
GlassAccordion(questions, expanded: $expanded, mode: singleMode ? .single : .multiple, style: .grouped) { question in
Text(question.title)
} content: { question in
Text(question.answer)
}
Text("\(expanded.count) open").font(.caption).foregroundStyle(.secondary)
}
.padding()
}
}
}
#Preview("GlassAccordion") { GlassAccordionExample() }
GlassCard
Content container: opaque for dense content, glass when it floats above other content.
import SwiftUI
import SPGlassKit
public struct GlassCardExample: GlassExample {
public static let componentID = "glass-card"
@State private var openCount = 0
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
GlassCard("Monthly rent") {
Text("1,450 $").font(.title2)
Text("Sample listing · 4½ · Plateau").foregroundStyle(.secondary)
}
GlassCard {
Text("A long description wraps on several lines and stays readable because the card is opaque: dense text never sits on glass.")
} header: {
Label("About this place", systemImage: "text.alignleft")
} footer: {
Text("Fictitious data")
}
GlassCard {
// Any view: a photo, a map, a drawing. Give it a height.
Rectangle().fill(.tint.opacity(0.25)).frame(height: 120)
.overlay { Image(systemName: "building.2").font(.largeTitle).foregroundStyle(.tint) }
.accessibilityHidden(true)
} content: {
Text("Two bedrooms · 74 m² · Balcony").foregroundStyle(.secondary)
} header: {
Text("Loft on the canal")
} footer: {
Label("Available 1 July", systemImage: "calendar")
}
GlassCard(style: .floating, action: { openCount += 1 }) {
Label("3 listings nearby", systemImage: "mappin.and.ellipse")
Text("Opened \(openCount) times").font(.caption)
}
.accessibilityHint("Opens the list")
}
.padding()
}
}
}
#Preview("GlassCard") { GlassCardExample().glassTheme(.ocean) }
GlassPanel
Floating panel of actions, resizable on macOS, with managed focus.
import SwiftUI
import SPGlassKit
public struct GlassPanelExample: GlassExample {
public static let componentID = "glass-panel"
@State private var isShown = true
@State private var showsTransit = true
@State private var showsTraffic = false
@State private var size = CGSize(width: 300, height: 220)
public init() {}
public var body: some View {
ZStack {
LinearGradient(colors: [.teal, .indigo], startPoint: .topLeading, endPoint: .bottomTrailing)
.ignoresSafeArea()
.accessibilityHidden(true)
if isShown {
GlassPanel(
"Layers",
size: $size,
sizeLimits: GlassPanelSizeLimits(minimum: CGSize(width: 240, height: 180), maximum: CGSize(width: 480, height: 360)),
onClose: { isShown = false }
) {
Toggle("Transit", isOn: $showsTransit)
Toggle("Traffic", isOn: $showsTraffic)
}
.padding()
} else {
GlassButton("Show layers", systemImage: "square.3.layers.3d") { isShown = true }
}
}
}
}
#Preview("GlassPanel") { GlassPanelExample() }
GlassPopover
System popover with anchoring, compact adaptation and an accessible close action.
import SwiftUI
import SPGlassKit
public struct GlassPopoverExample: GlassExample {
public static let componentID = "glass-popover"
@State private var showsDetails = false
@State private var showsHelp = false
public init() {}
public var body: some View {
HStack(spacing: 24) {
GlassIconButton(systemImage: "info", accessibilityLabel: "Price details") { showsDetails = true }
.glassPopover(isPresented: $showsDetails, title: "Price details", arrowEdge: .top, compactAdaptation: .popover) {
Text("Sample price, taxes included.")
.padding()
.frame(minWidth: 220, alignment: .leading)
}
GlassButton("Help", systemImage: "questionmark.circle") { showsHelp = true }
.glassPopover(isPresented: $showsHelp, title: "Help", compactAdaptation: .sheet) {
Text("On a compact width this popover becomes a sheet with a close button.")
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding()
}
}
#Preview("GlassPopover") { GlassPopoverExample() }
GlassSheet
System sheet with detents, keyboard handling and an accessible close action.
import SwiftUI
import SPGlassKit
public struct GlassSheetExample: GlassExample {
public static let componentID = "glass-sheet"
@State private var showsFilters = false
@State private var showsTerms = false
@State private var keyword = ""
@State private var onlyAvailable = true
public init() {}
public var body: some View {
VStack(spacing: 16) {
GlassButton("Filters", systemImage: "line.3.horizontal.decrease") { showsFilters = true }
GlassButton("Terms of use") { showsTerms = true }
}
.padding()
.glassSheet(isPresented: $showsFilters, title: "Filters", configuration: .halfAndFull) {
Form {
TextField("Keyword", text: $keyword)
Toggle("Only available", isOn: $onlyAvailable)
}
}
.glassSheet(
isPresented: $showsTerms,
title: "Terms of use",
configuration: GlassSheetConfiguration(detents: [.fraction(0.4), .large], isInteractiveDismissDisabled: true)
) {
ScrollView {
Text("Sample terms. This sheet cannot be swiped away: the close button is the way out.")
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
}
}
}
}
#Preview("GlassSheet") { GlassSheetExample() }
Feedback
GlassAlert
System alert and confirmation dialog described by a value with correct button roles.
import SwiftUI
import SPGlassKit
public struct GlassAlertExample: GlassExample {
public static let componentID = "glass-alert"
@State private var alert: GlassAlert?
@State private var outcome = "Nothing chosen yet"
public init() {}
public var body: some View {
VStack(spacing: 16) {
GlassButton("Show information") {
alert = GlassAlert(title: "Export finished", message: "The sample file was written to Documents.")
}
GlassButton("Unsaved changes…") {
alert = GlassAlert(
title: "Save changes?",
message: "Your edits to “Budget 2027” will be lost otherwise.",
buttons: [
GlassAlertButton("Save") { outcome = "Saved" },
.destructive("Discard") { outcome = "Discarded" },
.cancel { outcome = "Cancelled" },
]
)
}
GlassButton("Delete draft…", systemImage: "trash", role: .destructive) {
// No cancel button is given: validation adds one because the only action is destructive.
alert = GlassAlert(
title: "Delete this draft?",
message: "This cannot be undone.",
style: .confirmation,
buttons: [.destructive("Delete draft") { outcome = "Deleted" }]
)
}
Text(outcome).font(.callout).foregroundStyle(.secondary)
}
.padding()
.glassAlert($alert)
}
}
#Preview("GlassAlert") { GlassAlertExample() }
GlassBadge
Count, value or status marker that never relies on colour alone.
import SwiftUI
import SPGlassKit
public struct GlassBadgeExample: GlassExample {
public static let componentID = "glass-badge"
@State private var unread = 7
public init() {}
public var body: some View {
VStack(alignment: .leading, spacing: 16) {
HStack(spacing: 12) {
Text("Inbox")
GlassBadge(count: unread)
Spacer()
Stepper("Unread", value: $unread, in: -1...150, step: 31).labelsHidden()
}
HStack(spacing: 12) {
GlassBadge("New", tone: .accent)
GlassBadge("Beta")
GlassBadge("−12 %", tone: .critical)
GlassBadge(count: 0, showsZero: true, tone: .neutral)
}
HStack(spacing: 12) {
GlassBadge("Paid", tone: .success, style: .soft)
GlassBadge("Due soon", tone: .warning, style: .soft)
GlassBadge("Draft", style: .outline)
GlassBadge(status: "Online", tone: .success, style: .soft)
}
Image(systemName: "bell")
.font(.title2)
.frame(width: 44, height: 44)
.glassBadge(count: unread)
.accessibilityLabel("Notifications")
VStack(alignment: .leading, spacing: 8) {
GlassBadge(status: "Online", tone: .success)
GlassBadge(status: "Degraded", tone: .warning)
GlassBadge(status: "Offline", tone: .critical)
GlassBadge(status: "Unknown", tone: .neutral)
}
}
.padding()
}
}
#Preview("GlassBadge") { GlassBadgeExample().glassTheme(.aurora) }
GlassBanner
Inline information, success, warning or error message with icon, text and dismissal.
import SwiftUI
import SPGlassKit
public struct GlassBannerExample: GlassExample {
public static let componentID = "glass-banner"
@State private var showsWarning = true
@State private var retryCount = 0
public init() {}
public var body: some View {
ScrollView {
VStack(spacing: 12) {
GlassBanner(.information, title: "Maintenance on Sunday", message: "The sample service will be read-only from 2:00 to 4:00.")
GlassBanner(.success, title: "Payment received")
if showsWarning {
GlassBanner(
.warning,
title: "Your card expires soon",
message: "Update your payment method before the end of the month to avoid an interruption.",
action: GlassBannerAction("Update card") { showsWarning = false },
onDismiss: { showsWarning = false }
)
}
GlassBanner(
.error,
verbatim: "Synchronisation failed (attempt \(retryCount + 1))",
message: "The server did not answer.",
action: GlassBannerAction("Retry") { retryCount += 1 }
)
}
.padding()
}
}
}
#Preview("GlassBanner") { GlassBannerExample().glassTheme(.emerald) }
GlassProgress
Determinate or indeterminate system progress with an optional cancel action.
import SwiftUI
import SPGlassKit
public struct GlassProgressExample: GlassExample {
public static let componentID = "glass-progress"
@State private var uploaded = 30.0
@State private var isCancelled = false
public init() {}
public var body: some View {
VStack(alignment: .leading, spacing: 20) {
if isCancelled {
Text("Upload cancelled").foregroundStyle(.secondary)
} else {
GlassProgress("Uploading sample.pdf", value: uploaded, total: 120, onCancel: { isCancelled = true })
}
GlassProgress("Storage used", value: 0.82, style: .circular)
GlassProgress("Connecting")
GlassProgress(style: .circular)
HStack(spacing: 24) {
GlassProgress("Storage", value: 0.82, style: .ring)
GlassProgress("Battery", value: 0.46, style: .ring)
}
GlassProgress("Shipping address", step: 2, of: 4)
HStack {
GlassButton("Add 30 MB") { uploaded += 30 }
GlassButton("Restart") {
uploaded = 0
isCancelled = false
}
}
}
.padding()
}
}
#Preview("GlassProgress") { GlassProgressExample() }
GlassToast
Transient message with a bounded queue, duration, optional action and an accessibility announcement.
import SwiftUI
import SPGlassKit
public struct GlassToastExample: GlassExample {
public static let componentID = "glass-toast"
@State private var toasts = GlassToastCenter(capacity: 3)
@State private var savedCount = 0
@State private var restored = false
public init() {}
public var body: some View {
VStack(spacing: 16) {
GlassButton("Save draft", systemImage: "tray.and.arrow.down") {
savedCount += 1
// A stable identifier: saving twice replaces the toast instead of stacking a duplicate.
toasts.show(GlassToast("Draft saved (\(savedCount))", systemImage: "checkmark.circle", id: "saved"))
}
GlassButton("Delete message", systemImage: "trash", role: .destructive) {
restored = false
toasts.show(GlassToast("Message deleted", systemImage: "trash", action: GlassToastAction("Undo") { restored = true }))
}
GlassButton("Show offline notice", systemImage: "wifi.slash") {
toasts.show(.persistent("You are offline", title: "Connection", systemImage: "wifi.slash", id: "offline"))
}
GlassButton("Dismiss all") { toasts.dismissAll() }
Text(restored ? "Message restored" : "\(toasts.toasts.count) toasts on screen")
.font(.callout)
.foregroundStyle(.secondary)
}
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.glassToastHost(toasts)
}
}
#Preview("GlassToast") { GlassToastExample() }
Data
GlassChart
Swift Charts line, bar and area charts with axes, units and accessible descriptions.
import SwiftUI
import SPGlassKit
public struct GlassChartExample: GlassExample {
public static let componentID = "glass-chart"
// Fictitious data: energy produced by two imaginary sites.
private static let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
private static let north: [Double] = [42, 48, 55, 61, 58, 70]
private static let south: [Double] = [65, 60, 57, 52, 49, 44]
private static let production: [GlassChartPoint] =
zip(months, north).map { GlassChartPoint(label: $0, value: $1, series: "North") }
+ zip(months, south).map { GlassChartPoint(label: $0, value: $1, series: "South") }
private static let visits: [GlassChartPoint] = {
let start = Date(timeIntervalSince1970: 1_780_272_000)
let values: [Double] = [120, 135, 128, 160, 190, 240, 210]
return values.enumerated().map { GlassChartPoint(date: start.addingTimeInterval(Double($0.offset) * 86_400), value: $0.element) }
}()
@State private var kind = GlassChartKind.line
@State private var series = "All"
public init() {}
private var visibleProduction: [GlassChartPoint] {
series == "All" ? Self.production : Self.production.filter { $0.series == series }
}
public var body: some View {
ScrollView {
VStack(spacing: 16) {
Picker("Mark", selection: $kind) {
Text("Line").tag(GlassChartKind.line)
Text("Bar").tag(GlassChartKind.bar)
Text("Area").tag(GlassChartKind.area)
}
.pickerStyle(.segmented)
GlassChart("Energy produced", points: visibleProduction, kind: kind, xAxisTitle: "Month", yAxisTitle: "Energy", unit: "MWh") {
Picker("Series", selection: $series) {
Text("All").tag("All")
ForEach(GlassChartLogic.seriesNames(Self.production), id: \.self) { Text(verbatim: $0).tag($0) }
}
.pickerStyle(.menu)
}
GlassChart("Daily visits", points: Self.visits, kind: .area, xAxisTitle: "Day", yAxisTitle: "Visits")
GlassChart("Nothing measured yet", points: [])
}
.padding()
}
}
}
#Preview("GlassChart") { GlassChartExample().glassTheme(.ocean) }
GlassDataGrid
Lazy grid for large collections with stable identifiers and generic cells.
import SwiftUI
import SPGlassKit
public struct GlassDataGridExample: GlassExample {
public static let componentID = "glass-data-grid"
struct Sample: Identifiable {
let id: Int
var reading: Double { Double((id * 37) % 100) / 100 }
}
/// Thirty thousand fictitious samples, produced on demand: no array of that size is ever built.
struct Samples: RandomAccessCollection {
let count: Int
var startIndex: Int { 0 }
var endIndex: Int { count }
subscript(position: Int) -> Sample { Sample(id: position) }
}
@State private var selection: Set<Int> = [2]
@State private var fixedColumns = false
public init() {}
public var body: some View {
VStack(alignment: .leading, spacing: 12) {
Toggle("Three fixed columns", isOn: $fixedColumns)
Text("\(selection.count) of \(Samples(count: 30_000).count) samples selected")
.font(.callout)
.foregroundStyle(.secondary)
GlassDataGrid(
Samples(count: 30_000),
layout: fixedColumns ? .fixed(3) : .adaptive(minimum: 110),
selection: $selection
) { sample, isSelected in
VStack(alignment: .leading, spacing: 4) {
Text("Sample \(sample.id + 1)")
.font(.headline)
Text(sample.reading, format: .percent.precision(.fractionLength(0)))
.font(.callout.monospacedDigit())
.foregroundStyle(.secondary)
Text(isSelected ? "Selected" : "Tap to select")
.font(.caption)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(12)
.background(.quaternary, in: RoundedRectangle(cornerRadius: 12, style: .continuous))
}
}
.padding()
}
}
#Preview("GlassDataGrid") { GlassDataGridExample() }
GlassMetricCard
A value with unit, change and period, and states for missing, loading and failed data.
import SwiftUI
import SPGlassKit
public struct GlassMetricCardExample: GlassExample {
public static let componentID = "glass-metric-card"
// Fictitious figures.
@State private var latency: GlassLoadState<GlassMetric> = .loaded(
GlassMetric(value: 182, unit: "ms", change: -0.062, period: "vs last week", tone: .negativeIsGood)
)
public init() {}
public var body: some View {
ScrollView {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 220), spacing: 12)], spacing: 12) {
GlassMetricCard("Response time", state: latency) {
latency = .loaded(GlassMetric(value: 175, unit: "ms", change: -0.098, period: "vs last week", tone: .negativeIsGood))
}
GlassMetricCard("Monthly revenue", state: .loaded(
GlassMetric(value: 48_250.5, unit: "$", change: 0.042, period: "vs last month", fractionDigits: 2...2, tone: .positiveIsGood)
))
GlassMetricCard("Bookings", systemImage: "calendar", state: .loaded(
GlassMetric(value: 1284, change: 0.082, period: "vs last week", tone: .positiveIsGood, sparkline: [31, 34, 33, 38, 41, 40, 46])
))
GlassMetricCard("Open tickets", state: .loaded(GlassMetric(value: 37, change: 0, period: "since yesterday")))
GlassMetricCard("Active sessions", state: .loading)
GlassMetricCard("Conversion", state: .empty)
GlassMetricCard("Forecast", state: .idle)
GlassMetricCard("Churn", state: .failed(message: "The report could not be loaded.")) {}
}
.padding()
HStack {
GlassButton("Simulate a failure", size: .small) { latency = .failed(message: "The probe did not answer.") }
GlassButton("Reload", size: .small) { latency = .loading }
}
.padding(.bottom)
}
}
}
#Preview("GlassMetricCard") { GlassMetricCardExample().glassTheme(.emerald) }
GlassTable
System Table where available and a List elsewhere, with typed sorting and selection.
import SwiftUI
import SPGlassKit
public struct GlassTableExample: GlassExample {
public static let componentID = "glass-table"
struct Station: Identifiable {
let id: String
let name: String
let line: String
let dailyRiders: Int
let opened: Int
}
// Fictitious data.
private let stations = [
Station(id: "s1", name: "Harbour Square", line: "Blue", dailyRiders: 48_200, opened: 1987),
Station(id: "s2", name: "Élan–Université", line: "Green", dailyRiders: 31_750, opened: 2004),
Station(id: "s3", name: "North Mills", line: "Blue", dailyRiders: 9_640, opened: 1991),
Station(id: "s4", name: "Parc des Érables", line: "Orange", dailyRiders: 22_310, opened: 2016),
Station(id: "s5", name: "Old Foundry", line: "Green", dailyRiders: 9_640, opened: 1979),
]
private let columns: [GlassTableColumn<Station>] = [
GlassTableColumn("Station", id: "name") { $0.name },
GlassTableColumn("Line", id: "line") { $0.line }
.badged { _ in .neutral },
GlassTableColumn("Daily riders", id: "riders", sortingBy: { $0.dailyRiders }) { $0.dailyRiders.formatted(.number) }
.aligned(.trailing),
GlassTableColumn("Opened", id: "opened", sortingBy: { $0.opened }) { $0.opened.formatted(.number.grouping(.never)) }
.aligned(.trailing),
]
@State private var sort: GlassTableSort? = GlassTableSort(columnID: "riders", order: .reverse)
@State private var selection: Set<String> = ["s2"]
@State private var showsEmpty = false
public init() {}
public var body: some View {
VStack(alignment: .leading, spacing: 12) {
Toggle("Show the empty state", isOn: $showsEmpty)
Text("\(selection.count) selected")
.font(.callout)
.foregroundStyle(.secondary)
GlassTable(showsEmpty ? [] : stations, columns: columns, sort: $sort, selection: .multiple($selection), emptyTitle: "No station")
.frame(minHeight: 320)
}
.padding()
}
}
#Preview("GlassTable") { GlassTableExample() }
GlassTimeline
Dated events in order, grouped by day and localised, with an empty state.
import SwiftUI
import SPGlassKit
public struct GlassTimelineExample: GlassExample {
public static let componentID = "glass-timeline"
// Fictitious delivery log, relative to a fixed instant so that the example is reproducible.
private static let events: [GlassTimelineEvent] = {
let start = Date(timeIntervalSince1970: 1_780_300_800)
func at(_ hours: Double) -> Date { start.addingTimeInterval(hours * 3600) }
return [
GlassTimelineEvent(id: "ordered", date: at(0), title: "Order placed", detail: "Order A-1042, three items", systemImage: "cart"),
GlassTimelineEvent(id: "paid", date: at(0.2), title: "Payment confirmed"),
GlassTimelineEvent(id: "packed", date: at(21), title: "Parcel packed", detail: "Warehouse 4, aisle 12 — a long note that wraps over several lines on a narrow screen without being cut off."),
GlassTimelineEvent(id: "shipped", date: at(27.5), title: "Handed to the carrier", systemImage: "shippingbox"),
GlassTimelineEvent(id: "transit", date: at(52), title: "In transit 🚚", detail: "مركز الفرز · Centre de tri"),
GlassTimelineEvent(id: "delivered", date: at(76), title: "Delivered", systemImage: "checkmark", tone: .success),
]
}()
@State private var order = GlassTimelineOrder.descending
@State private var showsEmpty = false
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
Picker("Order", selection: $order) {
Text("Newest first").tag(GlassTimelineOrder.descending)
Text("Oldest first").tag(GlassTimelineOrder.ascending)
}
.pickerStyle(.segmented)
Toggle("Show the empty state", isOn: $showsEmpty)
GlassTimeline(showsEmpty ? [] : Self.events, order: order, emptyTitle: "Nothing has happened yet")
}
.padding()
}
}
}
#Preview("GlassTimeline") { GlassTimelineExample() }
#Preview("GlassTimeline — français, Tokyo") {
GlassTimelineExample()
.environment(\.locale, Locale(identifier: "fr_CA"))
.environment(\.timeZone, TimeZone(identifier: "Asia/Tokyo") ?? .gmt)
}
Media
GlassAudioPlayer
Audio transport with play, pause, seek, times and interruption handling; never starts by itself.
import SwiftUI
import SPGlassKit
/// A silent playback engine for the example: it only moves a clock, no audio is produced.
@MainActor
@Observable
final class SampleAudioPlayback: GlassAudioPlayback {
private(set) var isPlaying = false
private(set) var currentTime: TimeInterval = 42
let duration: TimeInterval
let isAvailable: Bool
init(duration: TimeInterval = 215, isAvailable: Bool = true) {
self.duration = duration
self.isAvailable = isAvailable
}
func play() {
guard isAvailable else { return }
if currentTime >= duration { currentTime = 0 }
isPlaying = true
}
func pause() { isPlaying = false }
func seek(to time: TimeInterval) {
currentTime = GlassPlaybackMath.clampedSeek(time, duration: duration)
}
/// Advances the simulated clock; called by the example while "playing".
func advance(by seconds: TimeInterval) {
currentTime = GlassPlaybackMath.clampedSeek(currentTime + seconds, duration: duration)
if currentTime >= duration { isPlaying = false }
}
}
public struct GlassAudioPlayerExample: GlassExample {
public static let componentID = "glass-audio-player"
@State private var playback = SampleAudioPlayback()
@State private var unavailable = SampleAudioPlayback(duration: 0, isAvailable: false)
/// Amplitudes of a fictitious recording, aggregated once.
private static let waveform = GlassWaveformData(samples: GlassWaveformExample.syntheticSamples(count: 9_600), maxBuckets: 64)
public init() {}
public var body: some View {
VStack(spacing: 16) {
GlassAudioPlayer(playback: playback, title: "Harbour Lines", subtitle: "Sample data · simulated clock, no audio", artwork: SampleArtwork.image(1))
GlassAudioPlayer(playback: playback, title: "Harbour Lines", subtitle: "With a waveform as the seek track", skipInterval: 30, waveform: Self.waveform)
GlassAudioPlayer(playback: playback, title: "Harbour Lines", subtitle: "Compact", artwork: SampleArtwork.image(1), style: .compact)
GlassAudioPlayer(playback: unavailable, title: "Missing recording", skipInterval: 30)
}
.padding()
.task(id: playback.isPlaying) {
// The fake engine has no audio clock: tick it while it is "playing".
while playback.isPlaying, !Task.isCancelled {
try? await Task.sleep(for: .milliseconds(500))
if !Task.isCancelled { playback.advance(by: 0.5) }
}
}
}
}
#Preview("GlassAudioPlayer") { GlassAudioPlayerExample().glassTheme(.ocean) }
GlassGallery
Lazy image grid with a zoomable viewer, navigation and cancellable loading.
import SwiftUI
import CoreGraphics
import SPGlassKit
public struct GlassGalleryExample: GlassExample {
public static let componentID = "glass-gallery"
public init() {}
public var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text("Sample data · drawings and gradients generated in code, one slow image and one failing image.")
.font(.caption)
.foregroundStyle(.secondary)
.padding(.horizontal)
GlassGallery(items: Self.items, cacheCapacity: 12, layout: .featured, selection: "drawing-1")
}
}
private struct SampleLoadingError: Error {}
static let items: [GlassGalleryItem] = {
let names = ["Dawn", "Lagoon", "Orchard", "Ember", "Glacier", "Dusk", "Moss", "Coral", "Slate", "Saffron", "Iris", "Tundra"]
var items = names.enumerated().map { index, name in
GlassGalleryItem(id: "gradient-\(index)", description: "\(name) gradient", loadCGImage: {
// Stands in for decoding a file; the sleep makes cancellation observable while scrolling.
try await Task.sleep(for: .milliseconds(index == 3 ? 1_500 : 120))
return try gradient(hue: Double(index) / Double(names.count))
})
}
// Local images, already in memory: the drawn compositions of the examples.
for index in (0..<6).reversed() {
items.insert(GlassGalleryItem(id: "drawing-\(index)", description: SampleArtwork.title(index), image: SampleArtwork.image(index)), at: 0)
}
items.insert(GlassGalleryItem(id: "broken", description: "An image that fails to load", load: { throw SampleLoadingError() }), at: 8)
return items
}()
/// Draws a diagonal two-colour gradient into a bitmap.
nonisolated static func gradient(hue: Double, side: Int = 256) throws -> CGImage {
let space = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
throw SampleLoadingError()
}
let colors = [rgb(hue: hue), rgb(hue: (hue + 0.18).truncatingRemainder(dividingBy: 1))] as CFArray
guard let gradient = CGGradient(colorsSpace: space, colors: colors, locations: [0, 1]) else {
throw SampleLoadingError()
}
context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: side, y: side), options: [])
guard let image = context.makeImage() else { throw SampleLoadingError() }
return image
}
/// A saturated colour for a hue in 0…1, without any platform colour type.
nonisolated private static func rgb(hue: Double) -> CGColor {
let sector = hue * 6
let x = 1 - abs(sector.truncatingRemainder(dividingBy: 2) - 1)
let (r, g, b): (Double, Double, Double) = switch Int(sector) % 6 {
case 0: (1, x, 0)
case 1: (x, 1, 0)
case 2: (0, 1, x)
case 3: (0, x, 1)
case 4: (x, 0, 1)
default: (1, 0, x)
}
return CGColor(red: 0.25 + 0.6 * r, green: 0.25 + 0.6 * g, blue: 0.25 + 0.6 * b, alpha: 1)
}
}
#Preview("GlassGallery") { GlassGalleryExample().glassTheme(.crystal) }
GlassVideoPlayer
AVKit video player with system controls and full screen where the platform offers it.
import SwiftUI
import AVFoundation
import SPGlassKit
public struct GlassVideoPlayerExample: GlassExample {
public static let componentID = "glass-video-player"
/// An empty player: the repository ships no media file, so the example shows the states without a video.
@State private var emptyPlayer = AVPlayer()
/// A silent clock: it drives the glass controls drawn over a poster.
@State private var playback = SampleAudioPlayback(duration: 134)
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
Text("Glass controls over a drawn poster")
.font(.headline)
GlassVideoControls(playback: playback, title: "The Shore House · Trailer") {
SampleArtwork(3)
}
Text("No player")
.font(.headline)
GlassVideoPlayer(player: nil, accessibilityLabel: "Trailer")
Text("Player without an item, 4:3")
.font(.headline)
GlassVideoPlayer(player: emptyPlayer, aspectRatio: 4.0 / 3.0, accessibilityLabel: "Lecture recording")
Text("Missing URL")
.font(.headline)
GlassVideoPlayer(url: nil)
Text("Sample data · give the player a real URL to see the system controls.")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding()
}
.task(id: playback.isPlaying) {
// The fake engine has no clock of its own: tick it while it is "playing".
while playback.isPlaying, !Task.isCancelled {
try? await Task.sleep(for: .milliseconds(500))
if !Task.isCancelled { playback.advance(by: 0.5) }
}
}
}
}
#Preview("GlassVideoPlayer") { GlassVideoPlayerExample().glassTheme(.obsidian) }
GlassVolumeControl
Volume of the application's own playback, with mute.
import SwiftUI
import SPGlassKit
public struct GlassVolumeControlExample: GlassExample {
public static let componentID = "glass-volume-control"
@State private var musicVolume = 0.65
@State private var effectsVolume = 0.0
public init() {}
public var body: some View {
Form {
Section("Music") {
GlassVolumeControl(volume: $musicVolume, showsValue: true)
LabeledContent("Level applied to the player", value: musicVolume, format: .percent.precision(.fractionLength(0)))
}
Section("Effects (starts muted)") {
GlassVolumeControl(volume: $effectsVolume, unmuteLevel: 0.4)
}
Section("Disabled") {
GlassVolumeControl(volume: .constant(0.3))
.disabled(true)
}
}
.formStyle(.grouped)
}
}
#Preview("GlassVolumeControl") { GlassVolumeControlExample().glassTheme(.emerald) }
GlassWaveform
Bounded, aggregated audio samples drawn with Canvas and described in text.
import SwiftUI
import SPGlassKit
public struct GlassWaveformExample: GlassExample {
public static let componentID = "glass-waveform"
/// Aggregated once, when the example is created, not on every frame.
@State private var voice = GlassWaveformData(samples: Self.syntheticSamples(count: 48_000), maxBuckets: 96, aggregation: .rms)
@State private var peaks = GlassWaveformData(samples: Self.syntheticSamples(count: 48_000), maxBuckets: 160)
@State private var progress = 0.35
public init() {}
public var body: some View {
VStack(alignment: .leading, spacing: 16) {
Text("RMS, 96 buckets, with progress")
.font(.headline)
GlassWaveform(voice, progress: progress)
Slider(value: $progress, in: 0...1) { Text("Progress") }
Text("Peak, 160 buckets")
.font(.headline)
GlassWaveform(peaks, minimumHeight: 72)
Text("Progress without the playhead")
.font(.headline)
GlassWaveform(voice, progress: progress, showsPlayhead: false)
Text("No samples")
.font(.headline)
GlassWaveform(.empty, minimumHeight: 24)
Text("Sample data · a synthetic signal built from sine waves.")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding()
}
/// A deterministic signal: a carrier shaped by two slow envelopes.
static func syntheticSamples(count: Int) -> [Float] {
(0..<count).map { index in
let t = Double(index) / Double(count)
let envelope = 0.55 + 0.45 * sin(t * .pi * 6)
let swell = 0.6 + 0.4 * cos(t * .pi * 17)
return Float(sin(Double(index) * 0.21) * envelope * swell)
}
}
}
#Preview("GlassWaveform") { GlassWaveformExample().glassTheme(.aurora) }
Maps
GlassCompass
Compass driven by an injected heading, with reset to north and an unavailable state.
import SwiftUI
import SPGlassKit
public struct GlassCompassExample: GlassExample {
public static let componentID = "glass-compass"
@State private var heading = 315.0
@State private var resetCount = 0
public init() {}
public var body: some View {
VStack(spacing: 16) {
SampleMapBackdrop(heading: heading)
.overlay(alignment: .topTrailing) {
VStack(spacing: 12) {
GlassCompass(heading: heading, size: .large) {
heading = 0
resetCount += 1
}
GlassCompass(heading: heading) { heading = 0 }
GlassCompass(heading: heading, size: .small) { heading = 0 }
GlassCompass(heading: nil) {}
}
.padding()
}
Slider(value: $heading, in: 0...359, step: 1) { Text("Heading") }
.padding(.horizontal)
Text("Heading \(Int(heading))° · reset to north \(resetCount) times · the last compass has no heading")
.font(.caption)
.foregroundStyle(.secondary)
.padding(.horizontal)
}
.padding(.bottom)
}
}
#Preview("GlassCompass") { GlassCompassExample().glassTheme(.crystal) }
GlassLocationButton
Location action with injected state; permission is requested by the host application only.
import SwiftUI
import SPGlassKit
public struct GlassLocationButtonExample: GlassExample {
public static let componentID = "glass-location-button"
/// The example plays the host's role with a simulated state: no permission is requested, no position is read.
@State private var state = GlassLocationState.idle
@State private var message = "Sample data · simulated states, no location access"
public init() {}
public var body: some View {
VStack(spacing: 16) {
SampleMapBackdrop()
.overlay(alignment: .bottomTrailing) {
GlassLocationButton(state: state, hint: hint) { advance() }
.padding()
}
Picker("Simulated state", selection: $state) {
ForEach(GlassLocationState.allCases, id: \.self) { state in
Text(GlassLocationPresentation(state).label).tag(state)
}
}
.padding(.horizontal)
HStack(spacing: 12) {
ForEach(GlassLocationState.allCases, id: \.self) { state in
GlassLocationButton(state: state, size: .small) {}
}
}
Text(message)
.font(.caption)
.foregroundStyle(.secondary)
.padding(.horizontal)
}
.padding(.bottom)
}
private var hint: String? {
switch state {
case .denied: "Location access was refused. Activating the button would open Settings in a real application."
case .unavailable: "Location services are off on this device."
default: nil
}
}
/// What a host might do on a tap, simulated.
private func advance() {
switch state {
case .idle:
state = .locating
message = "The host would start location updates here."
case .locating:
state = .following
message = "A position arrived: the map follows it."
case .following:
state = .idle
message = "Following stopped."
case .denied:
message = "The host would open Settings here."
case .unavailable:
break
}
}
}
#Preview("GlassLocationButton") { GlassLocationButtonExample().glassTheme(.emerald) }
GlassMapControls
Zoom and orientation actions in a glass container, independent of the map provider.
import SwiftUI
import SPGlassKit
#if canImport(MapKit)
import MapKit
#endif
public struct GlassMapControlsExample: GlassExample {
public static let componentID = "glass-map-controls"
@State private var engine = SampleMapEngine()
#if canImport(MapKit)
@State private var usesMapKit = false
@State private var mapKitEngine = GlassMapKitEngine(
position: .camera(MapCamera(centerCoordinate: CLLocationCoordinate2D(latitude: 45.4215, longitude: -75.6972), distance: 6_000, heading: 30))
)
#endif
public init() {}
public var body: some View {
VStack(spacing: 12) {
#if canImport(MapKit)
Toggle("Use the MapKit adapter (loads map tiles)", isOn: $usesMapKit)
.padding(.horizontal)
if usesMapKit {
mapKitMap
} else {
placeholderMap
}
#else
placeholderMap
#endif
}
}
/// A provider-independent engine: the controls only see `GlassMapEngine`.
private var placeholderMap: some View {
SampleMapBackdrop(heading: engine.heading ?? 0, zoom: engine.zoomScale)
.overlay(alignment: .topTrailing) {
GlassMapControls(engine: engine) {
GlassCompass(heading: engine.heading) { engine.resetNorth() }
GlassIconButton(systemImage: "rotate.right", accessibilityLabel: "Rotate the sample map") {
engine.rotate(by: 45)
}
}
.padding()
}
.overlay(alignment: .bottom) {
GlassMapControls(canZoomIn: engine.canZoomIn, canZoomOut: engine.canZoomOut, axis: .horizontal, size: .small) {
engine.zoomIn()
} onZoomOut: {
engine.zoomOut()
}
.padding(.bottom, 40)
}
}
#if canImport(MapKit)
private var mapKitMap: some View {
Map(position: $mapKitEngine.position)
.onMapCameraChange(frequency: .continuous) { context in
mapKitEngine.cameraChanged(context.camera)
}
.overlay(alignment: .topTrailing) {
GlassMapControls(engine: mapKitEngine)
.padding()
}
}
#endif
}
#Preview("GlassMapControls") { GlassMapControlsExample().glassTheme(.ocean) }
GlassMapPanel
Extensible results panel that keeps the map behind it interactive.
import SwiftUI
import SPGlassKit
public struct GlassMapPanelExample: GlassExample {
public static let componentID = "glass-map-panel"
@State private var isPresented = false
@State private var detent = GlassMapPanelDetent.half
@State private var selection: String?
@State private var query = ""
@State private var engine = SampleMapEngine()
/// Fictitious results.
private let results = [
GlassMapResult(id: "1", title: "Café Exemple", subtitle: "Sample data · café", systemImage: "cup.and.saucer.fill", detail: "120 m"),
GlassMapResult(id: "2", title: "Bibliothèque fictive", subtitle: "Sample data · library", systemImage: "books.vertical.fill", detail: "350 m"),
GlassMapResult(id: "3", title: "A place with a very long name that wraps over several lines in a narrow panel", subtitle: "Sample data · 1.2 km"),
GlassMapResult(id: "4", title: "مقهى تجريبي", subtitle: "Sample data · 2 km", systemImage: "cup.and.saucer"),
GlassMapResult(id: "5", title: "Parc d’essai", subtitle: "Sample data · 2.4 km", systemImage: "tree"),
]
private var filteredResults: [GlassMapResult] {
let trimmed = query.trimmingCharacters(in: .whitespaces)
return trimmed.isEmpty ? results : results.filter { $0.title.localizedStandardContains(trimmed) }
}
public init() {}
public var body: some View {
GlassMapPanel("Nearby", isPresented: $isPresented, detent: $detent) {
SampleMapBackdrop(heading: engine.heading ?? 0, zoom: engine.zoomScale)
.overlay(alignment: .topTrailing) {
// The map and its controls stay usable while the panel is open.
GlassMapControls(engine: engine)
.padding()
}
.overlay(alignment: .bottomTrailing) {
GlassButton(isPresented ? "Hide results" : "Show results", systemImage: "list.bullet") {
isPresented.toggle()
}
.padding()
}
} content: {
VStack(alignment: .leading, spacing: 12) {
TextField("Search sample places", text: $query)
.textFieldStyle(.roundedBorder)
GlassMapResultList(results: filteredResults, selection: selection) { result in
selection = result.id
detent = .peek
}
}
}
}
}
#Preview("GlassMapPanel") { GlassMapPanelExample().glassTheme(.ocean) }
GlassMapPin
Configurable marker with selection and an accessible label; clustering is left to the map engine.
import SwiftUI
import SPGlassKit
public struct GlassMapPinExample: GlassExample {
public static let componentID = "glass-map-pin"
private struct Place: Identifiable {
let id: String
let title: String
let content: GlassMapPinContent
let tint: GlassColorToken
/// Position in the unit square of the placeholder map.
let position: UnitPoint
}
/// Fictitious places.
private let places = [
Place(id: "cafe", title: "Café Exemple", content: .symbol("cup.and.saucer.fill"), tint: .primary, position: UnitPoint(x: 0.25, y: 0.3)),
Place(id: "museum", title: "Musée fictif des très longs noms de lieux", content: .symbol("building.columns.fill"), tint: .accent, position: UnitPoint(x: 0.7, y: 0.25)),
Place(id: "price", title: "Listing A-12", content: .text("$1.2M"), tint: .success, position: UnitPoint(x: 0.5, y: 0.55)),
Place(id: "warning", title: "Road works", content: .symbol("exclamationmark.triangle.fill"), tint: .warning, position: UnitPoint(x: 0.2, y: 0.75)),
]
@State private var selection: String? = "cafe"
public init() {}
public var body: some View {
GeometryReader { proxy in
SampleMapBackdrop()
.overlay {
ForEach(places) { place in
Button {
selection = selection == place.id ? nil : place.id
} label: {
GlassMapPin(place.content, title: place.title, tint: place.tint, isSelected: selection == place.id)
}
.buttonStyle(.plain)
.position(x: proxy.size.width * place.position.x, y: proxy.size.height * place.position.y)
}
// Cluster markers: the count comes from the map engine, the pin only formats it.
GlassMapPin(clusterCount: 12)
.position(x: proxy.size.width * 0.8, y: proxy.size.height * 0.6)
GlassMapPin(clusterCount: 1_340, title: "Downtown")
.position(x: proxy.size.width * 0.75, y: proxy.size.height * 0.8)
}
}
}
}
#Preview("GlassMapPin") { GlassMapPinExample().glassTheme(.solar) }
AI interfaces
GlassAgentPanel
Tasks and observable steps with status, progress, errors and cancellation.
import SwiftUI
import SPGlassKit
public struct GlassAgentPanelExample: GlassExample {
public static let componentID = "glass-agent-panel"
/// Fictitious tasks: nothing is executed, the example only edits these values.
@State private var tasks = [
GlassAgentTask(id: "t1", title: "Prepare the sample weekly digest", status: .running, steps: [
GlassAgentStep(id: "s1", title: "Collect sample notes", status: .succeeded, detail: "12 notes found"),
GlassAgentStep(id: "s2", title: "Group by topic", status: .running, detail: "Topic 3 of 5"),
GlassAgentStep(id: "s3", title: "Write the digest", status: .pending),
]),
GlassAgentTask(id: "t2", title: "Rename sample files with a deliberately long task title that wraps over two lines", status: .failed, steps: [
GlassAgentStep(id: "s1", title: "List files", status: .succeeded),
GlassAgentStep(id: "s2", title: "Apply new names", status: .failed, detail: "4 of 9 renamed", errorMessage: "Sample failure: a file with this name already exists."),
]),
GlassAgentTask(id: "t3", title: "Translate sample page", status: .succeeded, steps: [
GlassAgentStep(id: "s1", title: "Detect language", status: .succeeded),
GlassAgentStep(id: "s2", title: "Translate", status: .succeeded),
]),
GlassAgentTask(id: "t4", title: "Queued sample export", status: .pending),
GlassAgentTask(id: "t5", title: "Sample clean-up", status: .cancelled, steps: [
GlassAgentStep(id: "s1", title: "Scan", status: .cancelled),
], errorMessage: nil),
]
public init() {}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 12) {
Text("Sample data · simulated tasks, no agent is running")
.font(.caption)
.foregroundStyle(.secondary)
GlassAgentPanel(tasks: tasks) { task in
cancel(task.id)
}
GlassButton("Advance the running task", systemImage: "forward.frame") { advance() }
Divider()
Text("No task")
.font(.headline)
GlassAgentPanel(tasks: [])
}
.padding()
}
}
private func cancel(_ id: String) {
guard let index = tasks.firstIndex(where: { $0.id == id }) else { return }
tasks[index].status = .cancelled
for step in tasks[index].steps.indices where !tasks[index].steps[step].status.isTerminal {
tasks[index].steps[step].status = .cancelled
}
}
/// Completes the running step of the first running task and starts the next one.
private func advance() {
guard let index = tasks.firstIndex(where: { $0.status == .running }) else { return }
if let running = tasks[index].steps.firstIndex(where: { $0.status == .running }) {
tasks[index].steps[running].status = .succeeded
}
if let next = tasks[index].steps.firstIndex(where: { $0.status == .pending }) {
tasks[index].steps[next].status = .running
} else {
tasks[index].status = .succeeded
}
}
}
#Preview("GlassAgentPanel") { GlassAgentPanelExample().glassTheme(.obsidian) }
GlassChatBubble
Message bubble with role, streaming state, text selection and copy.
import SwiftUI
import SPGlassKit
public struct GlassChatBubbleExample: GlassExample {
public static let componentID = "glass-chat-bubble"
/// Fictitious conversation: no model produced these messages.
@State private var messages = [
GlassChatMessage(id: "1", role: .system, text: "Sample data — this conversation is fictitious."),
GlassChatMessage(id: "2", role: .user, text: "Can you summarise the sample quarterly note in two sentences? 🙂"),
GlassChatMessage(id: "3", role: .assistant, text: "Certainly. The sample note reports steady demand and a slightly lower margin. It expects the next quarter to look similar, with one new product line."),
GlassChatMessage(id: "4", role: .tool, text: "{\n \"tool\": \"sample_lookup\",\n \"rows\": 3,\n \"a_very_long_key_without_any_space_to_test_wrapping_inside_the_bubble\": true\n}"),
GlassChatMessage(id: "4b", role: .assistant, text: "The note says:\n> Demand stayed steady over the quarter.\nAs a filter:\n```swift\nlet steady = notes.filter { $0.demand == .steady }\n```"),
GlassChatMessage(id: "5", role: .user, text: "هل يمكنك كتابة الخلاصة بالعربية؟"),
GlassChatMessage(id: "6", role: .assistant, text: "The sample answer is still being writ", state: .streaming),
GlassChatMessage(id: "7", role: .assistant, text: "", state: .streaming),
GlassChatMessage(id: "8", role: .assistant, text: "A partial sample answer that stopped.", state: .failed(reason: "Sample failure: the connection was interrupted.")),
]
@State private var lastCopied = "Nothing copied yet"
@State private var retryCount = 0
public init() {}
public var body: some View {
ScrollView {
LazyVStack(spacing: 12) {
ForEach(messages) { message in
GlassChatBubble(
message,
usesMonospacedFont: message.role == .tool,
onCopy: { text in lastCopied = "Copied \(text.count) characters (kept inside the example)" },
onRetry: { retryCount += 1 }
)
}
Text("\(lastCopied) · retried \(retryCount) times")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding()
}
}
}
#Preview("GlassChatBubble") { GlassChatBubbleExample().glassTheme(.aurora) }
GlassModelPicker
Picker over an injected list of models with capabilities and local or remote state.
import SwiftUI
import SPGlassKit
public struct GlassModelPickerExample: GlassExample {
public static let componentID = "glass-model-picker"
/// Fictitious models and providers.
private let models = [
GlassModelInfo(id: "sample-nano", name: "Sample Nano", provider: "On this device (sample)", capabilities: [.text], availability: .local),
GlassModelInfo(id: "sample-vision", name: "Sample Vision", provider: "On this device (sample)", capabilities: [.text, .vision], availability: .unavailable(reason: "Not downloaded")),
GlassModelInfo(id: "sample-large", name: "Sample Large", provider: "Example Cloud (sample)", capabilities: [.text, .vision, .tools, .reasoning], availability: .remote),
GlassModelInfo(id: "sample-code", name: "Sample Code", provider: "Example Cloud (sample)", capabilities: [.text, .code, .tools], availability: .remote),
GlassModelInfo(id: "sample-voice", name: "Sample Voice", provider: "Example Cloud (sample)", capabilities: [.audio], availability: .unavailable(reason: "Sign-in required")),
]
@State private var selection: String? = "sample-nano"
@State private var emptySelection: String?
public init() {}
public var body: some View {
Form {
Section("Sample data · fictitious models") {
LabeledContent("Model") {
GlassModelPicker(models: models, selection: $selection)
}
if let model = GlassModelCatalog.model(withID: selection, in: models) {
LabeledContent("Runs", value: GlassModelCatalog.subtitle(for: model))
HStack {
ForEach(model.capabilities.descriptors, id: \.self) { capability in
Label(capability.label, systemImage: capability.symbolName)
.font(.caption)
}
}
}
}
Section("As a list") {
GlassModelPicker(models: models, selection: $selection, style: .list)
.listRowInsets(EdgeInsets())
.listRowBackground(Color.clear)
}
Section("No selection yet") {
GlassModelPicker("Choose a sample model", models: models, selection: $emptySelection)
}
Section("Empty list") {
GlassModelPicker(models: [], selection: .constant(nil))
}
}
.formStyle(.grouped)
}
}
#Preview("GlassModelPicker") { GlassModelPickerExample().glassTheme(.ocean) }
GlassPromptBar
Multiline prompt editor with send and stop, attachments through callbacks and keyboard shortcuts.
import SwiftUI
import SPGlassKit
public struct GlassPromptBarExample: GlassExample {
public static let componentID = "glass-prompt-bar"
@State private var draft = ""
@State private var isResponding = false
@State private var sent: [String] = []
@State private var attachments = [
GlassPromptAttachment(id: "a1", name: "sample-report.pdf", systemImage: "doc.richtext"),
GlassPromptAttachment(id: "a2", name: "a-sample-image-with-a-rather-long-file-name.png", systemImage: "photo"),
]
@State private var nextAttachment = 3
@State private var modelID: String? = "sample-large"
/// Fictitious models.
private let models = [
GlassModelInfo(id: "sample-large", name: "Sample Large", provider: "Example Cloud (sample)", capabilities: [.text, .tools], availability: .remote),
GlassModelInfo(id: "sample-nano", name: "Sample Nano", provider: "On this device (sample)", availability: .local),
]
public init() {}
public var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Sample data · nothing is sent anywhere; prompts are only listed below.")
.font(.caption)
.foregroundStyle(.secondary)
ScrollView {
VStack(alignment: .leading, spacing: 8) {
ForEach(Array(sent.enumerated()), id: \.offset) { _, prompt in
Text(prompt)
.frame(maxWidth: .infinity, alignment: .leading)
}
if isResponding {
GlassThinkingIndicator(.writing, label: "Simulating a response")
}
}
}
GlassPromptBar(text: $draft, placeholder: "Ask the sample assistant", isResponding: isResponding, attachments: attachments) { prompt in
sent.append(prompt)
isResponding = true
} onStop: {
isResponding = false
} onAttach: {
// A real host presents its own file importer or photo picker here.
attachments.append(GlassPromptAttachment(id: "a\(nextAttachment)", name: "sample-\(nextAttachment).txt"))
nextAttachment += 1
} onRemoveAttachment: { attachment in
attachments.removeAll { $0.id == attachment.id }
} accessory: {
// Any small control fits here: a model picker, a context chip.
GlassModelPicker(models: models, selection: $modelID)
}
}
.padding()
.task(id: isResponding) {
guard isResponding else { return }
try? await Task.sleep(for: .seconds(3))
if !Task.isCancelled { isResponding = false }
}
}
}
#Preview("GlassPromptBar") { GlassPromptBarExample().glassTheme(.aurora) }
GlassThinkingIndicator
Explicit activity indicator with a reduced-motion form; it never shows presumed reasoning.
import SwiftUI
import SPGlassKit
public struct GlassThinkingIndicatorExample: GlassExample {
public static let componentID = "glass-thinking-indicator"
/// Fictitious activity labels, written by the host — never text coming from a model.
private let stages: [(kind: GlassActivityKind, label: String)] = [
(.thinking, "Preparing the sample answer"),
(.searching, "Searching the sample library"),
(.reading, "Reading 3 sample documents"),
(.writing, "Writing the summary"),
(.waiting, "Waiting for your confirmation"),
]
@State private var stage = 0
public init() {}
public var body: some View {
VStack(alignment: .leading, spacing: 16) {
Text("Sample data · simulated activity")
.font(.caption)
.foregroundStyle(.secondary)
GlassThinkingIndicator(stages[stage].kind, label: stages[stage].label)
GlassButton("Next activity", systemImage: "forward.end") {
stage = (stage + 1) % stages.count
}
Divider()
ForEach(stages.indices, id: \.self) { index in
GlassThinkingIndicator(stages[index].kind, label: stages[index].label, announcesChanges: false)
}
GlassThinkingIndicator(.custom(systemImage: "arrow.down.circle"), label: "Downloading the sample model, which has a long label that wraps on narrow screens", announcesChanges: false)
GlassThinkingIndicator(announcesChanges: false)
GlassThinkingIndicator(.waiting, label: "Plain style, for a status line", announcesChanges: false, style: .plain)
Divider()
Text("Reduce Motion (simulated): static symbol")
.font(.caption)
GlassThinkingIndicator(.searching, label: "Searching the sample library", announcesChanges: false)
.glassSimulatedAccessibility(reduceMotion: true)
}
.padding()
}
}
#Preview("GlassThinkingIndicator") { GlassThinkingIndicatorExample().glassTheme(.crystal) }