// The cover, the eighth face: a record as a tall tinted card — the title in // the serif at the top and the footer line typed at the foot (the Reader's // paperback cover, `ReaderCover`, fed from a definition). A table whose slip // draws a picture at the right (`trailing_picture`) wears its cover landscape: // the Locations postcard, its words on the left half and the picture on the // right. // // An unread record (the definition's `opened` column empty) wears the red ink // dot in the cover's top corner, and is read aloud as unread. // // The cover's paper is the record's tint (`FaceTint`), never a meaning: the // Reader's dye by site is not carried. // // A cover the definition binds (`cover.bound`) is a script: the pages under // it just showing at the right and the foot, and two brads in pencil down its // left edge, the words kept clear of them. // // `TrailingPicture` is the picture itself, drawn once for the slip and the // postcard: a place's map from its coordinates, or a photo or file's image. import CottonKit import CottonValues import PDFKit import SwiftUI public struct CoverFace: View { @Environment(\.theme) private var theme private let definition: TableDefinition private let record: TableRecord private let width: CGFloat? @Environment(\.linkTitles) private var links /// - Parameter width: the cover's width when its size is decided outside /// it (a tile); nil takes the width it is offered. public init(definition: TableDefinition, record: TableRecord, width: CGFloat? = nil) { self.definition = definition self.record = record self.width = width } /// Covers across in a list's grid: three paperbacks, or one postcard. public static func columns(_ definition: TableDefinition) -> Int { isPostcard(definition) ? 1 : 3 } static func isPostcard(_ definition: TableDefinition) -> Bool { definition.slip.trailingPicture != nil } private var title: String { record.said?.slip.title ?? "" } private var footerParts: [String]? { record.said?.slip.cover_footer } private var footer: String? { footerParts?.joined(separator: " \u{00B7} ") } private var titleInk: PaperInk { let key = RecordValue.isBlank(record[definition.slip.title]) ? definition.slip.titleFallback ?? definition.title : definition.slip.title return record.ink(key) } private var footerInk: PaperInk { let keys = definition.cover?.footer ?? [definition.slip.subtitle].compactMap { $0 } return keys.contains { record.ink($0) == .red } ? .red : .pencil } public var body: some View { Group { if Self.isPostcard(definition) { postcard } else if definition.cover?.bound == true { BoundPages(seed: record.id) { paperback } // Room for the pages under it, so neighbours do not overlap them. .padding(.trailing, CoverFaceKnobs.faceCoverBoundRoomTrailing) .padding(.bottom, CoverFaceKnobs.faceCoverBoundRoomBottom) } else { paperback } } .frame(width: width) .overlay(alignment: .topTrailing) { if record.said?.slip.unread == true { UnreadDot().padding(CoverFaceKnobs.faceCoverUnreadPadding) } } .accessibilityElement(children: .combine) .accessibilityLabel(record.said?.slip.unread == true ? ShellLines.line("faces", "cover.unread_title", ["title": title]) : title) } // ── The paperback ─────────────────────────────────────────────────────── /// The title shrinks with a cover drawn small (a tile's), up to the /// Reader's 15.5 at a list's width. private var titleSize: CGFloat { let scale = theme.scale return width.map { min(CoverFaceKnobs.faceCoverTitleSize, max(CoverFaceKnobs.faceCoverTitleMinSize, $0 * CoverFaceKnobs.faceCoverTitleWidthFraction)) } ?? CoverFaceKnobs.faceCoverTitleSize } private var wholeWordTitle: some View { CoverTitle(title: title, size: titleSize, ink: titleInk) } /// The record's file, when its table keeps one (a document's scan): its /// first page is the cover's picture. private var fileRef: String? { definition.columns.first { $0.type == .file }.flatMap { AttachmentValue.read(record[$0.key])?.ref } } private var paperback: some View { Paper(dye: FaceTint.dye(for: record.id), edge: .cut, seed: record.id, tilt: false, inset: 0, fills: true) { VStack(alignment: .leading, spacing: 0) { if let fileRef { FirstPageThumbnail(ref: fileRef) .padding(.bottom, CoverFaceKnobs.faceCoverFooterGap) } wholeWordTitle Spacer(minLength: CoverFaceKnobs.faceCoverFooterGap) if let parts = footerParts { // Caption size, one line, never shrunk: a footer too long // for the cover gives up whole parts from its end, never // half a word (walker 604bcce6: a 5 pt cut footer). ViewThatFits(in: .horizontal) { ForEach((1...parts.count).reversed(), id: \.self) { count in Text(parts.prefix(count).joined(separator: " \u{00B7} ")) .paperMeta(theme.scale.metaSize, ink: footerInk) .lineLimit(1) .fixedSize() } // A first part wider than the cover: cut at its end, // inside the cover, never running past its edge. Text(parts[0]) .paperMeta(theme.scale.metaSize, ink: footerInk) .lineLimit(1) } } } // Clear of the brads on a bound script. .padding(.leading, definition.cover?.bound == true ? CoverFaceKnobs.faceCoverBoundLeadingPadding : CoverFaceKnobs.faceCoverLeadingPadding) .padding(.trailing, CoverFaceKnobs.faceCoverTrailingPadding) .padding(.vertical, CoverFaceKnobs.faceCoverVerticalPadding) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) // The spine: a book's fold, a shade darker down the left edge. .overlay(alignment: .leading) { LinearGradient( colors: [theme.print(.ink).opacity(CoverFaceKnobs.faceCoverGradientOpacity), theme.print(.ink).opacity(0)], startPoint: .leading, endPoint: .trailing ) .frame(width: CoverFaceKnobs.faceCoverSpineWidth) .accessibilityHidden(true) } } .aspectRatio(CoverFaceKnobs.faceCoverPaperbackAspect, contentMode: .fit) } // ── The postcard ──────────────────────────────────────────────────────── /// The words on the left; the picture on the right half when the record /// has one, else the words take the whole card rather than sit by a blank. private var postcard: some View { Paper(dye: FaceTint.dye(for: record.id), edge: .cut, seed: record.id, inset: CoverFaceKnobs.faceCoverPostcardInset, fills: true) { HStack(alignment: .center, spacing: CoverFaceKnobs.faceCoverPostcardPictureGap) { VStack(alignment: .leading, spacing: CoverFaceKnobs.faceCoverPostcardWordsGap) { Text(title) .paperTitle(theme.scale.titleSize + 6) .lineLimit(CoverFaceKnobs.faceCoverPostcardTitleLineLimit) .multilineTextAlignment(.leading) .layoutPriority(1) if let footer { Text(footer) .paperBody(theme.scale.bodySize - 1.5) .lineSpacing(CoverFaceKnobs.faceCoverPostcardFooterLineSpacing) .lineLimit(CoverFaceKnobs.faceCoverPostcardFooterLineLimit) .multilineTextAlignment(.leading) } } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) .padding(.leading, CoverFaceKnobs.faceCoverPostcardLeadingPadding) if TrailingPicture.has(definition, record) { TrailingPicture(definition: definition, record: record) .clipShape(PaperShape(edge: .cut, seed: record.id + "-picture", theme: theme)) .frame(maxWidth: .infinity, maxHeight: .infinity) } } } .aspectRatio(CoverFaceKnobs.faceCoverPostcardAspect, contentMode: .fit) } } /// The picture a slip's `trailing_picture` names — or a page section's /// `picture`: a place's map for a latitude paired with its longitude, the /// image for a photo or a file, and nothing for a record that has none. public struct TrailingPicture: View { private let definition: TableDefinition private let record: TableRecord private let key: String? public init(definition: TableDefinition, record: TableRecord) { self.definition = definition self.record = record self.key = definition.slip.trailingPicture } /// Whether the record has a picture to draw in the slip's trailing place. public static func has(_ definition: TableDefinition, _ record: TableRecord) -> Bool { record.said?.slip.pin != nil || imageKey(definition, record, at: definition.slip.trailingPicture) != nil } /// The media key of a photo or file picture. static func imageKey(_ definition: TableDefinition, _ record: TableRecord, at key: String?) -> String? { guard let column = definition.column(key), column.type == .photo || column.type == .file else { return nil } return record[column.key].text } public var body: some View { if let pin = record.said?.slip.pin { MapPicture(lat: pin.lat, lng: pin.lng) } else if let image = Self.imageKey(definition, record, at: key) { GeometryReader { geo in RecordPicture(avatarKey: image, edge: max(geo.size.width, geo.size.height)) .frame(width: geo.size.width, height: geo.size.height) .clipped() } } } } /// The one mark an unread record carries: a small red ink dot — no badge, no /// bold, no count, because a pile of things kept by oneself is not a debt. struct UnreadDot: View { @Environment(\.theme) private var theme /// Read aloud as "Unread" — on a slip, whose own words are its children; /// a cover says it in its label instead. var spoken = false var body: some View { Circle() .fill(theme.print(.red)) .frame(width: CoverFaceKnobs.faceCoverUnreadDotSize, height: CoverFaceKnobs.faceCoverUnreadDotSize) .accessibilityHidden(!spoken) .accessibilityLabel(ShellLines.line("faces", "unread")) } } // ── The binding ───────────────────────────────────────────────────────────── /// The two brads down a script's left edge, as pencil dots — metal is drawn /// in pencil, as the key-tag ring is. struct Brads: Shape { /// Along the edge, top to bottom, as fractions of the height. let at: [CGFloat] /// A brad's diameter: a fraction of the cover's width, held between a /// smallest and a largest. let minDiameter: CGFloat let maxDiameter: CGFloat let diameterFraction: CGFloat /// How far in from the left edge a brad's centre sits, as a fraction of /// the width (never nearer than its own diameter). let insetFraction: CGFloat /// The brads the theme draws. init(_ scale: ThemeScale) { at = [CoverFaceKnobs.faceCoverBradTop, CoverFaceKnobs.faceCoverBradBottom] minDiameter = CoverFaceKnobs.faceCoverBradMinDiameter maxDiameter = CoverFaceKnobs.faceCoverBradMaxDiameter diameterFraction = CoverFaceKnobs.faceCoverBradDiameterFraction insetFraction = CoverFaceKnobs.faceCoverBradInsetFraction } func path(in rect: CGRect) -> Path { var path = Path() let diameter = max(minDiameter, min(maxDiameter, rect.width * diameterFraction)) let x = rect.minX + max(diameter, rect.width * insetFraction) for fraction in at { let y = rect.minY + rect.height * fraction path.addEllipse(in: CGRect(x: x - diameter * 0.5, y: y - diameter * 0.5, width: diameter, height: diameter)) } return path } } /// A cover bound as a script: two sheets under it, each a little further /// down and to the right, and the brads through it. struct BoundPages: View { @Environment(\.theme) private var theme let seed: String @ViewBuilder let content: () -> Content var body: some View { content() .overlay { ZStack { Brads(theme.scale).fill(theme.print(.pencil)) // The shine a brad head catches, so a dot reads as a thing // pushed through the paper rather than a printed spot. Brads(theme.scale).stroke( theme.print(.ink).opacity(CoverFaceKnobs.faceCoverBradOpacity), lineWidth: CoverFaceKnobs.faceCoverBradLineWidth) } .allowsHitTesting(false) .accessibilityHidden(true) } .background { ZStack { PaperSurface(dye: FaceTint.dye(for: seed), edge: .cut, seed: seed + "-3") .offset(x: CoverFaceKnobs.faceCoverArtShadowOffsetX, y: CoverFaceKnobs.faceCoverArtShadowOffsetY) .shadow( color: theme.colors.shadow.color.opacity(CoverFaceKnobs.faceCoverShadowOpacity), radius: CoverFaceKnobs.faceCoverShadowRadius, x: CoverFaceKnobs.faceCoverShadowOffsetX, y: CoverFaceKnobs.faceCoverShadowOffsetY) PaperSurface(dye: FaceTint.dye(for: seed), edge: .cut, seed: seed + "-2") .offset(x: CoverFaceKnobs.faceCoverSecondaryShadowOffsetX, y: CoverFaceKnobs.faceCoverSecondaryShadowOffsetY) .shadow( color: theme.colors.shadow.color.opacity(CoverFaceKnobs.faceCoverShadowOpacity), radius: CoverFaceKnobs.faceCoverShadowRadius, x: CoverFaceKnobs.faceCoverShadowOffsetX, y: CoverFaceKnobs.faceCoverShadowOffsetY) } .accessibilityHidden(true) } } } /// The sizes, counts and timings CoverFace draws with: Swift's own, beside /// their reader — a theme sets only its tokens (`scale.tokens`). enum CoverFaceKnobs { static let faceCoverArtShadowOffsetX: CGFloat = 4 static let faceCoverArtShadowOffsetY: CGFloat = 6 static let faceCoverBoundLeadingPadding: CGFloat = 24 static let faceCoverBoundRoomBottom: CGFloat = 6 static let faceCoverBoundRoomTrailing: CGFloat = 4 static let faceCoverBradBottom: CGFloat = 0.8 static let faceCoverBradDiameterFraction: CGFloat = 0.045 static let faceCoverBradInsetFraction: CGFloat = 0.075 static let faceCoverBradLineWidth: CGFloat = 0.6 static let faceCoverBradMaxDiameter: CGFloat = 9 static let faceCoverBradMinDiameter: CGFloat = 4 static let faceCoverBradOpacity: CGFloat = 0.35 static let faceCoverBradTop: CGFloat = 0.2 static let faceCoverFooterGap: CGFloat = 8 /// A document cover's first-page picture: its drawn height, and the /// long edge it is rendered at (3× a cover's width). static let faceCoverThumbnailHeight: CGFloat = 64 static let faceCoverThumbnailPixels: CGFloat = 360 static let faceCoverGradientOpacity: CGFloat = 0.1 static let faceCoverLeadingPadding: CGFloat = 15 static let faceCoverPaperbackAspect: CGFloat = 0.64 static let faceCoverPostcardAspect: CGFloat = 1.85 static let faceCoverPostcardFooterLineLimit = 3 static let faceCoverPostcardFooterLineSpacing: CGFloat = 2 static let faceCoverPostcardInset: CGFloat = 16 static let faceCoverPostcardLeadingPadding: CGFloat = 4 static let faceCoverPostcardPictureGap: CGFloat = 14 /// A place's name keeps the lines the postcard has before its note /// does (walker292: 'Basav Kalyani Em…' cut at two lines over two free). static let faceCoverPostcardTitleLineLimit = 3 static let faceCoverPostcardWordsGap: CGFloat = 8 static let faceCoverSecondaryShadowOffsetX: CGFloat = 2 static let faceCoverSecondaryShadowOffsetY: CGFloat = 3 static let faceCoverShadowOffsetX: CGFloat = 0.5 static let faceCoverShadowOffsetY: CGFloat = 1 static let faceCoverShadowOpacity: CGFloat = 0.12 static let faceCoverShadowRadius: CGFloat = 1 static let faceCoverSpineWidth: CGFloat = 7 static let faceCoverTitleFitFifth: CGFloat = 0.6 static let faceCoverTitleFitFourth: CGFloat = 0.7 static let faceCoverTitleFitSecond: CGFloat = 0.9 static let faceCoverTitleFitThird: CGFloat = 0.8 /// Two lines, cut at a word (294 row 6, walker293: a document's file /// name ran out of its cover over the next one's). static let faceCoverTitleLineLimit = 2 static let faceCoverTitleMinSize: CGFloat = 9 static let faceCoverTitleSize: CGFloat = 15.5 static let faceCoverTitleWidthFraction: CGFloat = 0.14 static let faceCoverTrailingPadding: CGFloat = 12 static let faceCoverUnreadDotSize: CGFloat = 7 static let faceCoverUnreadPadding: CGFloat = 9 static let faceCoverVerticalPadding: CGFloat = 14 } /// A file's first page, small, on its cover: a PDF's page drawn by PDFKit, a /// picture decoded bounded, once per file and kept for the session /// (`cache`); nothing at all while the bytes are not on this phone, so the /// cover reads as its title alone and never waits. struct FirstPageThumbnail: View { let ref: String @Environment(\.attachmentStore) private var store @Environment(\.cottonCore) private var core @State private var image: UIImage? @MainActor static let cache = NSCache() var body: some View { Group { if let image { Image(uiImage: image) .resizable() .scaledToFill() .frame(maxWidth: .infinity) .frame(height: CoverFaceKnobs.faceCoverThumbnailHeight, alignment: .top) .clipped() .blendMode(.multiply) .accessibilityHidden(true) } } .task(id: ref) { if let kept = Self.cache.object(forKey: ref as NSString) { image = kept; return } guard let source = store ?? core.map({ CoreAttachmentStore(core: $0) }), let url = await source.localURL(for: ref) else { return } let drawn = await Task.detached(priority: .utility) { Self.draw(url) }.value guard let drawn, !Task.isCancelled else { return } Self.cache.setObject(drawn, forKey: ref as NSString) image = drawn } } nonisolated static func draw(_ url: URL) -> UIImage? { let edge = CoverFaceKnobs.faceCoverThumbnailPixels if let page = PDFDocument(url: url)?.page(at: 0) { return page.thumbnail(of: CGSize(width: edge, height: edge), for: .mediaBox) } return FilePreview.bounded(url) } } /// A cover's title at the first size its longest word fits the cover's /// width, so a line never breaks inside a word ("Lighthou se"): each /// candidate measures as wide as that word, laid unseen on one line, and /// `ViewThatFits` takes the first that fits. A /// file's name is words between its marks ("scan_2019_final.pdf"), and it /// breaks there; a word wider than the cover at every size gives way in its /// middle on one line inside the cover, never set past its edge over the next /// card (294 row 6, walker293: Documents' names ran one line over their /// neighbours). struct CoverTitle: View { let title: String let size: CGFloat let ink: PaperInk /// The marks a file's name joins its words with: a line may break after one. static let joins: Set = ["_", "-", ".", "/"] /// The title with a break allowed after each join, drawn the same. static func breakable(_ title: String) -> String { var out = "" for character in title { out.append(character) if joins.contains(character) { out.append("\u{200B}") } } return out } var body: some View { let words = title.split { $0.isWhitespace || Self.joins.contains($0) }.map(String.init) let shown = Self.breakable(title) ViewThatFits(in: .horizontal) { ForEach([ 1, CoverFaceKnobs.faceCoverTitleFitSecond, CoverFaceKnobs.faceCoverTitleFitThird, CoverFaceKnobs.faceCoverTitleFitFourth, CoverFaceKnobs.faceCoverTitleFitFifth, ], id: \.self) { scale in ZStack(alignment: .topLeading) { ForEach(Array(words.enumerated()), id: \.offset) { _, word in Text(word).paperTitle(size * scale, ink: ink).lineLimit(1).fixedSize().hidden() } lines(shown, size: size * scale) } } // A word wider than the cover at every size: one line, its middle // given way, Finder's way with a file's name — its start and its // extension stay ("5522XX…9960.pdf"), never broken inside it. Text(title) .paperTitle(size * CoverFaceKnobs.faceCoverTitleFitFifth, ink: ink) .lineLimit(1) .truncationMode(.middle) .frame(idealWidth: 0, maxWidth: .infinity, alignment: .leading) } } private func lines(_ shown: String, size: CGFloat) -> some View { Text(shown) .paperTitle(size, ink: ink) .lineLimit(CoverFaceKnobs.faceCoverTitleLineLimit) .truncationMode(.tail) .fixedSize(horizontal: false, vertical: true) .frame(idealWidth: 0, maxWidth: .infinity, alignment: .leading) } }