Build persistent patient library and image viewer
This commit is contained in:
1 parent
d861462e55
commit
48177fc7fb
5 files changed
+437
-112
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# EzDent для macOS
|
||||
|
||||
Каркас нативного приложения на SwiftUI для macOS 13 и новее. Универсальный пакет содержит исполняемый код для Intel (`x86_64`) и Apple Silicon (`arm64`).
|
||||
Нативное приложение на SwiftUI для macOS 13 и новее. Универсальный пакет содержит исполняемый код для Intel (`x86_64`) и Apple Silicon (`arm64`).
|
||||
|
||||
## Разработка
|
||||
|
||||
@@ -21,7 +21,11 @@ open dist/EzDent.app
|
||||
|
||||
## Текущая версия клиента
|
||||
|
||||
В боковой панели можно искать демонстрационные карточки по имени и номеру. Кнопка «Открыть снимки…» загружает поддерживаемые macOS изображения, например JPEG, PNG и TIFF, в выбранную карточку на время работы окна. DICOM, данные с сервера и управление рентгеновским оборудованием пока не поддерживаются.
|
||||
Создайте карточку пациента, укажите имя и номер карты. Найти карточку можно по обоим полям. Кнопка «Добавить снимки…» копирует JPEG, PNG, TIFF и другие изображения, которые поддерживает macOS, в локальную библиотеку. Карточки и снимки сохраняются после перезапуска в `~/Library/Application Support/EzDent/Library`.
|
||||
|
||||
В просмотрщике можно менять масштаб, поворот, яркость и контраст. Настройки просмотра не изменяют оригинал. Кнопка «Экспорт оригинала…» сохраняет исходный файл.
|
||||
|
||||
Из справки Windows-версии взяты сценарии поиска и редактирования карточек, импорта и просмотра снимков и настройки яркости и контраста. DICOM, 3D, отчёты и захват с оборудования пока не реализованы.
|
||||
|
||||
В настройках приложения (`⌘,`) можно сохранить хост и порт ezServer и проверить TCP-подключение к этому адресу. Клиент пока не выполняет авторизацию и запросы к API.
|
||||
|
||||
|
||||
@@ -2,10 +2,13 @@ import SwiftUI
|
||||
|
||||
@main
|
||||
struct EzDentApp: App {
|
||||
@StateObject private var library = PatientLibrary()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
PatientWorkspace()
|
||||
.frame(minWidth: 760, minHeight: 480)
|
||||
.environmentObject(library)
|
||||
.frame(minWidth: 920, minHeight: 480)
|
||||
}
|
||||
.defaultSize(width: 1050, height: 680)
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import AppKit
|
||||
import ImageIO
|
||||
import SwiftUI
|
||||
|
||||
struct ImageViewer: View {
|
||||
let image: PatientImage
|
||||
let url: URL
|
||||
let reportError: (String) -> Void
|
||||
|
||||
@State private var preview: CGImage?
|
||||
@State private var isLoading = true
|
||||
@State private var zoom = 1.0
|
||||
@State private var quarterTurns = 0
|
||||
@State private var brightness = 0.0
|
||||
@State private var contrast = 1.0
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
ControlGroup {
|
||||
Button { zoom = max(1, zoom / 1.25) } label: {
|
||||
Label("Уменьшить", systemImage: "minus.magnifyingglass")
|
||||
}
|
||||
Button("Вписать") { zoom = 1 }
|
||||
Button { zoom = min(8, zoom * 1.25) } label: {
|
||||
Label("Увеличить", systemImage: "plus.magnifyingglass")
|
||||
}
|
||||
}
|
||||
Button { quarterTurns = (quarterTurns + 1) % 4 } label: {
|
||||
Label("Повернуть", systemImage: "rotate.right")
|
||||
}
|
||||
Spacer()
|
||||
Button("Экспорт оригинала…", action: exportOriginal)
|
||||
}
|
||||
.padding(10)
|
||||
|
||||
GeometryReader { geometry in
|
||||
if let preview {
|
||||
let isSideways = !quarterTurns.isMultiple(of: 2)
|
||||
let width = max(1, geometry.size.width - 24)
|
||||
let height = max(1, geometry.size.height - 24)
|
||||
ScrollView([.horizontal, .vertical]) {
|
||||
Image(decorative: preview, scale: 1)
|
||||
.resizable().scaledToFit()
|
||||
.brightness(brightness).contrast(contrast)
|
||||
.frame(width: (isSideways ? height : width) * zoom,
|
||||
height: (isSideways ? width : height) * zoom)
|
||||
.rotationEffect(.degrees(Double(quarterTurns) * 90))
|
||||
.frame(width: width * zoom, height: height * zoom)
|
||||
.accessibilityLabel(image.name)
|
||||
.padding(12)
|
||||
}
|
||||
} else if isLoading {
|
||||
ProgressView()
|
||||
.controlSize(.large)
|
||||
.colorScheme(.dark)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
} else {
|
||||
Text("Снимок недоступен для просмотра")
|
||||
.foregroundStyle(.white)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
.background(Color(white: 0.10))
|
||||
|
||||
HStack(spacing: 16) {
|
||||
Slider(value: $brightness, in: -0.5...0.5) { Text("Яркость") }
|
||||
Slider(value: $contrast, in: 0.5...2) { Text("Контраст") }
|
||||
Button("Сбросить") {
|
||||
zoom = 1
|
||||
quarterTurns = 0
|
||||
brightness = 0
|
||||
contrast = 1
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.disabled(preview == nil)
|
||||
}
|
||||
.task {
|
||||
preview = await Task.detached(priority: .userInitiated) {
|
||||
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
|
||||
let bitmap = CGImageSourceCreateThumbnailAtIndex(source, 0, [
|
||||
kCGImageSourceCreateThumbnailFromImageAlways: true,
|
||||
kCGImageSourceCreateThumbnailWithTransform: true,
|
||||
kCGImageSourceThumbnailMaxPixelSize: 4096
|
||||
] as CFDictionary) else { return nil as CGImage? }
|
||||
return bitmap
|
||||
}.value
|
||||
isLoading = false
|
||||
}
|
||||
}
|
||||
|
||||
private func exportOriginal() {
|
||||
let panel = NSSavePanel()
|
||||
panel.nameFieldStringValue = image.name
|
||||
guard panel.runModal() == .OK, let destination = panel.url else { return }
|
||||
do {
|
||||
try Data(contentsOf: url).write(to: destination, options: .atomic)
|
||||
} catch {
|
||||
reportError(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
import ImageIO
|
||||
|
||||
struct PatientRecord: Codable, Identifiable {
|
||||
let id: UUID
|
||||
var name: String
|
||||
var chartNumber: String
|
||||
var images: [PatientImage] = []
|
||||
}
|
||||
|
||||
struct PatientImage: Codable, Identifiable {
|
||||
let id: UUID
|
||||
let name: String
|
||||
let importedAt: Date
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class PatientLibrary: ObservableObject {
|
||||
@Published private(set) var patients: [PatientRecord] = []
|
||||
@Published private(set) var loadError: String?
|
||||
|
||||
private let directory: URL
|
||||
private var index: URL { directory.appendingPathComponent("patients.json") }
|
||||
|
||||
init(directory: URL = URL.applicationSupportDirectory.appendingPathComponent("EzDent/Library")) {
|
||||
self.directory = directory
|
||||
do {
|
||||
if FileManager.default.fileExists(atPath: index.path) {
|
||||
patients = try JSONDecoder().decode([PatientRecord].self, from: Data(contentsOf: index))
|
||||
}
|
||||
} catch {
|
||||
loadError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func savePatient(id: UUID?, name: String, chartNumber: String) throws -> UUID {
|
||||
let name = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let chartNumber = chartNumber.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !name.isEmpty, !chartNumber.isEmpty else { throw LibraryError.missingFields }
|
||||
guard !patients.contains(where: {
|
||||
$0.id != id && $0.chartNumber.caseInsensitiveCompare(chartNumber) == .orderedSame
|
||||
}) else { throw LibraryError.duplicateChart }
|
||||
|
||||
var updated = patients
|
||||
let patientID = id ?? UUID()
|
||||
if let position = updated.firstIndex(where: { $0.id == patientID }) {
|
||||
updated[position].name = name
|
||||
updated[position].chartNumber = chartNumber
|
||||
} else {
|
||||
updated.append(PatientRecord(id: patientID, name: name, chartNumber: chartNumber))
|
||||
}
|
||||
try save(updated)
|
||||
return patientID
|
||||
}
|
||||
|
||||
func importImage(from source: URL, for patientID: UUID) throws -> PatientImage {
|
||||
guard let position = patients.firstIndex(where: { $0.id == patientID }) else {
|
||||
throw LibraryError.patientMissing
|
||||
}
|
||||
try prepareDirectory()
|
||||
let hasAccess = source.startAccessingSecurityScopedResource()
|
||||
defer { if hasAccess { source.stopAccessingSecurityScopedResource() } }
|
||||
|
||||
guard let imageSource = CGImageSourceCreateWithURL(source as CFURL, nil),
|
||||
CGImageSourceGetCount(imageSource) > 0,
|
||||
CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) != nil else {
|
||||
throw LibraryError.unsupportedImage
|
||||
}
|
||||
|
||||
let image = PatientImage(id: UUID(), name: source.lastPathComponent, importedAt: Date())
|
||||
let destination = url(for: image)
|
||||
try FileManager.default.copyItem(at: source, to: destination)
|
||||
do {
|
||||
var updated = patients
|
||||
updated[position].images.insert(image, at: 0)
|
||||
try save(updated)
|
||||
} catch {
|
||||
try? FileManager.default.removeItem(at: destination)
|
||||
throw error
|
||||
}
|
||||
return image
|
||||
}
|
||||
|
||||
func url(for image: PatientImage) -> URL {
|
||||
directory.appendingPathComponent(image.id.uuidString)
|
||||
}
|
||||
|
||||
private func prepareDirectory() throws {
|
||||
guard loadError == nil else { throw LibraryError.indexUnavailable }
|
||||
try FileManager.default.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700]
|
||||
)
|
||||
}
|
||||
|
||||
private func save(_ updated: [PatientRecord]) throws {
|
||||
try prepareDirectory()
|
||||
let sorted = updated.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
|
||||
try JSONEncoder().encode(sorted).write(to: index, options: .atomic)
|
||||
patients = sorted
|
||||
}
|
||||
}
|
||||
|
||||
private enum LibraryError: LocalizedError {
|
||||
case missingFields, duplicateChart, patientMissing, unsupportedImage, indexUnavailable
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .missingFields: return "Введите имя и номер карты."
|
||||
case .duplicateChart: return "Карточка с таким номером уже существует."
|
||||
case .patientMissing: return "Карточка пациента недоступна."
|
||||
case .unsupportedImage: return "Формат снимка не поддерживается."
|
||||
case .indexUnavailable: return "Индекс библиотеки недоступен."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,161 +3,258 @@ import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct PatientWorkspace: View {
|
||||
private struct Patient: Identifiable {
|
||||
let id: String
|
||||
let name: String
|
||||
}
|
||||
|
||||
private struct Attachment: Identifiable {
|
||||
let id = UUID()
|
||||
let name: String
|
||||
let image: NSImage
|
||||
}
|
||||
|
||||
private let patients = [
|
||||
Patient(id: "DEMO-001", name: "Демо-пациент 1"),
|
||||
Patient(id: "DEMO-002", name: "Демо-пациент 2")
|
||||
]
|
||||
|
||||
@EnvironmentObject private var library: PatientLibrary
|
||||
@State private var search = ""
|
||||
@State private var patientID: Patient.ID?
|
||||
@State private var attachments: [Patient.ID: [Attachment]] = [:]
|
||||
@State private var attachmentID: Attachment.ID?
|
||||
@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 importError: String?
|
||||
@State private var errorMessage: String?
|
||||
|
||||
private var filteredPatients: [Patient] {
|
||||
private var filteredPatients: [PatientRecord] {
|
||||
let query = search.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return patients.filter {
|
||||
return library.patients.filter {
|
||||
query.isEmpty || $0.name.localizedStandardContains(query)
|
||||
|| $0.id.localizedStandardContains(query)
|
||||
|| $0.chartNumber.localizedStandardContains(query)
|
||||
}
|
||||
}
|
||||
|
||||
private var patient: Patient? {
|
||||
patients.first { $0.id == patientID }
|
||||
}
|
||||
|
||||
private var patientAttachments: [Attachment] {
|
||||
patientID.flatMap { attachments[$0] } ?? []
|
||||
private var patient: PatientRecord? {
|
||||
library.patients.first { $0.id == patientID }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationSplitView {
|
||||
List(filteredPatients, selection: $patientID) { patient in
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(patient.name)
|
||||
Text(patient.id)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
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("Очистить поиск")
|
||||
}
|
||||
}
|
||||
.tag(patient.id)
|
||||
.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)
|
||||
}
|
||||
.searchable(text: $search, placement: .sidebar, prompt: "Имя или номер карты")
|
||||
.navigationTitle("Пациенты")
|
||||
.navigationSplitViewColumnWidth(min: 190, ideal: 240)
|
||||
.safeAreaInset(edge: .bottom) {
|
||||
Text("Демонстрационные данные")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(12)
|
||||
.background(.bar)
|
||||
}
|
||||
.navigationSplitViewColumnWidth(min: 220, ideal: 260)
|
||||
} detail: {
|
||||
if let patient {
|
||||
imageWorkspace
|
||||
.navigationTitle(patient.name)
|
||||
.navigationSubtitle(patient.id)
|
||||
.toolbar {
|
||||
Button {
|
||||
showImporter = true
|
||||
} label: {
|
||||
Label("Открыть снимки…", systemImage: "folder")
|
||||
}
|
||||
}
|
||||
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 {
|
||||
placeholder("Выберите пациента", icon: "person.crop.rectangle")
|
||||
.navigationTitle("EzDent")
|
||||
emptyState("Выберите пациента", detail: "Найдите карточку по имени или номеру.", icon: "person.crop.rectangle")
|
||||
}
|
||||
}
|
||||
.onChange(of: patientID) { _ in
|
||||
attachmentID = patientAttachments.first?.id
|
||||
imageID = patient?.images.first?.id
|
||||
}
|
||||
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.image], allowsMultipleSelection: true) {
|
||||
importImages($0)
|
||||
.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
|
||||
}
|
||||
}
|
||||
.alert("Не удалось открыть снимки", isPresented: Binding(
|
||||
get: { importError != nil },
|
||||
set: { if !$0 { importError = nil } }
|
||||
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.image], allowsMultipleSelection: true,
|
||||
onCompletion: importImages)
|
||||
.alert("Ошибка", isPresented: Binding(
|
||||
get: { errorMessage != nil },
|
||||
set: { if !$0 { errorMessage = nil } }
|
||||
)) {
|
||||
Button("ОК", role: .cancel) {}
|
||||
Button("Закрыть", role: .cancel) {}
|
||||
} message: {
|
||||
Text(importError ?? "")
|
||||
Text(errorMessage ?? "")
|
||||
}
|
||||
}
|
||||
|
||||
private var imageWorkspace: some View {
|
||||
private func patientDetail(_ record: PatientRecord) -> some View {
|
||||
VStack(spacing: 0) {
|
||||
if let attachment = patientAttachments.first(where: { $0.id == attachmentID }) {
|
||||
Image(nsImage: attachment.image)
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.accessibilityLabel(attachment.name)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.padding(16)
|
||||
} else {
|
||||
placeholder("Откройте локальные снимки", icon: "photo")
|
||||
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 !patientAttachments.isEmpty {
|
||||
Divider()
|
||||
Picker("Снимок", selection: $attachmentID) {
|
||||
ForEach(patientAttachments) { attachment in
|
||||
Text(attachment.name).tag(Optional(attachment.id))
|
||||
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)
|
||||
}
|
||||
.padding(12)
|
||||
}
|
||||
}
|
||||
.navigationTitle("Карточка пациента")
|
||||
}
|
||||
|
||||
private func placeholder(_ title: String, icon: String) -> some View {
|
||||
VStack(spacing: 12) {
|
||||
Image(systemName: icon)
|
||||
.font(.largeTitle)
|
||||
.accessibilityHidden(true)
|
||||
Text(title)
|
||||
.font(.headline)
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
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 patientID else { return }
|
||||
guard let importPatientID else { return }
|
||||
self.importPatientID = nil
|
||||
do {
|
||||
var imported: [Attachment] = []
|
||||
var failures: [String] = []
|
||||
var errors: [String] = []
|
||||
var firstImported: UUID?
|
||||
for url in try result.get() {
|
||||
let hasAccess = url.startAccessingSecurityScopedResource()
|
||||
defer { if hasAccess { url.stopAccessingSecurityScopedResource() } }
|
||||
if let data = try? Data(contentsOf: url),
|
||||
let image = NSImage(data: data), image.isValid {
|
||||
imported.append(Attachment(name: url.lastPathComponent, image: image))
|
||||
} else {
|
||||
failures.append(url.lastPathComponent)
|
||||
do {
|
||||
let image = try library.importImage(from: url, for: importPatientID)
|
||||
firstImported = firstImported ?? image.id
|
||||
} catch {
|
||||
errors.append("\(url.lastPathComponent) — \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
if let first = imported.first {
|
||||
attachments[patientID, default: []].append(contentsOf: imported)
|
||||
attachmentID = first.id
|
||||
}
|
||||
if !failures.isEmpty {
|
||||
importError = failures.joined(separator: "\n")
|
||||
if patientID == importPatientID, let firstImported {
|
||||
imageID = firstImported
|
||||
}
|
||||
if !errors.isEmpty { errorMessage = errors.joined(separator: "\n") }
|
||||
} catch {
|
||||
importError = error.localizedDescription
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user