feat(AI): 集成MNN推理引擎替换MLX作为主AI运行时

- 引入MNN(alibaba) + Arm SME2 + CPU作为主AI运行时,支持A19/iPhone17的
  SME2和A17的NEON加速
- 添加MLX Swift作为兜底GPU推理方案,实现双后端切换机制
- 使用单一Qwen3.5-2B多模态模型(1.2GB),替代原有的LLM+VL分离架构
- 实现InferenceEngine.current引擎选择逻辑,真机默认MNN,模拟器回退MLX
- 更新AIAgent架构,通过MNNLLMBridge(ObjC++) → MNNBackend进行推理
- 修改队列机制防止并发推理导致OOM,使用信号量闸门控制显存占用
- 更新文档中的技术栈说明、模块边界和周次交付计划
```
This commit is contained in:
link2026
2026-06-15 09:24:59 +08:00
parent 6c6a950140
commit 9d856fcfc4
37 changed files with 2605 additions and 430 deletions

View File

@@ -23,9 +23,12 @@ struct ArchiveListView: View {
@Query(sort: \MetricReminder.updatedAt, order: .reverse)
private var metricReminders: [MetricReminder]
@Query(sort: \Medication.updatedAt, order: .reverse)
private var medications: [Medication]
/// push `navigationDestination(item:)`
/// `navigationDestination(isPresented:)` SwiftUI ()
private enum Route: Hashable { case exports, reminders }
private enum Route: Hashable { case exports, reminders, medicationLibrary }
@State private var filter: TimelineKind? = nil
@State private var endingSymptom: Symptom?
@@ -33,57 +36,73 @@ struct ArchiveListView: View {
@State private var selectedGroup: IndicatorGroup?
@State private var route: Route?
/// :,(///), chip
@State private var searching = false
@State private var query = ""
@MainActor
private var allEntries: [TimelineEntry] {
let mapped =
TimelineEntry.from(indicators: indicators) +
TimelineEntry.aggregatedIndicators(indicators) +
reports.map(TimelineEntry.from(report:)) +
diaries.map(TimelineEntry.from(diary:)) +
symptoms.map(TimelineEntry.from(symptom:))
let filtered = filter.map { kind in mapped.filter { $0.kind == kind } } ?? mapped
return filtered.sorted { $0.date > $1.date }
let byKind = filter.map { kind in mapped.filter { $0.kind == kind } } ?? mapped
let q = query.trimmingCharacters(in: .whitespaces)
let byQuery = q.isEmpty ? byKind : byKind.filter { $0.title.localizedCaseInsensitiveContains(q) }
return byQuery.sorted { $0.date > $1.date }
}
private var grouped: [(section: DateSection, items: [TimelineEntry])] {
TimelineGrouping.group(allEntries)
}
private var totalCount: Int { allEntries.count }
var body: some View {
NavigationStack {
content
.navigationDestination(item: $route) { route in
switch route {
case .exports: HealthExportListView()
case .reminders: RemindersListView()
case .exports: HealthExportListView()
case .reminders: RemindersListView()
case .medicationLibrary: MedicationLibraryView()
}
}
}
}
private var content: some View {
VStack(alignment: .leading, spacing: 0) {
header
// ( O(m²))+ / body .isEmpty
// allEntries,;,
let entries = allEntries
let groups = TimelineGrouping.group(entries)
return VStack(alignment: .leading, spacing: 0) {
header(total: entries.count)
.padding(.horizontal, 20)
.padding(.top, 8)
.padding(.bottom, 14)
if reminderTotal > 0 {
reminderBoard
.padding(.horizontal, 20)
.padding(.bottom, 10)
}
// :/,
medicationBoard
.padding(.horizontal, 20)
.padding(.bottom, 14)
filterChips
.padding(.bottom, searching ? 10 : 14)
if searching {
searchField
.padding(.horizontal, 20)
.padding(.bottom, 14)
}
filterChips
.padding(.bottom, 14)
if allEntries.isEmpty {
if entries.isEmpty {
emptyState
} else {
ScrollView(showsIndicators: false) {
LazyVStack(alignment: .leading, spacing: 18, pinnedViews: [.sectionHeaders]) {
ForEach(grouped, id: \.section) { group in
ForEach(groups, id: \.section) { group in
Section {
VStack(spacing: 10) {
ForEach(group.items) { entry in
@@ -149,12 +168,12 @@ struct ArchiveListView: View {
diaries: diaries, symptoms: symptoms)
}
private var header: some View {
private func header(total: Int) -> some View {
HStack(alignment: .lastTextBaseline) {
Text("记录")
.font(.tjTitle(26))
.foregroundStyle(Tj.Palette.text)
Text(totalCount == 0 ? "" : String(appLoc: "\(totalCount)"))
Text(total == 0 ? "" : String(appLoc: "\(total)"))
.font(.tjScaled( 12))
.foregroundStyle(Tj.Palette.text3)
Spacer()
@@ -173,9 +192,57 @@ struct ArchiveListView: View {
}
.buttonStyle(.plain)
}
searchToggle
}
}
private var searchToggle: some View {
Button {
withAnimation(.easeInOut(duration: 0.18)) {
searching.toggle()
if !searching { query = "" }
}
} label: {
Image(systemName: searching ? "xmark" : "magnifyingglass")
.font(.tjScaled( 14, weight: .semibold))
.foregroundStyle(Tj.Palette.text)
.frame(width: 32, height: 32)
.background(Circle().fill(Tj.Palette.sand2))
}
.buttonStyle(.plain)
.accessibilityLabel(searching ? String(appLoc: "关闭搜索") : String(appLoc: "搜索记录"))
}
private var searchField: some View {
HStack(spacing: 8) {
Image(systemName: "magnifyingglass")
.font(.tjScaled( 13))
.foregroundStyle(Tj.Palette.text3)
TextField(String(appLoc: "搜索指标 / 报告 / 症状名"), text: $query)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.foregroundStyle(Tj.Palette.text)
.tint(Tj.Palette.ink)
if !query.isEmpty {
Button { query = "" } label: {
Image(systemName: "xmark.circle.fill")
.foregroundStyle(Tj.Palette.text3)
}
.buttonStyle(.plain)
}
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background(
RoundedRectangle(cornerRadius: Tj.Radius.sm, style: .continuous)
.fill(Tj.Palette.paper)
)
.overlay(
RoundedRectangle(cornerRadius: Tj.Radius.sm, style: .continuous)
.strokeBorder(Tj.Palette.line, lineWidth: 1)
)
}
// MARK: -
/// ( + ),
@@ -241,6 +308,58 @@ struct ArchiveListView: View {
.buttonStyle(.plain)
}
// MARK: -
/// :, · N
private var medicationCountLabel: String {
medications.isEmpty
? String(appLoc: "药品库")
: String(appLoc: "药品库 · \(medications.count) 种常用药")
}
/// :; 3 (,)
private var medicationPreviewLine: String {
if medications.isEmpty { return String(appLoc: "拍药盒或手动添加常用药") }
let names = medications.prefix(3).map(\.name).joined(separator: " · ")
return medications.count > 3 ? names + "" : names
}
/// (MedicationLibraryView,push );
private var medicationBoard: some View {
Button { route = .medicationLibrary } label: {
HStack(spacing: 12) {
ZStack {
Circle().fill(medications.isEmpty ? Tj.Palette.sand2 : Tj.Palette.leafSoft)
Image(systemName: "pills.fill")
.font(.tjScaled( 16))
.foregroundStyle(medications.isEmpty ? Tj.Palette.text3 : Tj.Palette.ink)
}
.frame(width: 36, height: 36)
VStack(alignment: .leading, spacing: 2) {
Text(medicationCountLabel)
.font(.tjScaled( 15, weight: .semibold))
.foregroundStyle(Tj.Palette.text)
.lineLimit(1)
Text(medicationPreviewLine)
.font(.tjScaled( 12))
.foregroundStyle(Tj.Palette.text3)
.lineLimit(1)
}
Spacer(minLength: 0)
Image(systemName: "chevron.right")
.font(.tjScaled( 12, weight: .semibold))
.foregroundStyle(Tj.Palette.text3)
}
.padding(14)
.contentShape(Rectangle())
.tjCard()
}
.buttonStyle(.plain)
}
private var filterChips: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
@@ -291,13 +410,19 @@ struct ArchiveListView: View {
}
private var emptyState: some View {
VStack(spacing: 14) {
let q = query.trimmingCharacters(in: .whitespaces)
let isSearchMiss = !q.isEmpty
return VStack(spacing: 14) {
Spacer()
TjPlaceholder(label: String(appLoc: "还没有任何记录\n点底部 + 号开始"))
TjPlaceholder(label: isSearchMiss
? String(appLoc: "没有匹配「\(q)」的记录")
: String(appLoc: "还没有任何记录\n点底部 + 号开始"))
.frame(width: 240, height: 140)
Text(filter == nil ? String(appLoc: "记录会按时间归类显示") : String(appLoc: "这个类别下没有记录"))
.font(.tjScaled( 13))
.foregroundStyle(Tj.Palette.text3)
if !isSearchMiss {
Text(filter == nil ? String(appLoc: "记录会按时间归类显示") : String(appLoc: "这个类别下没有记录"))
.font(.tjScaled( 13))
.foregroundStyle(Tj.Palette.text3)
}
Spacer()
}
.frame(maxWidth: .infinity)

View File

@@ -8,9 +8,12 @@ struct CaptureReviewForm: View {
@State var parsed: ParsedReport
let assets: [FileVault.SavedAsset]
let warning: String?
/// : + (///),
/// ( 2B OOM ), CaptureService.extractReportMeta
var metaOnly: Bool = false
let onSave: (ParsedReport) -> Void
let onCancel: () -> Void
/// assets () nil,banner
/// assets () nil,banner
var onReanalyze: (() -> Void)? = nil
var body: some View {
@@ -23,7 +26,9 @@ struct CaptureReviewForm: View {
pageThumbnails
}
metaSection
indicatorSection
if !metaOnly {
indicatorSection
}
Spacer(minLength: 8)
actions
}
@@ -68,20 +73,26 @@ struct CaptureReviewForm: View {
private var pageThumbnails: some View {
VStack(alignment: .leading, spacing: 8) {
sectionLabel(String(appLoc: "已保存 \(assets.count) 页(端侧加密)"))
if metaOnly {
Text("原图已加密保存,详情页随时可翻看放大。系统只识别报告日期与机构作为标签,不逐项录入数值。")
.font(.tjScaled( 11))
.foregroundStyle(Tj.Palette.text3)
.fixedSize(horizontal: false, vertical: true)
}
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 10) {
ForEach(Array(assets.enumerated()), id: \.offset) { _, asset in
if let img = try? FileVault.shared.loadImage(relativePath: asset.relativePath) {
Image(uiImage: img)
.resizable()
.scaledToFill()
.frame(width: 84, height: 110)
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.strokeBorder(Tj.Palette.line, lineWidth: 1)
)
VaultImage(relativePath: asset.relativePath, maxPixel: 400) { img in
Image(uiImage: img).resizable().scaledToFill()
} placeholder: { _ in
Tj.Palette.paper
}
.frame(width: 84, height: 110)
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.strokeBorder(Tj.Palette.line, lineWidth: 1)
)
}
}
}
@@ -117,9 +128,11 @@ struct CaptureReviewForm: View {
labeledField(String(appLoc: "机构(可选)")) {
TextField("如:协和医院", text: $parsed.institution)
}
labeledField(String(appLoc: "摘要(可选)")) {
TextField("一句话总结", text: $parsed.summary, axis: .vertical)
.lineLimit(1...3)
if !metaOnly {
labeledField(String(appLoc: "摘要(可选)")) {
TextField("一句话总结", text: $parsed.summary, axis: .vertical)
.lineLimit(1...3)
}
}
}
.padding(12)

View File

@@ -62,7 +62,7 @@ struct UnifiedCaptureFlow: View {
switch phase {
case .idle: return String(appLoc: "拍摄报告")
case .analyzing: return String(appLoc: "本地识别中…")
case .editing: return String(appLoc: "核对识别结果")
case .editing: return String(appLoc: "核对报告信息")
}
}
@@ -86,6 +86,7 @@ struct UnifiedCaptureFlow: View {
parsed: parsed,
assets: assets,
warning: warning,
metaOnly: true, // + meta,(§ CaptureService.extractReportMeta)
onSave: { final in saveAll(parsed: final, assets: assets) },
onCancel: cancelAll,
onReanalyze: assets.isEmpty ? nil : { reanalyze(assets: assets) }
@@ -152,9 +153,7 @@ struct UnifiedCaptureFlow: View {
phase = .analyzing(images: images, assets: nil)
let timeout = analyzeTimeoutSeconds
analyzeTask = Task {
// Step 1: Vault
// UI , CaptureService.analyze /退,
// assets phase ,cancelAll ,editingFallback
// Step 1: Vault(,)
let assets = images.compactMap { try? FileVault.shared.writeJPEG($0) }
// :,View dismisscancelAll
// phase .analyzing(_, nil),
@@ -167,7 +166,7 @@ struct UnifiedCaptureFlow: View {
phase = .editing(
parsed: .empty(),
assets: [],
warning: String(appLoc: "图片保存失败,手动录入并保留文本")
warning: String(appLoc: "图片保存失败,请重试")
)
}
return
@@ -179,49 +178,40 @@ struct UnifiedCaptureFlow: View {
}
}
// Step 2: VL (timeout cancel ,VLSession token break)
// Step 2: meta (OCR + LLM,///)
// 2B OOM watchdog cancel
let watchdog = Task {
try? await Task.sleep(for: .seconds(timeout))
analyzeTask?.cancel()
}
defer { watchdog.cancel() }
do {
let parsed = try await CaptureService.shared.reanalyze(assets: assets)
if Task.isCancelled {
await editingFallback(assets: assets,
msg: String(appLoc: "识别超时(>\(timeout)s),先手动录入"))
return
}
let (meta, recognized) = await CaptureService.shared.extractReportMeta(assets: assets)
if Task.isCancelled {
await MainActor.run {
phase = .editing(
parsed: parsed,
assets: assets,
warning: parsed.isEmpty ? String(appLoc: "识别没有读出指标,请手动补充") : nil
)
phase = .editing(parsed: .empty(), assets: assets,
warning: String(appLoc: "识别超时,已保存原图,请手动填写信息"))
}
} catch let CaptureError.parseFailed(msg) {
await editingFallback(assets: assets, msg: String(appLoc: "VL 输出无法解析:\(msg)"))
} catch let CaptureError.inferenceFailed(msg) {
await editingFallback(assets: assets,
msg: Task.isCancelled
? String(appLoc: "识别超时(>\(timeout)s),先手动录入")
: String(appLoc: "推理失败:\(msg)"))
} catch CaptureError.modelNotReady {
await editingFallback(assets: assets, msg: String(appLoc: "VL 模型未就绪,先手动录入"))
} catch {
await editingFallback(assets: assets,
msg: String(appLoc: "未知错误:\(error.localizedDescription)"))
return
}
await MainActor.run {
phase = .editing(
parsed: meta,
assets: assets,
warning: recognized ? nil
: String(appLoc: "未能自动识别报告信息,已保存原图,可手动填写日期 / 机构")
)
}
}
}
/// : assets,, VL
/// : assets,, meta
private func reanalyze(assets: [FileVault.SavedAsset]) {
analyzeTask?.cancel()
// UIImage,AnalyzingView
// UIImage,AnalyzingView , 600px ,
// ( MB)
let thumbnails: [UIImage] = assets.compactMap {
try? FileVault.shared.loadImage(relativePath: $0.relativePath)
try? FileVault.shared.loadDownsampledImage(relativePath: $0.relativePath, maxPixelSize: 600)
}
phase = .analyzing(images: thumbnails, assets: assets)
let timeout = analyzeTimeoutSeconds
@@ -232,40 +222,19 @@ struct UnifiedCaptureFlow: View {
}
defer { watchdog.cancel() }
do {
let parsed = try await CaptureService.shared.reanalyze(assets: assets)
if Task.isCancelled {
await editingFallback(assets: assets,
msg: String(appLoc: "识别超时(>\(timeout)s),保留旧编辑"))
return
}
let (meta, recognized) = await CaptureService.shared.extractReportMeta(assets: assets)
if Task.isCancelled {
await MainActor.run {
phase = .editing(
parsed: parsed,
assets: assets,
warning: parsed.isEmpty ? String(appLoc: "重新识别没有读出新指标") : nil
)
phase = .editing(parsed: .empty(), assets: assets,
warning: String(appLoc: "识别超时,已保留原图"))
}
} catch CaptureError.modelNotReady {
await editingFallback(assets: assets, msg: String(appLoc: "VL 模型未就绪"))
} catch let CaptureError.parseFailed(msg) {
await editingFallback(assets: assets, msg: String(appLoc: "VL 输出无法解析:\(msg)"))
} catch let CaptureError.inferenceFailed(msg) {
await editingFallback(assets: assets,
msg: Task.isCancelled
? String(appLoc: "识别超时(>\(timeout)s)")
: String(appLoc: "推理失败:\(msg)"))
} catch {
await editingFallback(assets: assets,
msg: String(appLoc: "未知错误:\(error.localizedDescription)"))
return
}
await MainActor.run {
phase = .editing(parsed: meta, assets: assets,
warning: recognized ? nil
: String(appLoc: "未能自动识别报告信息,可手动填写"))
}
}
}
/// reanalyze editing, assets parsed
private func editingFallback(assets: [FileVault.SavedAsset], msg: String) async {
await MainActor.run {
phase = .editing(parsed: .empty(), assets: assets, warning: msg)
}
}

View File

@@ -11,8 +11,10 @@ struct DiaryQuickSheet: View {
@State private var content: String = ""
@State private var createdAt: Date = .now
/// :,tag
/// :,
@State private var showMedicationScan = false
/// :( + + ),tag
@State private var showMedicationLog = false
/// : SymptomStartSheet(/,)
@State private var showSymptomStart = false
@@ -98,14 +100,20 @@ struct DiaryQuickSheet: View {
.padding(.horizontal, 20)
.padding(.bottom, 10)
// :()/ ()/ (SymptomStartSheet)
HStack(spacing: 10) {
// (2×2):()/ (MedicationLogSheet,+)/
// ()/ (SymptomStartSheet)
LazyVGrid(columns: [GridItem(.flexible(), spacing: 10),
GridItem(.flexible(), spacing: 10)], spacing: 10) {
modeCard(icon: "pencil", title: String(appLoc: "写日记"),
subtitle: String(appLoc: "文字或语音"), active: true) {
contentFocused = true
}
modeCard(icon: "pills.fill", title: String(appLoc: "拍药盒"),
subtitle: String(appLoc: "识别用药"), active: false) {
modeCard(icon: "pills.fill", title: String(appLoc: "用药"),
subtitle: String(appLoc: "记剂量与时间"), active: false) {
showMedicationLog = true
}
modeCard(icon: "camera.viewfinder", title: String(appLoc: "拍药盒"),
subtitle: String(appLoc: "识别入药品库"), active: false) {
showMedicationScan = true
}
modeCard(icon: "waveform.path.ecg", title: String(appLoc: "记症状"),
@@ -252,9 +260,9 @@ struct DiaryQuickSheet: View {
.presentationCornerRadius(Tj.Radius.xl)
.fullScreenCover(isPresented: $showMedicationScan) {
MedicationScanFlow(
onSave: { entries in
// :(线)+ ·
MedicationArchiver.archive(entries: entries, in: ctx)
onSave: { meds, images in
// (), ·
MedicationArchiver.archive(medications: meds, images: images, in: ctx)
dismiss()
},
onClose: { showMedicationScan = false }
@@ -264,6 +272,10 @@ struct DiaryQuickSheet: View {
// sheet:/;,
SymptomStartSheet()
}
.sheet(isPresented: $showMedicationLog) {
// sheet:/;()
MedicationLogSheet()
}
.onDisappear {
suggestTask?.cancel()
voiceFlowTask?.cancel()

View File

@@ -0,0 +1,133 @@
import SwiftUI
import SwiftData
/// · : ()+ +
/// `DiaryEntry.medicationTag` ,线
///
/// (`Medication`,master ):
/// sheet, / ( `SymptomStartSheet`),
struct MedicationLogSheet: View {
@Environment(\.modelContext) private var ctx
@Environment(\.dismiss) private var dismiss
@Query(sort: \Medication.updatedAt, order: .reverse)
private var library: [Medication]
/// ; nil
@State private var selectedMed: Medication?
/// (,) selectedMed
@State private var manualName = ""
@State private var dosage = ""
@State private var takenAt: Date = .now
private var resolvedName: String {
(selectedMed?.name ?? manualName).trimmingCharacters(in: .whitespacesAndNewlines)
}
private var canSave: Bool { !resolvedName.isEmpty }
var body: some View {
NavigationStack {
Form {
Section {
if library.isEmpty {
TextField(String(appLoc: "药名,如:缬沙坦胶囊"), text: $manualName)
.foregroundStyle(Tj.Palette.text)
} else {
ForEach(library) { m in
Button { select(m) } label: { medRow(m) }
.buttonStyle(.plain)
}
HStack(spacing: 8) {
Image(systemName: "pencil")
.foregroundStyle(Tj.Palette.text3)
TextField(String(appLoc: "或手动输入药名"), text: $manualName)
.foregroundStyle(Tj.Palette.text)
.onChange(of: manualName) { _, v in
if !v.trimmingCharacters(in: .whitespaces).isEmpty {
selectedMed = nil
}
}
}
}
} header: {
Text("吃了哪个药")
} footer: {
if library.isEmpty {
Text("药品库还没有药,可在「记录 · 药品库」拍药盒或手动添加。这里直接手输也行。")
}
}
Section {
TextField(String(appLoc: "剂量,如:1 片 / 80mg"), text: $dosage)
.foregroundStyle(Tj.Palette.text)
} header: {
Text("剂量")
}
Section {
DatePicker(String(appLoc: "时间"), selection: $takenAt, in: ...Date.now)
} header: {
Text("时间")
}
}
.scrollContentBackground(.hidden)
.background(Tj.Palette.sand.ignoresSafeArea())
.navigationTitle("记录用药")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button(String(appLoc: "取消")) { dismiss() }
}
ToolbarItem(placement: .topBarTrailing) {
Button(String(appLoc: "保存")) { save() }
.fontWeight(.semibold)
.disabled(!canSave)
}
}
}
}
private func medRow(_ m: Medication) -> some View {
let on = selectedMed === m
return HStack(spacing: 10) {
Image(systemName: on ? "checkmark.circle.fill" : "circle")
.foregroundStyle(on ? Tj.Palette.ink : Tj.Palette.text3)
VStack(alignment: .leading, spacing: 2) {
Text(m.name)
.foregroundStyle(Tj.Palette.text)
if !m.detailLine.isEmpty {
Text(m.detailLine)
.font(.tjScaled( 11))
.foregroundStyle(Tj.Palette.text3)
}
}
Spacer(minLength: 0)
}
.contentShape(Rectangle())
}
private func select(_ m: Medication) {
selectedMed = m
manualName = ""
}
private func save() {
guard canSave else { return }
// content : [] · , createdAt
// TimelineEntry.firstLine / TimelineEntryDetailView.medicationLines
var line = resolvedName
if let s = selectedMed?.strength, !s.isEmpty { line += " \(s)" }
let dose = dosage.trimmingCharacters(in: .whitespacesAndNewlines)
if !dose.isEmpty { line += " · \(dose)" }
let entry = DiaryEntry(content: line, createdAt: takenAt, tags: [DiaryEntry.medicationTag])
ctx.insert(entry)
try? ctx.save()
dismiss()
}
}
#Preview {
MedicationLogSheet()
.modelContainer(for: [Medication.self, DiaryEntry.self, Asset.self], inMemory: true)
}

View File

@@ -18,21 +18,19 @@ struct HomeView: View {
/// sheet( C1 )
@State private var selectedEntry: TimelineEntry?
/// ( + , C1 )
@State private var selectedGroup: IndicatorGroup?
@MainActor
private var recentEntries: [TimelineEntry] {
let all =
TimelineEntry.from(indicators: indicators) +
TimelineEntry.aggregatedIndicators(indicators) +
reports.map(TimelineEntry.from(report:)) +
diaries.map(TimelineEntry.from(diary:)) +
symptoms.map(TimelineEntry.from(symptom:))
return all.sorted { $0.date > $1.date }.prefix(6).map { $0 }
}
private var recentGrouped: [(section: DateSection, items: [TimelineEntry])] {
TimelineGrouping.group(recentEntries)
}
var body: some View {
ScrollView(showsIndicators: false) {
VStack(alignment: .leading, spacing: 0) {
@@ -65,6 +63,9 @@ struct HomeView: View {
TimelineEntryDetailView(detail: d)
}
}
.sheet(item: $selectedGroup) { group in
IndicatorSeriesDetailView(group: group)
}
}
private var greeting: some View {
@@ -100,7 +101,10 @@ struct HomeView: View {
}
private var recentSection: some View {
VStack(alignment: .leading, spacing: 10) {
// ( O(m²)) body ,, .isEmpty
let entries = recentEntries
let groups = TimelineGrouping.group(entries)
return VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .lastTextBaseline) {
Text("最近记录").font(.tjH2()).foregroundStyle(Tj.Palette.text)
Spacer()
@@ -112,11 +116,11 @@ struct HomeView: View {
.buttonStyle(.plain)
}
if recentEntries.isEmpty {
if entries.isEmpty {
emptyRecent
} else {
VStack(alignment: .leading, spacing: 14) {
ForEach(recentGrouped, id: \.section) { group in
ForEach(groups, id: \.section) { group in
VStack(alignment: .leading, spacing: 8) {
Text(group.section.label)
.font(.tjScaled( 11, weight: .semibold))
@@ -125,12 +129,16 @@ struct HomeView: View {
VStack(spacing: 10) {
ForEach(group.items) { entry in
Button {
if TimelineDetail.resolve(
// ( + ); C1
guard let d = TimelineDetail.resolve(
for: entry,
indicators: indicators, reports: reports,
diaries: diaries, symptoms: symptoms
) != nil {
selectedEntry = entry
) else { return }
switch d {
case .indicator(let i): selectedGroup = IndicatorGroup.of(i)
case .bloodPressure(let sys, _): selectedGroup = IndicatorGroup.of(sys)
default: selectedEntry = entry
}
} label: {
TimelineRow(entry: entry)

View File

@@ -31,6 +31,18 @@ struct IndicatorQuickSheet: View {
/// nil ( Preview)
var onRequestCamera: (() -> Void)? = nil
/// nil =
/// seriesKey MonitorMetric / CustomMonitorMetric ( + );
/// name/unit/range ,
var prefill: Prefill? = nil
struct Prefill: Equatable {
var seriesKey: String?
var name: String = ""
var unit: String = ""
var range: String = ""
}
@Environment(\.modelContext) private var ctx
@Environment(\.dismiss) private var dismiss
@Query private var profiles: [UserProfile]
@@ -69,6 +81,32 @@ struct IndicatorQuickSheet: View {
// sheet
@State private var showHiddenSheet: Bool = false
//
@State private var didApplyPrefill = false
// :, / /
@State private var searchingMetrics = false
@State private var metricQuery = ""
private var isSearchingMetrics: Bool {
!metricQuery.trimmingCharacters(in: .whitespaces).isEmpty
}
private var filteredMonitorMetrics: [MonitorMetric] {
let q = metricQuery.trimmingCharacters(in: .whitespaces)
guard !q.isEmpty else { return visibleMonitorMetrics }
return visibleMonitorMetrics.filter { $0.displayName.localizedCaseInsensitiveContains(q) }
}
private var filteredCustomMetrics: [CustomMonitorMetric] {
let q = metricQuery.trimmingCharacters(in: .whitespaces)
guard !q.isEmpty else { return customMetrics }
return customMetrics.filter { $0.name.localizedCaseInsensitiveContains(q) }
}
private var filteredLabPresets: [IndicatorPreset] {
let q = metricQuery.trimmingCharacters(in: .whitespaces)
guard !q.isEmpty else { return labPresets }
return labPresets.filter { $0.name.localizedCaseInsensitiveContains(q) }
}
private static var defaultReminderTime: Date {
Calendar.current.date(bySettingHour: 8, minute: 0, second: 0, of: .now) ?? .now
}
@@ -137,6 +175,7 @@ struct IndicatorQuickSheet: View {
footer
}
.onAppear { applyPrefillIfNeeded() }
.task(id: longTermKey) { hydrateReminder() }
.background(
Tj.Palette.sand
@@ -161,19 +200,64 @@ struct IndicatorQuickSheet: View {
}
private var header: some View {
HStack {
Text("记录指标")
.font(.tjH2())
.foregroundStyle(Tj.Palette.text)
Spacer()
Text("本地处理 · 永不上传")
.font(.tjScaled( 12))
.foregroundStyle(Tj.Palette.text3)
VStack(spacing: 12) {
HStack(spacing: 10) {
Text("记录指标")
.font(.tjH2())
.foregroundStyle(Tj.Palette.text)
Spacer()
Text("本地处理 · 永不上传")
.font(.tjScaled( 12))
.foregroundStyle(Tj.Palette.text3)
searchToggle
}
if searchingMetrics { searchField }
}
.padding(.horizontal, 20)
.padding(.bottom, 16)
}
private var searchToggle: some View {
Button {
withAnimation(.easeInOut(duration: 0.18)) {
searchingMetrics.toggle()
if !searchingMetrics { metricQuery = "" }
}
} label: {
Image(systemName: searchingMetrics ? "xmark" : "magnifyingglass")
.font(.tjScaled( 14, weight: .semibold))
.foregroundStyle(Tj.Palette.text)
.frame(width: 32, height: 32)
.background(Circle().fill(Tj.Palette.sand2))
}
.buttonStyle(.plain)
.accessibilityLabel(searchingMetrics ? String(appLoc: "关闭搜索") : String(appLoc: "搜索指标"))
}
private var searchField: some View {
HStack(spacing: 8) {
Image(systemName: "magnifyingglass")
.font(.tjScaled( 13))
.foregroundStyle(Tj.Palette.text3)
TextField(String(appLoc: "搜索指标名"), text: $metricQuery)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.foregroundStyle(Tj.Palette.text)
.tint(Tj.Palette.ink)
if !metricQuery.isEmpty {
Button { metricQuery = "" } label: {
Image(systemName: "xmark.circle.fill")
.foregroundStyle(Tj.Palette.text3)
}
.buttonStyle(.plain)
}
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background(fieldBg)
.overlay(fieldBorder)
}
/// : RootView VL
@ViewBuilder
private var cameraEntrySection: some View {
@@ -241,13 +325,19 @@ struct IndicatorQuickSheet: View {
}
let columns = [GridItem(.flexible()), GridItem(.flexible())]
LazyVGrid(columns: columns, spacing: 8) {
ForEach(visibleMonitorMetrics) { m in
ForEach(filteredMonitorMetrics) { m in
monitorTile(m)
}
ForEach(customMetrics) { cm in
ForEach(filteredCustomMetrics) { cm in
customTile(cm)
}
addCustomTile
// (),
if !isSearchingMetrics { addCustomTile }
}
if isSearchingMetrics, filteredMonitorMetrics.isEmpty, filteredCustomMetrics.isEmpty {
Text("没有匹配的长期监测指标")
.font(.tjScaled( 12))
.foregroundStyle(Tj.Palette.text3)
}
}
.sheet(isPresented: $showHiddenSheet) {
@@ -386,14 +476,18 @@ struct IndicatorQuickSheet: View {
}
}
@ViewBuilder
private var labPresetSection: some View {
VStack(alignment: .leading, spacing: 8) {
sectionLabel(String(appLoc: "化验项快捷(不进趋势)"))
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(labPresets) { p in
chip(p.name, selected: selectedLabPreset == p) {
applyLab(p)
// :()
if !(isSearchingMetrics && filteredLabPresets.isEmpty) {
VStack(alignment: .leading, spacing: 8) {
sectionLabel(String(appLoc: "化验项快捷(不进趋势)"))
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(filteredLabPresets) { p in
chip(p.name, selected: selectedLabPreset == p) {
applyLab(p)
}
}
}
}
@@ -941,6 +1035,29 @@ struct IndicatorQuickSheet: View {
// MARK: - apply preset
/// :seriesKey / ( + ),
/// name/unit/range
private func applyPrefillIfNeeded() {
guard !didApplyPrefill, let p = prefill else { return }
didApplyPrefill = true
if let key = p.seriesKey {
if let m = MonitorMetric.allCases.first(where: { metric in
metric.fields.contains { $0.seriesKey == key }
}) {
applyMonitor(m)
return
}
if let cm = customMetrics.first(where: { $0.seriesKey == key }) {
applyCustom(cm)
return
}
}
// seriesKey ( / / ):, seriesKey,
name = p.name
unit = p.unit
range = p.range
}
private func applyMonitor(_ m: MonitorMetric) {
if selectedMonitor == m {
//

View File

@@ -0,0 +1,39 @@
import SwiftUI
extension IndicatorQuickSheet.Prefill {
/// :
/// seriesKey / ( + ), name/unit/range
init(indicator i: Indicator) {
self.init(seriesKey: i.seriesKey, name: i.name, unit: i.unit, range: i.range)
}
}
/// / :(,)
/// ,`TimelineEntryDetailView` `IndicatorSeriesDetailView`
struct RecordAnotherButton: View {
/// ()
let name: String
///
let prefill: IndicatorQuickSheet.Prefill
@State private var showSheet = false
var body: some View {
Button { showSheet = true } label: {
Label(String(appLoc: "再记一条「\(name)"), systemImage: "plus.circle.fill")
.font(.tjScaled( 13, weight: .semibold))
.foregroundStyle(Tj.Palette.ink)
.frame(maxWidth: .infinity)
.padding(.vertical, 12)
.background(
RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous)
.fill(Tj.Palette.leaf.opacity(0.16))
)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.sheet(isPresented: $showSheet) {
IndicatorQuickSheet(prefill: prefill)
}
}
}

View File

@@ -10,13 +10,20 @@ struct CustomReminderEditSheet: View {
/// nil =
let reminder: CustomReminder?
/// (,:+ )
/// (reminder != nil)
private let prefillTitle: String
private let prefillNote: String
@State private var title = ""
@State private var note = ""
@State private var pickedTime: Date = .now
@State private var frequency: CustomReminder.Frequency = .daily
/// (/// )
@State private var frequencies: Set<CustomReminder.Frequency> = [.daily]
@State private var weekdays: Set<Int> = Set(1...7)
@State private var dayOfMonth = 1
/// (1...31)
@State private var monthDays: Set<Int> = [1]
@State private var dayOfMonth = 1 //
@State private var month = 1
@State private var hydrated = false
@State private var showAuthDeniedAlert = false
@@ -24,8 +31,10 @@ struct CustomReminderEditSheet: View {
/// (, ): / / /
private let timePresets: [(h: Int, m: Int)] = [(8, 0), (12, 0), (18, 0), (22, 0)]
init(reminder: CustomReminder? = nil) {
init(reminder: CustomReminder? = nil, prefillTitle: String = "", prefillNote: String = "") {
self.reminder = reminder
self.prefillTitle = prefillTitle
self.prefillNote = prefillNote
}
private var isEditing: Bool { reminder != nil }
@@ -33,8 +42,9 @@ struct CustomReminderEditSheet: View {
title.trimmingCharacters(in: .whitespacesAndNewlines)
}
private var canSave: Bool {
guard !trimmedTitle.isEmpty else { return false }
if frequency == .weekly { return !weekdays.isEmpty }
guard !trimmedTitle.isEmpty, !frequencies.isEmpty else { return false }
if frequencies.contains(.weekly) && weekdays.isEmpty { return false }
if frequencies.contains(.monthly) && monthDays.isEmpty { return false }
return true
}
@@ -51,18 +61,12 @@ struct CustomReminderEditSheet: View {
}
Section {
Picker(String(appLoc: "重复"), selection: $frequency) {
Text(String(appLoc: "每日")).tag(CustomReminder.Frequency.daily)
Text(String(appLoc: "每周")).tag(CustomReminder.Frequency.weekly)
Text(String(appLoc: "每月")).tag(CustomReminder.Frequency.monthly)
Text(String(appLoc: "每年")).tag(CustomReminder.Frequency.yearly)
}
.pickerStyle(.segmented)
.listRowBackground(Color.clear)
frequencyChips
frequencyDetail
} header: {
Text("重复")
} footer: {
Text("可多选:如同时勾选「每周一三五」+「每月1日」,两种节奏都会提醒。")
}
Section {
@@ -109,23 +113,60 @@ struct CustomReminderEditSheet: View {
}
}
// MARK: -
// MARK: - chip
private static let freqOrder: [CustomReminder.Frequency] = [.daily, .weekly, .monthly, .yearly]
private func freqLabel(_ f: CustomReminder.Frequency) -> String {
switch f {
case .daily: return String(appLoc: "每日")
case .weekly: return String(appLoc: "每周")
case .monthly: return String(appLoc: "每月")
case .yearly: return String(appLoc: "每年")
}
}
private var frequencyChips: some View {
HStack(spacing: 8) {
ForEach(Self.freqOrder, id: \.self) { f in
let on = frequencies.contains(f)
Button {
if on { frequencies.remove(f) } else { frequencies.insert(f) }
} label: {
Text(freqLabel(f))
.font(.tjScaled( 13, weight: on ? .semibold : .regular))
.foregroundStyle(on ? Tj.Palette.paper : Tj.Palette.text)
.frame(maxWidth: .infinity, minHeight: 32)
.background(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.fill(on ? Tj.Palette.ink : Tj.Palette.paper)
)
.overlay(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.strokeBorder(Tj.Palette.line, lineWidth: on ? 0 : 1)
)
}
.buttonStyle(.plain)
}
}
.listRowBackground(Color.clear)
}
// MARK: - (,)
@ViewBuilder
private var frequencyDetail: some View {
switch frequency {
case .daily:
EmptyView()
case .weekly:
if frequencies.contains(.weekly) {
subCaption(String(appLoc: "每周 · 选星期几"))
weekdayRow
case .monthly:
Picker(String(appLoc: "日期"), selection: $dayOfMonth) {
ForEach(1...31, id: \.self) { d in
Text(String(appLoc: "\(d)")).tag(d)
}
}
if dayOfMonth >= 29 { skipHint }
case .yearly:
}
if frequencies.contains(.monthly) {
subCaption(String(appLoc: "每月 · 选日期(可多选)"))
monthDayGrid
if monthDays.contains(where: { $0 >= 29 }) { skipHint }
}
if frequencies.contains(.yearly) {
subCaption(String(appLoc: "每年 · 选月/日"))
Picker(String(appLoc: "月份"), selection: $month) {
ForEach(1...12, id: \.self) { mo in
Text(String(appLoc: "\(mo)")).tag(mo)
@@ -140,6 +181,41 @@ struct CustomReminderEditSheet: View {
}
}
private func subCaption(_ text: String) -> some View {
Text(text)
.font(.tjScaled( 11, weight: .semibold))
.foregroundStyle(Tj.Palette.text3)
.frame(maxWidth: .infinity, alignment: .leading)
.listRowBackground(Color.clear)
}
/// (1...31,7 )
private var monthDayGrid: some View {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 7), spacing: 6) {
ForEach(1...31, id: \.self) { d in
let on = monthDays.contains(d)
Button {
if on { monthDays.remove(d) } else { monthDays.insert(d) }
} label: {
Text("\(d)")
.font(.tjScaled( 12, weight: on ? .semibold : .regular))
.foregroundStyle(on ? Tj.Palette.paper : Tj.Palette.text)
.frame(maxWidth: .infinity, minHeight: 30)
.background(
RoundedRectangle(cornerRadius: 6, style: .continuous)
.fill(on ? Tj.Palette.ink : Tj.Palette.paper)
)
.overlay(
RoundedRectangle(cornerRadius: 6, style: .continuous)
.strokeBorder(Tj.Palette.line, lineWidth: on ? 0 : 1)
)
}
.buttonStyle(.plain)
}
}
.listRowBackground(Color.clear)
}
private var skipHint: some View {
Text(String(appLoc: "部分月份无此日,该月将跳过"))
.font(.tjScaled( 11))
@@ -229,13 +305,18 @@ struct CustomReminderEditSheet: View {
if let r = reminder {
title = r.title
note = r.note
frequency = r.frequency
frequencies = r.frequencies
weekdays = Set(r.weekdays)
monthDays = Set(r.monthlyDays)
dayOfMonth = r.dayOfMonth
month = r.month
pickedTime = Calendar.current.date(
bySettingHour: r.hour, minute: r.minute, second: 0, of: .now
) ?? .now
} else {
// :( / )
title = prefillTitle
note = prefillNote
}
}
@@ -245,6 +326,7 @@ struct CustomReminderEditSheet: View {
let hour = cal.component(.hour, from: pickedTime)
let minute = cal.component(.minute, from: pickedTime)
let sortedDays = weekdays.sorted()
let sortedMonthDays = monthDays.sorted()
let target: CustomReminder
if let r = reminder {
@@ -253,8 +335,9 @@ struct CustomReminderEditSheet: View {
r.hour = hour
r.minute = minute
r.weekdays = sortedDays
r.frequency = frequency
r.dayOfMonth = dayOfMonth
r.frequencies = frequencies // frequenciesRaw(+ frequencyRaw)
r.monthlyDays = sortedMonthDays // monthDays
r.dayOfMonth = dayOfMonth //
r.month = month
r.updatedAt = .now
target = r
@@ -265,10 +348,11 @@ struct CustomReminderEditSheet: View {
hour: hour,
minute: minute,
weekdays: sortedDays,
frequency: frequency,
dayOfMonth: dayOfMonth,
month: month
)
new.frequencies = frequencies
new.monthlyDays = sortedMonthDays
ctx.insert(new)
target = new
}

View File

@@ -282,6 +282,6 @@ struct MeView: View {
.modelContainer(for: [
UserProfile.self, Indicator.self, Report.self, DiaryEntry.self,
Asset.self, ChatTurn.self, Symptom.self, MetricReminder.self,
CustomMonitorMetric.self,
CustomMonitorMetric.self, Medication.self,
], inMemory: true)
}

View File

@@ -0,0 +1,383 @@
import SwiftUI
import SwiftData
/// · : master ( / / / )
/// ; · ( `DiaryEntry.medicationTag` , + )
/// / `CustomMetricsListView`; `CustomReminderEditSheet`
struct MedicationLibraryView: View {
@Environment(\.modelContext) private var ctx
@Environment(\.dismiss) private var dismiss
@Query(sort: \Medication.updatedAt, order: .reverse)
private var medications: [Medication]
/// sheet ();push ,
var presentedAsSheet: Bool = false
@State private var editingTarget: MedicationEditTarget?
@State private var showScan = false
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 12) {
hintBanner
if medications.isEmpty {
emptyState
} else {
ForEach(medications) { m in
Button {
editingTarget = MedicationEditTarget(medication: m)
} label: {
row(m)
}
.buttonStyle(.plain)
}
}
}
.padding(.horizontal, 16)
.padding(.top, 8)
.padding(.bottom, 32)
}
.background(Tj.Palette.sand.ignoresSafeArea())
.navigationTitle("药品库")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
if presentedAsSheet {
ToolbarItem(placement: .topBarLeading) {
Button(String(appLoc: "完成")) { dismiss() }
}
}
ToolbarItem(placement: .topBarTrailing) {
HStack(spacing: 16) {
Button { showScan = true } label: {
Image(systemName: "camera")
.font(.tjScaled( 16, weight: .semibold))
}
.accessibilityLabel(String(appLoc: "拍药盒添加"))
Button { editingTarget = MedicationEditTarget(medication: nil) } label: {
Image(systemName: "plus")
.font(.tjScaled( 16, weight: .semibold))
}
.accessibilityLabel(String(appLoc: "手动添加"))
}
}
}
.sheet(item: $editingTarget) { target in
MedicationEditSheet(existing: target.medication)
}
.fullScreenCover(isPresented: $showScan) {
// OCR + LLM ()
MedicationScanFlow(
onSave: { meds, images in
MedicationArchiver.archive(medications: meds, images: images, in: ctx)
},
onClose: { showScan = false }
)
}
}
// MARK: - subviews
private var hintBanner: some View {
HStack(spacing: 10) {
Image(systemName: "info.circle.fill")
.foregroundStyle(Tj.Palette.text3)
Text("药品库是你的常用药清单。记录某次服用请到「写日记 · 用药」,可填剂量和时间。")
.font(.tjScaled( 12))
.foregroundStyle(Tj.Palette.text2)
.fixedSize(horizontal: false, vertical: true)
Spacer(minLength: 0)
}
.padding(12)
.background(
RoundedRectangle(cornerRadius: Tj.Radius.sm, style: .continuous)
.fill(Tj.Palette.sand2.opacity(0.5))
)
}
private var emptyState: some View {
VStack(spacing: 14) {
Spacer(minLength: 40)
TjPlaceholder(label: String(appLoc: "药品库还是空的"))
.frame(width: 220, height: 130)
Text("右上角拍药盒或 + 手动添加")
.font(.tjScaled( 12))
.foregroundStyle(Tj.Palette.text3)
Spacer()
}
.frame(maxWidth: .infinity)
}
private func row(_ m: Medication) -> some View {
HStack(spacing: 12) {
ZStack {
Circle().fill(Tj.Palette.leafSoft)
Image(systemName: "pills.fill")
.font(.tjScaled( 17, weight: .medium))
.foregroundStyle(Tj.Palette.ink)
}
.frame(width: 40, height: 40)
VStack(alignment: .leading, spacing: 3) {
Text(m.name)
.font(.tjScaled( 15, weight: .semibold))
.foregroundStyle(Tj.Palette.text)
.lineLimit(1)
if !m.detailLine.isEmpty {
Text(m.detailLine)
.font(.tjScaled( 11))
.foregroundStyle(Tj.Palette.text3)
.lineLimit(1)
}
}
Spacer(minLength: 8)
if !m.assets.isEmpty {
Text("📷 \(m.assets.count)")
.font(.tjScaled( 11))
.foregroundStyle(Tj.Palette.text3)
}
Image(systemName: "chevron.right")
.font(.tjScaled( 11, weight: .medium))
.foregroundStyle(Tj.Palette.text3)
}
.padding(14)
.background(
RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous)
.fill(Tj.Palette.paper)
)
.overlay(
RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous)
.strokeBorder(Tj.Palette.lineSoft, lineWidth: 1)
)
}
}
/// `medication == nil` ;`id` UUID sheet
private struct MedicationEditTarget: Identifiable {
let id = UUID()
let medication: Medication?
}
/// / ( `CustomReminderEditSheet`: @State ,)
private struct MedicationEditSheet: View {
@Environment(\.modelContext) private var ctx
@Environment(\.dismiss) private var dismiss
/// nil =
let existing: Medication?
@State private var name = ""
@State private var strength = ""
@State private var usage = ""
@State private var note = ""
@State private var hydrated = false
/// ;nil =
@State private var viewerStart: PhotoIndex?
private var isEditing: Bool { existing != nil }
private var canSave: Bool {
!name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
var body: some View {
NavigationStack {
Form {
if let m = existing, !m.assets.isEmpty {
Section {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 10) {
ForEach(Array(m.assets.enumerated()), id: \.offset) { idx, asset in
Button {
viewerStart = PhotoIndex(index: idx)
} label: {
MedicationAssetThumb(asset: asset)
}
.buttonStyle(.plain)
}
}
.padding(.vertical, 4)
}
.listRowInsets(EdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12))
} header: {
Text(String(appLoc: "原图\(m.assets.count)"))
} footer: {
Text("点图片可放大查看。原图均存在本机加密目录,不上传。")
}
}
Section {
TextField(String(appLoc: "药名,如:缬沙坦胶囊"), text: $name)
.foregroundStyle(Tj.Palette.text)
TextField(String(appLoc: "规格,如:80mg×7粒"), text: $strength)
.foregroundStyle(Tj.Palette.text2)
TextField(String(appLoc: "用法,如:一日一次,一次一粒"), text: $usage)
.foregroundStyle(Tj.Palette.text2)
} footer: {
Text("仅作清单记录,不提供任何用药或剂量建议。")
}
Section {
TextField(String(appLoc: "备注(可选)"), text: $note, axis: .vertical)
.lineLimit(1...3)
.foregroundStyle(Tj.Palette.text2)
}
if isEditing {
Section {
Button(role: .destructive) { deleteMedication() } label: {
Label(String(appLoc: "从药品库删除"), systemImage: "trash")
}
}
}
}
.scrollContentBackground(.hidden)
.background(Tj.Palette.sand.ignoresSafeArea())
.navigationTitle(isEditing ? String(appLoc: "编辑药品") : String(appLoc: "添加药品"))
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button(String(appLoc: "取消")) { dismiss() }
}
ToolbarItem(placement: .topBarTrailing) {
Button(String(appLoc: "保存")) { save() }
.fontWeight(.semibold)
.disabled(!canSave)
}
}
.onAppear(perform: hydrate)
.fullScreenCover(item: $viewerStart) { start in
if let m = existing {
MedicationPhotoViewer(assets: m.assets, startIndex: start.index)
}
}
}
}
private func hydrate() {
guard !hydrated else { return }
hydrated = true
if let m = existing {
name = m.name
strength = m.strength
usage = m.usage
note = m.note ?? ""
}
}
private func save() {
guard canSave else { return }
let n = name.trimmingCharacters(in: .whitespacesAndNewlines)
let s = strength.trimmingCharacters(in: .whitespacesAndNewlines)
let u = usage.trimmingCharacters(in: .whitespacesAndNewlines)
let nt = note.trimmingCharacters(in: .whitespacesAndNewlines)
if let m = existing {
m.name = n
m.strength = s
m.usage = u
m.note = nt.isEmpty ? nil : nt
m.updatedAt = .now
} else {
let med = Medication(name: n, strength: s, usage: u, note: nt.isEmpty ? nil : nt)
ctx.insert(med)
}
try? ctx.save()
dismiss()
}
private func deleteMedication() {
guard let m = existing else { return }
// Vault JPEG(cascade Asset , unlink,§6 )
for a in m.assets {
try? FileVault.shared.remove(relativePath: a.relativePath)
}
ctx.delete(m)
try? ctx.save()
dismiss()
}
}
// MARK: -
/// (`.fullScreenCover(item:)` Identifiable)
private struct PhotoIndex: Identifiable {
let id = UUID()
let index: Int
}
/// / Vault (, EvidenceImagePage )
private struct MedicationAssetThumb: View {
let asset: Asset
var body: some View {
VaultImage(relativePath: asset.relativePath, maxPixel: 500) { img in
Image(uiImage: img).resizable().scaledToFill()
} placeholder: { isLoading in
if isLoading {
Tj.Palette.paper
} else {
TjPlaceholder(label: String(appLoc: "原图无法读取"))
}
}
.frame(width: 150, height: 150)
.clipped()
.clipShape(RoundedRectangle(cornerRadius: Tj.Radius.sm, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: Tj.Radius.sm, style: .continuous)
.strokeBorder(Tj.Palette.lineSoft, lineWidth: 1)
)
}
}
/// ()
private struct MedicationPhotoViewer: View {
@Environment(\.dismiss) private var dismiss
let assets: [Asset]
@State private var selection: Int
init(assets: [Asset], startIndex: Int) {
self.assets = assets
_selection = State(initialValue: min(max(startIndex, 0), max(assets.count - 1, 0)))
}
var body: some View {
ZStack(alignment: .topTrailing) {
Color.black.ignoresSafeArea()
TabView(selection: $selection) {
ForEach(Array(assets.enumerated()), id: \.offset) { idx, asset in
VaultImage(relativePath: asset.relativePath, maxPixel: 2000) { img in
Image(uiImage: img).resizable().scaledToFit()
} placeholder: { isLoading in
if isLoading {
ProgressView().tint(.white)
} else {
TjPlaceholder(label: String(appLoc: "原图无法读取"))
}
}
.tag(idx)
}
}
.tabViewStyle(.page(indexDisplayMode: assets.count > 1 ? .automatic : .never))
.ignoresSafeArea()
Button { dismiss() } label: {
Image(systemName: "xmark")
.font(.tjScaled( 16, weight: .semibold))
.foregroundStyle(.white)
.frame(width: 36, height: 36)
.background(Circle().fill(.black.opacity(0.4)))
}
.padding(.trailing, 18)
.padding(.top, 14)
}
}
}
#Preview {
NavigationStack {
MedicationLibraryView(presentedAsSheet: true)
}
.modelContainer(for: [Medication.self, Asset.self], inMemory: true)
}

View File

@@ -2,28 +2,41 @@ import SwiftUI
import SwiftData
import UIKit
/// :/ Vision OCR LLM
/// :+ · · · ·
/// `MedicationArchiver`:(线)+
/// ,/(§1)
/// :/( 5 ,) Vision OCR LLM ()
/// : · · ·
/// `MedicationArchiver`: `Medication`(),
/// · `medicationTag` DiaryEntry,/(§1)
///
/// ( QuickRegionCaptureFlow ):
/// :
/// ```
/// idle(/) recognizing(OCR + LLM) confirm() onSave
/// / confirm( + ,)
/// idle(/) 1 collecting(:/5//)
///
///
/// recognizing( OCR + LLM) confirm() onSave
/// / confirm( + )
/// ```
struct MedicationScanFlow: View {
/// (, " 80mg · ")
let onSave: ([String]) -> Void
/// (, )( MedicationArchiver.archive(medications:))
let onSave: ([ParsedMedication], [UIImage]) -> Void
let onClose: () -> Void
/// 5 (//)
static let maxImages = 5
@State private var phase: Phase = .idle
/// /, collecting recognizing confirm ,
@State private var images: [UIImage] = []
/// () OCR ;
@State private var recognizeIndex = 0
/// collecting /
@State private var showMoreCapture = false
/// :,
@State private var recognitionTask: Task<Void, Never>?
enum Phase {
case idle
case recognizing(image: UIImage)
case collecting
case recognizing
case confirm(items: [EditableMedication], warning: String?)
}
@@ -35,6 +48,8 @@ struct MedicationScanFlow: View {
var include: Bool = true
}
private var remainingSlots: Int { max(0, Self.maxImages - images.count) }
var body: some View {
content
.background(Tj.Palette.sand.ignoresSafeArea())
@@ -45,10 +60,14 @@ struct MedicationScanFlow: View {
switch phase {
case .idle:
// ignoresSafeArea:,
captureEntry
initialCaptureEntry
case .recognizing(let image):
recognizingView(image: image)
case .collecting:
collectingView
.fullScreenCover(isPresented: $showMoreCapture) { moreCaptureSheet }
case .recognizing:
recognizingView
case .confirm(let items, let warning):
NavigationStack {
@@ -56,7 +75,7 @@ struct MedicationScanFlow: View {
items: items,
warning: warning,
onSave: { saveItems($0) },
onRetake: { phase = .idle }
onRetake: { images = []; phase = .idle }
)
.navigationTitle("核对药品")
.navigationBarTitleDisplayMode(.inline)
@@ -72,31 +91,160 @@ struct MedicationScanFlow: View {
// MARK: - :()/ ()
/// :/ collecting
@ViewBuilder
private var captureEntry: some View {
private var initialCaptureEntry: some View {
#if targetEnvironment(simulator)
PhotoPickerSheet(
onFinish: { images in
if let first = images.first { startRecognition(first) } else { onClose() }
onFinish: { picked in
appendImages(picked)
if images.isEmpty { onClose() } else { phase = .collecting }
},
onCancel: onClose
)
#else
SingleShotCameraView(
onCapture: { startRecognition($0) },
onCapture: { appendImages([$0]); phase = .collecting },
onCancel: onClose
)
#endif
}
private func recognizingView(image: UIImage) -> some View {
/// collecting /
@ViewBuilder
private var moreCaptureSheet: some View {
#if targetEnvironment(simulator)
PhotoPickerSheet(
onFinish: { picked in appendImages(picked); showMoreCapture = false },
onCancel: { showMoreCapture = false }
)
#else
SingleShotCameraView(
onCapture: { appendImages([$0]); showMoreCapture = false },
onCancel: { showMoreCapture = false }
)
#endif
}
private func appendImages(_ new: [UIImage]) {
guard remainingSlots > 0 else { return }
images.append(contentsOf: new.prefix(remainingSlots))
}
// MARK: - ( N : / / )
private var collectingView: some View {
VStack(spacing: 0) {
ScrollView {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 96), spacing: 12)], spacing: 12) {
ForEach(Array(images.enumerated()), id: \.offset) { idx, img in
let isPick = idx == recognizeIndex
ZStack(alignment: .topTrailing) {
Image(uiImage: img)
.resizable()
.scaledToFill()
.frame(width: 96, height: 96)
.clipShape(RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous)
.strokeBorder(isPick ? Tj.Palette.ink : Color.clear, lineWidth: 3)
)
.overlay(alignment: .bottomLeading) {
if isPick {
Text("识别此张")
.font(.tjScaled(10, weight: .semibold))
.foregroundStyle(Tj.Palette.paper)
.padding(.horizontal, 6)
.padding(.vertical, 3)
.background(Capsule().fill(Tj.Palette.ink))
.padding(5)
}
}
// ()
.onTapGesture { recognizeIndex = idx }
Button {
images.remove(at: idx)
// :;
if images.isEmpty {
recognizeIndex = 0
phase = .idle
} else if idx < recognizeIndex {
recognizeIndex -= 1
} else if recognizeIndex >= images.count {
recognizeIndex = images.count - 1
}
} label: {
Image(systemName: "xmark.circle.fill")
.font(.tjScaled(20))
.foregroundStyle(.white, .black.opacity(0.5))
.padding(4)
}
.buttonStyle(.plain)
}
}
if remainingSlots > 0 {
Button { showMoreCapture = true } label: {
VStack(spacing: 6) {
Image(systemName: "plus")
.font(.tjScaled(22, weight: .medium))
Text("继续拍")
.font(.tjScaled(12))
}
.foregroundStyle(Tj.Palette.text2)
.frame(width: 96, height: 96)
.background(
RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous)
.strokeBorder(Tj.Palette.line, style: StrokeStyle(lineWidth: 1, dash: [4]))
)
}
.buttonStyle(.plain)
}
}
.padding(18)
}
VStack(spacing: 8) {
Text("已拍 \(images.count)/\(Self.maxImages) 张 · 可拍正面、背面、说明书")
.font(.tjScaled(12))
.foregroundStyle(Tj.Palette.text3)
if images.count > 1 {
Text("点照片选「识别此张」· 一次记一种药")
.font(.tjScaled(11))
.foregroundStyle(Tj.Palette.ink)
}
Text("照片与文字均不离开设备")
.font(.tjScaled(11))
.foregroundStyle(Tj.Palette.text3)
Button {
startRecognition()
} label: {
Text("开始识别")
.frame(maxWidth: .infinity)
}
.buttonStyle(TjPrimaryButton())
.disabled(images.isEmpty)
.opacity(images.isEmpty ? 0.4 : 1)
}
.padding(.horizontal, 18)
.padding(.bottom, 12)
}
.overlay(alignment: .topLeading) {
flowCancelButton { onClose() }
}
}
private var recognizingView: some View {
VStack(spacing: 18) {
Image(uiImage: image)
.resizable()
.scaledToFit()
.frame(maxHeight: 320)
.clipShape(RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous))
.padding(.horizontal, 24)
if images.indices.contains(recognizeIndex) {
Image(uiImage: images[recognizeIndex])
.resizable()
.scaledToFit()
.frame(maxHeight: 320)
.clipShape(RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous))
.padding(.horizontal, 24)
}
ProgressView().tint(Tj.Palette.ink)
Text("正在本地识别药品…")
.font(.tjScaled(14))
@@ -108,31 +256,37 @@ struct MedicationScanFlow: View {
.frame(maxWidth: .infinity, maxHeight: .infinity)
// 退,(§3.2 )
.overlay(alignment: .topLeading) {
Button {
flowCancelButton {
recognitionTask?.cancel()
onClose()
} label: {
Text("取消")
.font(.tjScaled( 16, weight: .medium))
.foregroundStyle(Tj.Palette.text)
.padding(.horizontal, 18)
.frame(minHeight: 44)
.background(Capsule().fill(Tj.Palette.paper))
.overlay(Capsule().strokeBorder(Tj.Palette.line, lineWidth: 1))
.contentShape(Capsule())
}
.buttonStyle(.plain)
.padding(.leading, 16)
.padding(.top, 8)
}
}
// MARK: - ( OCR LLM )
private func flowCancelButton(_ action: @escaping () -> Void) -> some View {
Button(action: action) {
Text("取消")
.font(.tjScaled(16, weight: .medium))
.foregroundStyle(Tj.Palette.text)
.padding(.horizontal, 18)
.frame(minHeight: 44)
.background(Capsule().fill(Tj.Palette.paper))
.overlay(Capsule().strokeBorder(Tj.Palette.line, lineWidth: 1))
.contentShape(Capsule())
}
.buttonStyle(.plain)
.padding(.leading, 16)
.padding(.top, 8)
}
private func startRecognition(_ image: UIImage) {
phase = .recognizing(image: image)
// MARK: - ( OCR LLM )
private func startRecognition() {
guard images.indices.contains(recognizeIndex) else { return }
phase = .recognizing
let target = images[recognizeIndex]
recognitionTask = Task {
let (items, warning) = await recognize(image)
let (items, warning) = await recognize(target)
guard !Task.isCancelled else { return } // : phase
await MainActor.run {
// :(§3.2 退线)
@@ -148,13 +302,15 @@ struct MedicationScanFlow: View {
private func recognize(_ image: UIImage) async -> (items: [EditableMedication], warning: String?) {
do {
let text = try await OCRService.recognizeText(in: image)
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty {
//
let text = (try? await OCRService.recognizeText(in: image))?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if text.isEmpty {
return ([], String(appLoc: "没识别到文字,拍清楚一点再试"))
}
let parsed = try await MedicationScanService.shared.recognizeMedications(fromOCRText: trimmed)
let items = parsed.map {
let parsed = try await MedicationScanService.shared.recognizeMedications(fromOCRText: text)
// :使,
let items = parsed.prefix(1).map {
EditableMedication(name: $0.name, strength: $0.strength, usage: $0.usage)
}
return (items, items.isEmpty ? String(appLoc: "没读出药品,可以手动填写") : nil)
@@ -172,34 +328,56 @@ struct MedicationScanFlow: View {
// MARK: -
private func saveItems(_ items: [EditableMedication]) {
let entries = items
let meds = items
.filter { $0.include && !$0.name.trimmingCharacters(in: .whitespaces).isEmpty }
.map {
ParsedMedication(name: $0.name, strength: $0.strength, usage: $0.usage).entryText
ParsedMedication(name: $0.name.trimmingCharacters(in: .whitespaces),
strength: $0.strength.trimmingCharacters(in: .whitespaces),
usage: $0.usage.trimmingCharacters(in: .whitespaces))
}
onSave(entries)
// (),
onSave(meds, images)
onClose()
}
}
// MARK: - (MainActor,SwiftData View ctx ,§3.1)
// MARK: - (MainActor,SwiftData View ctx ,§3.1)
/// ,:
/// 1. tag DiaryEntry 线
/// 2. UserProfile.currentMedications() AI / prompt
/// ,( · ):
/// `Medication`(), name+strength ;** currentMedications**
/// · `DiaryEntry.medicationTag`
@MainActor
enum MedicationArchiver {
static func archive(entries: [String], in ctx: ModelContext) {
guard !entries.isEmpty else { return }
let diary = DiaryEntry(content: entries.joined(separator: "\n"),
tags: [DiaryEntry.medicationTag])
ctx.insert(diary)
static func archive(medications: [ParsedMedication], images: [UIImage] = [], in ctx: ModelContext) {
guard !medications.isEmpty else { return }
let profile = UserProfileStore.loadOrCreate(in: ctx)
for entry in entries where !profile.currentMedications.contains(entry) {
profile.currentMedications.append(entry)
// Vault(§5/§6: Application Support/Vault,)
// , JPEG Asset
// cascade
let savedAssets = images
.prefix(MedicationScanFlow.maxImages)
.compactMap { try? FileVault.shared.writeJPEG($0) }
let existing = (try? ctx.fetch(FetchDescriptor<Medication>())) ?? []
var attachedImages = false
for m in medications {
// : name+strength / ,
if let dup = existing.first(where: { $0.name == m.name && $0.strength == m.strength }) {
if dup.usage.isEmpty, !m.usage.isEmpty { dup.usage = m.usage }
dup.updatedAt = .now
continue
}
let med = Medication(name: m.name, strength: m.strength, usage: m.usage)
if !attachedImages {
for s in savedAssets {
let asset = Asset(relativePath: s.relativePath, bytes: s.bytes)
ctx.insert(asset)
med.assets.append(asset)
}
attachedImages = true
}
ctx.insert(med)
}
profile.updatedAt = .now
try? ctx.save()
}
}
@@ -231,13 +409,8 @@ private struct MedicationConfirmView: View {
ForEach($items) { $item in
Section {
HStack {
TextField(String(appLoc: "药品名,如:缬沙坦胶囊"), text: $item.name)
.foregroundStyle(Tj.Palette.text)
Toggle("", isOn: $item.include)
.labelsHidden()
.tint(Tj.Palette.ink)
}
TextField(String(appLoc: "药品名,如:缬沙坦胶囊"), text: $item.name)
.foregroundStyle(Tj.Palette.text)
TextField(String(appLoc: "规格,如:80mg×7粒"), text: $item.strength)
.foregroundStyle(Tj.Palette.text2)
TextField(String(appLoc: "用法,如:一日一次,一次一粒"), text: $item.usage)
@@ -246,12 +419,6 @@ private struct MedicationConfirmView: View {
}
Section {
Button {
items.append(.init(name: "", strength: "", usage: ""))
} label: {
Label("再加一种", systemImage: "plus.circle")
.foregroundStyle(Tj.Palette.ink)
}
Button {
onRetake()
} label: {
@@ -259,7 +426,7 @@ private struct MedicationConfirmView: View {
.foregroundStyle(Tj.Palette.ink)
}
} footer: {
Text("将记入健康日记(记录页可查),并同步到「当前用药」供 AI 解读参考。不提供任何用药建议。")
Text("一次记一种药,多张照片都会作为这种药的原图存入药品库,供查看与 AI 解读参考。不提供任何用药建议。")
}
}
.scrollContentBackground(.hidden)
@@ -267,7 +434,7 @@ private struct MedicationConfirmView: View {
Button {
onSave(items)
} label: {
Text("保存用药记录")
Text("存入药品库")
.frame(maxWidth: .infinity)
}
.buttonStyle(TjPrimaryButton())
@@ -281,5 +448,5 @@ private struct MedicationConfirmView: View {
}
#Preview {
MedicationScanFlow(onSave: { print($0) }, onClose: {})
MedicationScanFlow(onSave: { _, _ in }, onClose: {})
}

View File

@@ -38,7 +38,6 @@ private struct ProfileEditForm: View {
@State private var healthImportDraft: HealthProfileImportDraft?
@State private var healthImportError: String?
@State private var isImportingHealthProfile = false
@State private var showMedicationScan = false
var body: some View {
Form {
@@ -88,9 +87,6 @@ private struct ProfileEditForm: View {
items: $profile.allergies)
StringListSection(title: String(appLoc: "家族史"), placeholder: String(appLoc: "如:母亲 高血压"),
items: $profile.familyHistory)
StringListSection(title: String(appLoc: "当前用药"), placeholder: String(appLoc: "如:缬沙坦 80mg qd"),
items: $profile.currentMedications,
onScan: { showMedicationScan = true })
}
.navigationTitle("个人资料")
.navigationBarTitleDisplayMode(.inline)
@@ -100,16 +96,6 @@ private struct ProfileEditForm: View {
profile.updatedAt = .now
try? ctx.save()
}
.fullScreenCover(isPresented: $showMedicationScan) {
// OCR + LLM :
// (线)+ ()
MedicationScanFlow(
onSave: { entries in
MedicationArchiver.archive(entries: entries, in: ctx)
},
onClose: { showMedicationScan = false }
)
}
.sheet(item: $healthImportDraft) { draft in
HealthProfileImportPreviewSheet(
draft: draft,
@@ -468,27 +454,10 @@ private struct StringListSection: View {
let title: String
let placeholder: String
@Binding var items: [String]
/// nil ()
var onScan: (() -> Void)? = nil
@State private var newInput = ""
var body: some View {
Section(title) {
if let onScan {
Button(action: onScan) {
HStack(spacing: 10) {
Image(systemName: "camera.viewfinder")
.foregroundStyle(Tj.Palette.ink)
VStack(alignment: .leading, spacing: 2) {
Text("拍药盒自动识别")
.foregroundStyle(Tj.Palette.text)
Text("拍药盒或说明书,本地识别药名与规格")
.font(.tjScaled( 12))
.foregroundStyle(Tj.Palette.text3)
}
}
}
}
ForEach(items, id: \.self) { item in
HStack {
Text(item)

View File

@@ -1,13 +1,15 @@
import SwiftUI
enum RecordKind: String, Identifiable, CaseIterable {
case quick, indicator, healthExport, archive, diary, symptom, reminder
case quick, indicator, healthExport, archive, diary, symptom, reminder, medicationLibrary
var id: String { rawValue }
/// RecordSheet () enum ,
/// :`.quick`() `.indicator`();
/// `.symptom`() `.diary`(),
static let displayOrder: [RecordKind] = [.diary, .reminder, .indicator, .healthExport, .archive]
/// `.symptom`() `.diary`(),;
/// `.medicationLibrary`()/,Tab ,
/// (,)
static let displayOrder: [RecordKind] = [.diary, .reminder, .indicator, .healthExport, .archive, .medicationLibrary]
/// pill( subtitle,"/")
/// :,( ProfileEditView presets )
@@ -24,6 +26,7 @@ enum RecordKind: String, Identifiable, CaseIterable {
case .diary: return String(appLoc: "健康日记")
case .symptom: return String(appLoc: "记录症状")
case .reminder: return String(appLoc: "开启一个提醒")
case .medicationLibrary: return String(appLoc: "药品库")
}
}
var subtitle: String {
@@ -35,6 +38,7 @@ enum RecordKind: String, Identifiable, CaseIterable {
case .diary: return String(appLoc: "写日记或拍药盒记录用药 · 可让 AI 辅助")
case .symptom: return String(appLoc: "开始一个持续症状,结束时再点结束")
case .reminder: return String(appLoc: "管理用药、复查、监测的周期提醒")
case .medicationLibrary: return String(appLoc: "管理常用药清单 · 拍药盒或手动添加")
}
}
var icon: String {
@@ -46,6 +50,7 @@ enum RecordKind: String, Identifiable, CaseIterable {
case .diary: return "heart.text.square"
case .symptom: return "waveform.path.ecg"
case .reminder: return "bell.badge"
case .medicationLibrary: return "pills.fill"
}
}
var accent: Color {
@@ -57,6 +62,7 @@ enum RecordKind: String, Identifiable, CaseIterable {
case .diary: return Tj.Palette.leaf
case .symptom: return Tj.Palette.amber
case .reminder: return Tj.Palette.leaf
case .medicationLibrary: return Tj.Palette.ink
}
}
}
@@ -83,7 +89,7 @@ struct RecordSheet: View {
}
.padding(.bottom, 14)
// ScrollView :6 detent ,
// ScrollView : detent ,
ScrollView {
VStack(spacing: 10) {
ForEach(RecordKind.displayOrder) { kind in

View File

@@ -140,6 +140,7 @@ struct IndicatorSeriesDetailView: View {
} else {
pages
pager
recordAnotherRow
if bucket != nil { trendButton }
}
}
@@ -311,6 +312,30 @@ struct IndicatorSeriesDetailView: View {
.disabled(!enabled)
}
// MARK: - ( RecordAnotherButton )
/// :, name/unit/range/seriesKey
@ViewBuilder
private var recordAnotherRow: some View {
if records.indices.contains(currentIndex) {
switch records[currentIndex] {
case .single(let i):
RecordAnotherButton(name: i.name, prefill: .init(indicator: i))
.padding(.horizontal, 20)
.padding(.bottom, bucket == nil ? 20 : 10)
case .bp(let sys, _):
RecordAnotherButton(
name: String(appLoc: "血压"),
prefill: .init(seriesKey: sys.seriesKey ?? "bp.systolic",
name: String(appLoc: "血压"),
unit: "mmHg", range: sys.range)
)
.padding(.horizontal, 20)
.padding(.bottom, bucket == nil ? 20 : 10)
}
}
}
// MARK: - /
private var trendButton: some View {

View File

@@ -42,10 +42,12 @@ struct TimelineEntry: Identifiable, Hashable {
let kind: TimelineKind
let date: Date
let title: String
let subtitle: String
var subtitle: String
let trailing: String?
let trailingIsAlert: Bool
let isOngoing: Bool
/// (>1 N ) 1
var aggregateCount: Int = 1
static func from(indicator i: Indicator) -> TimelineEntry {
TimelineEntry(
@@ -87,6 +89,34 @@ struct TimelineEntry: Identifiable, Hashable {
return entries
}
/// / :(),,
/// (`aggregateCount`,>1 N )
/// `IndicatorSeriesDetailView` /
/// (`IndicatorGroup`):(bp.*) seriesKey key seriesKey name+unit
static func aggregatedIndicators(_ indicators: [Indicator]) -> [TimelineEntry] {
var order: [String] = []
var groups: [String: [Indicator]] = [:]
for i in indicators {
let key = IndicatorGroup.of(i).id
if groups[key] == nil { order.append(key) }
groups[key, default: []].append(i)
}
return order.compactMap { key -> TimelineEntry? in
guard let members = groups[key] else { return nil }
// ( sys/dia),
guard var rep = from(indicators: members).max(by: { $0.date < $1.date }) else { return nil }
// :(bp.systolic ),
let count = key == IndicatorGroup.bloodPressure.id
? members.filter { $0.seriesKey == "bp.systolic" }.count
: members.count
rep.aggregateCount = count
if count > 1 {
rep.subtitle += " · " + String(appLoc: "\(count)")
}
return rep
}
}
private static func mergedBP(systolic sys: Indicator, diastolic dia: Indicator) -> TimelineEntry {
let abnormal = sys.status != .normal || dia.status != .normal
// status : /;

View File

@@ -54,6 +54,27 @@ struct TimelineEntryDetailView: View {
@State private var showDeleteConfirm = false
@State private var evidenceTarget: Indicator?
@State private var reminderPrefill: ReminderPrefill?
///
private struct ReminderPrefill: Identifiable {
let id = UUID()
let title: String
let note: String
}
///
@State private var reportPhotoStart: ReportPhotoPage?
private struct ReportPhotoPage: Identifiable {
let id = UUID()
let index: Int
}
/// ,
private var reportEntry: Report? {
if case .report(let r) = detail { return r }
return nil
}
var body: some View {
VStack(spacing: 0) {
@@ -84,6 +105,15 @@ struct TimelineEntryDetailView: View {
EvidenceImagePreview(report: report, indicator: indicator)
}
}
.sheet(item: $reminderPrefill) { prefill in
// (/// + ;)
CustomReminderEditSheet(prefillTitle: prefill.title, prefillNote: prefill.note)
}
.sheet(item: $reportPhotoStart) { start in
if let r = reportEntry {
ReportImagesViewer(assets: r.assets, startIndex: start.index)
}
}
}
// MARK: - (:SwiftData + Vault unlink, CLAUDE.md §6)
@@ -120,6 +150,10 @@ struct TimelineEntryDetailView: View {
for p in paths { try? FileVault.shared.remove(relativePath: p) }
ctx.delete(r)
case .diary(let d):
// ;cascade Asset ,Vault JPEG unlink
for p in Set(d.assets.map(\.relativePath)) {
try? FileVault.shared.remove(relativePath: p)
}
ctx.delete(d)
case .symptom(let s):
ctx.delete(s)
@@ -167,7 +201,7 @@ struct TimelineEntryDetailView: View {
case .indicator: return String(appLoc: "指标详情")
case .bloodPressure: return String(appLoc: "血压详情")
case .report: return String(appLoc: "报告详情")
case .diary: return String(appLoc: "日记详情")
case .diary(let d): return d.isMedicationLog ? String(appLoc: "用药详情") : String(appLoc: "日记详情")
case .symptom: return String(appLoc: "症状详情")
}
}
@@ -186,28 +220,31 @@ struct TimelineEntryDetailView: View {
// MARK: -
private func indicatorBody(_ i: Indicator) -> some View {
card {
HStack(alignment: .firstTextBaseline) {
Text(i.name).font(.tjH2()).foregroundStyle(Tj.Palette.text)
Spacer()
statusChip(i.status)
}
HStack(alignment: .firstTextBaseline, spacing: 4) {
Text(i.value)
.font(.tjScaled( 30, weight: .bold, design: .rounded))
.foregroundStyle(i.status == .normal ? Tj.Palette.text : Tj.Palette.brick)
if !i.unit.isEmpty {
Text(i.unit).font(.tjScaled( 14)).foregroundStyle(Tj.Palette.text3)
VStack(alignment: .leading, spacing: 16) {
card {
HStack(alignment: .firstTextBaseline) {
Text(i.name).font(.tjH2()).foregroundStyle(Tj.Palette.text)
Spacer()
statusChip(i.status)
}
HStack(alignment: .firstTextBaseline, spacing: 4) {
Text(i.value)
.font(.tjScaled( 30, weight: .bold, design: .rounded))
.foregroundStyle(i.status == .normal ? Tj.Palette.text : Tj.Palette.brick)
if !i.unit.isEmpty {
Text(i.unit).font(.tjScaled( 14)).foregroundStyle(Tj.Palette.text3)
}
}
divider
if !i.range.isEmpty { field(String(appLoc: "参考范围"), i.range) }
field(String(appLoc: "记录时间"), Self.dateTimeText(i.capturedAt))
field(String(appLoc: "来源"), i.report?.title ?? i.source.label)
if let report = i.report {
evidenceButton(for: i, assets: report.assets)
}
if let note = i.note, !note.isEmpty { field(String(appLoc: "备注"), note) }
}
divider
if !i.range.isEmpty { field(String(appLoc: "参考范围"), i.range) }
field(String(appLoc: "记录时间"), Self.dateTimeText(i.capturedAt))
field(String(appLoc: "来源"), i.report?.title ?? i.source.label)
if let report = i.report {
evidenceButton(for: i, assets: report.assets)
}
if let note = i.note, !note.isEmpty { field(String(appLoc: "备注"), note) }
RecordAnotherButton(name: i.name, prefill: .init(indicator: i))
}
}
@@ -217,21 +254,28 @@ struct TimelineEntryDetailView: View {
let combined: IndicatorStatus = sys.status != .normal
? sys.status
: (dia?.status ?? .normal)
return card {
HStack(alignment: .firstTextBaseline) {
Text(String(appLoc: "血压")).font(.tjH2()).foregroundStyle(Tj.Palette.text)
Spacer()
statusChip(combined)
return VStack(alignment: .leading, spacing: 16) {
card {
HStack(alignment: .firstTextBaseline) {
Text(String(appLoc: "血压")).font(.tjH2()).foregroundStyle(Tj.Palette.text)
Spacer()
statusChip(combined)
}
HStack(alignment: .firstTextBaseline, spacing: 4) {
Text("\(sys.value)/\(dia?.value ?? "")")
.font(.tjScaled( 30, weight: .bold, design: .rounded))
.foregroundStyle(combined == .normal ? Tj.Palette.text : Tj.Palette.brick)
Text("mmHg").font(.tjScaled( 14)).foregroundStyle(Tj.Palette.text3)
}
divider
if !sys.range.isEmpty { field(String(appLoc: "参考范围"), sys.range) }
field(String(appLoc: "记录时间"), Self.dateTimeText(sys.capturedAt))
}
HStack(alignment: .firstTextBaseline, spacing: 4) {
Text("\(sys.value)/\(dia?.value ?? "")")
.font(.tjScaled( 30, weight: .bold, design: .rounded))
.foregroundStyle(combined == .normal ? Tj.Palette.text : Tj.Palette.brick)
Text("mmHg").font(.tjScaled( 14)).foregroundStyle(Tj.Palette.text3)
}
divider
if !sys.range.isEmpty { field(String(appLoc: "参考范围"), sys.range) }
field(String(appLoc: "记录时间"), Self.dateTimeText(sys.capturedAt))
// :seriesKey bp.systolic MonitorMetric.bloodPressure
RecordAnotherButton(name: String(appLoc: "血压"),
prefill: .init(seriesKey: sys.seriesKey ?? "bp.systolic",
name: String(appLoc: "血压"),
unit: "mmHg", range: sys.range))
}
}
@@ -248,16 +292,16 @@ struct TimelineEntryDetailView: View {
TjBadge(text: r.type.label, style: .neutral)
Text(Self.dateText(r.reportDate))
.font(.tjScaled( 12)).foregroundStyle(Tj.Palette.text3)
if !r.assets.isEmpty {
Text(String(appLoc: "原图\(r.assets.count)"))
.font(.tjScaled( 12)).foregroundStyle(Tj.Palette.text3)
}
}
if let inst = r.institution, !inst.isEmpty {
field(String(appLoc: "机构"), inst)
}
}
if !r.assets.isEmpty {
reportPhotosCard(r.assets)
}
ReportSummaryCard(report: r)
if !r.indicators.isEmpty {
@@ -286,26 +330,146 @@ struct TimelineEntryDetailView: View {
}
}
// MARK: -
private func diaryBody(_ d: DiaryEntry) -> some View {
VStack(alignment: .leading, spacing: 16) {
card {
Text(Self.dateTimeText(d.createdAt))
.font(.tjScaled( 12)).foregroundStyle(Tj.Palette.text3)
Text(d.content)
.font(.tjScaled( 15))
.foregroundStyle(Tj.Palette.text)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
if !d.tags.isEmpty {
field(String(appLoc: "标签"), d.tags.map { "#\($0)" }.joined(separator: " "))
/// : ,,
private func reportPhotosCard(_ assets: [Asset]) -> some View {
card {
HStack {
Text(String(appLoc: "原图\(assets.count)"))
.font(.tjScaled( 12, weight: .semibold)).foregroundStyle(Tj.Palette.text2)
Spacer()
Text(String(appLoc: "点图放大")).font(.tjScaled( 11)).foregroundStyle(Tj.Palette.text3)
}
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 10) {
ForEach(Array(assets.enumerated()), id: \.offset) { idx, asset in
Button {
reportPhotoStart = ReportPhotoPage(index: idx)
} label: {
reportThumb(asset)
}
.buttonStyle(.plain)
}
}
}
}
}
private func reportThumb(_ asset: Asset) -> some View {
VaultImage(relativePath: asset.relativePath, maxPixel: 400) { img in
Image(uiImage: img).resizable().scaledToFill()
} placeholder: { isLoading in
if isLoading {
Tj.Palette.paper
} else {
TjPlaceholder(label: String(appLoc: "原图无法读取"))
}
}
.frame(width: 96, height: 120)
.clipped()
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.strokeBorder(Tj.Palette.line, lineWidth: 1)
)
}
// MARK: -
@ViewBuilder
private func diaryBody(_ d: DiaryEntry) -> some View {
if d.isMedicationLog {
medicationBody(d)
} else {
VStack(alignment: .leading, spacing: 16) {
card {
Text(Self.dateTimeText(d.createdAt))
.font(.tjScaled( 12)).foregroundStyle(Tj.Palette.text3)
Text(d.content)
.font(.tjScaled( 15))
.foregroundStyle(Tj.Palette.text)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
if !d.tags.isEmpty {
field(String(appLoc: "标签"), d.tags.map { "#\($0)" }.joined(separator: " "))
}
}
}
}
}
// MARK: - 使(// + )
/// 使(tag ): [] · + ,
/// ,/(CLAUDE.md §1§10)
private func medicationBody(_ d: DiaryEntry) -> some View {
let lines = Self.medicationLines(d.content)
return VStack(alignment: .leading, spacing: 16) {
card {
Text(Self.dateTimeText(d.createdAt))
.font(.tjScaled( 12)).foregroundStyle(Tj.Palette.text3)
if lines.isEmpty {
Text(d.content)
.font(.tjScaled( 15)).foregroundStyle(Tj.Palette.text)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
} else {
ForEach(Array(lines.enumerated()), id: \.offset) { idx, line in
if idx > 0 { divider }
Text(line)
.font(.tjScaled( 15)).foregroundStyle(Tj.Palette.text)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
}
}
}
medicationActionRow(d)
Text("「设置提醒」只到点提示,不提供任何用药或剂量建议。")
.font(.tjScaled( 11)).foregroundStyle(Tj.Palette.text3)
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
}
}
/// :(, + ),
private func medicationActionRow(_ d: DiaryEntry) -> some View {
HStack(spacing: 10) {
medAction(title: String(appLoc: "设置提醒"), icon: "bell.badge") {
let lines = Self.medicationLines(d.content)
if lines.count <= 1 {
let f = Self.medicationReminderFields(forLine: lines.first ?? d.content)
reminderPrefill = ReminderPrefill(title: f.title, note: f.note)
} else {
// :,,/
reminderPrefill = ReminderPrefill(title: String(appLoc: "服药提醒"),
note: lines.joined(separator: "\n"))
}
}
}
}
private func medAction(title: String, icon: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
VStack(spacing: 6) {
Image(systemName: icon).font(.tjScaled( 18, weight: .medium))
Text(title).font(.tjScaled( 12, weight: .semibold))
}
.foregroundStyle(Tj.Palette.ink)
.frame(maxWidth: .infinity)
.padding(.vertical, 12)
.background(
RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous)
.fill(Tj.Palette.amber.opacity(0.14))
)
.contentShape(RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous))
}
.buttonStyle(.plain)
}
// MARK: -
private func symptomBody(_ s: Symptom) -> some View {
@@ -412,6 +576,76 @@ struct TimelineEntryDetailView: View {
private nonisolated static func dateText(_ d: Date) -> String {
d.formatted(.dateTime.year().month().day())
}
// MARK: - (,便)
/// content ,
nonisolated static func medicationLines(_ content: String) -> [String] {
content.split(whereSeparator: \.isNewline)
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
}
/// ( 80mg · ):
/// =:<+>, = (" · " ,/)
nonisolated static func medicationReminderFields(forLine line: String) -> (title: String, note: String) {
let parts = line.components(separatedBy: " · ")
let head = (parts.first ?? line).trimmingCharacters(in: .whitespaces)
let usage = parts.count > 1
? parts.dropFirst().joined(separator: " · ").trimmingCharacters(in: .whitespaces)
: ""
let name = head.isEmpty ? line.trimmingCharacters(in: .whitespaces) : head
return (title: String(appLoc: "吃药:") + name, note: usage)
}
}
/// (,)
private struct ReportImagesViewer: View {
@Environment(\.dismiss) private var dismiss
let assets: [Asset]
@State private var selection: Int
init(assets: [Asset], startIndex: Int) {
self.assets = assets
_selection = State(initialValue: min(max(startIndex, 0), max(assets.count - 1, 0)))
}
var body: some View {
VStack(spacing: 0) {
HStack(spacing: 12) {
Button { dismiss() } label: {
Image(systemName: "xmark")
.font(.tjScaled( 16, weight: .semibold))
.foregroundStyle(Tj.Palette.text)
.frame(width: 32, height: 32)
.background(Circle().fill(Tj.Palette.sand2))
}
Text("原图 · 第 \(selection + 1)/\(assets.count)")
.font(.tjScaled( 14, weight: .semibold))
.foregroundStyle(Tj.Palette.text)
Spacer()
}
.padding(.horizontal, 20)
.padding(.vertical, 14)
.background(Tj.Palette.sand)
.overlay(alignment: .bottom) {
Rectangle().fill(Tj.Palette.lineSoft).frame(height: 1)
}
TabView(selection: $selection) {
ForEach(Array(assets.enumerated()), id: \.offset) { index, asset in
EvidenceImagePage(asset: asset, highlight: nil)
.tag(index)
.padding(16)
}
}
.tabViewStyle(.page(indexDisplayMode: assets.count > 1 ? .automatic : .never))
}
.background(Tj.Palette.sand.ignoresSafeArea())
.presentationDetents([.large])
.presentationDragIndicator(.visible)
.presentationBackground(Tj.Palette.sand)
}
}
/// ( + ),
@@ -479,19 +713,16 @@ private struct EvidenceImagePage: View {
let asset: Asset
let highlight: CGRect?
private var image: UIImage? {
try? FileVault.shared.loadImage(relativePath: asset.relativePath)
}
var body: some View {
GeometryReader { geo in
if let image {
VaultImage(relativePath: asset.relativePath, maxPixel: 2000) { image in
ZStack {
Image(uiImage: image)
.resizable()
.scaledToFit()
.frame(width: geo.size.width, height: geo.size.height)
if let highlight {
// ,imageSize letterbox ,
EvidenceHighlightOverlay(imageSize: image.size, normalizedRect: highlight)
}
}
@@ -502,9 +733,14 @@ private struct EvidenceImagePage: View {
RoundedRectangle(cornerRadius: Tj.Radius.md, style: .continuous)
.strokeBorder(Tj.Palette.lineSoft, lineWidth: 1)
)
} else {
TjPlaceholder(label: String(appLoc: "原图无法读取"))
.frame(width: geo.size.width, height: geo.size.height)
} placeholder: { isLoading in
if isLoading {
ProgressView()
.frame(width: geo.size.width, height: geo.size.height)
} else {
TjPlaceholder(label: String(appLoc: "原图无法读取"))
.frame(width: geo.size.width, height: geo.size.height)
}
}
}
}

View File

@@ -12,6 +12,10 @@ struct TrendsView: View {
private var profile: UserProfile? { profiles.first }
/// :,(bucket.title)
@State private var searching = false
@State private var query = ""
private var seriesBuckets: [SeriesBucket] {
SeriesBucket.build(from: indicators,
profile: profile,
@@ -25,6 +29,14 @@ struct TrendsView: View {
seriesBuckets.filter { $0.kind == .lab }
}
private func filtered(_ buckets: [SeriesBucket]) -> [SeriesBucket] {
let q = query.trimmingCharacters(in: .whitespaces)
guard !q.isEmpty else { return buckets }
return buckets.filter { $0.title.localizedCaseInsensitiveContains(q) }
}
private var filteredMonitor: [SeriesBucket] { filtered(monitorBuckets) }
private var filteredLab: [SeriesBucket] { filtered(labBuckets) }
var body: some View {
NavigationStack {
ScrollView(showsIndicators: false) {
@@ -32,12 +44,14 @@ struct TrendsView: View {
header.padding(.top, 4)
if seriesBuckets.isEmpty {
emptyState
} else if filteredMonitor.isEmpty && filteredLab.isEmpty {
noMatchState
} else {
if !monitorBuckets.isEmpty {
section(title: String(appLoc: "长期监测"), buckets: monitorBuckets)
if !filteredMonitor.isEmpty {
section(title: String(appLoc: "长期监测"), buckets: filteredMonitor)
}
if !labBuckets.isEmpty {
section(title: String(appLoc: "化验指标趋势"), buckets: labBuckets)
if !filteredLab.isEmpty {
section(title: String(appLoc: "化验指标趋势"), buckets: filteredLab)
}
}
}
@@ -51,9 +65,73 @@ struct TrendsView: View {
}
private var header: some View {
Text("趋势")
.font(.tjTitle(26))
.foregroundStyle(Tj.Palette.text)
VStack(alignment: .leading, spacing: 12) {
HStack(alignment: .lastTextBaseline) {
Text("趋势")
.font(.tjTitle(26))
.foregroundStyle(Tj.Palette.text)
Spacer()
searchToggle
}
if searching { searchField }
}
}
private var searchToggle: some View {
Button {
withAnimation(.easeInOut(duration: 0.18)) {
searching.toggle()
if !searching { query = "" }
}
} label: {
Image(systemName: searching ? "xmark" : "magnifyingglass")
.font(.tjScaled( 15, weight: .semibold))
.foregroundStyle(Tj.Palette.text)
.frame(width: 36, height: 36)
.background(Circle().fill(Tj.Palette.sand2))
}
.buttonStyle(.plain)
.accessibilityLabel(searching ? String(appLoc: "关闭搜索") : String(appLoc: "搜索指标"))
}
private var searchField: some View {
HStack(spacing: 8) {
Image(systemName: "magnifyingglass")
.font(.tjScaled( 13))
.foregroundStyle(Tj.Palette.text3)
TextField(String(appLoc: "搜索指标名"), text: $query)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.foregroundStyle(Tj.Palette.text)
.tint(Tj.Palette.ink)
if !query.isEmpty {
Button { query = "" } label: {
Image(systemName: "xmark.circle.fill")
.foregroundStyle(Tj.Palette.text3)
}
.buttonStyle(.plain)
}
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background(
RoundedRectangle(cornerRadius: Tj.Radius.sm, style: .continuous)
.fill(Tj.Palette.paper)
)
.overlay(
RoundedRectangle(cornerRadius: Tj.Radius.sm, style: .continuous)
.strokeBorder(Tj.Palette.line, lineWidth: 1)
)
}
private var noMatchState: some View {
VStack(spacing: 12) {
TjPlaceholder(label: String(appLoc: "没有匹配「\(query)」的指标"))
.frame(height: 120)
.frame(maxWidth: 260)
}
.frame(maxWidth: .infinity)
.padding(.top, 60)
}
private func section(title: String, buckets: [SeriesBucket]) -> some View {