示例工程 58-capstone-data-and-navigation

58-capstone-data-and-navigation/Sources/Ch58Kit/Bookmarks.swift

swift · 6.8 KB

import Foundation
import SwiftData
import SwiftUI
 
@Model
public final class Bookmark {
    @Attribute(.unique) public var id: UUID
    public var title: String
    public var url: String
    public var tags: [String]
    public var createdAt: Date
 
    public init(
        id: UUID = UUID(),
        title: String,
        url: String,
        tags: [String] = [],
        createdAt: Date = Date(timeIntervalSince1970: 0)
    ) {
        self.id = id
        self.title = title
        self.url = url
        self.tags = tags
        self.createdAt = createdAt
    }
}
 
public enum Route: Hashable, Codable, Sendable {
    case bookmark(UUID)
    case settings
}
 
public struct NavigationModel: Equatable, Sendable {
    public private(set) var path: [Route] = []
 
    public init(path: [Route] = []) {
        self.path = path
    }
 
    public mutating func open(_ route: Route) {
        path.append(route)
    }
 
    public mutating func pop() {
        guard !path.isEmpty else { return }
        path.removeLast()
    }
 
    public func encoded() throws -> Data {
        try JSONEncoder().encode(path)
    }
 
    public static func restored(_ data: Data) throws -> NavigationModel {
        NavigationModel(path: try JSONDecoder().decode([Route].self, from: data))
    }
}
 
public enum Library {
    public static func makeContainer() throws -> ModelContainer {
        try ModelContainer(
            for: Bookmark.self,
            configurations: ModelConfiguration(isStoredInMemoryOnly: true)
        )
    }
 
    @discardableResult
    public static func add(
        title: String,
        url: String,
        tags: [String] = [],
        in context: ModelContext
    ) -> Bookmark {
        let bookmark = Bookmark(title: title, url: url, tags: tags)
        context.insert(bookmark)
        return bookmark
    }
 
    public static func all(in context: ModelContext) throws -> [Bookmark] {
        try context.fetch(
            FetchDescriptor<Bookmark>(sortBy: [
                SortDescriptor(\.title), SortDescriptor(\.createdAt),
            ])
        )
    }
 
    public static func search(_ query: String, in context: ModelContext) throws -> [Bookmark] {
        let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return try all(in: context) }
        return try all(in: context).filter {
            $0.title.localizedCaseInsensitiveContains(trimmed)
                || $0.url.localizedCaseInsensitiveContains(trimmed)
                || $0.tags.contains { $0.localizedCaseInsensitiveContains(trimmed) }
        }
    }
 
    public static func delete(_ bookmark: Bookmark, in context: ModelContext) {
        context.delete(bookmark)
    }
}
 
public struct BookmarkListModel: Sendable {
    public let title: String
    public let subtitle: String
    public let badge: String
 
    public init(title: String, subtitle: String, badge: String) {
        self.title = title
        self.subtitle = subtitle
        self.badge = badge
    }
 
    public static func rows(from bookmarks: [Bookmark]) -> [BookmarkListModel] {
        bookmarks.map {
            BookmarkListModel(
                title: $0.title,
                subtitle: $0.url,
                badge: $0.tags.first ?? "未分类"
            )
        }
    }
}
 
public struct LibraryBoard: View {
    public init() {}
 
    private let rows = [
        ("Swift 文档", "developer.apple.com", "Swift"),
        ("SwiftData", "developer.apple.com/swiftdata", "Swift"),
        ("OpenCode", "opencode.ai", "工具"),
        ("本地笔记", "file:///notes.md", "未分类"),
    ]
 
    public var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("书签管理器").font(.system(size: 18, weight: .semibold))
            ForEach(rows, id: \.0) { row in
                HStack(spacing: 10) {
                    VStack(alignment: .leading, spacing: 2) {
                        Text(row.0).font(.system(size: 12, weight: .medium))
                        Text(row.1)
                            .font(.system(size: 10, design: .monospaced))
                            .foregroundStyle(.secondary)
                    }
                    Spacer()
                    Text(row.2)
                        .font(.system(size: 9, design: .monospaced))
                        .padding(.horizontal, 6)
                        .padding(.vertical, 2)
                        .background(.quaternary, in: Capsule())
                }
            }
        }
        .padding(18)
        .frame(width: 340, alignment: .leading)
        .background(Color.white)
        .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.quaternary))
    }
}
 
public struct BookmarksEmptyBoard: View {
    public init() {}
 
    public var body: some View {
        VStack(spacing: 8) {
            Text("还没有书签")
                .font(.system(size: 15, weight: .semibold))
            Text("新建第一条,或从浏览器导入")
                .font(.system(size: 11))
                .foregroundStyle(.secondary)
            Text("新建书签")
                .font(.system(size: 11, design: .monospaced))
                .padding(.horizontal, 10)
                .padding(.vertical, 4)
                .background(.quaternary, in: Capsule())
        }
        .padding(18)
        .frame(width: 340)
        .background(Color.white)
        .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.quaternary))
    }
}
 
public struct BookmarksSearchBoard: View {
    public init() {}
 
    private let rows = [
        ("Swift 文档", "swift.org", "Swift"),
        ("SwiftData", "developer.apple.com/swiftdata", "Swift"),
        ("OpenCode", "opencode.ai", "工具"),
    ]
 
    public var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("搜索:swift")
                .font(.system(size: 10, design: .monospaced))
                .foregroundStyle(.secondary)
            ForEach(rows, id: \.0) { row in
                HStack(spacing: 8) {
                    VStack(alignment: .leading, spacing: 2) {
                        Text(row.0).font(.system(size: 12, weight: .medium))
                        Text(row.1)
                            .font(.system(size: 10, design: .monospaced))
                            .foregroundStyle(.secondary)
                    }
                    Spacer()
                    Text(row.2)
                        .font(.system(size: 9, design: .monospaced))
                        .padding(.horizontal, 6)
                        .padding(.vertical, 2)
                        .background(.quaternary, in: Capsule())
                }
            }
        }
        .padding(18)
        .frame(width: 340, alignment: .leading)
        .background(Color.white)
        .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.quaternary))
    }
}