示例工程 36-lists-and-navigation

36-lists-and-navigation/Sources/Ch36Kit/Navigation.swift

swift · 7.6 KB

import Foundation
import SwiftUI
 
/// 可编码的路由:用于 `NavigationStack(path:)` 与「恢复上次位置」。
public enum Route: Hashable, Codable, Sendable {
    case library
    case book(UUID)
    case settings
}
 
/// 导航状态:路径即真相,push/pop 都改它。
public struct NavigationModel: Equatable, Sendable {
    public var path: [Route] = []
 
    public init(path: [Route] = []) {
        self.path = path
    }
 
    public mutating func push(_ route: Route) {
        path.append(route)
    }
 
    public mutating func pop() {
        guard !path.isEmpty else { return }
        path.removeLast()
    }
 
    public mutating func popToRoot() {
        path.removeAll()
    }
 
    public func encoded() throws -> Data {
        try JSONEncoder().encode(path)
    }
 
    public static func restored(from data: Data) throws -> NavigationModel {
        NavigationModel(path: try JSONDecoder().decode([Route].self, from: data))
    }
}
 
public struct Book: Identifiable, Hashable, Sendable {
    public let id: UUID
    public var title: String
    public var author: String
 
    public init(id: UUID = UUID(), title: String, author: String) {
        self.id = id
        self.title = title
        self.author = author
    }
}
 
public enum SampleData {
    public static let books: [Book] = [
        Book(
            id: UUID(uuidString: "00000000-0000-0000-0000-000000000001")!, title: "Swift 语言",
            author: "Apple"),
        Book(
            id: UUID(uuidString: "00000000-0000-0000-0000-000000000002")!, title: "SwiftUI",
            author: "Apple"),
        Book(
            id: UUID(uuidString: "00000000-0000-0000-0000-000000000003")!, title: "并发编程",
            author: "wrtx"),
        Book(
            id: UUID(uuidString: "00000000-0000-0000-0000-000000000004")!, title: "App 工程",
            author: "wrtx"),
    ]
}
 
/// 列表:`id` 用稳定 UUID,标题变化不丢状态。
public struct BookList: View {
    public let books: [Book]
 
    public init(books: [Book] = SampleData.books) {
        self.books = books
    }
 
    public var body: some View {
        List(books) { book in
            NavigationLink(value: Route.book(book.id)) {
                HStack {
                    VStack(alignment: .leading, spacing: 2) {
                        Text(book.title).font(.system(size: 13, weight: .medium))
                        Text(book.author)
                            .font(.system(size: 11))
                            .foregroundStyle(.secondary)
                    }
                    Spacer()
                    Text(book.id.uuidString.prefix(4))
                        .font(.system(size: 10, design: .monospaced))
                        .foregroundStyle(.tertiary)
                }
            }
        }
    }
}
 
/// 栈式导航的完整页面。
public struct LibraryScreen: View {
    @State private var navigation = NavigationModel()
 
    public init() {}
 
    public var body: some View {
        NavigationStack(path: $navigation.path) {
            BookList()
                .navigationTitle("书库")
                .navigationDestination(for: Route.self) { route in
                    switch route {
                    case .library:
                        Text("书库")
                    case .book(let id):
                        Text("书籍 \(id.uuidString.prefix(4))")
                    case .settings:
                        Text("设置")
                    }
                }
        }
    }
}
 
/// 截图用的静态列表:避免 `List` 在 `ImageRenderer` 里的滚动容器差异。
public struct StaticBookList: View {
    public let books: [Book]
 
    public init(books: [Book] = SampleData.books) {
        self.books = books
    }
 
    public var body: some View {
        VStack(spacing: 0) {
            ForEach(books) { book in
                HStack {
                    VStack(alignment: .leading, spacing: 2) {
                        Text(book.title).font(.system(size: 13, weight: .medium))
                        Text(book.author).font(.system(size: 11)).foregroundStyle(.secondary)
                    }
                    Spacer()
                    Image(systemName: "chevron.right")
                        .font(.system(size: 10, weight: .semibold))
                        .foregroundStyle(.tertiary)
                }
                .padding(.vertical, 8)
                .padding(.horizontal, 12)
                if book.id != books.last?.id {
                    Divider()
                }
            }
        }
        .frame(width: 320)
        .background(Color.white, in: RoundedRectangle(cornerRadius: 10))
        .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.quaternary))
    }
}
 
/// 截图:三种导航形态的静态预览(栈式 / 分栏 / 多列)。
public struct NavigationStylePreview: View {
    public enum Style: String, CaseIterable, Sendable {
        case stack = "栈式"
        case split = "分栏"
        case columns = "多列"
    }
 
    public let style: Style
 
    public init(style: Style) {
        self.style = style
    }
 
    public var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("\(style.rawValue)导航")
                .font(.system(size: 12, weight: .semibold))
            switch style {
            case .stack:
                stack
            case .split:
                HStack(spacing: 8) {
                    sidebar
                    detail
                }
            case .columns:
                HStack(spacing: 8) {
                    sidebar
                    list
                    detail
                }
            }
        }
        .padding(12)
        .frame(width: 340)
        .background(Color.white, in: RoundedRectangle(cornerRadius: 10))
        .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.quaternary))
    }
 
    private var stack: some View {
        VStack(spacing: 0) {
            HStack(spacing: 6) {
                Text("‹").font(.system(size: 12, weight: .semibold))
                Text("书库").font(.system(size: 10, weight: .medium))
                Spacer()
            }
            .padding(8)
            Divider()
            list
        }
        .frame(height: 120)
    }
 
    private var sidebar: some View {
        VStack(alignment: .leading, spacing: 6) {
            Text("书库").font(.system(size: 10, weight: .semibold))
            ForEach(["全部", "最近", "收藏"], id: \.self) { item in
                Text(item).font(.system(size: 9, design: .monospaced)).foregroundStyle(.secondary)
            }
            Spacer()
        }
        .padding(8)
        .frame(width: 64, height: 120, alignment: .topLeading)
        .background(.quaternary, in: RoundedRectangle(cornerRadius: 6))
    }
 
    private var list: some View {
        VStack(alignment: .leading, spacing: 5) {
            ForEach(SampleData.books.prefix(3)) { book in
                Text(book.title).font(.system(size: 9, design: .monospaced))
            }
            Spacer()
        }
        .padding(8)
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
        .background(.quaternary, in: RoundedRectangle(cornerRadius: 6))
    }
 
    private var detail: some View {
        VStack(alignment: .leading, spacing: 4) {
            Text("详情").font(.system(size: 9, weight: .semibold))
            Text("书籍内容").font(.system(size: 8, design: .monospaced)).foregroundStyle(.secondary)
            Spacer()
        }
        .padding(8)
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
        .background(.quaternary, in: RoundedRectangle(cornerRadius: 6))
    }
}