Cotton code
447 lines · 20.0 KB · SwiftRaw
// ALBUMS' SCREENS (assets/design/albums/albums.html; DECISIONS "The screens"): first run with its faces line and// switch, no permission, the pass's honest lines, Albums with Photos' own albums and All photos, an album by day, All// photos by month, one photo large, and the sheets. Tidy, a Set, the lists and the Bin are in `AlbumsTidy.swift`;// People in `AlbumsPeople.swift`; You in `AlbumsYou.swift`. Every word, count and size is the core's answer.#if os(iOS)import CottonKitimport SwiftUI// MARK: - First runstruct AlbumsFirstRun: View {    let model: AlbumsModel    let words: AlbumsStart.FirstRun    @State private var asking = false    @State private var faces = true    var body: some View {        VStack(alignment: .leading, spacing: 0) {            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    AlbumsCornerMark(size: 62).padding(.top, 40)                    AlbumsTitle(text: words.title).padding(.top, 26)                    Text(verbatim: words.lead).font(AlbumsType.lead).foregroundStyle(Olive.quiet)                        .fixedSize(horizontal: false, vertical: true).padding(.top, 12)                    Text(verbatim: words.promise).font(AlbumsType.body).foregroundStyle(Olive.ink)                        .fixedSize(horizontal: false, vertical: true).padding(.top, 16)                    if let f = words.faces {                        Toggle(isOn: $faces) {                            VStack(alignment: .leading, spacing: 3) {                                Text(verbatim: f.label).font(AlbumsType.name).foregroundStyle(Olive.ink)                                Text(verbatim: f.line).font(AlbumsType.line).foregroundStyle(Olive.quiet).fixedSize(horizontal: false, vertical: true)                            }                        }                        .tint(Olive.accent)                        .padding(.vertical, 12)                        .overlay(alignment: .bottom) { AlbumsRule() }                        .padding(.top, 20)                        .accessibilityIdentifier("albums-first-faces")                        .onAppear { faces = f.on }                    }                    AlbumsBand(head: words.nextHead, lines: [words.nextLine]).padding(.top, 24)                }                .padding(.horizontal, Olive.side)            }            .scrollIndicators(.hidden)            Button(words.start) {                asking = true                Task {                    if faces != (words.faces?.on ?? true) { await model.setFaces(faces) }                    await model.start()                    asking = false                }            }            .buttonStyle(AlbumsMainButtonStyle())            .disabled(asking)            .padding(.horizontal, Olive.side).padding(.top, 12).padding(.bottom, 16)            .accessibilityIdentifier("albums-start")        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("albums-first-run")    }}/// No permission: what Albums cannot do, and Settings.struct AlbumsNoPermission: View {    let model: AlbumsModel    let words: AlbumsStart.NoPermission    @Environment(\.openURL) private var openURL    var body: some View {        VStack(alignment: .leading, spacing: 0) {            AlbumsCornerMark(size: 62).padding(.top, 40)            AlbumsTitle(text: words.title).padding(.top, 26)            Text(verbatim: words.line).font(AlbumsType.lead).foregroundStyle(Olive.quiet).fixedSize(horizontal: false, vertical: true).padding(.top, 12)            Spacer()            Button(words.act) { if let url = URL(string: UIApplication.openSettingsURLString) { openURL(url) } }                .buttonStyle(AlbumsMainButtonStyle())                .padding(.bottom, 16)                .accessibilityIdentifier("albums-open-settings")        }        .padding(.horizontal, Olive.side)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("albums-no-permission")    }}// MARK: - The pass's lines/// "Looking through 64,212 photos and videos · 18,400 done · about 35 min left while charging", the thin line, the note;/// paused and why; only in iCloud. Each line is the core's and may be absent.struct AlbumsPassBand: View {    let lines: AlbumsPassLines?    var body: some View {        if let lines {            VStack(alignment: .leading, spacing: 0) {                if lines.head != nil || lines.detail != nil {                    AlbumsBand(head: lines.head, lines: [lines.detail].compactMap { $0 }, end: {                        if lines.paused == true {                            Image(systemName: "powerplug").font(.system(size: 15, weight: .light)).foregroundStyle(Olive.ink).accessibilityHidden(true)                        }                    }, below: {                        VStack(alignment: .leading, spacing: 0) {                            if let fraction = lines.fraction { AlbumsProgressBar(fraction: fraction, paused: lines.paused == true) }                            if let note = lines.note {                                Text(verbatim: note).font(AlbumsType.line).foregroundStyle(Olive.quiet).padding(.top, 10)                            }                        }                    })                }                if let cloud = lines.cloud {                    HStack(alignment: .top, spacing: 14) {                        Image(systemName: "cloud").font(.system(size: 16, weight: .light)).foregroundStyle(Olive.ink).padding(.top, 2).accessibilityHidden(true)                        Text(verbatim: cloud).font(AlbumsType.line).foregroundStyle(Olive.quiet).fixedSize(horizontal: false, vertical: true)                    }                    .padding(.vertical, 12)                    .overlay(alignment: .bottom) { AlbumsRule() }                    .accessibilityElement(children: .combine)                    .accessibilityIdentifier("albums-cloud-line")                }            }            .accessibilityElement(children: .contain)            .accessibilityIdentifier("albums-pass-line")        }    }}// MARK: - Albumsstruct AlbumsListScreen: View {    @Bindable var model: AlbumsModel    @State private var answer: AlbumsHome?    @Environment(\.openURL) private var openURL    var body: some View {        AlbumsPage(tag: "albums-home", pull: read) {            HStack(alignment: .center) {                AlbumsTitle(text: answer?.title ?? AlbumsWords.line("home.title"))                if !AlbumsBook.lookOnly {                    AlbumsRoundButton(symbol: "plus", label: answer?.make ?? "", tag: "albums-make") { model.sheet = .makeAlbum }                }            }            .padding(.top, 8).padding(.bottom, 10)            if let limited = answer?.limited ?? model.opening?.limited {                AlbumsBand(head: nil, lines: [limited.line]) {                    Button(limited.act) { if let url = URL(string: UIApplication.openSettingsURLString) { openURL(url) } }                        .buttonStyle(AlbumsPillStyle()).accessibilityIdentifier("albums-limited-settings")                }            }            AlbumsPassBand(lines: model.linesRead ? model.lines : answer?.progress)            if let answer {                ForEach(answer.rows) { row in                    AlbumsListRow(cover: row.cover, title: row.title, line: row.line, end: row.count, tag: "albums-row-\(row.id)") {                        model.open(.album(id: row.id))                    }                }                if let coming = answer.coming {                    AlbumsHeading(coming.heading)                    VStack(spacing: 0) {                        AlbumsRule()                        ForEach(coming.rows) { row in                            AlbumsListRow(title: row.title, line: row.line, opens: false, dim: true, tag: "albums-\(row.id)")                        }                    }                }                if let photos = answer.fromPhotos {                    AlbumsHeading(photos.heading)                    VStack(spacing: 0) {                        AlbumsRule()                        ForEach(photos.rows) { row in                            AlbumsListRow(symbol: symbol(row), title: row.title, end: row.count, tag: "albums-photos-\(row.id)") {                                model.open(.album(id: row.id))                            }                        }                    }                }                Spacer().frame(height: 18)                AlbumsRule()                AlbumsListRow(symbol: "square.grid.2x2", title: answer.allPhotos.title, end: answer.allPhotos.count, tag: "albums-all") {                    model.open(.allPhotos)                }                if answer.rows.isEmpty, answer.fromPhotos == nil, let empty = answer.empty {                    Text(verbatim: empty).font(AlbumsType.body).foregroundStyle(Olive.quiet).padding(.top, 16)                }            }        }        .task(id: model.changed) { await read() }    }    private func symbol(_ row: AlbumsHome.Row) -> String {        switch row.kind {        case "smart": row.title == AlbumsWords.line("home.favourites") ? "heart" : row.title == AlbumsWords.line("home.screenshots") ? "iphone" : "rectangle.stack"        default: "rectangle.on.rectangle"        }    }    private func read() async {        model.readAlbums()        do { answer = try await model.book.home(system: model.photoAlbums) } catch { model.refused(error) }    }}// MARK: - A photo/// One photo, square, from the phone's own picture (never the network); a video says its length.struct AlbumsTile: View {    let id: String    let side: CGFloat    var duration: String?    @State private var image: UIImage?    @State private var request: Int32?    var body: some View {        ZStack(alignment: .bottomTrailing) {            Olive.well            if let image {                Image(uiImage: image).resizable().scaledToFill().frame(width: side, height: side).clipped()            }            if let duration {                Text(verbatim: duration).font(AlbumsType.mono(11, .caption2, upTo: 13)).foregroundStyle(.white)                    .padding(.horizontal, 4).padding(.vertical, 2)                    .background(Color.black.opacity(0.35))                    .padding(4)            }        }        .frame(width: side, height: side)        .clipped()        .onAppear {            request = AlbumsLibrary.shared.thumbnail(id, side: side) { picture in                Task { @MainActor in if let picture { image = picture } }            }        }        .onDisappear { if let request { AlbumsLibrary.shared.cancel(request) } }        .accessibilityHidden(true)    }}/// Photos by day (or month): each heading with its count, then a grid of four.struct AlbumsDays: View {    let groups: [AlbumsAlbum.Group]    let tap: (String) -> Void    var body: some View {        GeometryReader { geo in            let side = floor((geo.size.width - Olive.side * 2 - 6) / 4)            ScrollView {                LazyVStack(alignment: .leading, spacing: 0, pinnedViews: []) {                    ForEach(groups) { group in                        HStack(alignment: .firstTextBaseline) {                            Text(verbatim: group.heading).font(AlbumsType.heading).foregroundStyle(Olive.ink)                            Spacer()                            if let count = group.count { Text(verbatim: count).font(AlbumsType.heading).foregroundStyle(Olive.quiet) }                        }                        .padding(.top, 18).padding(.bottom, 8)                        .accessibilityElement(children: .combine)                        LazyVGrid(columns: Array(repeating: GridItem(.fixed(side), spacing: 2), count: 4), spacing: 2) {                            ForEach(Array(group.ids.enumerated()), id: \.element) { at, id in                                Button { tap(id) } label: { AlbumsTile(id: id, side: side) }                                    .buttonStyle(.plain)                                    .accessibilityLabel(AlbumsWords.line("spoken.photo_day", ["n": (at + 1).formatted(), "total": group.ids.count.formatted(), "day": group.heading]))                                    .accessibilityIdentifier("albums-photo-\(id)")                            }                        }                    }                }                .padding(.horizontal, Olive.side)                .padding(.bottom, 24)            }            .scrollIndicators(.hidden)        }    }}struct AlbumsScreenView: View {    let model: AlbumsModel    let screen: AlbumsScreen    var body: some View {        switch screen {        case .album(let id): AlbumsAlbumScreen(model: model, id: id)        case .allPhotos: AlbumsAlbumScreen(model: model, id: nil)        case .photo(let id, let back): AlbumsPhotoScreen(model: model, id: id, back: back)        case .sets: AlbumsSetsScreen(model: model)        case .set(let id): AlbumsSetScreen(model: model, id: id)        case .list(let key): AlbumsListPage(model: model, key: key)        case .bin(let back): AlbumsBinScreen(model: model, back: back)        case .looked: AlbumsLookedScreen(model: model)        }    }}/// An album from Photos, or All photos (`id` nil): title, its line, the photos by day or month; ··· for his own.struct AlbumsAlbumScreen: View {    let model: AlbumsModel    let id: String?    @State private var answer: AlbumsAlbum?    /// The one Share sheet (CONTACTS-ANSWERS 10, app albums): a shared album of this name, with people from the Circle.    @State private var sharing = false    var body: some View {        VStack(alignment: .leading, spacing: 0) {            AlbumsBar(back: AlbumsWords.line("home.title"), tap: model.back) {                if let id, let menu = answer?.menu, !AlbumsBook.lookOnly {                    Menu {                        Button(menu.rename) { model.sheet = .rename(id: id, title: answer?.title ?? "") }                        Button(ShellLines.line("share", "open")) { sharing = true }                        Button(menu.delete, role: .destructive) { model.askDelete(id, menu) }                    } label: {                        Image(systemName: "ellipsis").font(.system(size: 17)).foregroundStyle(Olive.ink)                            .frame(width: 40, height: 40).overlay(Circle().stroke(Olive.ink, lineWidth: 1.5)).frame(width: 44, height: 44)                    }                    .accessibilityLabel(menu.rename)                    .accessibilityIdentifier("albums-album-more")                }            }            if let answer {                VStack(alignment: .leading, spacing: 4) {                    AlbumsTitle(text: answer.title)                    if let line = answer.line { Text(verbatim: line).font(AlbumsType.body).foregroundStyle(Olive.quiet) }                }                .padding(.horizontal, Olive.side).padding(.top, 2)                // Keep this album in Cotton (KEEP slice 1): his own albums and Photos' smart ones, never a shared one.                // Only a build that may keep (a Dev build: the first build only looks) draws it.                if AlbumsKeeper.allowed, let id, let album = model.photoAlbums.first(where: { $0.id == id }), album.kind != .shared {                    AlbumsKeepBand(model: model, id: id, title: album.title)                }                if let empty = answer.empty {                    Text(verbatim: empty).font(AlbumsType.body).foregroundStyle(Olive.quiet).padding(.horizontal, Olive.side).padding(.top, 20)                    Spacer()                } else {                    AlbumsDays(groups: answer.groups) { model.open(.photo(id: $0, back: answer.title)) }                }            } else {                Spacer()            }        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier(id == nil ? "albums-all-photos" : "albums-album")        .sheet(isPresented: $sharing) {            let core = model.core            let ids = answer?.groups.flatMap(\.ids) ?? []            ShareSheetView(core: core, app: "albums", thing: .object(["kind": .string("album"), "name": .string(answer?.title ?? "")]), after: { shared in                // The album founded with the people picked gets this album's photos, each re-encoded with no metadata.                let (added, left) = await AlbumsSharedPhotos.add(core: core, thing: shared, ids: ids)                Log.write("albums: shared album filled, \(added) added, \(left) left out")            })        }        .task(id: model.changed) {            do {                if let id { answer = try await model.book.album(id) } else { answer = try await model.book.allPhotos() }            } catch { model.refused(error) }        }    }}/// One photo, large, from what the phone holds.struct AlbumsPhotoScreen: View {    let model: AlbumsModel    let id: String    let back: String    @State private var image: UIImage?    var body: some View {        VStack(spacing: 0) {            AlbumsBar(back: back, tap: model.back)            Spacer()            if let image { Image(uiImage: image).resizable().scaledToFit() }            Spacer()        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("albums-photo")        .onAppear {            _ = AlbumsLibrary.shared.thumbnail(id, side: UIScreen.main.bounds.width * 2) { picture in                Task { @MainActor in if let picture { image = picture } }            }        }    }}// MARK: - Sheets/// A question asked once: the question, its line, the act in the main button, the way out under it.struct AlbumsAskView: View {    let ask: AlbumsAsk    let close: () -> Void    var body: some View {        VStack(alignment: .leading, spacing: 0) {            Text(verbatim: ask.question).font(AlbumsType.sans(25, .bold, .title2)).foregroundStyle(Olive.ink)                .fixedSize(horizontal: false, vertical: true).accessibilityAddTraits(.isHeader)            if let line = ask.line {                Text(verbatim: line).font(AlbumsType.body).foregroundStyle(Olive.ink).fixedSize(horizontal: false, vertical: true).padding(.top, 10)            }            VStack(spacing: 10) {                Button(ask.yes) { close(); ask.act() }.buttonStyle(AlbumsMainButtonStyle()).accessibilityIdentifier("albums-ask-\(ask.tag)-yes")                Button(ask.no, action: close).buttonStyle(AlbumsOutlineButtonStyle(quiet: true)).accessibilityIdentifier("albums-ask-\(ask.tag)-no")            }            .padding(.top, 22)        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("albums-ask-\(ask.tag)")    }}/// A name to give: Make an album, Rename, Who is this.struct AlbumsTitleSheet: View {    let title: String    let yes: String    let start: String    var hint: String?    let tag: String    let close: () -> Void    let done: (String) async -> Void    @State private var text = ""    @FocusState private var focused: Bool    var body: some View {        VStack(alignment: .leading, spacing: 0) {            Text(verbatim: title).font(AlbumsType.sans(25, .bold, .title2)).foregroundStyle(Olive.ink).accessibilityAddTraits(.isHeader)            TextField(hint ?? AlbumsWords.line("album.name"), text: $text)                .font(AlbumsType.lead).foregroundStyle(Olive.ink)                .focused($focused)                .submitLabel(.done)                .padding(.vertical, 12)                .overlay(alignment: .bottom) { Rectangle().fill(Olive.ink).frame(height: 1.5) }                .padding(.top, 16)                .accessibilityIdentifier("albums-\(tag)-field")                .onSubmit { go() }            Button(yes) { go() }                .buttonStyle(AlbumsMainButtonStyle())                .disabled(text.trimmingCharacters(in: .whitespaces).isEmpty)                .padding(.top, 20)                .accessibilityIdentifier("albums-\(tag)-yes")        }        .onAppear { text = start; focused = true }    }    private func go() {        let name = text.trimmingCharacters(in: .whitespaces)        guard !name.isEmpty else { return }        focused = false        close()        Task { await done(name) }    }}#endif