SPB Git

Repository Public

MaintenanceScreen.swift 16.3 KB 329 lines swift

1import MCCCore2import SwiftUI34/// Maintenance calendar designed for touch: a month grid with large day cells and the selected day's windows5/// underneath (beside it when the width is regular), an agenda, and a search across the notes.6struct MaintenanceScreen: View {7    @Environment(Navigator.self) private var nav8    @Environment(\.mccTheme) private var theme9    @Environment(\.dynamicTypeSize) private var typeSize10    @Environment(\.horizontalSizeClass) private var hSize11    @Environment(\.accessibilityReduceMotion) private var reduceMotion12    @Session private var session1314    @State private var scope: MaintenanceScope = .month15    @State private var month = Date()16    @State private var selectedDay: Date?17    @State private var noteText = ""18    @State private var noteQuery = ""19    @State private var runner = MutationRunner()20    @State private var export: ExportedCalendar?2122    private var calendar: Calendar { CalendarMath.calendar() }23    private var days: [CalendarDay] { CalendarMath.monthGrid(containing: month, calendar: calendar) }24    private var resource: Resource<API.MaintenanceOccurrenceList>? {25        CalendarMath.window(for: days, calendar: calendar).map { session.maintenance.occurrences[$0] }26    }27    private var selection: Date {28        if let d = selectedDay, MaintenanceLogic.isSameMonth(d, month, calendar: calendar) { return d }29        return MaintenanceLogic.defaultSelection(month: month, today: Date(), calendar: calendar)30    }31    private var canWrite: Bool { session.canMutate && session.can(MaintenancePermission.write) }3233    var body: some View {34        ScreenStack {35            Picker(tr("maintenance.scope.title"), selection: $scope) {36                ForEach(MaintenanceScope.allCases) { Text($0.title).tag($0) }37            }38            .pickerStyle(.segmented)39            .accessibilityIdentifier("maintenance-scope")4041            switch scope {42            case .month, .agenda:43                monthHeader44                if let resource {45                    ResourceSection(resource: resource) { list in46                        VStack(alignment: .leading, spacing: Tokens.Space.s4) {47                            if list.truncated {48                                InfoBanner(tone: .warning, title: tr("maintenance.truncated.title"), message: tr("maintenance.truncated.message"))49                            }50                            // At accessibility text sizes the 7-column grid cannot stay legible (a day number and its51                            // marker no longer fit in a seventh of the width): the agenda replaces it.52                            if scope == .month && !typeSize.isAccessibilitySize {53                                monthLayout(list.items)54                            } else {55                                agenda(list.items)56                            }57                        }58                    }59                    .loads(resource, maxAge: 30)60                }61            case .notes:62                notesSearch63            }64        }65        .screen("maintenance", title: tr("section.maintenance"), load: {66            await session.nodes.list.loadIfNeeded(maxAge: 60)67        }, reload: {68            async let a: Void = session.nodes.list.load()69            async let b: Void = resource?.load() ?? ()70            _ = await (a, b)71            if scope == .notes { await session.maintenance.notes[NotesQuery(text: noteQuery.isEmpty ? nil : noteQuery)].load() }72        })73        .toolbar {74            ToolbarItemGroup(placement: .topBarTrailing) {75                Button { nav.sheet = .noteEditor(NoteContext()) } label: { Label(tr("commands.quick_note"), systemImage: "square.and.pencil") }76                    .disabled(!canWrite)77                    .accessibilityIdentifier("maintenance-quick-note")78                Button { nav.sheet = .windowEditor(windowID: nil, day: selection, nodeID: nil) } label: { Label(tr("maintenance.add"), systemImage: "plus") }79                    .disabled(!canWrite)80                    .accessibilityIdentifier("maintenance-add")81                Menu {82                    Button { exportCalendar() } label: { Label(tr("maintenance.export"), systemImage: "square.and.arrow.up") }83                        .accessibilityIdentifier("maintenance-export")84                } label: { Label(tr("maintenance.more"), systemImage: "ellipsis.circle") }85                    .accessibilityIdentifier("maintenance-more")86            }87        }88        .mutationError(runner)89        .sheet(item: $export) { e in90            NavigationStack { ExportSheet(export: e) }.mccThemed().presentationDetents([.medium])91        }92    }9394    // MARK: Month navigation9596    private var monthHeader: some View {97        HStack(spacing: Tokens.Space.s3) {98            Button { move(-1) } label: { Image(systemName: "chevron.left").touchTarget().contentShape(Rectangle()) }99                .accessibilityLabel(tr("maintenance.month.previous"))100                .accessibilityIdentifier("maintenance-month-previous")101            Text(MaintenanceLogic.monthTitle(month, calendar: calendar))102                .font(.title3.weight(.semibold)).foregroundStyle(theme.textPrimary)103                .frame(maxWidth: .infinity)104                .accessibilityAddTraits(.isHeader)105                .accessibilityIdentifier("maintenance-month-title")106            Button(tr("maintenance.today")) { go(to: Date()) }107                .frame(minHeight: Tokens.Size.touchMin)108                .disabled(MaintenanceLogic.isSameMonth(month, Date(), calendar: calendar) && calendar.isDateInToday(selection))109                .accessibilityIdentifier("maintenance-today")110            Button { move(1) } label: { Image(systemName: "chevron.right").touchTarget().contentShape(Rectangle()) }111                .accessibilityLabel(tr("maintenance.month.next"))112                .accessibilityIdentifier("maintenance-month-next")113        }114        .buttonStyle(.borderless)115    }116117    private func move(_ offset: Int) {118        let target = MaintenanceLogic.month(month, offset: offset, calendar: calendar)119        withAnimation(reduceMotion ? nil : .easeInOut(duration: Tokens.Motion.base)) {120            month = target121            selectedDay = nil122        }123    }124125    private func go(to date: Date) {126        withAnimation(reduceMotion ? nil : .easeInOut(duration: Tokens.Motion.base)) {127            month = date128            selectedDay = calendar.startOfDay(for: date)129        }130    }131132    // MARK: Month grid + selected day133134    @ViewBuilder private func monthLayout(_ items: [API.MaintenanceOccurrence]) -> some View {135        // Same order in both layouts: grid first, then the day.136        if hSize == .regular {137            HStack(alignment: .top, spacing: Tokens.Space.s6) {138                grid(items).frame(maxWidth: 560)139                dayPanel(items).frame(maxWidth: .infinity, alignment: .topLeading)140            }141        } else {142            grid(items)143            dayPanel(items)144        }145    }146147    private func grid(_ items: [API.MaintenanceOccurrence]) -> some View {148        let cols = Array(repeating: GridItem(.flexible(), spacing: Tokens.Space.s2), count: 7)149        return VStack(spacing: Tokens.Space.s2) {150            LazyVGrid(columns: cols, spacing: Tokens.Space.s2) {151                ForEach(Array(CalendarMath.weekdaySymbols(calendar: calendar).enumerated()), id: \.offset) { _, s in152                    Text(s).font(.caption.weight(.medium)).foregroundStyle(theme.textTertiary).frame(maxWidth: .infinity).accessibilityHidden(true)153                }154                ForEach(days) { day in155                    DayCell(day: day, marker: MaintenanceLogic.marker(on: day.date, in: items, calendar: calendar),156                            selected: calendar.isDate(day.date, inSameDayAs: selection)) {157                        if day.inDisplayedMonth { selectedDay = day.date } else { go(to: day.date) }158                    }159                }160            }161        }162        .contentShape(Rectangle())163        .simultaneousGesture(DragGesture(minimumDistance: 24).onEnded { g in164            let dx = g.translation.width, dy = g.translation.height165            guard abs(dx) > 60, abs(dx) > abs(dy) * 1.5 else { return }166            move(dx < 0 ? 1 : -1)167        })168        .accessibilityIdentifier("maintenance-grid")169    }170171    private func dayPanel(_ items: [API.MaintenanceOccurrence]) -> some View {172        let todays = CalendarMath.occurrences(on: selection, in: items, calendar: calendar)173        return VStack(alignment: .leading, spacing: Tokens.Space.s3) {174            Text(Format.date(selection)).font(.headline).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)175                .accessibilityIdentifier("maintenance-selected-day")176            if todays.isEmpty {177                Text(tr("maintenance.day.empty")).font(.callout).foregroundStyle(theme.textSecondary)178                MutationButton(title: tr("maintenance.day.add"), systemImage: "plus", permission: MaintenancePermission.write, identifier: "maintenance-day-add") {179                    nav.sheet = .windowEditor(windowID: nil, day: selection, nodeID: nil)180                }181            } else {182                ForEach(todays, id: \.occurrenceID) { OccurrenceRow(occurrence: $0) }183            }184        }185    }186187    // MARK: Agenda188189    @ViewBuilder private func agenda(_ items: [API.MaintenanceOccurrence]) -> some View {190        let groups = CalendarMath.agenda(items, calendar: calendar)191        if groups.isEmpty {192            EmptyStateView(tr("maintenance.agenda.empty"), message: tr("maintenance.agenda.empty_message"), systemImage: "calendar")193        } else {194            ForEach(groups, id: \.day) { group in195                VStack(alignment: .leading, spacing: Tokens.Space.s3) {196                    HStack(alignment: .firstTextBaseline, spacing: Tokens.Space.s3) {197                        Text(Format.date(group.day)).font(.headline).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)198                        if calendar.isDateInToday(group.day) {199                            Text(tr("maintenance.today")).font(.footnote.weight(.semibold)).foregroundStyle(theme.accent)200                        }201                    }202                    ForEach(group.items, id: \.occurrenceID) { OccurrenceRow(occurrence: $0) }203                }204            }205        }206    }207208    // MARK: Notes search209210    private var notesSearch: some View {211        VStack(alignment: .leading, spacing: Tokens.Space.s4) {212            HStack(spacing: Tokens.Space.s3) {213                Image(systemName: "magnifyingglass").foregroundStyle(theme.textTertiary).accessibilityHidden(true)214                TextField(tr("notes.search.prompt"), text: $noteText)215                    .textInputAutocapitalization(.never).autocorrectionDisabled().submitLabel(.search)216                    .frame(minHeight: Tokens.Size.touchMin)217                    .accessibilityIdentifier("notes-search")218                if !noteText.isEmpty {219                    Button { noteText = "" } label: { Image(systemName: "xmark.circle.fill").touchTarget() }220                        .buttonStyle(.borderless).accessibilityLabel(tr("notes.search.clear"))221                }222            }223            .padding(.horizontal, Tokens.Space.s4)224            .background(theme.inset, in: RoundedRectangle(cornerRadius: Tokens.Radius.lg, style: .continuous))225            .overlay(RoundedRectangle(cornerRadius: Tokens.Radius.lg, style: .continuous).strokeBorder(theme.border, lineWidth: 1))226            NotesBlock(query: NotesQuery(text: noteQuery.isEmpty ? nil : noteQuery), runner: runner, showsContext: true,227                       emptyText: noteQuery.isEmpty ? tr("notes.empty") : tr("notes.search.empty"))228        }229        // Debounced: one request once typing pauses (cancelled when the text changes again).230        .task(id: noteText) {231            let q = noteText.trimmingCharacters(in: .whitespacesAndNewlines)232            guard q != noteQuery else { return }233            try? await Task.sleep(for: .milliseconds(300))234            if !Task.isCancelled { noteQuery = q }235        }236    }237238    // MARK: Export239240    private func exportCalendar() {241        guard let from = days.first?.date, let last = days.last?.date else { return }242        let to = calendar.date(byAdding: .day, value: 1, to: last)243        Task {244            if let data = await runner.run({ try await session.maintenance.exportICS(from: from, to: to, nodeID: nil) }) {245                let url = FileManager.default.temporaryDirectory.appendingPathComponent("maclustr-maintenance.ics")246                do {247                    try data.write(to: url, options: .atomic)248                    export = ExportedCalendar(url: url, bytes: data.count)249                } catch {250                    runner.error = APIError(code: "client.export", message: error.localizedDescription)251                }252            }253        }254    }255}256257struct ExportedCalendar: Identifiable, Hashable {258    let url: URL259    let bytes: Int260    var id: URL { url }261}262263private struct ExportSheet: View {264    @Environment(\.dismiss) private var dismiss265    @Environment(\.mccTheme) private var theme266    let export: ExportedCalendar267    var body: some View {268        VStack(spacing: Tokens.Space.s5) {269            Image(systemName: "calendar.badge.checkmark").font(.largeTitle).foregroundStyle(theme.accent).accessibilityHidden(true)270            Text(tr("maintenance.export.ready", Format.bytes(Int64(export.bytes)))).font(.callout).foregroundStyle(theme.textSecondary).multilineTextAlignment(.center)271            ShareLink(item: export.url) { Label(tr("maintenance.export.share"), systemImage: "square.and.arrow.up").frame(maxWidth: .infinity, minHeight: Tokens.Size.touchMin) }272                .buttonStyle(.mccProminent)273                .accessibilityIdentifier("maintenance-export-share")274        }275        .padding(Tokens.Space.s7)276        .frame(maxWidth: .infinity, maxHeight: .infinity)277        .background(theme.canvas.ignoresSafeArea())278        .navigationTitle(tr("maintenance.export"))279        .navigationBarTitleDisplayMode(.inline)280        .toolbar { ToolbarItem(placement: .cancellationAction) { Button(tr("common.close")) { dismiss() } } }281    }282}283284/// One day of the month grid: at least 44 pt, the day number, and a marker made of a symbol and a count.285private struct DayCell: View {286    @Environment(\.mccTheme) private var theme287    let day: CalendarDay288    let marker: DayMarker?289    let selected: Bool290    let action: () -> Void291292    var body: some View {293        Button(action: action) {294            VStack(spacing: Tokens.Space.s1) {295                Text(day.date, format: .dateTime.day())296                    .font(.callout.weight(day.isToday ? .bold : .regular).monospacedDigit())297                    .foregroundStyle(selected ? theme.accentContrast : day.inDisplayedMonth ? theme.textPrimary : theme.textSecondary)298                    .underline(day.isToday)299                if let marker {300                    HStack(spacing: Tokens.Space.s1) {301                        Image(systemName: marker.hasActive ? "wrench.and.screwdriver.fill" : (marker.symbols.first ?? "calendar"))302                        Text("\(marker.count)").monospacedDigit()303                    }304                    .font(.caption2.weight(.semibold))305                    .foregroundStyle(selected ? theme.accentContrast : marker.hasActive ? StatusTone.maintenance.color(theme) : theme.accent)306                } else {307                    Text(" ").font(.caption2)308                }309            }310            .frame(maxWidth: .infinity, minHeight: Tokens.Size.touchMin + Tokens.Space.s3)311            .background(selected ? theme.accent : theme.surface, in: RoundedRectangle(cornerRadius: Tokens.Radius.md, style: .continuous))312            .overlay(RoundedRectangle(cornerRadius: Tokens.Radius.md, style: .continuous)313                .strokeBorder(day.isToday ? theme.accent : theme.borderSubtle, lineWidth: day.isToday ? 2 : 1))314            .contentShape(Rectangle())315        }316        .buttonStyle(.plain)317        .hoverEffect(.highlight)318        .accessibilityElement(children: .ignore)319        .accessibilityLabel(label)320        .accessibilityValue(marker.map { tr("maintenance.day.windows", $0.count) + ($0.hasActive ? ", " + API.MaintenanceStatus.inProgress.label : "") } ?? tr("maintenance.day.no_window"))321        .accessibilityAddTraits(selected ? [.isButton, .isSelected] : [.isButton])322        .accessibilityIdentifier("day-cell")323    }324325    private var label: String {326        Format.date(day.date) + (day.isToday ? ", " + tr("maintenance.today") : "")327    }328}329
Files main
Menu

Theme