261 lines
10 KiB
Swift
261 lines
10 KiB
Swift
import AppKit
|
|
import SwiftUI
|
|
import UniformTypeIdentifiers
|
|
|
|
struct PatientWorkspace: View {
|
|
@EnvironmentObject private var library: PatientLibrary
|
|
@State private var search = ""
|
|
@State private var patientID: PatientRecord.ID?
|
|
@State private var imageID: PatientImage.ID?
|
|
@State private var editor: PatientEditor?
|
|
@State private var importPatientID: PatientRecord.ID?
|
|
@State private var showImporter = false
|
|
@State private var errorMessage: String?
|
|
|
|
private var filteredPatients: [PatientRecord] {
|
|
let query = search.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
return library.patients.filter {
|
|
query.isEmpty || $0.name.localizedStandardContains(query)
|
|
|| $0.chartNumber.localizedStandardContains(query)
|
|
}
|
|
}
|
|
|
|
private var patient: PatientRecord? {
|
|
library.patients.first { $0.id == patientID }
|
|
}
|
|
|
|
var body: some View {
|
|
NavigationSplitView {
|
|
VStack(spacing: 0) {
|
|
HStack(spacing: 8) {
|
|
Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
|
|
TextField("Имя или номер карты", text: $search)
|
|
.textFieldStyle(.plain)
|
|
if !search.isEmpty {
|
|
Button { search = "" } label: { Image(systemName: "xmark.circle.fill") }
|
|
.buttonStyle(.plain)
|
|
.accessibilityLabel("Очистить поиск")
|
|
}
|
|
}
|
|
.padding(9)
|
|
.background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8))
|
|
.padding(12)
|
|
|
|
if filteredPatients.isEmpty, !search.isEmpty {
|
|
Text("Пациенты не найдены")
|
|
.foregroundStyle(.secondary)
|
|
.padding(.bottom, 12)
|
|
}
|
|
List(filteredPatients, selection: $patientID) { record in
|
|
Label {
|
|
VStack(alignment: .leading, spacing: 3) {
|
|
Text(record.name).fontWeight(.medium)
|
|
Text(record.chartNumber).font(.caption).foregroundStyle(.secondary)
|
|
}
|
|
} icon: {
|
|
Image(systemName: "person.crop.circle")
|
|
}
|
|
.padding(.vertical, 5)
|
|
.tag(record.id)
|
|
}
|
|
.listStyle(.sidebar)
|
|
|
|
Divider()
|
|
Button { newPatient() } label: {
|
|
Label("Новый пациент", systemImage: "plus")
|
|
.frame(maxWidth: .infinity)
|
|
}
|
|
.controlSize(.large)
|
|
.padding(12)
|
|
.disabled(library.loadError != nil)
|
|
}
|
|
.navigationTitle("Пациенты")
|
|
.navigationSplitViewColumnWidth(min: 220, ideal: 260)
|
|
} detail: {
|
|
if let patient {
|
|
patientDetail(patient)
|
|
} else if let error = library.loadError {
|
|
emptyState("Библиотека недоступна", detail: error, icon: "exclamationmark.triangle")
|
|
} else if library.patients.isEmpty {
|
|
emptyState("Создайте карточку пациента",
|
|
detail: "После этого вы сможете добавить и просмотреть локальные снимки.",
|
|
icon: "person.crop.rectangle") {
|
|
Button("Новый пациент", action: newPatient).buttonStyle(.borderedProminent)
|
|
}
|
|
} else {
|
|
emptyState("Выберите пациента", detail: "Найдите карточку по имени или номеру.", icon: "person.crop.rectangle")
|
|
}
|
|
}
|
|
.onChange(of: patientID) { _ in
|
|
imageID = patient?.images.first?.id
|
|
}
|
|
.sheet(item: $editor) { draft in
|
|
PatientEditorSheet(draft: draft) { name, chart in
|
|
let id = try library.savePatient(id: draft.patientID, name: name, chartNumber: chart)
|
|
search = ""
|
|
patientID = id
|
|
}
|
|
}
|
|
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.image], allowsMultipleSelection: true,
|
|
onCompletion: importImages)
|
|
.alert("Ошибка", isPresented: Binding(
|
|
get: { errorMessage != nil },
|
|
set: { if !$0 { errorMessage = nil } }
|
|
)) {
|
|
Button("Закрыть", role: .cancel) {}
|
|
} message: {
|
|
Text(errorMessage ?? "")
|
|
}
|
|
}
|
|
|
|
private func patientDetail(_ record: PatientRecord) -> some View {
|
|
VStack(spacing: 0) {
|
|
HStack(spacing: 14) {
|
|
VStack(alignment: .leading, spacing: 4) {
|
|
Text(record.name).font(.title2.weight(.semibold))
|
|
Text("Карта № \(record.chartNumber)").foregroundStyle(.secondary)
|
|
}
|
|
Spacer()
|
|
Button { editor = PatientEditor(record) } label: {
|
|
Label("Править карточку", systemImage: "pencil")
|
|
}
|
|
Button { chooseImages(for: record.id) } label: {
|
|
Label("Добавить снимки…", systemImage: "plus")
|
|
}
|
|
.buttonStyle(.borderedProminent)
|
|
}
|
|
.padding(18)
|
|
Divider()
|
|
|
|
if record.images.isEmpty {
|
|
emptyState("Снимков пока нет", detail: "Добавьте JPEG, PNG, TIFF или другой поддерживаемый файл.",
|
|
icon: "photo.on.rectangle")
|
|
} else {
|
|
let selected = record.images.first { $0.id == imageID } ?? record.images[0]
|
|
HStack(spacing: 0) {
|
|
List(record.images, selection: $imageID) { image in
|
|
VStack(alignment: .leading, spacing: 4) {
|
|
Text(image.name).lineLimit(2)
|
|
Text(image.importedAt.formatted(date: .abbreviated, time: .shortened))
|
|
.font(.caption).foregroundStyle(.secondary)
|
|
}
|
|
.padding(.vertical, 5)
|
|
.tag(image.id)
|
|
}
|
|
.frame(width: 200)
|
|
Divider()
|
|
ImageViewer(image: selected, url: library.url(for: selected)) { message in
|
|
errorMessage = message
|
|
}
|
|
.id(selected.id)
|
|
}
|
|
}
|
|
}
|
|
.navigationTitle("Карточка пациента")
|
|
}
|
|
|
|
private func newPatient() {
|
|
editor = PatientEditor(nil)
|
|
}
|
|
|
|
private func chooseImages(for id: UUID) {
|
|
importPatientID = id
|
|
showImporter = true
|
|
}
|
|
|
|
private func importImages(_ result: Result<[URL], Error>) {
|
|
guard let importPatientID else { return }
|
|
self.importPatientID = nil
|
|
do {
|
|
var errors: [String] = []
|
|
var firstImported: UUID?
|
|
for url in try result.get() {
|
|
do {
|
|
let image = try library.importImage(from: url, for: importPatientID)
|
|
firstImported = firstImported ?? image.id
|
|
} catch {
|
|
errors.append("\(url.lastPathComponent) — \(error.localizedDescription)")
|
|
}
|
|
}
|
|
if patientID == importPatientID, let firstImported {
|
|
imageID = firstImported
|
|
}
|
|
if !errors.isEmpty { errorMessage = errors.joined(separator: "\n") }
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
private func emptyState(
|
|
_ title: String, detail: String, icon: String,
|
|
@ViewBuilder action: () -> some View = { EmptyView() }
|
|
) -> some View {
|
|
VStack(spacing: 12) {
|
|
Image(systemName: icon).font(.system(size: 36)).foregroundStyle(.secondary)
|
|
.accessibilityHidden(true)
|
|
Text(title).font(.title3.weight(.semibold))
|
|
Text(detail).foregroundStyle(.secondary).multilineTextAlignment(.center)
|
|
action()
|
|
}
|
|
.padding(24)
|
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
|
}
|
|
}
|
|
|
|
private struct PatientEditor: Identifiable {
|
|
let id = UUID()
|
|
let patientID: UUID?
|
|
let name: String
|
|
let chartNumber: String
|
|
|
|
init(_ patient: PatientRecord?) {
|
|
patientID = patient?.id
|
|
name = patient?.name ?? ""
|
|
chartNumber = patient?.chartNumber ?? ""
|
|
}
|
|
}
|
|
|
|
private struct PatientEditorSheet: View {
|
|
@Environment(\.dismiss) private var dismiss
|
|
@State private var name: String
|
|
@State private var chartNumber: String
|
|
@State private var error: String?
|
|
let isNew: Bool
|
|
let save: (String, String) throws -> Void
|
|
|
|
init(draft: PatientEditor, save: @escaping (String, String) throws -> Void) {
|
|
_name = State(initialValue: draft.name)
|
|
_chartNumber = State(initialValue: draft.chartNumber)
|
|
isNew = draft.patientID == nil
|
|
self.save = save
|
|
}
|
|
|
|
var body: some View {
|
|
VStack(alignment: .leading, spacing: 16) {
|
|
Text(isNew ? "Новый пациент" : "Редактирование карточки").font(.title2.bold())
|
|
Form {
|
|
TextField("Имя пациента", text: $name)
|
|
TextField("Номер карты", text: $chartNumber)
|
|
}
|
|
if let error { Text(error).foregroundStyle(.red) }
|
|
HStack {
|
|
Spacer()
|
|
Button("Отмена") { dismiss() }.keyboardShortcut(.cancelAction)
|
|
Button("Сохранить") {
|
|
do {
|
|
try save(name, chartNumber)
|
|
dismiss()
|
|
} catch {
|
|
self.error = error.localizedDescription
|
|
}
|
|
}
|
|
.keyboardShortcut(.defaultAction)
|
|
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
|
|| chartNumber.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
|
}
|
|
}
|
|
.padding(24)
|
|
.frame(width: 440)
|
|
}
|
|
}
|