SPB Git

Repository Public

LibraryView.swift 15.5 KB 287 lines swift

1// SP Lecture Studio2// File: Apps/LectureStudio/Shared/Library/LibraryView.swift3// Description: Lecture library: search, recents, import (file picker, drag and drop), rename, duplicate, archive, recoverable trash, storage usage.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import UniformTypeIdentifiers9import LectureCore10import LectureStorage11import LecturePDF1213extension UTType {14    static let slecture = UTType(exportedAs: "ai.spboucher.slecture")15}1617/// Small cache of cover thumbnails (first / chosen page of each project PDF).18@MainActor @Observable19final class CoverCache {20    static let shared = CoverCache()21    private var images: [String: CGImage] = [:]22    private var pending: Set<String> = []23    private(set) var revision = 02425    func cover(for item: LectureStorage.LibraryItem) -> CGImage? {26        let key = "\(item.id.uuidString)-\(item.manifest.coverPage)-\(item.manifest.pdf?.sha256.prefix(8) ?? "")"27        if let img = images[key] { return img }28        guard !pending.contains(key) else { return nil }29        pending.insert(key)30        let url = item.package.pdfURL, page = item.manifest.coverPage31        Task.detached(priority: .utility) {32            let img = (try? SlideDocument(url: url))?.thumbnail(page: page, maxDimension: 240)33            await MainActor.run {34                self.pending.remove(key)35                if let img { self.images[key] = img; self.revision += 1 }36            }37        }38        return nil39    }40}4142struct LibraryView: View {43    let model: AppModel44    var compact: Bool45    var onOpen: (UUID) -> Void46    @State private var importing = false47    @State private var pendingPDF: URL?48    @State private var renaming: LectureStorage.LibraryItem?49    @State private var renameText = ""50    @State private var deleting: LectureStorage.LibraryItem?51    @State private var showTrash = false52    @State private var showSettings = false53    @State private var dropTargeted = false54    private let covers = CoverCache.shared5556    var body: some View {57        VStack(spacing: 0) {58            header59            Divider()60            if model.items.isEmpty { emptyState } else { list }61            Divider()62            footer63        }64        .background(DS.panel)65        .overlay { if dropTargeted { RoundedRectangle(cornerRadius: 12).strokeBorder(DS.accent, style: StrokeStyle(lineWidth: 3, dash: [8])).padding(6).allowsHitTesting(false) } }66        .dropDestination(for: URL.self) { urls, _ in67            for u in urls { if u.pathExtension.lowercased() == "pdf" { pendingPDF = u } else { model.open(url: u) } }68            return !urls.isEmpty69        } isTargeted: { dropTargeted = $0 }70        .fileImporter(isPresented: $importing, allowedContentTypes: [.pdf, .slecture, .zip], allowsMultipleSelection: false) { result in71            guard case .success(let urls) = result, let url = urls.first else { return }72            if url.pathExtension.lowercased() == "pdf" { pendingPDF = url } else { model.open(url: url) }73        }74        .sheet(item: Binding(get: { pendingPDF.map(PendingPDF.init) }, set: { pendingPDF = $0?.url })) { p in75            NewLectureSheet(model: model, url: p.url) { id in pendingPDF = nil; if let id { onOpen(id) } }76        }77        .sheet(isPresented: $showTrash) { TrashSheet(model: model) }78        .sheet(isPresented: $showSettings) { SettingsView(settings: model.settings, embedded: false) }79        .alert("Renommer la séance", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {80            TextField("Titre", text: $renameText)81            Button("Renommer") { if let r = renaming { model.rename(r, to: renameText) }; renaming = nil }82            Button("Annuler", role: .cancel) { renaming = nil }83        }84        .confirmationDialog("Mettre cette séance à la corbeille ?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {85            Button("Mettre à la corbeille", role: .destructive) { if let d = deleting { model.trash(d) }; deleting = nil }86            Button("Annuler", role: .cancel) { deleting = nil }87        } message: { Text("Le projet et ses enregistrements restent récupérables depuis la corbeille de la bibliothèque tant qu'elle n'est pas vidée.") }88    }8990    private struct PendingPDF: Identifiable { var url: URL; var id: String { url.path } }9192    private var header: some View {93        VStack(spacing: 8) {94            HStack {95                Text("Séances").font(.title2.weight(.bold))96                Spacer()97                #if os(iOS)98                Button { showSettings = true } label: { Image(systemName: "gearshape") }.buttonStyle(IconButtonStyle()).accessibilityLabel("Réglages")99                #endif100                Button { importing = true } label: { Image(systemName: "plus") }101                    .buttonStyle(IconButtonStyle(active: true)).keyboardShortcut("n", modifiers: [.command])102                    .help("Nouvelle séance à partir d'un PDF (⌘N)").accessibilityLabel("Nouvelle séance à partir d'un PDF").accessibilityIdentifier("library.new")103            }104            HStack(spacing: 6) {105                Image(systemName: "magnifyingglass").foregroundStyle(.secondary)106                TextField("Rechercher", text: Binding(get: { model.query }, set: { model.query = $0 })).textFieldStyle(.plain).accessibilityIdentifier("library.search")107                if !model.query.isEmpty { Button { model.query = "" } label: { Image(systemName: "xmark.circle.fill") }.buttonStyle(.plain).foregroundStyle(.secondary).accessibilityLabel("Effacer la recherche") }108            }109            .padding(.horizontal, 8).frame(height: 32)110            .background(Color.primary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))111        }112        .padding(12)113    }114115    private var emptyState: some View {116        VStack(spacing: 14) {117            Spacer()118            Image(systemName: "doc.richtext").font(.system(size: 44)).foregroundStyle(DS.accent)119            Text("Aucune séance").font(.title3.weight(.semibold))120            Text("Importez le PDF de vos diapositives pour préparer, annoter et enregistrer un cours. Tout reste sur cet appareil.")121                .font(.callout).foregroundStyle(.secondary).multilineTextAlignment(.center).padding(.horizontal, 24)122            Button { importing = true } label: { Label("Importer un PDF", systemImage: "square.and.arrow.down") }123                .buttonStyle(.borderedProminent).controlSize(.large).accessibilityIdentifier("library.import")124            Text("Vous pouvez aussi glisser un PDF ici.").font(.caption).foregroundStyle(.tertiary)125            Spacer()126        }127        .frame(maxWidth: .infinity)128    }129130    private var list: some View {131        let _ = covers.revision132        return ScrollView {133            LazyVStack(alignment: .leading, spacing: 4) {134                if model.settings.stored.showArchived { SectionTitle("Archives").padding(.horizontal, 6).padding(.top, 6) }135                else if model.query.isEmpty { SectionTitle("Toutes les séances").padding(.horizontal, 6).padding(.top, 6) }136                ForEach(model.visibleItems) { item in row(item) }137                if model.visibleItems.isEmpty {138                    Text(model.query.isEmpty ? "Rien ici." : "Aucune séance ne correspond à « \(model.query) ».").font(.callout).foregroundStyle(.secondary).padding(12)139                }140                if !model.unreadable.isEmpty {141                    SectionTitle("Projets illisibles").padding(.horizontal, 6).padding(.top, 10)142                    ForEach(model.unreadable, id: \.self) { u in143                        Label { Text(verbatim: u.lastPathComponent).font(.caption) } icon: { Image(systemName: "exclamationmark.triangle").foregroundStyle(DS.paused) }.padding(.horizontal, 8)144                    }145                }146            }147            .padding(8)148        }149    }150151    private func row(_ item: LectureStorage.LibraryItem) -> some View {152        let selected = model.selectedID == item.id153        let m = item.manifest154        return Button { model.selectedID = item.id; onOpen(item.id) } label: {155            HStack(spacing: 10) {156                Group {157                    if let img = covers.cover(for: item) { Image(cg: img).resizable().aspectRatio(contentMode: .fill) }158                    else { Rectangle().fill(Color.primary.opacity(0.08)).overlay(Image(systemName: "doc").foregroundStyle(.secondary)) }159                }160                .frame(width: 72, height: 46).clipShape(RoundedRectangle(cornerRadius: 5)).overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(Color.primary.opacity(0.12)))161                VStack(alignment: .leading, spacing: 2) {162                    Text(verbatim: m.title).font(.subheadline.weight(.semibold)).lineLimit(1)163                    let sub = m.subtitle(sessionWord: String(localized: "Séance"))164                    if !sub.isEmpty { Text(verbatim: sub).font(.caption).foregroundStyle(selected ? Color.white.opacity(0.85) : .secondary).lineLimit(1) }165                    HStack(spacing: 6) {166                        Text(verbatim: m.lectureDate.formatted(.dateTime.day().month(.abbreviated))).layoutPriority(1)167                        if m.hasRecording { Label { Text(verbatim: DS.duration(m.duration)) } icon: { Image(systemName: "waveform") }.layoutPriority(2) }168                        Text(verbatim: DS.bytes(item.byteCount))169                        if item.needsRecovery { Image(systemName: "bandage").help("Enregistrement interrompu : sera récupéré à l'ouverture") }170                        if model.isRecording(item.id) { Image(systemName: "record.circle.fill").foregroundStyle(DS.recording) }171                    }172                    .font(.caption2).foregroundStyle(selected ? Color.white.opacity(0.8) : Color.secondary).labelStyle(.titleAndIcon).lineLimit(1)173                }174                Spacer(minLength: 0)175            }176            .padding(6)177            .foregroundStyle(selected ? Color.white : Color.primary)178            .background(selected ? AnyShapeStyle(DS.accent) : AnyShapeStyle(Color.clear), in: RoundedRectangle(cornerRadius: 8, style: .continuous))179            .contentShape(Rectangle())180        }181        .buttonStyle(.plain)182        .accessibilityElement(children: .combine)183        .accessibilityAddTraits(selected ? .isSelected : [])184        .accessibilityIdentifier("library.row.\(m.title)")185        .contextMenu {186            Button { model.selectedID = item.id; onOpen(item.id) } label: { Label("Ouvrir", systemImage: "arrow.right.circle") }187            Button { renameText = m.title; renaming = item } label: { Label("Renommer…", systemImage: "pencil") }188            Button { model.duplicate(item) } label: { Label("Dupliquer", systemImage: "plus.square.on.square") }189            Button { model.setArchived(item, !m.archived) } label: { Label(m.archived ? "Désarchiver" : "Archiver", systemImage: "archivebox") }190            #if os(macOS)191            Button { NSWorkspace.shared.activateFileViewerSelecting([item.package.url]) } label: { Label("Afficher dans le Finder", systemImage: "folder") }192            #endif193            Divider()194            Button(role: .destructive) { deleting = item } label: { Label("Mettre à la corbeille…", systemImage: "trash") }195        }196    }197198    private var footer: some View {199        HStack(spacing: 10) {200            VStack(alignment: .leading, spacing: 1) {201                Text("\(model.items.count) séance(s) · \(DS.bytes(model.totalBytes))").font(.caption)202                Text("\(DS.bytes(model.freeBytes)) libres").font(.caption2).foregroundStyle(.secondary)203            }204            Spacer()205            Button { model.settings.stored.showArchived.toggle() } label: { Image(systemName: model.settings.stored.showArchived ? "archivebox.fill" : "archivebox") }206                .buttonStyle(IconButtonStyle(active: model.settings.stored.showArchived)).help("Archives (\(model.archivedCount))").accessibilityLabel("Afficher les archives")207            Button { showTrash = true } label: { Image(systemName: model.trashed.isEmpty ? "trash" : "trash.fill") }208                .buttonStyle(IconButtonStyle()).help("Corbeille (\(model.trashed.count))").accessibilityLabel("Corbeille de la bibliothèque")209        }210        .padding(.horizontal, 10).frame(height: 50)211    }212}213214struct NewLectureSheet: View {215    let model: AppModel216    let url: URL217    var done: (UUID?) -> Void218    @State private var title = ""219    @State private var course = ""220    @State private var number = ""221    @State private var date = Date()222223    var body: some View {224        NavigationStack {225            Form {226                Section {227                    TextField("Titre", text: $title).accessibilityIdentifier("new.title")228                    TextField("Sigle du cours (ex. IMM1003)", text: $course).accessibilityIdentifier("new.course")229                    TextField("Numéro de séance", text: $number)230                    #if os(iOS)231                        .keyboardType(.numberPad)232                    #endif233                    DatePicker("Date du cours", selection: $date, displayedComponents: .date)234                } footer: { Text("Le PDF est copié dans le projet. Le fichier d'origine n'est jamais modifié.") }235            }236            .formStyle(.grouped)237            .navigationTitle("Nouvelle séance").inlineTitle()238            .toolbar {239                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { done(nil) } }240                ToolbarItem(placement: .confirmationAction) {241                    Button("Créer") { done(model.createLecture(fromPDF: url, title: title, courseCode: course.trimmingCharacters(in: .whitespaces), sessionNumber: Int(number), date: date)) }242                        .accessibilityIdentifier("new.create")243                }244            }245            .onAppear { if title.isEmpty { title = url.deletingPathExtension().lastPathComponent } }246        }247        #if os(macOS)248        .frame(minWidth: 440, minHeight: 300)249        #endif250    }251}252253struct TrashSheet: View {254    let model: AppModel255    @Environment(\.dismiss) private var dismiss256    @State private var confirmEmpty = false257    var body: some View {258        NavigationStack {259            List {260                if model.trashed.isEmpty { Text("La corbeille est vide.").foregroundStyle(.secondary) }261                ForEach(model.trashed) { item in262                    HStack {263                        VStack(alignment: .leading) {264                            Text(verbatim: item.manifest.title)265                            Text(verbatim: "\(DS.duration(item.manifest.duration)) · \(DS.bytes(item.byteCount))").font(.caption).foregroundStyle(.secondary)266                        }267                        Spacer()268                        Button("Restaurer") { model.restore(item) }.buttonStyle(.bordered)269                    }270                }271            }272            .navigationTitle("Corbeille")273            .toolbar {274                ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } }275                ToolbarItem(placement: .destructiveAction) { Button("Vider…", role: .destructive) { confirmEmpty = true }.disabled(model.trashed.isEmpty) }276            }277            .confirmationDialog("Supprimer définitivement \(model.trashed.count) projet(s) ?", isPresented: $confirmEmpty, titleVisibility: .visible) {278                Button("Supprimer définitivement", role: .destructive) { model.emptyTrash() }279                Button("Annuler", role: .cancel) {}280            } message: { Text("Les enregistrements d'origine de ces projets seront effacés. Cette action est irréversible.") }281        }282        #if os(macOS)283        .frame(minWidth: 460, minHeight: 360)284        #endif285    }286}287
Files main
Menu

Theme