// 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.importCottonKitimportCottonValuesimport PDFKitimportSwiftUIpublicstructCoverFace: View { @Environment(\.theme) privatevar themeprivatelet definition: TableDefinitionprivatelet record: TableRecordprivatelet width: CGFloat? @Environment(\.linkTitles) privatevar links/// - Parameter width: the cover's width when its size is decided outside/// it (a tile); nil takes the width it is offered.publicinit(definition: TableDefinition, record: TableRecord, width: CGFloat? = nil) {self.definition = definitionself.record = recordself.width = width }/// Covers across in a list's grid: three paperbacks, or one postcard.publicstaticfunc columns(_ definition: TableDefinition) -> Int { isPostcard(definition) ? 1 : 3 }staticfunc isPostcard(_ definition: TableDefinition) -> Bool { definition.slip.trailingPicture != nil }privatevar title: String { record.said?.slip.title ?? "" }privatevar footerParts: [String]? { record.said?.slip.cover_footer }privatevar footer: String? { footerParts?.joined(separator: " \u{00B7} ") }privatevar titleInk: PaperInk {let key = RecordValue.isBlank(record[definition.slip.title]) ? definition.slip.titleFallback ?? definition.title : definition.slip.titlereturn record.ink(key) }privatevar footerInk: PaperInk {let keys = definition.cover?.footer ?? [definition.slip.subtitle].compactMap { $0 }return keys.contains { record.ink($0) == .red } ? .red : .pencil }publicvar body: someView {Group {ifSelf.isPostcard(definition) { postcard } elseif 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.privatevar titleSize: CGFloat {let scale = theme.scalereturn width.map { min(CoverFaceKnobs.faceCoverTitleSize, max(CoverFaceKnobs.faceCoverTitleMinSize, $0 * CoverFaceKnobs.faceCoverTitleWidthFraction)) } ?? CoverFaceKnobs.faceCoverTitleSize }privatevar wholeWordTitle: someView {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.privatevar fileRef: String? { definition.columns.first { $0.type == .file }.flatMap { AttachmentValue.read(record[$0.key])?.ref } }privatevar paperback: someView {Paper(dye: FaceTint.dye(for: record.id), edge: .cut, seed: record.id, tilt: false, inset: 0, fills: true) { VStack(alignment: .leading, spacing: 0) {iflet fileRef {FirstPageThumbnail(ref: fileRef) .padding(.bottom, CoverFaceKnobs.faceCoverFooterGap) } wholeWordTitleSpacer(minLength: CoverFaceKnobs.faceCoverFooterGap)iflet 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 inText(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.privatevar postcard: someView {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)iflet 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)ifTrailingPicture.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.publicstructTrailingPicture: View {privatelet definition: TableDefinitionprivatelet record: TableRecordprivatelet key: String?publicinit(definition: TableDefinition, record: TableRecord) {self.definition = definitionself.record = recordself.key = definition.slip.trailingPicture }/// Whether the record has a picture to draw in the slip's trailing place.publicstaticfunc 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.staticfunc imageKey(_ definition: TableDefinition, _ record: TableRecord, at key: String?) -> String? {guardlet column = definition.column(key), column.type == .photo || column.type == .file else { returnnil }return record[column.key].text }publicvar body: someView {iflet pin = record.said?.slip.pin {MapPicture(lat: pin.lat, lng: pin.lng) } elseiflet image = Self.imageKey(definition, record, at: key) {GeometryReader { geo inRecordPicture(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.structUnreadDot: View { @Environment(\.theme) privatevar theme/// Read aloud as "Unread" — on a slip, whose own words are its children;/// a cover says it in its label instead.var spoken = falsevar body: someView {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.structBrads: 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: CGFloatlet maxDiameter: CGFloatlet 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.structBoundPages<Content: View>: View { @Environment(\.theme) privatevar themelet seed: String @ViewBuilder let content: () -> Contentvar body: someView { 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`).enumCoverFaceKnobs {staticlet faceCoverArtShadowOffsetX: CGFloat = 4staticlet faceCoverArtShadowOffsetY: CGFloat = 6staticlet faceCoverBoundLeadingPadding: CGFloat = 24staticlet faceCoverBoundRoomBottom: CGFloat = 6staticlet faceCoverBoundRoomTrailing: CGFloat = 4staticlet faceCoverBradBottom: CGFloat = 0.8staticlet faceCoverBradDiameterFraction: CGFloat = 0.045staticlet faceCoverBradInsetFraction: CGFloat = 0.075staticlet faceCoverBradLineWidth: CGFloat = 0.6staticlet faceCoverBradMaxDiameter: CGFloat = 9staticlet faceCoverBradMinDiameter: CGFloat = 4staticlet faceCoverBradOpacity: CGFloat = 0.35staticlet faceCoverBradTop: CGFloat = 0.2staticlet 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).staticlet faceCoverThumbnailHeight: CGFloat = 64staticlet faceCoverThumbnailPixels: CGFloat = 360staticlet faceCoverGradientOpacity: CGFloat = 0.1staticlet faceCoverLeadingPadding: CGFloat = 15staticlet faceCoverPaperbackAspect: CGFloat = 0.64staticlet faceCoverPostcardAspect: CGFloat = 1.85staticlet faceCoverPostcardFooterLineLimit = 3staticlet faceCoverPostcardFooterLineSpacing: CGFloat = 2staticlet faceCoverPostcardInset: CGFloat = 16staticlet faceCoverPostcardLeadingPadding: CGFloat = 4staticlet 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).staticlet faceCoverPostcardTitleLineLimit = 3staticlet faceCoverPostcardWordsGap: CGFloat = 8staticlet faceCoverSecondaryShadowOffsetX: CGFloat = 2staticlet faceCoverSecondaryShadowOffsetY: CGFloat = 3staticlet faceCoverShadowOffsetX: CGFloat = 0.5staticlet faceCoverShadowOffsetY: CGFloat = 1staticlet faceCoverShadowOpacity: CGFloat = 0.12staticlet faceCoverShadowRadius: CGFloat = 1staticlet faceCoverSpineWidth: CGFloat = 7staticlet faceCoverTitleFitFifth: CGFloat = 0.6staticlet faceCoverTitleFitFourth: CGFloat = 0.7staticlet faceCoverTitleFitSecond: CGFloat = 0.9staticlet 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).staticlet faceCoverTitleLineLimit = 2staticlet faceCoverTitleMinSize: CGFloat = 9staticlet faceCoverTitleSize: CGFloat = 15.5staticlet faceCoverTitleWidthFraction: CGFloat = 0.14staticlet faceCoverTrailingPadding: CGFloat = 12staticlet faceCoverUnreadDotSize: CGFloat = 7staticlet faceCoverUnreadPadding: CGFloat = 9staticlet 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.structFirstPageThumbnail: View {let ref: String @Environment(\.attachmentStore) privatevar store @Environment(\.cottonCore) privatevar core @State privatevar image: UIImage? @MainActor staticlet cache = NSCache<NSString, UIImage>()var body: someView {Group {iflet image {Image(uiImage: image) .resizable() .scaledToFill() .frame(maxWidth: .infinity) .frame(height: CoverFaceKnobs.faceCoverThumbnailHeight, alignment: .top) .clipped() .blendMode(.multiply) .accessibilityHidden(true) } } .task(id: ref) {iflet kept = Self.cache.object(forKey: ref as NSString) { image = kept; return }guardlet source = store ?? core.map({ CoreAttachmentStore(core: $0) }),let url = await source.localURL(for: ref) else { return }let drawn = awaitTask.detached(priority: .utility) { Self.draw(url) }.valueguardlet drawn, !Task.isCancelled else { return }Self.cache.setObject(drawn, forKey: ref as NSString) image = drawn } } nonisolated staticfunc draw(_ url: URL) -> UIImage? {let edge = CoverFaceKnobs.faceCoverThumbnailPixelsiflet page = PDFDocument(url: url)?.page(at: 0) {return page.thumbnail(of: CGSize(width: edge, height: edge), for: .mediaBox) }returnFilePreview.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).structCoverTitle: View {let title: Stringlet size: CGFloatlet ink: PaperInk/// The marks a file's name joins its words with: a line may break after one.staticlet joins: Set<Character> = ["_", "-", ".", "/"]/// The title with a break allowed after each join, drawn the same.staticfunc 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: someView {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 inText(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) } }privatefunc lines(_ shown: String, size: CGFloat) -> someView {Text(shown) .paperTitle(size, ink: ink) .lineLimit(CoverFaceKnobs.faceCoverTitleLineLimit) .truncationMode(.tail) .fixedSize(horizontal: false, vertical: true) .frame(idealWidth: 0, maxWidth: .infinity, alignment: .leading) }}