示例工程 58-capstone-data-and-navigation
58-capstone-data-and-navigation/Sources/Ch58Demo/App.swift
import AppKit
import Ch58Kit
import SwiftData
import SwiftUI
@main
struct Ch58Demo {
@MainActor
static func main() {
do {
let container = try Library.makeContainer()
let context = ModelContext(container)
Library.add(title: "Swift", url: "https://swift.org", tags: ["语言"], in: context)
Library.add(title: "OpenCode", url: "https://opencode.ai", tags: ["工具"], in: context)
Library.add(
title: "SwiftData", url: "https://developer.apple.com", tags: ["Swift"], in: context
)
try context.save()
print("[58.1] 全部书签 = \(try Library.all(in: context).count)")
print("[58.2] 搜索 swift = \(try Library.search("swift", in: context).count)")
let rows = BookmarkListModel.rows(from: try Library.all(in: context))
print("[58.3] 首行标题 = \(rows.first?.title ?? "nil")")
let first = try Library.all(in: context).first
if let first {
Library.delete(first, in: context)
try context.save()
print("[58.4] 删除后 = \(try Library.all(in: context).count)")
}
var navigation = NavigationModel()
navigation.open(.bookmark(UUID(uuidString: "11111111-2222-3333-4444-555555555555")!))
navigation.open(.settings)
let data = try navigation.encoded()
let restored = try NavigationModel.restored(data)
print("[58.5] 路径往返 = \(restored == navigation)")
print("[58.6] 路径长度 = \(navigation.path.count)")
} catch {
print("[58.0] 失败 = \(error)")
}
print("[58.7] 书签板渲染 = \(size(LibraryBoard()))")
print("[58.8] MemoryLayout<BookmarkListModel> = \(MemoryLayout<BookmarkListModel>.size) 字节")
if let directory = ProcessInfo.processInfo.environment["SHOTS_DIR"] {
write(LibraryBoard(), name: "bookmark-board.png", directory: directory)
}
}
@MainActor
private static func size(_ view: some View) -> String {
guard let image = ImageRenderer(content: view).cgImage else { return "nil" }
return "\(image.width)x\(image.height)"
}
@MainActor
private static func write(_ view: some View, name: String, directory: String) {
let renderer = ImageRenderer(content: view)
renderer.scale = 2
guard
let image = renderer.cgImage,
let data = NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])
else {
print("[58.9] 截图失败:\(name)")
return
}
let url = URL(fileURLWithPath: directory).appendingPathComponent(name)
do {
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(),
withIntermediateDirectories: true
)
try data.write(to: url)
print("[58.9] 截图 = \(name) \(image.width)x\(image.height)")
} catch {
print("[58.9] 截图失败:\(error)")
}
}
}