diff --git a/README.md b/README.md index 2bd81de..fe123a9 100644 --- a/README.md +++ b/README.md @@ -11,4 +11,4 @@ Item Atlas 是一个家庭物品台账。它记录东西放在哪、搬动过几 | [deploy/](deploy/README.md) | 本地运行、Kubernetes 和入口配置 | | [docs/](docs/README.md) | 产品、UI、架构、部署说明和测试材料 | -当前版本处于设计阶段。可先看[产品需求](docs/product/requirements.md)、[界面方向稿](docs/ui/README.md)和[测试用例](docs/testing/cases.md)。 +iOS 已有可编译的本机演示版,支持登记、找物、位置、移位和收藏。可打开 [iOS 工程说明](apps/ios/README.md),或先看[产品需求](docs/product/requirements.md)、[界面方向稿](docs/ui/README.md)和[测试用例](docs/testing/cases.md)。 diff --git a/apps/README.md b/apps/README.md index a688d19..31f1638 100644 --- a/apps/README.md +++ b/apps/README.md @@ -5,7 +5,7 @@ | `h5/` | uni-app 移动网页 | `item-atlas-h5` | | `pc/` | 桌面浏览器网页 | `item-atlas-pc` | | `admin/` | 管理后台 | `item-atlas-admin` | -| `ios/` | iOS 原生应用 | Item Atlas | +| [ios/](ios/README.md) | iOS 原生应用 | Item Atlas | | `android/` | Android 原生应用 | Item Atlas | 前三个客户端独立构建,Web Dockerfile 随各自源码维护。各端对齐 OpenAPI 契约、错误码、术语和关键交互。Web 首版包含 H5、PC 和后台,原生端按各自设计和发布节奏推进。 diff --git a/apps/ios/.gitignore b/apps/ios/.gitignore new file mode 100644 index 0000000..4311a15 --- /dev/null +++ b/apps/ios/.gitignore @@ -0,0 +1,5 @@ +.build/ +.swiftpm/ +DerivedData/ +xcuserdata/ +*.xcuserstate diff --git a/apps/ios/.gitkeep b/apps/ios/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/apps/ios/InventoryCore/Package.swift b/apps/ios/InventoryCore/Package.swift new file mode 100644 index 0000000..0cfa428 --- /dev/null +++ b/apps/ios/InventoryCore/Package.swift @@ -0,0 +1,12 @@ +// swift-tools-version: 6.0 +import PackageDescription + +let package = Package( + name: "InventoryCore", + platforms: [.iOS(.v17), .macOS(.v14)], + products: [.library(name: "InventoryCore", targets: ["InventoryCore"])], + targets: [ + .target(name: "InventoryCore"), + .testTarget(name: "InventoryCoreTests", dependencies: ["InventoryCore"]), + ] +) diff --git a/apps/ios/InventoryCore/Sources/InventoryCore/Inventory.swift b/apps/ios/InventoryCore/Sources/InventoryCore/Inventory.swift new file mode 100644 index 0000000..69e7936 --- /dev/null +++ b/apps/ios/InventoryCore/Sources/InventoryCore/Inventory.swift @@ -0,0 +1,138 @@ +import Foundation + +public struct Location: Codable, Identifiable, Sendable { + public let id: UUID + public let name: String + public let parentID: UUID? +} + +public struct Move: Codable, Identifiable, Sendable { + public let id: UUID + public let from: String + public let to: String + public let date: Date +} + +public struct Item: Codable, Identifiable, Sendable { + public let id: UUID + public let name: String + public let aliases: [String] + public let quantity: Int + public let notes: String + public fileprivate(set) var locationID: UUID + public fileprivate(set) var moves: [Move] = [] + public fileprivate(set) var favorite = false +} + +public enum InventoryError: LocalizedError { + case nameRequired, invalidQuantity, locationMissing, itemMissing, duplicateLocation + + public var errorDescription: String? { + switch self { + case .nameRequired: "请填写名称。" + case .invalidQuantity: "数量必须在 1 到 9999 之间。" + case .locationMissing: "请选择一个已有位置。" + case .itemMissing: "找不到这件物品。" + case .duplicateLocation: "这个位置下已有同名位置。" + } + } +} + +public struct Inventory: Codable, Sendable { + public private(set) var items: [Item] = [] + public private(set) var locations: [Location] = [] + public var intakeText = "" + + public init() {} + + public func item(id: UUID) -> Item? { items.first { $0.id == id } } + + public func children(of parentID: UUID?) -> [Location] { + locations.filter { $0.parentID == parentID } + } + + public func path(to id: UUID) -> String { + var names: [String] = [] + var visited = Set() + var cursor: UUID? = id + while let current = cursor, + visited.insert(current).inserted, + let location = locations.first(where: { $0.id == current }) { + names.append(location.name) + cursor = location.parentID + } + return names.reversed().joined(separator: " / ") + } + + public func search(_ input: String, favoritesOnly: Bool = false) -> [Item] { + let words = input.split(whereSeparator: \.isWhitespace).map(String.init) + return items.reversed().filter { item in + guard !favoritesOnly || item.favorite else { return false } + let fields = [item.name, path(to: item.locationID)] + item.aliases + return words.allSatisfy { word in + fields.contains { $0.localizedStandardContains(word) } + } + } + } + + @discardableResult + public mutating func addLocation(name: String, parentID: UUID?) throws -> UUID { + let cleanName = name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !cleanName.isEmpty else { throw InventoryError.nameRequired } + if let parentID { try requireLocation(parentID) } + guard !children(of: parentID).contains(where: { + $0.name.compare(cleanName, options: [.caseInsensitive, .widthInsensitive]) == .orderedSame + }) else { throw InventoryError.duplicateLocation } + + let location = Location(id: UUID(), name: cleanName, parentID: parentID) + locations.append(location) + return location.id + } + + @discardableResult + public mutating func addItem( + name: String, + aliases: [String], + quantity: Int, + notes: String, + locationID: UUID + ) throws -> UUID { + let cleanName = name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !cleanName.isEmpty else { throw InventoryError.nameRequired } + guard (1...9999).contains(quantity) else { throw InventoryError.invalidQuantity } + try requireLocation(locationID) + + let cleanAliases = aliases.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + let item = Item(id: UUID(), name: cleanName, aliases: cleanAliases, quantity: quantity, + notes: notes.trimmingCharacters(in: .whitespacesAndNewlines), locationID: locationID) + items.append(item) + return item.id + } + + public mutating func moveItem(id: UUID, to locationID: UUID, at date: Date = .now) throws { + try requireLocation(locationID) + let index = try itemIndex(id) + let previous = items[index].locationID + guard previous != locationID else { return } + items[index].moves.insert( + Move(id: UUID(), from: path(to: previous), to: path(to: locationID), date: date), + at: 0 + ) + items[index].locationID = locationID + } + + public mutating func toggleFavorite(id: UUID) throws { + let index = try itemIndex(id) + items[index].favorite.toggle() + } + + private func requireLocation(_ id: UUID) throws { + guard locations.contains(where: { $0.id == id }) else { throw InventoryError.locationMissing } + } + + private func itemIndex(_ id: UUID) throws -> Int { + guard let index = items.firstIndex(where: { $0.id == id }) else { throw InventoryError.itemMissing } + return index + } +} diff --git a/apps/ios/InventoryCore/Sources/InventoryCore/InventoryArchive.swift b/apps/ios/InventoryCore/Sources/InventoryCore/InventoryArchive.swift new file mode 100644 index 0000000..b482c3e --- /dev/null +++ b/apps/ios/InventoryCore/Sources/InventoryCore/InventoryArchive.swift @@ -0,0 +1,36 @@ +import Foundation + +public struct InventoryArchive: Sendable { + private struct Contents: Codable { + let version: Int + let inventory: Inventory + } + + private let url: URL + + public init(url: URL) { self.url = url } + + public func load() throws -> Inventory? { + let data: Data + do { + data = try Data(contentsOf: url) + } catch let error as CocoaError where error.code == .fileReadNoSuchFile { + return nil + } + + let contents = try JSONDecoder().decode(Contents.self, from: data) + guard contents.version == 1 else { + throw CocoaError(.fileReadUnknown, userInfo: [ + NSLocalizedDescriptionKey: "这个数据文件由其他版本的 Item Atlas 创建。", + ]) + } + return contents.inventory + } + + public func save(_ inventory: Inventory) throws { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), + withIntermediateDirectories: true) + let data = try JSONEncoder().encode(Contents(version: 1, inventory: inventory)) + try data.write(to: url, options: .atomic) + } +} diff --git a/apps/ios/InventoryCore/Tests/InventoryCoreTests/InventoryTests.swift b/apps/ios/InventoryCore/Tests/InventoryCoreTests/InventoryTests.swift new file mode 100644 index 0000000..fe82696 --- /dev/null +++ b/apps/ios/InventoryCore/Tests/InventoryCoreTests/InventoryTests.swift @@ -0,0 +1,65 @@ +import Foundation +import InventoryCore +import Testing + +@Suite struct InventoryTests { + @Test func aliasAndLocationSearchDistinguishesSameNamedBoxes() throws { + var inventory = Inventory() + let study = try inventory.addLocation(name: "书房", parentID: nil) + let entry = try inventory.addLocation(name: "玄关", parentID: nil) + let studyBox = try inventory.addLocation(name: "白盒", parentID: study) + let entryBox = try inventory.addLocation(name: "白盒", parentID: entry) + let cable = try inventory.addItem( + name: "HDMI 线", aliases: ["视频线"], quantity: 2, notes: "", locationID: studyBox + ) + let key = try inventory.addItem( + name: "钥匙", aliases: [], quantity: 1, notes: "", locationID: entryBox + ) + + #expect(inventory.search("视频线").map(\.id) == [cable]) + #expect(inventory.search("书房 白盒").map(\.id) == [cable]) + #expect(inventory.search("玄关").map(\.id) == [key]) + #expect(inventory.path(to: entryBox) == "玄关 / 白盒") + } + + @Test func moveAndFavoriteRoundTripWithDraftText() throws { + var inventory = Inventory() + let study = try inventory.addLocation(name: "书房", parentID: nil) + let entry = try inventory.addLocation(name: "玄关", parentID: nil) + let cable = try inventory.addItem( + name: "网线", aliases: [], quantity: 1, notes: "", locationID: entry + ) + + try inventory.moveItem(id: cable, to: study) + try inventory.moveItem(id: cable, to: study) + try inventory.toggleFavorite(id: cable) + inventory.intakeText = "读卡器先别动。" + + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: folder) } + let archive = InventoryArchive(url: folder.appendingPathComponent("inventory.json")) + #expect(try archive.load() == nil) + try archive.save(inventory) + + let restored = try #require(try archive.load()) + let moved = try #require(restored.item(id: cable)) + #expect(moved.locationID == study) + #expect(moved.moves.count == 1) + #expect(moved.moves.first?.from == "玄关") + #expect(moved.moves.first?.to == "书房") + #expect(restored.search("", favoritesOnly: true).map(\.id) == [cable]) + #expect(restored.intakeText == "读卡器先别动。") + } + + @Test func rejectsInvalidQuantityAndDuplicateSibling() throws { + var inventory = Inventory() + let study = try inventory.addLocation(name: "书房", parentID: nil) + #expect(throws: InventoryError.duplicateLocation) { + try inventory.addLocation(name: " 书房 ", parentID: nil) + } + #expect(throws: InventoryError.invalidQuantity) { + try inventory.addItem(name: "网线", aliases: [], quantity: 0, notes: "", locationID: study) + } + #expect(inventory.items.isEmpty) + } +} diff --git a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj new file mode 100644 index 0000000..663618a --- /dev/null +++ b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj @@ -0,0 +1,167 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = {}; + objectVersion = 77; + objects = { + A10000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + }; + buildConfigurationList = A10000000000000000000002 /* Project configurations */; + developmentRegion = "zh-Hans"; + hasScannedForEncodings = 0; + knownRegions = ("zh-Hans", Base, en); + mainGroup = A10000000000000000000003; + packageReferences = (A10000000000000000000004 /* InventoryCore */); + preferredProjectObjectVersion = 77; + productRefGroup = A10000000000000000000005 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = (A10000000000000000000006 /* ItemAtlas */); + }; + A10000000000000000000002 /* Project configurations */ = { + isa = XCConfigurationList; + buildConfigurations = (A10000000000000000000011 /* Debug */, A10000000000000000000012 /* Release */); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A10000000000000000000003 = { + isa = PBXGroup; + children = (A10000000000000000000007 /* ItemAtlas */, A10000000000000000000005 /* Products */); + sourceTree = ""; + }; + A10000000000000000000004 /* InventoryCore */ = { + isa = XCLocalSwiftPackageReference; + relativePath = InventoryCore; + }; + A10000000000000000000005 /* Products */ = { + isa = PBXGroup; + children = (A10000000000000000000008 /* ItemAtlas.app */); + name = Products; + sourceTree = ""; + }; + A10000000000000000000006 /* ItemAtlas */ = { + isa = PBXNativeTarget; + buildConfigurationList = A10000000000000000000009 /* Target configurations */; + buildPhases = ( + A1000000000000000000000A /* Sources */, + A1000000000000000000000B /* Frameworks */, + A1000000000000000000000C /* Resources */, + ); + buildRules = (); + dependencies = (); + fileSystemSynchronizedGroups = (A10000000000000000000007 /* ItemAtlas */); + name = ItemAtlas; + packageProductDependencies = (A1000000000000000000000D /* InventoryCore */); + productName = ItemAtlas; + productReference = A10000000000000000000008 /* ItemAtlas.app */; + productType = "com.apple.product-type.application"; + }; + A10000000000000000000007 /* ItemAtlas */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = ItemAtlas; + sourceTree = ""; + }; + A10000000000000000000008 /* ItemAtlas.app */ = { + isa = PBXFileReference; + explicitFileType = wrapper.application; + includeInIndex = 0; + path = ItemAtlas.app; + sourceTree = BUILT_PRODUCTS_DIR; + }; + A10000000000000000000009 /* Target configurations */ = { + isa = XCConfigurationList; + buildConfigurations = (A10000000000000000000013 /* Debug */, A10000000000000000000014 /* Release */); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A1000000000000000000000A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = (); + runOnlyForDeploymentPostprocessing = 0; + }; + A1000000000000000000000B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = (A1000000000000000000000E /* InventoryCore in Frameworks */); + runOnlyForDeploymentPostprocessing = 0; + }; + A1000000000000000000000C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = (); + runOnlyForDeploymentPostprocessing = 0; + }; + A1000000000000000000000D /* InventoryCore */ = { + isa = XCSwiftPackageProductDependency; + package = A10000000000000000000004 /* InventoryCore */; + productName = InventoryCore; + }; + A1000000000000000000000E /* InventoryCore in Frameworks */ = { + isa = PBXBuildFile; + productRef = A1000000000000000000000D /* InventoryCore */; + }; + A10000000000000000000011 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ENABLE_TESTABILITY = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 6.0; + }; + name = Debug; + }; + A10000000000000000000012 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_VERSION = 6.0; + }; + name = Release; + }; + A10000000000000000000013 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_CFBundleDisplayName = "Item Atlas"; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.tutudog.itematlas; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Debug; + }; + A10000000000000000000014 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_CFBundleDisplayName = "Item Atlas"; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.tutudog.itematlas; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Release; + }; + }; + rootObject = A10000000000000000000001 /* Project object */; +} diff --git a/apps/ios/ItemAtlas.xcodeproj/xcshareddata/xcschemes/ItemAtlas.xcscheme b/apps/ios/ItemAtlas.xcodeproj/xcshareddata/xcschemes/ItemAtlas.xcscheme new file mode 100644 index 0000000..0d56392 --- /dev/null +++ b/apps/ios/ItemAtlas.xcodeproj/xcshareddata/xcschemes/ItemAtlas.xcscheme @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/apps/ios/ItemAtlas/Editors.swift b/apps/ios/ItemAtlas/Editors.swift new file mode 100644 index 0000000..70f25d5 --- /dev/null +++ b/apps/ios/ItemAtlas/Editors.swift @@ -0,0 +1,102 @@ +import InventoryCore +import SwiftUI + +struct ItemEditor: View { + let store: InventoryStore + var initialLocation: UUID? = nil + @Environment(\.dismiss) private var dismiss + @State private var name = "" + @State private var aliases = "" + @State private var quantity = 1 + @State private var notes = "" + @State private var locationID: UUID? + @State private var errorMessage: String? + + var body: some View { + NavigationStack { + Form { + Section("物品") { + TextField("名称", text: $name) + TextField("别名,用逗号隔开", text: $aliases) + Stepper("数量:\(quantity)", value: $quantity, in: 1...9999) + TextField("备注", text: $notes, axis: .vertical) + } + Section("放在哪") { + LocationPicker(inventory: store.inventory, selection: $locationID) + if store.inventory.locations.isEmpty { + Text("先在「位置」里建一个位置。").font(.footnote).foregroundStyle(.secondary) + } + } + if let errorMessage { Section { Text(errorMessage).foregroundStyle(.red) } } + } + .navigationTitle("记一件") + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("保存") { save() } + .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || locationID == nil) + } + } + } + .onAppear { if locationID == nil { locationID = initialLocation } } + } + + private func save() { + guard let locationID else { return } + do { + let aliasList = aliases.split(whereSeparator: { ",,、".contains($0) }).map(String.init) + try store.update { + try $0.addItem(name: name, aliases: aliasList, quantity: quantity, + notes: notes, locationID: locationID) + } + dismiss() + } catch { errorMessage = error.localizedDescription } + } +} + +struct MoveEditor: View { + let store: InventoryStore + let item: Item + @Environment(\.dismiss) private var dismiss + @State private var locationID: UUID? + @State private var errorMessage: String? + + var body: some View { + NavigationStack { + Form { + Section("原位置") { Text(store.inventory.path(to: item.locationID)) } + Section("新位置") { LocationPicker(inventory: store.inventory, selection: $locationID) } + if let errorMessage { Section { Text(errorMessage).foregroundStyle(.red) } } + } + .navigationTitle("移位") + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("确认移位") { + guard let locationID else { return } + do { + try store.update { try $0.moveItem(id: item.id, to: locationID) } + dismiss() + } catch { errorMessage = error.localizedDescription } + } + .disabled(locationID == nil || locationID == item.locationID) + } + } + } + } +} + +private struct LocationPicker: View { + let inventory: Inventory + @Binding var selection: UUID? + + var body: some View { + Picker("位置", selection: $selection) { + Text("请选择").tag(nil as UUID?) + ForEach(inventory.locations) { location in + Text(inventory.path(to: location.id)).tag(Optional(location.id)) + } + } + .pickerStyle(.navigationLink) + } +} diff --git a/apps/ios/ItemAtlas/IntakeView.swift b/apps/ios/ItemAtlas/IntakeView.swift new file mode 100644 index 0000000..d42c6b6 --- /dev/null +++ b/apps/ios/ItemAtlas/IntakeView.swift @@ -0,0 +1,46 @@ +import SwiftUI + +struct IntakeView: View { + let store: InventoryStore + @State private var showingAdd = false + @State private var draft: String? + @State private var feedback: String? + + var body: some View { + NavigationStack { + Form { + Section { + Button { showingAdd = true } label: { + Label("手工记一件", systemImage: "plus") + } + } + Section { + TextEditor(text: Binding( + get: { draft ?? store.inventory.intakeText }, + set: { draft = $0; feedback = nil } + )) + .frame(minHeight: 120) + .accessibilityLabel("整理原话") + Button("保存原话") { + guard let draft else { return } + do { + try store.update { $0.intakeText = draft } + self.draft = nil + feedback = "原话已保存在这台设备上。" + } catch { feedback = error.localizedDescription } + } + .disabled(draft == nil) + if let feedback { + Text(feedback).font(.footnote).foregroundStyle(.secondary) + } + } header: { + Text("批量录入") + } footer: { + Text("模型草稿待接入。可以先保存原话,或改用手工录入。") + } + } + .navigationTitle("录入") + .sheet(isPresented: $showingAdd) { ItemEditor(store: store) } + } + } +} diff --git a/apps/ios/ItemAtlas/InventoryStore.swift b/apps/ios/ItemAtlas/InventoryStore.swift new file mode 100644 index 0000000..b12506a --- /dev/null +++ b/apps/ios/ItemAtlas/InventoryStore.swift @@ -0,0 +1,49 @@ +import Foundation +import InventoryCore +import Observation + +@MainActor +@Observable +final class InventoryStore { + private let archive = InventoryArchive( + url: URL.applicationSupportDirectory.appending(path: "ItemAtlas/inventory.json") + ) + private(set) var inventory = Inventory() + private(set) var startupError: String? + + init() { + do { + inventory = try archive.load() ?? Self.sample() + } catch { + startupError = error.localizedDescription + } + } + + func update(_ change: (inout Inventory) throws -> Void) throws { + var next = inventory + try change(&next) + try archive.save(next) + inventory = next + } + + private static func sample() throws -> Inventory { + var inventory = Inventory() + let study = try inventory.addLocation(name: "书房", parentID: nil) + let desk = try inventory.addLocation(name: "书桌", parentID: study) + let drawer = try inventory.addLocation(name: "右抽屉", parentID: desk) + let livingRoom = try inventory.addLocation(name: "客厅", parentID: nil) + let cabinet = try inventory.addLocation(name: "电视柜", parentID: livingRoom) + let entry = try inventory.addLocation(name: "玄关", parentID: nil) + let box = try inventory.addLocation(name: "白盒", parentID: entry) + + try inventory.addItem(name: "备用钥匙", aliases: ["门钥匙"], quantity: 1, + notes: "", locationID: box) + try inventory.addItem(name: "HDMI 线", aliases: ["视频线"], quantity: 2, + notes: "一根长线,一根短线。", locationID: drawer) + let ssd = try inventory.addItem(name: "外接固态硬盘", aliases: ["移动硬盘"], quantity: 1, + notes: "带电脑出门时一起拿。", locationID: cabinet) + try inventory.moveItem(id: ssd, to: drawer) + try inventory.toggleFavorite(id: ssd) + return inventory + } +} diff --git a/apps/ios/ItemAtlas/InventoryView.swift b/apps/ios/ItemAtlas/InventoryView.swift new file mode 100644 index 0000000..4322d9c --- /dev/null +++ b/apps/ios/ItemAtlas/InventoryView.swift @@ -0,0 +1,178 @@ +import InventoryCore +import SwiftUI + +struct InventoryView: View { + let store: InventoryStore + var favoritesOnly = false + @State private var query = "" + @State private var showingAdd = false + + private var rows: [Item] { store.inventory.search(query, favoritesOnly: favoritesOnly) } + + var body: some View { + NavigationStack { + VStack(spacing: 0) { + searchHeader + if rows.isEmpty { + ContentUnavailableView( + favoritesOnly && query.isEmpty ? "还没有收藏" : "没找到物品", + systemImage: favoritesOnly ? "star" : "magnifyingglass", + description: Text(favoritesOnly && query.isEmpty + ? "可以在物品详情收藏经常用的东西。" + : "试试别名、房间或收纳盒名称。") + ) + } else { + List { + Section { + ForEach(rows) { item in + NavigationLink { + ItemDetailView(store: store, itemID: item.id) + } label: { + ItemRow(item: item, path: store.inventory.path(to: item.locationID)) + } + } + } header: { + Text("\(rows.count) 条记录") + } + } + .listStyle(.plain) + .scrollDismissesKeyboard(.interactively) + } + } + .toolbar(.hidden, for: .navigationBar) + .sheet(isPresented: $showingAdd) { ItemEditor(store: store) } + } + } + + private var searchHeader: some View { + VStack(alignment: .leading, spacing: 14) { + HStack { + Label("Item Atlas", systemImage: "square.grid.2x2.fill") + .font(.subheadline.weight(.semibold)) + Spacer() + Text("本机演示").font(.caption) + } + HStack(alignment: .center) { + Text(favoritesOnly ? "我的收藏" : "找东西") + .font(.largeTitle.weight(.bold)) + .accessibilityAddTraits(.isHeader) + Spacer() + if !favoritesOnly { + Button { showingAdd = true } label: { + Label("记一件", systemImage: "plus") + .font(.subheadline.weight(.semibold)) + } + .buttonStyle(.bordered) + .tint(.white) + } + } + HStack(spacing: 10) { + Image(systemName: "magnifyingglass").accessibilityHidden(true) + TextField("搜物品、别名或位置", text: $query) + .submitLabel(.search) + .textInputAutocapitalization(.never) + if !query.isEmpty { + Button { query = "" } label: { + Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary) + } + .accessibilityLabel("清除搜索") + } + } + .padding(12) + .foregroundStyle(Color.atlasNavy) + .environment(\.colorScheme, .light) + .background(.white, in: RoundedRectangle(cornerRadius: 10)) + } + .padding(18) + .foregroundStyle(.white) + .background(Color.atlasNavy) + } +} + +struct ItemRow: View { + let item: Item + let path: String + + var body: some View { + HStack(spacing: 12) { + Image(systemName: "archivebox") + .font(.title3) + .foregroundStyle(Color.atlasBlue) + .frame(width: 43, height: 43) + .background(Color.atlasBlue.opacity(0.10), in: RoundedRectangle(cornerRadius: 10)) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 3) { + HStack { + Text(item.name).font(.headline) + if item.quantity > 1 { + Text("×\(item.quantity)").font(.caption).foregroundStyle(.secondary) + } + } + Text(path).font(.subheadline).foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(.vertical, 4) + } +} + +struct ItemDetailView: View { + let store: InventoryStore + let itemID: UUID + @State private var showingMove = false + @State private var errorMessage: String? + + var body: some View { + Group { + if let item = store.inventory.item(id: itemID) { + List { + Section("当前位置") { + Label(store.inventory.path(to: item.locationID), systemImage: "location.fill") + .foregroundStyle(Color.atlasBlue) + Button("移位") { showingMove = true } + } + Section("物品信息") { + LabeledContent("数量", value: "\(item.quantity)") + if !item.aliases.isEmpty { + LabeledContent("别名", value: item.aliases.joined(separator: "、")) + } + if !item.notes.isEmpty { Text(item.notes) } + } + if !item.moves.isEmpty { + Section("移位历史") { + ForEach(item.moves) { move in + VStack(alignment: .leading, spacing: 4) { + Text("\(move.from) → \(move.to)") + Text(move.date.formatted(date: .abbreviated, time: .omitted)) + .font(.caption).foregroundStyle(.secondary) + } + } + } + } + } + .navigationTitle(item.name) + .navigationBarTitleDisplayMode(.inline) + .toolbar(.visible, for: .navigationBar) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button { + do { try store.update { try $0.toggleFavorite(id: item.id) } } + catch { errorMessage = error.localizedDescription } + } label: { + Image(systemName: item.favorite ? "star.fill" : "star") + } + .accessibilityLabel(item.favorite ? "取消收藏" : "收藏") + } + } + .sheet(isPresented: $showingMove) { MoveEditor(store: store, item: item) } + .alert("保存失败", isPresented: Binding( + get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } } + )) { + Button("好", role: .cancel) {} + } message: { Text(errorMessage ?? "") } + } else { + ContentUnavailableView("找不到这件物品", systemImage: "archivebox") + } + } + } +} diff --git a/apps/ios/ItemAtlas/ItemAtlasApp.swift b/apps/ios/ItemAtlas/ItemAtlasApp.swift new file mode 100644 index 0000000..98c5564 --- /dev/null +++ b/apps/ios/ItemAtlas/ItemAtlasApp.swift @@ -0,0 +1,32 @@ +import SwiftUI + +@main +struct ItemAtlasApp: App { + @State private var store = InventoryStore() + + var body: some Scene { + WindowGroup { + if let startupError = store.startupError { + ContentUnavailableView("无法打开物品台账", systemImage: "externaldrive.badge.exclamationmark", + description: Text(startupError)) + } else { + TabView { + InventoryView(store: store) + .tabItem { Label("找物", systemImage: "magnifyingglass") } + LocationView(store: store) + .tabItem { Label("位置", systemImage: "square.stack") } + IntakeView(store: store) + .tabItem { Label("录入", systemImage: "square.and.pencil") } + InventoryView(store: store, favoritesOnly: true) + .tabItem { Label("收藏", systemImage: "star") } + } + .tint(.atlasBlue) + } + } + } +} + +extension Color { + static let atlasNavy = Color(red: 0.09, green: 0.15, blue: 0.28) + static let atlasBlue = Color(red: 0.19, green: 0.32, blue: 0.81) +} diff --git a/apps/ios/ItemAtlas/LocationView.swift b/apps/ios/ItemAtlas/LocationView.swift new file mode 100644 index 0000000..524a22e --- /dev/null +++ b/apps/ios/ItemAtlas/LocationView.swift @@ -0,0 +1,65 @@ +import InventoryCore +import SwiftUI + +struct LocationView: View { + let store: InventoryStore + + var body: some View { + NavigationStack { LocationContents(store: store, location: nil) } + } +} + +private struct LocationContents: View { + let store: InventoryStore + let location: Location? + @State private var editingLocation = false + @State private var addingItem = false + @State private var newName = "" + @State private var errorMessage: String? + + var body: some View { + List { + if let location { + Section { Text(store.inventory.path(to: location.id)).foregroundStyle(.secondary) } + } + Section(location == nil ? "房间和区域" : "子位置") { + ForEach(store.inventory.children(of: location?.id)) { child in + NavigationLink { + LocationContents(store: store, location: child) + } label: { Label(child.name, systemImage: "folder") } + } + Button { + newName = "" + editingLocation = true + } label: { + Label(location == nil ? "新建位置" : "新建子位置", systemImage: "plus") + } + } + if let location { + Section("这里的物品") { + ForEach(store.inventory.search("").filter { $0.locationID == location.id }) { item in + NavigationLink { + ItemDetailView(store: store, itemID: item.id) + } label: { + Text(item.name) + } + } + Button("记一件") { addingItem = true } + } + } + if let errorMessage { Section { Text(errorMessage).foregroundStyle(.red) } } + } + .navigationTitle(location?.name ?? "位置") + .alert("新建位置", isPresented: $editingLocation) { + TextField("名称", text: $newName) + Button("取消", role: .cancel) {} + Button("保存") { + do { + try store.update { try $0.addLocation(name: newName, parentID: location?.id) } + errorMessage = nil + } catch { errorMessage = error.localizedDescription } + } + } + .sheet(isPresented: $addingItem) { ItemEditor(store: store, initialLocation: location?.id) } + } +} diff --git a/apps/ios/README.md b/apps/ios/README.md new file mode 100644 index 0000000..95f2a16 --- /dev/null +++ b/apps/ios/README.md @@ -0,0 +1,27 @@ +# Item Atlas for iOS + +最低系统版本为 iOS 17。用 Xcode 16 或更新版本打开 `ItemAtlas.xcodeproj`,选择 `ItemAtlas` 方案和已安装的 iOS 模拟器后运行。自己用 iPhone 调试时,在 Xcode 中添加 Apple 账户,并在主目标的 Signing & Capabilities 选择团队。 + +## 当前版本 + +- 手工登记物品、数量、别名、备注和位置。可按名称、别名和完整位置路径找物。 +- 新建房间和多层位置,进入位置查看物品,移位时保留历史。可收藏和取消收藏。 +- 「录入」可保存一段整理原话。批量生成的草稿和家庭同步随项目 API 接入。 + +首次启动内置一组示例数据。首次保存后,数据保存在应用沙盒的 `Application Support/ItemAtlas/inventory.json`,重启后可以继续使用。演示数据仅在本机保存。 + +## 本地检查 + +从 `apps/ios/` 执行。若要把构建产物放到外置磁盘,先将 `ITEM_ATLAS_BUILD_DIR` 指向其上的可写目录。 + +```sh +ITEM_ATLAS_BUILD_DIR="${ITEM_ATLAS_BUILD_DIR:-$PWD/DerivedData}" +xcodebuild -project ItemAtlas.xcodeproj -scheme ItemAtlas \ + -destination 'generic/platform=iOS' \ + -derivedDataPath "$ITEM_ATLAS_BUILD_DIR/iphone" CODE_SIGNING_ALLOWED=NO build +swift test --package-path InventoryCore --scratch-path "$ITEM_ATLAS_BUILD_DIR/core-tests" +``` + +无签名构建可用于编译验证。安装到 iPhone、使用 TestFlight 和商店发布时使用对应的签名方案。 + +[界面设计](../../docs/ui/README.md) · [测试与演示](../../docs/testing/plan.md) diff --git a/docs/architecture/clients.md b/docs/architecture/clients.md index 776d6a0..0b5debc 100644 --- a/docs/architecture/clients.md +++ b/docs/architecture/clients.md @@ -7,13 +7,13 @@ | H5 | uni-app(Vue 3、TypeScript、Vite),使用 DCloud 的 CLI 模板 | 面向临时找物、相机上传和快速录入。首版构建 H5 静态文件,由 Nginx 镜像托管。 | | PC 网页 | Vue 3、TypeScript、Vite、Vue Router | 面向批量草稿、详情查看和浏览位置树。独立 Nginx 镜像。 | | 管理后台 | Vue 3、TypeScript、Vite、Vue Router、Element Plus | 用数据表格和表单处理模型状态、用量、用户及家庭管理。独立 Nginx 镜像。 | -| iOS | Swift、SwiftUI | Xcode 工程。原生调用相机和录音能力,直接请求项目的 HTTPS API。 | +| iOS | Swift、SwiftUI,最低 iOS 17 | [本机演示版](../../apps/ios/README.md)先交付找物和手工录入。后续接入项目 HTTPS API、相机和录音。 | | Android | Kotlin、Jetpack Compose | Gradle 工程。相机、录音走 Android 平台能力,使用同一 HTTPS API。 | H5 选 uni-app 是为了用贴合移动端的组件和构建方式。正式交付范围只包含网页。微信小程序本期不列入需求、目录或构建目标。PC 和后台要处理高密度列表、桌面键盘交互以及表单,用标准 Vue 网页工程。Web 各端共享合适的 API 类型、校验和文案,H5 的 uni-app 组件单独维护。 [uni-app CLI](https://uniapp.dcloud.net.cn/worktile/CLI.html) · [uni-app Vue 3 TypeScript 模板](https://uniapp.dcloud.net.cn/quickstart-cli.html) · [Vue TypeScript](https://vuejs.org/guide/typescript/overview) · [Vue Router](https://router.vuejs.org/) · [Element Plus](https://element-plus.org/en-US/guide/quickstart) 三个 Web 站点在自己的域名下通过 `/api` 访问网关,原生端连接 `https://api-atlas.tutudog.com`。家庭权限由后端校验,后台接口另验管理角色。模型尚未配置时界面显示状态,凭证从服务环境读取。 -首批界面定稿覆盖 H5、PC 和后台。iOS 与 Android 按原生平台的导航、拍照、录音及权限规范单独设计。最低系统版本、签名和商店发布安排在原生端启动时确认。 [SwiftUI](https://developer.apple.com/swiftui/) · [Jetpack Compose](https://developer.android.com/compose) +各端按自己的导航、拍照、录音及权限规范单独设计。iOS 从本机全流程开始,后续联调时再接入共享家庭和模型草稿。签名和商店发布在准备分发时配置。 [SwiftUI](https://developer.apple.com/swiftui/) · [Jetpack Compose](https://developer.android.com/compose) [客户端工程目录](../../apps/README.md) · [产品需求](../product/requirements.md) · [部署与域名](../deployment/overview.md)