Cotton code
322 lines · 13.3 KB · SwiftRaw
// The one viewer for photos, videos and documents — a paper page like every// other (walker 604bcce6: it was a black system sheet).//// When somebody opens a picture, a film or a document, they mean to see it,// play it, read it: the media stands on the page's plaster ground, the head// row is a page's (the place in the set, the hand, the X at the right) and// hides on a tap, and what the engine knows about it is the record's card// behind the hand, never first. Every line it says is the// media definition's. It opens in place, by the zoom from the tile it was// tapped on, and while it is up the page beneath leaves the accessibility// tree (`ViewerHost`, a sheet's anchor).//// A swipe sideways walks the set it was opened from; a swipe down puts it// back, from any state (a zoomed picture first zooms out — a downward drag// on a magnified picture is a pan). The next and the previous picture are// decoded at screen size before they are reached, so the swipe never waits on// a decode.import CottonKitimport SwiftUIstruct MediaViewer: View {    let media: ViewerSet    @Binding var showing: String?    let onClose: () -> Void    @Environment(\.theme) private var theme    @Environment(\.tableDefinitions) private var definitions    @Environment(\.cottonCore) private var core    @Environment(\.accessibilityReduceMotion) private var reduceMotion    /// The item the pager stands on, by id.    @State private var position: String?    @State private var chromeShown = true    /// A chat photo's words show once, until the first tap.    @State private var captionShown = true    /// The picture on screen is magnified: the pager and the dismissal wait.    @State private var zoomed = false    /// Where the head ends on screen, measured once it is drawn: a document    /// starts below it, as every paper page's content does.    @State private var headHeight: CGFloat = 0    /// How tall the foot (the hand at the bottom right) stands above the    /// bottom edge: a kind's bottom strip starts above it.    @State private var footHeight: CGFloat = 0    /// The item whose details (its record's card) are raised.    @State private var details: ViewerItem?    /// Each item's file on this device, once its page has it: what Share hands on.    @State private var files: [String: URL] = [:]    /// A loaded web page owns its canvas, including the head above it.    @State private var pageGrounds: [String: ThemeColor] = [:]    private var words: ViewerWords? { ViewerWords.reading(definitions) }    private var index: Int { media.items.firstIndex { $0.id == position } ?? media.start }    private var item: ViewerItem? { media.items.indices.contains(index) ? media.items[index] : nil }    private var pageGround: ThemeColor? { item.flatMap { pageGrounds[$0.id] } }    var body: some View {        ZStack {            if let pageGround {                pageGround.color.ignoresSafeArea()            } else {                PageGroundFill().ignoresSafeArea()            }            pager            if chromeShown { chrome.transition(.opacity) }        }        .cottonPageGround(.groundMuted)        .cottonPageTexture(.plaster)        .environment(\.viewerChromeShown, chromeShown)        .environment(\.viewerHeadHeight, headHeight)        .environment(\.viewerFootHeight, chromeShown && item?.record != nil ? footHeight : 0)        #if os(iOS)        .statusBarHidden(!chromeShown)        .preferredColorScheme(pageGround.map { ViewerWebGround.isDark($0) ? .dark : .light })        #endif        .animation(reduceMotion ? nil : .easeOut(duration: ViewerKnobs.chromeFade), value: chromeShown)        .interactiveDismissDisabled(zoomed)        .onAppear { position = media.items[media.start].id }        .onChange(of: position) { _, now in            showing = now            zoomed = false            ViewerPreparer.prepare(around: index, in: media.items, core: core)        }        #if os(iOS)        .overlay(alignment: .bottom) {            if let record = details?.record {                ViewerDetails(record: record, onClose: { details = nil })            }        }        #endif        .cottonCard(item: Binding(            get: { details?.record == nil ? details : nil },            set: { details = $0 }), detents: [.half]) { one in                ViewerFacts(item: one)        }        .deckWriting()    }    // MARK: - The pager    private var pager: some View {        ScrollView(.horizontal) {            LazyHStack(spacing: 0) {                ForEach(media.items) { one in                    page(one)                        .containerRelativeFrame([.horizontal, .vertical])                        .id(one.id)                }            }            .scrollTargetLayout()        }        .scrollTargetBehavior(.paging)        .scrollPosition(id: $position)        .scrollIndicators(.hidden)        .scrollDisabled(zoomed || media.items.count < 2)        // A document owns vertical drags: scrolling it must never raise a        // record card. Pictures and films retain the swipe-up shortcut.        .simultaneousGesture(DragGesture(minimumDistance: ViewerKnobs.control).onEnded { drag in            guard let item, item.record != nil,                ViewerDetailsGesture.opens(kind: item.kind, zoomed: zoomed, translation: drag.translation)            else { return }            details = item        })        .ignoresSafeArea()        .sensoryFeedback(.selection, trigger: position)        .accessibilityIdentifier("viewer-pager")    }    @ViewBuilder private func page(_ one: ViewerItem) -> some View {        let current = one.id == position        Group {            if !one.hasBytes && one.kind != .video {                ViewerAbsentPage(item: one, words: words)            } else {                switch one.kind {                case .photo:                    ViewerPhotoPage(                        item: one, current: current, pins: media.pins, words: words,                        zoomed: current ? $zoomed : .constant(false), onTap: toggleChrome,                        onFile: { files[one.id] = $0 })                case .video:                    ViewerPlayerPage(item: one, current: current, words: words, onTap: toggleChrome, onFile: { files[one.id] = $0 })                case .document:                    ViewerDocumentPage(item: one, current: current, words: words, onTap: toggleChrome,                                       onFile: { files[one.id] = $0 }, onPageGround: { pageGrounds[one.id] = $0 })                }            }        }    }    private func toggleChrome() {        captionShown = false        chromeShown.toggle()    }    // MARK: - The chrome    private var chrome: some View {        VStack(spacing: 0) {            ViewerChrome(                item: item, index: index, count: media.items.count, file: item.flatMap { files[$0.id] },                words: words, onClose: onClose,                onDetails: { details = $0 })                .environment(\.viewerHeadInk, pageGround.map { ViewerWebGround.ink(on: $0, theme: theme).color })                .onGeometryChange(for: CGFloat.self) { $0.frame(in: .global).maxY } action: { headHeight = $0 }            Spacer(minLength: 0)            if captionShown, let caption = item?.caption, !caption.isEmpty {                Text(caption)                    .font(theme.type.interface(ViewerKnobs.captionSize))                    .foregroundStyle(theme.colors.ink.color)                    .frame(maxWidth: .infinity, alignment: .leading)                    .padding(ViewerKnobs.chromeInset)                    .background(theme.colors.groundElevated.color.ignoresSafeArea(edges: .bottom))                    .accessibilityIdentifier("viewer-caption")            }            if let item, item.record != nil {                ViewerFoot { details = item }                    .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { footHeight = $0 }            }        }    }}enum ViewerDetailsGesture {    static func opens(kind: ViewerItem.Kind, zoomed: Bool, translation: CGSize) -> Bool {        kind != .document && !zoomed && -translation.height > ViewerKnobs.pullToClose            && abs(translation.height) > abs(translation.width)    }}/// Whether the viewer's chrome is up: a player's controls and a document's/// strip come and go with it.private struct ViewerChromeShownKey: EnvironmentKey {    static let defaultValue = true}extension EnvironmentValues {    /// Where the viewer's head ends, from the top of the screen.    @Entry var viewerHeadHeight: CGFloat = 0    /// How tall the viewer's foot stands above the bottom edge: a kind's    /// bottom strip pads by it so the hand never covers a control.    @Entry var viewerFootHeight: CGFloat = 0    var viewerChromeShown: Bool {        get { self[ViewerChromeShownKey.self] }        set { self[ViewerChromeShownKey.self] = newValue }    }}// MARK: - Pieces of chrome/// A bare glyph control on one of the viewer's paper strips (a player's, the document search).struct ViewerButton: View {    let symbol: String    let label: String    let identifier: String    let action: () -> Void    var body: some View {        Button(action: action) { ViewerGlyph(symbol: symbol) }            .buttonStyle(.plain)            .accessibilityLabel(label)            .accessibilityIdentifier(identifier)    }}struct ViewerGlyph: View {    let symbol: String    @Environment(\.theme) private var theme    var body: some View {        Image(systemName: symbol)            .font(theme.type.interface(ViewerKnobs.glyphSize, weight: .semibold))            .foregroundStyle(theme.colors.ink.color)            .frame(width: ViewerKnobs.control, height: ViewerKnobs.control)            .contentShape(Rectangle())    }}/// An item whose bytes are not named, or whose record was removed: the slip/// over its dimmed preview. Nothing here can fetch it.struct ViewerAbsentPage: View {    let item: ViewerItem    let words: ViewerWords?    var body: some View {        AbsentOverPoster(slip: AbsentSlip(            kind: item.kind == .document ? .document : .photo, name: item.title, words: words, removed: item.missing)        ) {            if let blur = PhotosBlur.image(base64: item.preview) {                Image(uiImage: blur).resizable().scaledToFit().blur(radius: ViewerKnobs.blurRadius)            }        }        .padding(ViewerKnobs.chromeInset)    }}#if os(iOS)/// The same acts surface as the deck, over the media it acts on.struct ViewerDetails: View {    let record: ViewerRecord    let onClose: () -> Void    @Environment(\.tableDefinitions) private var definitions    @Environment(\.records) private var store    @Environment(\.cottonCore) private var core    @Environment(\.theme) private var theme    private var editor: DeckEditor { .session }    var body: some View {        let fan = FanGeometry(scale: theme.scale)        ZStack(alignment: .bottom) {            Color.black.opacity(0.2).ignoresSafeArea()                .onTapGesture { editor.close(); onClose() }            // The editor deals the acts onto its tier path; the viewer covers            // the fan that path stands on, so it draws the open tier itself.            EditingFan(editor: editor, fan: fan)            if let open = editor.navigation.open, open.editorState != nil {                FanTierArc(tier: open, geometry: fan, tiers: editor.navigation)                    .id(open.id)                    .padding(.bottom, ViewerKnobs.chromeInset)            }        }        .task(id: record.id) {            guard let definition = definitions.all.first(where: { $0.id == record.table }),                  let row = try? await store?.get(table: record.table, id: record.id) else { return }            editor.openActs(DeckEditTarget(table: record.table, record: record.id,                                          date: definition.whenColumn), record: row, core: core)        }        .onChange(of: editor.isEditing) { _, editing in if !editing { onClose() } }        .onDisappear { editor.close() }    }}#endif/// The sizes and timings the viewer draws with: Swift's own, beside their/// reader — a theme sets only its tokens.enum ViewerKnobs {    static let chromeFade: Double = 0.2    static let chromeGap: CGFloat = 12    static let chromeInset: CGFloat = 16    static let chromeVertical: CGFloat = 6    static let control: CGFloat = 44    static let glyphSize: CGFloat = 17    static let positionSize: CGFloat = 15    static let captionSize: CGFloat = 16    static let titleSize: CGFloat = 20    /// The place in the set ("3 of 12") stands in the head at this share of a head title's size.    static let placeScale: CGFloat = 0.6    static let blurRadius: CGFloat = 8    static let quiet: Double = 0.7    /// The picture's zoom: never past 6, where a phone-sized picture stops    /// carrying detail; a double tap goes to 2.5.    static let maxZoom: CGFloat = 6    static let doubleTapZoom: CGFloat = 2.5    static let pinMark: CGFloat = 24    static let stripHeight: CGFloat = 64    /// How far past a document's first page a pull goes before it closes the viewer.    static let pullToClose: CGFloat = 90    /// A found word sits this far (in the page's points) below the top bar, with a line of context above it.    static let matchLead: CGFloat = 24    static let thumbnails = 12}