// 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.importCottonKitimportSwiftUIstructMediaViewer: View {let media: ViewerSet @Binding var showing: String?let onClose: () -> Void @Environment(\.theme) privatevar theme @Environment(\.tableDefinitions) privatevar definitions @Environment(\.cottonCore) privatevar core @Environment(\.accessibilityReduceMotion) privatevar reduceMotion/// The item the pager stands on, by id. @State privatevar position: String? @State privatevar chromeShown = true/// A chat photo's words show once, until the first tap. @State privatevar captionShown = true/// The picture on screen is magnified: the pager and the dismissal wait. @State privatevar 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 privatevar 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 privatevar footHeight: CGFloat = 0/// The item whose details (its record's card) are raised. @State privatevar details: ViewerItem?/// Each item's file on this device, once its page has it: what Share hands on. @State privatevar files: [String: URL] = [:]/// A loaded web page owns its canvas, including the head above it. @State privatevar pageGrounds: [String: ThemeColor] = [:]privatevar words: ViewerWords? { ViewerWords.reading(definitions) }privatevar index: Int { media.items.firstIndex { $0.id == position } ?? media.start }privatevar item: ViewerItem? { media.items.indices.contains(index) ? media.items[index] : nil }privatevar pageGround: ThemeColor? { item.flatMap { pageGrounds[$0.id] } }var body: someView { ZStack {iflet pageGround { pageGround.color.ignoresSafeArea() } else {PageGroundFill().ignoresSafeArea() } pagerif 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 = falseViewerPreparer.prepare(around: index, in: media.items, core: core) } #if os(iOS) .overlay(alignment: .bottom) {iflet 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 inViewerFacts(item: one) } .deckWriting() }// MARK: - The pagerprivatevar pager: someView {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 inguardlet 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 privatefunc page(_ one: ViewerItem) -> someView {let current = one.id == positionGroup {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 }) } } } }privatefunc toggleChrome() { captionShown = false chromeShown.toggle() }// MARK: - The chromeprivatevar chrome: someView { 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") }iflet item, item.record != nil {ViewerFoot { details = item } .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { footHeight = $0 } } } }}enumViewerDetailsGesture {staticfunc 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.privatestructViewerChromeShownKey: EnvironmentKey {staticlet defaultValue = true}extensionEnvironmentValues {/// 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 = 0var 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).structViewerButton: View {let symbol: Stringlet label: Stringlet identifier: Stringlet action: () -> Voidvar body: someView {Button(action: action) { ViewerGlyph(symbol: symbol) } .buttonStyle(.plain) .accessibilityLabel(label) .accessibilityIdentifier(identifier) }}structViewerGlyph: View {let symbol: String @Environment(\.theme) privatevar themevar body: someView {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.structViewerAbsentPage: View {let item: ViewerItemlet words: ViewerWords?var body: someView {AbsentOverPoster(slip: AbsentSlip( kind: item.kind == .document ? .document : .photo, name: item.title, words: words, removed: item.missing) ) {iflet 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.structViewerDetails: View {let record: ViewerRecordlet onClose: () -> Void @Environment(\.tableDefinitions) privatevar definitions @Environment(\.records) privatevar store @Environment(\.cottonCore) privatevar core @Environment(\.theme) privatevar themeprivatevar editor: DeckEditor { .session }var body: someView {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)ifletopen = 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) {guardlet 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 inif !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.enumViewerKnobs {staticlet chromeFade: Double = 0.2staticlet chromeGap: CGFloat = 12staticlet chromeInset: CGFloat = 16staticlet chromeVertical: CGFloat = 6staticlet control: CGFloat = 44staticlet glyphSize: CGFloat = 17staticlet positionSize: CGFloat = 15staticlet captionSize: CGFloat = 16staticlet titleSize: CGFloat = 20/// The place in the set ("3 of 12") stands in the head at this share of a head title's size.staticlet placeScale: CGFloat = 0.6staticlet blurRadius: CGFloat = 8staticlet 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.staticlet maxZoom: CGFloat = 6staticlet doubleTapZoom: CGFloat = 2.5staticlet pinMark: CGFloat = 24staticlet stripHeight: CGFloat = 64/// How far past a document's first page a pull goes before it closes the viewer.staticlet 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.staticlet matchLead: CGFloat = 24staticlet thumbnails = 12}