SPB Git

Repository Public License

LibraryScreen.swift 19.0 KB 404 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : App/Sources/Features/Library/LibraryScreen.swift10// Description      : The app-owned media library: adaptive grid, filters,11//                    search, sorting, selection, albums and duplicates.12// Module           : Features13// Repository       : https://git.spboucher.ai/orix-camera14// Project Website  : https://www.orixlab.dev15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import ORIXDesign92import ORIXImaging93import SwiftUI9495struct LibraryScreen: View {96    let library: MediaLibrary97    let camera: CameraModel98    @Environment(\.dismiss) private var dismiss99    @State private var model: LibraryModel?100101    var body: some View {102        Group {103            if let model { LibraryContent(model: model, camera: camera, close: { dismiss() }) } else { Color.clear }104        }105        .onAppear { if model == nil { model = LibraryModel(library: library) } }106        .environment(\.orixAccent, .camera)107        .tint(ORIXAccent.camera.primary)108        .systemAppearance()109    }110}111112private struct LibraryContent: View {113    @Bindable var model: LibraryModel114    let camera: CameraModel115    let close: () -> Void116117    @State private var viewerID: UUID?118    @State private var showAlbums = false119    @State private var showDuplicates = false120    @State private var albumPickerItems: [MediaItem] = []121    @State private var showAlbumPicker = false122    @State private var exportItems: [ItemSnapshot]?123    @State private var pendingDelete: [MediaItem] = []124    @State private var confirmDelete = false125    @State private var confirmForget = false126    @State private var didRunDebug = false127128    private let columns = [GridItem(.adaptive(minimum: 108, maximum: 190), spacing: 3)]129130    var body: some View {131        NavigationStack {132            ScrollView {133                VStack(alignment: .leading, spacing: ORIX.Space.sm) {134                    filterChips135                    if !model.missing.isEmpty { missingNotice }136                    if model.items.isEmpty { emptyState } else { grid; footer }137                }138            }139            .background(ORIX.Palette.canvas)140            .navigationTitle(model.album.map { Text($0.name) } ?? Text("Library"))141            .navigationBarTitleDisplayMode(.inline)142            .searchable(text: $model.search, prompt: Text("Lens, ISO, kind, file name"))143            .toolbar { toolbar }144            .safeAreaInset(edge: .bottom) { if model.isSelecting { selectionBar } }145            .navigationDestination(item: $viewerID) { id in146                ViewerScreen(model: model, camera: camera, startID: id)147            }148            .sheet(isPresented: $showAlbums) { AlbumsView(model: model) }149            .sheet(isPresented: $showDuplicates) { DuplicatesView(model: model) }150            .sheet(isPresented: $showAlbumPicker) {151                AlbumPicker(model: model, items: albumPickerItems) { model.isSelecting = false }152            }153            .sheet(item: Binding(get: { exportItems.map(ExportRequest.init) }, set: { if $0 == nil { exportItems = nil } })) { request in154                ExportSheet(items: request.items, storage: model.library.storage, defaultStripLocation: camera.settings.stripLocationOnExport)155            }156            .confirmationDialog(deleteTitle, isPresented: $confirmDelete, titleVisibility: .visible) {157                Button("Delete from this device", role: .destructive) { model.delete(pendingDelete); pendingDelete = []; if model.selection.isEmpty { model.isSelecting = false } }158                Button("Cancel", role: .cancel) { pendingDelete = [] }159            } message: {160                Text("The files are removed from ORIX Camera on this device. Copies you saved to Photos or exported elsewhere are not affected. This cannot be undone.")161            }162            .confirmationDialog(Text("Remove entries without files?"), isPresented: $confirmForget, titleVisibility: .visible) {163                Button("Remove \(model.missing.count) entries", role: .destructive) { model.forgetMissing() }164                Button("Cancel", role: .cancel) {}165            } message: {166                Text("Their files are no longer on this device. Removing the entries only cleans the list.")167            }168            .onAppear { model.reload(); runDebugHook() }169        }170    }171172    private var deleteTitle: Text {173        pendingDelete.count == 1 ? Text("Delete this item?") : Text("Delete \(pendingDelete.count) items?")174    }175176    private func runDebugHook() {177        guard !didRunDebug else { return }178        didRunDebug = true179        if DebugHooks.openEditor || ["viewer", "metadata", "export"].contains(LibraryDebug.show ?? "") { viewerID = model.items.first?.id }180        if LibraryDebug.show == "albums" { showAlbums = true }181        if LibraryDebug.show == "duplicates" { showDuplicates = true }182    }183184    // MARK: Pieces185186    private var filterChips: some View {187        ScrollView(.horizontal, showsIndicators: false) {188            HStack(spacing: ORIX.Space.xs) {189                ForEach(MediaFilter.allCases, id: \.self) { filter in190                    Button { model.filter = filter } label: {191                        Text(LibraryModel.title(filter))192                            .font(.orixCaption)193                            .foregroundStyle(model.filter == filter ? ORIX.Palette.onAccent : ORIX.Palette.textPrimary)194                            .padding(.horizontal, ORIX.Space.sm)195                            .frame(minHeight: 34)196                            .background(model.filter == filter ? AnyShapeStyle(ORIXAccent.camera.primary) : AnyShapeStyle(ORIX.Palette.surface), in: Capsule())197                            .overlay(Capsule().strokeBorder(ORIX.Palette.hairline.opacity(model.filter == filter ? 0 : 1), lineWidth: 0.5))198                            .frame(minHeight: ORIX.minimumTarget)199                    }200                    .buttonStyle(.plain)201                    .accessibilityIdentifier("library.filter.\(filter.rawValue)")202                    .accessibilityAddTraits(model.filter == filter ? .isSelected : [])203                }204            }205            .padding(.horizontal, ORIX.Space.md)206        }207    }208209    private var missingNotice: some View {210        ORIXBanner(.warning, title: Text("\(model.missing.count) items have no file"), message: Text("Their files are no longer on this device.")) {211            Button("Review") { confirmForget = true }.font(.orixCaption)212        }213        .padding(.horizontal, ORIX.Space.md)214        .accessibilityIdentifier("library.missing")215    }216217    private var grid: some View {218        LazyVGrid(columns: columns, spacing: 3) {219            ForEach(Array(model.items.enumerated()), id: \.element.id) { index, item in220                let snapshot = model.snapshot(item)221                Button {222                    if model.isSelecting { model.toggleSelection(item) } else { viewerID = item.id }223                } label: {224                    MediaTile(item: snapshot, isFavorite: item.isFavorite, isSelecting: model.isSelecting, isSelected: model.selection.contains(item.id))225                }226                .buttonStyle(.plain)227                .accessibilityIdentifier("library.item.\(index)")228                .contextMenu {229                    Button { model.toggleFavorite(item) } label: { Label(item.isFavorite ? "Remove from Favorites" : "Add to Favorites", systemImage: item.isFavorite ? "heart.slash" : "heart") }230                    Button { albumPickerItems = [item]; showAlbumPicker = true } label: { Label("Add to Album", systemImage: "rectangle.stack.badge.plus") }231                    if let album = model.album {232                        Button { model.remove([item], from: album) } label: { Label("Remove from This Album", systemImage: "rectangle.stack.badge.minus") }233                    }234                    Button { exportItems = [snapshot] } label: { Label("Export", systemImage: "square.and.arrow.up") }235                    Button(role: .destructive) { pendingDelete = [item]; confirmDelete = true } label: { Label("Delete", systemImage: "trash") }236                }237            }238        }239        .padding(.horizontal, 3)240        .accessibilityIdentifier("library.grid")241    }242243    private var footer: some View {244        Text("\(model.items.count) shown · \(model.totalCount) items · \(MediaFormat.bytes(model.totalBytes)) in the library")245            .font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)246            .frame(maxWidth: .infinity).padding(.vertical, ORIX.Space.md)247            .accessibilityIdentifier("library.footer")248    }249250    @ViewBuilder private var emptyState: some View {251        if model.totalCount == 0 {252            ORIXEmptyState(systemName: "camera.aperture", title: "No captures yet", message: "Photos and videos you take with ORIX Camera appear here. They stay on this device.") {253                Button("Open the camera", action: close).buttonStyle(.orixPrimary)254            }255            .padding(.top, 60)256        } else {257            ORIXEmptyState(systemName: "magnifyingglass", title: "Nothing matches", message: "Try another filter or search term.") {258                Button("Show everything") { model.filter = .all; model.search = "" }.buttonStyle(.orixSecondary)259            }260            .padding(.top, 60)261        }262    }263264    @ToolbarContentBuilder private var toolbar: some ToolbarContent {265        ToolbarItem(placement: .topBarLeading) {266            if model.isSelecting {267                Button("Select All") { model.selectAll() }268            } else if model.album != nil {269                Button { model.album = nil } label: { Label("All Items", systemImage: "chevron.backward") }270            } else {271                Button(action: close) { Label("Camera", systemImage: "camera.fill").labelStyle(.titleAndIcon) }272                    .accessibilityIdentifier("library.close")273            }274        }275        ToolbarItemGroup(placement: .topBarTrailing) {276            Button(model.isSelecting ? "Done" : "Select") { model.isSelecting.toggle() }277                .disabled(model.items.isEmpty && !model.isSelecting)278                .accessibilityIdentifier("library.select")279            Menu {280                Picker("Sort", selection: $model.sort) {281                    ForEach(MediaSort.allCases, id: \.self) { Text(LibraryModel.title($0)).tag($0) }282                }283                Button { showAlbums = true } label: { Label("Albums", systemImage: "rectangle.stack") }284                Button { showDuplicates = true } label: { Label("Find Duplicates", systemImage: "square.on.square") }285            } label: {286                Label("More", systemImage: "ellipsis.circle")287            }288            .accessibilityIdentifier("library.more")289            Button { showAlbums = true } label: { Label("Albums", systemImage: "rectangle.stack") }290                .accessibilityIdentifier("library.albums")291        }292    }293294    private var selectionBar: some View {295        let chosen = model.selectedItems296        return HStack {297            barButton("Export", "square.and.arrow.up", id: "library.selection.export") { exportItems = chosen.map(model.snapshot) }298            Spacer()299            barButton("Album", "rectangle.stack.badge.plus", id: "library.selection.album") { albumPickerItems = chosen; showAlbumPicker = true }300            Spacer()301            Text("\(chosen.count) selected").font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary).accessibilityIdentifier("library.selection.count")302            Spacer()303            barButton("Favorite", "heart", id: "library.selection.favorite") { model.toggleFavoriteForSelection() }304            Spacer()305            barButton("Delete", "trash", id: "library.selection.delete", role: .destructive) { pendingDelete = chosen; confirmDelete = true }306        }307        .disabled(chosen.isEmpty)308        .padding(.horizontal, ORIX.Space.lg)309        .padding(.vertical, ORIX.Space.xs)310        .background(.bar)311    }312313    private func barButton(_ title: LocalizedStringKey, _ symbol: String, id: String, role: ButtonRole? = nil, action: @escaping () -> Void) -> some View {314        Button(role: role, action: action) {315            Image(systemName: symbol).font(.title3).frame(minWidth: ORIX.minimumTarget, minHeight: ORIX.minimumTarget)316        }317        .accessibilityLabel(Text(title))318        .accessibilityIdentifier(id)319    }320}321322struct ExportRequest: Identifiable {323    let id = UUID()324    let items: [ItemSnapshot]325}326327/// One square tile of the grid.328struct MediaTile: View {329    let item: ItemSnapshot330    let isFavorite: Bool331    var isSelecting = false332    var isSelected = false333    @State private var image: UIImage?334335    var body: some View {336        Color.clear337            .aspectRatio(1, contentMode: .fit)338            .overlay {339                if let image {340                    Image(uiImage: image).resizable().scaledToFill()341                } else {342                    ORIX.Palette.surfaceRaised.overlay(Image(systemName: item.isVideo ? "video" : "photo").foregroundStyle(ORIX.Palette.textTertiary))343                }344            }345            .clipped()346            .overlay(alignment: .topLeading) { badges.padding(5) }347            .overlay(alignment: .bottomLeading) {348                if item.isVideo {349                    Label(ExposureMath.timecode(item.duration), systemImage: "video.fill")350                        .font(.system(.caption2, design: .rounded, weight: .bold).monospacedDigit())351                        .foregroundStyle(.white).padding(.horizontal, 6).padding(.vertical, 3)352                        .background(.black.opacity(0.55), in: Capsule()).padding(5)353                }354            }355            .overlay(alignment: .bottomTrailing) {356                HStack(spacing: 4) {357                    if item.recipe != nil { Image(systemName: "slider.horizontal.3") }358                    if isFavorite { Image(systemName: "heart.fill") }359                }360                .font(.caption2.weight(.bold)).foregroundStyle(.white).shadow(color: .black.opacity(0.6), radius: 2).padding(6)361            }362            .overlay {363                if isSelecting {364                    ZStack(alignment: .topTrailing) {365                        Color.black.opacity(isSelected ? 0.28 : 0)366                        Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")367                            .font(.title3).symbolRenderingMode(.palette)368                            .foregroundStyle(.white, isSelected ? ORIXAccent.camera.primary : .clear)369                            .shadow(color: .black.opacity(0.5), radius: 2).padding(6)370                    }371                }372            }373            .contentShape(Rectangle())374            .task(id: ThumbnailCache.key(item)) {375                image = ThumbnailCache.shared.cached(item) ?? image376                image = await ThumbnailCache.shared.image(for: item) ?? image377            }378            .accessibilityElement()379            .accessibilityLabel(Text(accessibilityText))380            .accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton)381    }382383    private var badges: some View {384        HStack(spacing: 3) {385            if let badge = MediaFormat.badge(item.kind) { tag(badge) }386            if item.isSynthetic { tag(String(localized: "SIM")) }387        }388    }389390    private func tag(_ text: String) -> some View {391        Text(text).font(.system(size: 9, weight: .heavy, design: .rounded)).foregroundStyle(.white)392            .padding(.horizontal, 5).padding(.vertical, 2).background(.black.opacity(0.6), in: Capsule())393    }394395    private var accessibilityText: String {396        var parts = [MediaFormat.kindTitle(item.kind), item.createdAt.formatted(date: .abbreviated, time: .shortened)]397        if item.isVideo { parts.append(ExposureMath.timecode(item.duration)) }398        if item.recipe != nil { parts.append(String(localized: "Edited")) }399        if isFavorite { parts.append(String(localized: "Favorite")) }400        if item.isSynthetic { parts.append(String(localized: "Synthetic test scene")) }401        return parts.joined(separator: ", ")402    }403}404
Files main
Menu

Theme