Components

Cart

Items with quantity steppers, a promo code, totals and checkout. Built in all 5 Effect UI styles, in light and dark mode.

Cart in Prism, light mode
Cart in Prism, dark mode
Prism ProLiquid Glass on living colour.
Cart in Ledger, light mode
Cart in Ledger, dark mode
Ledger FreeCalm, precise, trustworthy.
Cart in Bounce, light mode
Cart in Bounce, dark mode
Bounce ProChunky, tactile, joyful.
Cart in Folio, light mode
Cart in Folio, dark mode
Folio ProEditorial and literary.
Cart in Bloom, light mode
Cart in Bloom, dark mode
Bloom ProSoft, organic, calming.

Source: Ledger

CartView.swift in the free Ledger style. It needs Ledger's Theme.swift, which comes with the style: join early access on the home page and it's emailed to you.

import SwiftUI

// MARK: - Sample data

private struct CartItem: Identifiable {
    let id: Int
    let name: String
    let option: String
    let symbol: String
    /// Product colour, shown as a small chip on the thumbnail. Data, not decoration.
    let finish: Color?
    let price: Double
    var quantity: Int
}

private let starterCart: [CartItem] = [
    CartItem(id: 1, name: "Slim card wallet", option: "Tan · Bridle leather", symbol: "creditcard", finish: Color(hex: "#B4532A"), price: 64.00, quantity: 1),
    CartItem(id: 2, name: "Dot-grid notebook, A5", option: "Pack of 3 · 96 pages", symbol: "book.closed", finish: nil, price: 24.00, quantity: 2),
    CartItem(id: 3, name: "Brass mechanical pencil", option: "0.7 mm lead", symbol: "pencil", finish: Color(hex: "#A08A4E"), price: 38.00, quantity: 1),
    CartItem(id: 4, name: "Desk ledger pad", option: "A4 · 50 sheets", symbol: "list.bullet.rectangle", finish: nil, price: 16.50, quantity: 1),
]

private let promoCodes: [String: Double] = ["WINTER10": 0.10]

// MARK: - Screen

struct CartView: View {
    @State private var items = starterCart
    @State private var code = "WINTER10"
    @State private var appliedCode: String? = "WINTER10"
    @State private var codeRejected = false
    @FocusState private var editingCode: Bool

    private let shipping = 6.00

    private var itemCount: Int { items.reduce(0) { $0 + $1.quantity } }
    private var subtotal: Double { items.reduce(0) { $0 + $1.price * Double($1.quantity) } }
    private var discount: Double {
        guard let appliedCode, let rate = promoCodes[appliedCode] else { return 0 }
        return (subtotal * rate * 100).rounded() / 100
    }
    private var total: Double { subtotal - discount + shipping }

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: Theme.Space.xxl) {
                header
                itemList
                promo
                summary
            }
            .padding(.horizontal, Theme.Space.margin)
            .padding(.top, Theme.Space.sm)
            .padding(.bottom, Theme.Space.xl)
        }
        .scrollIndicators(.hidden)
        .scrollDismissesKeyboard(.interactively)
        .paperBackground()
        .safeAreaInset(edge: .bottom) { checkoutBar }
        .animation(Theme.Motion.stateChange, value: total)
    }

    // MARK: Sections

    private var header: some View {
        VStack(alignment: .leading, spacing: Theme.Space.xl) {
            HStack {
                IconButton(symbol: "chevron.left")
                Spacer()
                Button("Save for later") {}
                    .buttonStyle(TextButtonStyle(color: Theme.onSurfaceVariant))
            }
            ScreenHeader(eyebrow: "\(itemCount) items", title: "Cart")
        }
    }

    private var itemList: some View {
        RuledStack(closed: true) {
            ForEach($items) { $item in
                CartRow(item: $item)
            }
        }
    }

    private var promo: some View {
        VStack(alignment: .leading, spacing: Theme.Space.md) {
            SectionHeader(title: "Promo code")
            HStack(spacing: Theme.Space.sm) {
                Image(systemName: "tag")
                    .font(.system(size: 13, weight: .semibold))
                    .foregroundStyle(Theme.onSurfaceMuted)
                TextField("Enter a code", text: $code)
                    .font(.system(size: 15, weight: .regular, design: .monospaced))
                    .foregroundStyle(Theme.onSurface)
                    .textInputAutocapitalization(.characters)
                    .autocorrectionDisabled()
                    .focused($editingCode)
                    .submitLabel(.done)
                    .onSubmit(apply)
                Button(appliedCode == nil ? "Apply" : "Remove") {
                    if appliedCode == nil { apply() } else { appliedCode = nil; code = "" }
                }
                .buttonStyle(.ledgerText)
            }
            .ledgerField(focused: editingCode, invalid: codeRejected)
            Group {
                if let appliedCode {
                    Label("\(appliedCode) applied: 10% off items", systemImage: "checkmark")
                        .foregroundStyle(Theme.onSurfaceVariant)
                } else if codeRejected {
                    Label("That code isn’t valid. Check the spelling and try again.", systemImage: "exclamationmark.circle")
                        .foregroundStyle(Theme.negative)
                }
            }
            .ledgerType(.bodySm)
            .labelStyle(PromoLabelStyle())
            .transition(.opacity)
        }
        .animation(Theme.Motion.stateChange, value: appliedCode)
        .animation(Theme.Motion.stateChange, value: codeRejected)
        .onChange(of: code) { codeRejected = false }
    }

    private func apply() {
        let normalised = code.trimmingCharacters(in: .whitespaces).uppercased()
        if promoCodes[normalised] != nil {
            appliedCode = normalised
            code = normalised
            codeRejected = false
        } else {
            codeRejected = !normalised.isEmpty
        }
        editingCode = false
    }

    private var summary: some View {
        VStack(alignment: .leading, spacing: 0) {
            SectionHeader(title: "Summary")
            RuledStack {
                LedgerRow(title: "Subtotal", subtitle: "\(itemCount) items") {
                    AmountText(value: subtotal)
                }
                if let appliedCode {
                    LedgerRow(title: "Promo", subtitle: appliedCode) {
                        AmountText(value: -discount)
                    }
                }
                LedgerRow(title: "Shipping", subtitle: "Standard · arrives Dec 2 – 4") {
                    AmountText(value: shipping)
                }
            }
            Hairline(strong: true)
            HStack(alignment: .firstTextBaseline) {
                Text("Total")
                    .ledgerType(.headlineMd)
                    .foregroundStyle(Theme.onSurface)
                Spacer()
                Text(Money.format(total, decimals: 2))
                    .ledgerType(.numeralLg)
                    .foregroundStyle(Theme.onSurface)
                    .contentTransition(.numericText(value: total))
            }
            .frame(minHeight: Theme.Space.rowHeight + Theme.Space.sm)
        }
    }

    private var checkoutBar: some View {
        BottomActionBar {
            Button {} label: {
                Text("Checkout · \(Money.format(total, decimals: 2))")
                    .contentTransition(.numericText(value: total))
            }
            .buttonStyle(.ledgerPrimary)
            .disabled(items.isEmpty)
            HStack(spacing: Theme.Space.xs) {
                Image(systemName: "lock")
                    .font(.system(size: 11, weight: .semibold))
                Text("Pay with Apple Pay or card. Sales tax is included.")
                    .ledgerType(.bodySm)
            }
            .foregroundStyle(Theme.onSurfaceMuted)
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(.top, Theme.Space.sm)
        }
    }
}

// MARK: - Row

private struct CartRow: View {
    @Binding var item: CartItem

    var body: some View {
        HStack(alignment: .top, spacing: Theme.Space.md) {
            thumbnail
            VStack(alignment: .leading, spacing: Theme.Space.xxs) {
                Text(item.name)
                    .ledgerType(.bodyMd)
                    .foregroundStyle(Theme.onSurface)
                    .lineLimit(1)
                Text(item.option)
                    .ledgerType(.bodySm)
                    .foregroundStyle(Theme.onSurfaceVariant)
                    .lineLimit(1)
                QuantityStepper(quantity: $item.quantity)
                    .padding(.top, Theme.Space.sm)
            }
            Spacer(minLength: Theme.Space.sm)
            VStack(alignment: .trailing, spacing: Theme.Space.xxs) {
                AmountText(value: item.price * Double(item.quantity))
                    .contentTransition(.numericText(value: item.price * Double(item.quantity)))
                if item.quantity > 1 {
                    Text("\(Money.format(item.price, decimals: 2)) each")
                        .font(.system(size: 13, weight: .regular, design: .monospaced))
                        .foregroundStyle(Theme.onSurfaceMuted)
                        .transition(.opacity)
                }
            }
        }
        .padding(.vertical, Theme.Space.lg)
        .animation(Theme.Motion.stateChange, value: item.quantity)
    }

    private var thumbnail: some View {
        RoundedRectangle(cornerRadius: Theme.Radius.md, style: .continuous)
            .fill(Theme.surfaceRaised)
            .frame(width: 56, height: 56)
            .overlay(
                Image(systemName: item.symbol)
                    .font(.system(size: 22, weight: .regular))
                    .foregroundStyle(Theme.onSurface)
            )
            .overlay(alignment: .bottomTrailing) {
                if let finish = item.finish {
                    RoundedRectangle(cornerRadius: 2, style: .continuous)
                        .fill(finish)
                        .frame(width: 10, height: 10)
                        .padding(6)
                }
            }
            .overlay(
                RoundedRectangle(cornerRadius: Theme.Radius.md, style: .continuous)
                    .strokeBorder(Theme.rule, lineWidth: 0.5)
            )
            .accessibilityHidden(true)
    }
}

/// Square-cornered stepper: minus, tabular count, plus, inside a ruled radius-10 box.
private struct QuantityStepper: View {
    @Binding var quantity: Int
    var range: ClosedRange<Int> = 1...9

    var body: some View {
        HStack(spacing: 0) {
            step("minus", enabled: quantity > range.lowerBound) { quantity -= 1 }
            Rectangle().fill(Theme.rule).frame(width: 0.5)
            Text("\(quantity)")
                .font(.system(size: 15, weight: .semibold, design: .monospaced))
                .foregroundStyle(Theme.onSurface)
                .contentTransition(.numericText(value: Double(quantity)))
                .frame(width: 36)
            Rectangle().fill(Theme.rule).frame(width: 0.5)
            step("plus", enabled: quantity < range.upperBound) { quantity += 1 }
        }
        .frame(height: 32)
        .background(RoundedRectangle(cornerRadius: Theme.Radius.md, style: .continuous).fill(Theme.surfaceRaised))
        .overlay(RoundedRectangle(cornerRadius: Theme.Radius.md, style: .continuous).strokeBorder(Theme.rule, lineWidth: 0.5))
        .sensoryFeedback(.selection, trigger: quantity)
        .accessibilityElement(children: .ignore)
        .accessibilityLabel("Quantity")
        .accessibilityValue("\(quantity)")
        .accessibilityAdjustableAction { direction in
            switch direction {
            case .increment: if quantity < range.upperBound { quantity += 1 }
            case .decrement: if quantity > range.lowerBound { quantity -= 1 }
            @unknown default: break
            }
        }
    }

    private func step(_ symbol: String, enabled: Bool, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Image(systemName: symbol)
                .font(.system(size: 11, weight: .semibold))
                .foregroundStyle(Theme.onSurface)
                .frame(width: 32, height: 32)
                .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
        .disabled(!enabled)
        .opacity(enabled ? 1 : 0.3)
    }
}

private struct PromoLabelStyle: LabelStyle {
    func makeBody(configuration: Configuration) -> some View {
        HStack(spacing: Theme.Space.xs) {
            configuration.icon.font(.system(size: 11, weight: .semibold))
            configuration.title
        }
    }
}

#Preview("Light") {
    CartView()
}

#Preview("Dark") {
    CartView().preferredColorScheme(.dark)
}

More screens