// The reader is bare cream by day and a reading lamp by night. Its close // control has the first row; the record's title and byline, when present, // precede the body in one column below it. Even one line starts at the top // of that column. Pages turn by tap or swipe; a long press edits the column // through the shell's editor where the definition permits it. // // PRINT IS FIXED AT THE READER'S SIZE: it does not follow Dynamic Type, as no // print on an object does (`Fonts.swift`); Loom's text-size picker went // because it changed nothing. // // The pages are cut by measure, not by sentence count (`ReadPages`): a page // holds as many words as the text block's room takes to a comfortable depth // at that size, breaks only at a sentence's end, never splits a paragraph // that fits on a page, keeps a list a list, and a short body stands whole. // Each body column starts its own pages: a memory's one sentence is its // first page and the quote behind it the next; a book's notes, then its // favourite quote. // // It is a screen kind with slots, as card, slip and chat are: the head, the // bodies and the byline are columns its definition names (`ReadSlots`). // Every word on it is the record's or the definition's. import CottonFaces import CottonKit import CottonPaper import CottonValues import NaturalLanguage import SwiftUI enum ReadPageKnobs { /// The words' type: Libre Caslon at a reading size, its lines 1.45 of /// the size apart. 22 pt, as the centred picture's proportion asks: its /// words run a little smaller than that against its screen, never larger. static let bodySize: CGFloat = 22 static let bodyPitch: CGFloat = 1.45 /// The running head: the typewriter, small, read off the picture. static let headSize: CGFloat = 11 /// The byline under the head, a fact: the typewriter, small. static let bylineSize: CGFloat = 12 /// The text block's margin at either side: the page is centred, so the /// two are one. static let margin: CGFloat = 32 /// The least room between the head (or the byline) and the words, and /// between the words and the progress line. static let gap: CGFloat = 34 static let bylineGap: CGFloat = 4 /// The progress line: its weight, and its place above the bottom of the /// safe area. static let progress: CGFloat = 1.5 static let foot: CGFloat = 24 /// The close mark: its glyph, the square it is tapped in, and that /// square's place — in the top-left corner, its middle a little under /// the top of the safe area. The running head stands on the same line. static let closeSize: CGFloat = 17 static let closeBox: CGFloat = 44 static let closeInset: CGFloat = 10 static let closeTop: CGFloat = 0 /// How far the words' average letter is widened, so a line the page is /// cut for never holds more than Caslon draws. static let widen: CGFloat = 1.1 /// How deep a page fills: of the words the text block holds, the share /// that reads comfortably — a few sentences, empty paper around them. static let comfort: Double = 0.5 /// How far a swipe travels before it turns the page, or closes it. static let turn: CGFloat = 40 static let down: CGFloat = 90 } /// Where the page's parts stand on a screen `size` (the safe area's), in its /// coordinates: one layout in both lights. struct ReadGeometry: Equatable { let size: CGSize /// Whether a byline stands under the head. let byline: Bool var titled = true /// The close mark's square, in the top-left corner. var close: CGRect { CGRect(x: ReadPageKnobs.closeInset, y: ReadPageKnobs.closeTop, width: ReadPageKnobs.closeBox, height: ReadPageKnobs.closeBox) } /// The title sits in the reading column one margin below Close. var head: CGRect { return CGRect(x: ReadPageKnobs.margin, y: close.maxY + ReadPageKnobs.margin, width: max(0, size.width - 2 * ReadPageKnobs.margin), height: ReadText.headHeight) } /// The byline's line in the title's column. var bylineLine: CGRect { CGRect(x: head.minX, y: head.maxY + ReadPageKnobs.bylineGap, width: head.width, height: ReadText.bylineHeight) } /// The hair-thin progress line at the foot, as wide as the text block. var progress: CGRect { CGRect(x: ReadPageKnobs.margin, y: size.height - ReadPageKnobs.foot - ReadPageKnobs.progress, width: max(0, size.width - 2 * ReadPageKnobs.margin), height: ReadPageKnobs.progress) } /// The text block's room: the margins at either side, from a gap under /// the head's line (the ×'s square, or the byline) to a gap above the /// progress line. The page is cut by it (`ReadPages.words`). var room: CGRect { let top = byline ? bylineLine.maxY + ReadPageKnobs.gap : titled ? head.maxY + ReadPageKnobs.gap : close.maxY + ReadPageKnobs.margin let bottom = progress.minY - ReadPageKnobs.gap return CGRect(x: ReadPageKnobs.margin, y: top, width: progress.width, height: max(0, bottom - top)) } /// Every block starts at the room's top, including a one-line note. func blockTop(_ height: CGFloat) -> CGFloat { room.minY } } // MARK: - The page rule /// A body cut into pages by measure. enum ReadPages { /// The words a page holds at a comfortable depth: `columns` characters a /// line and `lines` lines, a word being its letters and the space after /// it (`FaceMeasureKnobs.wordLetters`). static func words(columns: Int, lines: Int) -> Int { let perLine = Double(columns) / (Double(FaceMeasureKnobs.wordLetters) + 1) return max(1, Int(perLine * Double(lines) * ReadPageKnobs.comfort)) } /// The words a page holds in a text block `width` by `height`, set in /// Caslon at the reader's size and pitch (`ReadText`): the characters a /// line takes at Caslon's average letter, widened, and the lines the /// block takes at the pitch: the room `ReadGeometry` gives the words. static func words(width: CGFloat, height: CGFloat) -> Int { let pitch = ReadText.pitch let columns = max(8, Int(width / (ReadText.advance * ReadPageKnobs.widen))) return words(columns: columns, lines: max(1, Int(height / pitch))) } /// `bodies` cut into pages of about `words` words each, every body /// starting its own page. static func pages(_ bodies: [String], words: Int) -> [String] { cuts(bodies, words: words).map(\.text) } /// The same pages, each with the body it was cut from (its index in /// `bodies`): what a long press on a page writes. static func cuts(_ bodies: [String], words: Int) -> [ReadCut] { bodies.enumerated().flatMap { body, text in cut(text, words: words).map { ReadCut(body: body, text: $0) } } } /// `text` cut into pages of about `words` words: whole paragraphs while /// they fit, a paragraph that fits on a page never split (it starts the /// next), and one too long for any page poured on a sentence at a time — /// a list an item at a time — so a page breaks only at a sentence's end. /// A body that fits is one page. static func cut(_ text: String, words cap: Int) -> [String] { let blocks = ReadBlock.blocks(of: text) guard !blocks.isEmpty else { return [] } var pages: [String] = [] var page: [String] = [] var held = 0 func turn() { if !page.isEmpty { pages.append(page.joined(separator: "\n\n")) } page = [] held = 0 } for block in blocks { let count = block.words if held + count <= cap { page.append(block.text) held += count continue } if count <= cap { turn() page = [block.text] held = count continue } // Too long for any page: its sentences (a list's items) poured // on, the page turning only between two of them. var run: [String] = [] for unit in block.units { let size = Self.count(unit) if held + size > cap, !(page.isEmpty && run.isEmpty) { if !run.isEmpty { page.append(run.joined(separator: block.join)) } turn() run = [] } run.append(unit) held += size } if !run.isEmpty { page.append(run.joined(separator: block.join)) } } turn() return pages } /// The words in `text`. static func count(_ text: String) -> Int { text.split(whereSeparator: \.isWhitespace).count } } /// One page's words and the body they were cut from. struct ReadCut: Equatable { let body: Int let text: String } /// A paragraph of a body, or a list: what a page keeps whole while it can. struct ReadBlock: Equatable { let text: String /// What it is poured on by when it is too long for a page: its sentences, /// or a list's items. let units: [String] /// What its units are joined with on a page. let join: String var words: Int { ReadPages.count(text) } /// The paragraphs of `text` (split at a blank line), each a list when a /// line of it starts as a list's item does. static func blocks(of text: String) -> [ReadBlock] { let normal = text.replacingOccurrences(of: "\r\n", with: "\n") var paragraphs: [[String]] = [[]] for line in normal.components(separatedBy: "\n") { if line.trimmingCharacters(in: .whitespaces).isEmpty { if !(paragraphs.last ?? []).isEmpty { paragraphs.append([]) } } else { paragraphs[paragraphs.count - 1].append(line) } } return paragraphs.filter { !$0.isEmpty }.map { lines in let text = lines.joined(separator: "\n") if lines.contains(where: isItem) { return ReadBlock(text: text, units: items(lines), join: "\n") } return ReadBlock(text: text, units: sentences(text), join: " ") } } /// A line that starts a list's item: a dash, a star, a bullet, or a /// number with its stop. static func isItem(_ line: String) -> Bool { line.range(of: #"^\s*([-*•–☐☑]|\d+[.)])\s+\S"#, options: .regularExpression) != nil } /// A list's items, each with the lines that run on under it; any lines /// before the first item are one unit of their own. static func items(_ lines: [String]) -> [String] { var items: [[String]] = [] for line in lines { if isItem(line) || items.isEmpty { items.append([line]) } else { items[items.count - 1].append(line) } } return items.map { $0.joined(separator: "\n") } } /// The sentences of a paragraph, each as written. static func sentences(_ text: String) -> [String] { let tokenizer = NLTokenizer(unit: .sentence) tokenizer.string = text var found: [String] = [] tokenizer.enumerateTokens(in: text.startIndex.. = [.notePage, .memory, .bookHardback] /// The reading page's slots for `definition`, nil for a table that /// opens no reading page. Read from the keys it carries: a card of a /// kind that is its own words, with no picture unless it is a book (a /// pictured note is a studio's class or place on its photograph; a /// book's cover is the book, not what it says); its bodies are the /// table's title column when that is long text (a memory's one /// sentence), then the card's body column, then its quote column, each /// long text; the head is the table's title column when it is not read /// as a body — with the card's subtitle after it (a book's author) — /// else the card's subtitle's column (a memory's project), and then its /// date's. static func of(_ definition: TableDefinition) -> ReadSlots? { guard let card = definition.card, kinds.contains(card.face), card.face == .bookHardback || !card.fields.contains(where: { $0.slot == .photo }) else { return nil } func column(_ slot: DefinitionCardSlot) -> String? { card.fields.first { $0.slot == slot }?.column } let titleIsBody = definition.column(definition.title)?.type == .longtext var bodies: [String] = titleIsBody ? [definition.title] : [] for slot in [DefinitionCardSlot.body, .quote] { if let body = column(slot), !bodies.contains(body), definition.column(body)?.type == .longtext { bodies.append(body) } } guard !bodies.isEmpty else { return nil } if titleIsBody { return ReadSlots(title: column(.subtitle), date: column(.date), bodies: bodies) } return ReadSlots(title: definition.title, with: column(.subtitle), bodies: bodies) } } /// One record's reading page: its words, as the slots read them. struct ReadDocument: Equatable { /// The running head. let title: String? /// The definition's byline for the record (its slip's), when it says one. let byline: String? let bodies: [String] /// The record, card, slots and definition it was read from, where the /// deck opened it (`DeckOpening.of`): what a long press writes. Not part /// of what the page reads, so not of its equality. var markdown: [Bool] = [] var source: ReadSource? static func == (lhs: ReadDocument, rhs: ReadDocument) -> Bool { lhs.title == rhs.title && lhs.byline == rhs.byline && lhs.bodies == rhs.bodies } /// `record` read by `slots`: the head in the core's words when its card /// says that column (`DeckCard`), else as the record holds it, a book's /// author after its title; when the title says nothing, the date's /// words where the slots name one (a memory's) — the card's alone: a /// date the card says nothing of (a memory kept today) leaves the head /// bare, never its stamp ("2026-10-29T13:55:00.000Z") — else the first /// sentence of the words, as the note's torn page titles an untitled /// note (`TornPageSetting`). Each body as written. init(record: TableRecord, card: DeckCard?, slots: ReadSlots, definition: TableDefinition) { func onCard(_ column: String) -> String? { definition.card?.fields.first { $0.column == column }.flatMap { card?.text($0.slot.rawValue) } } func trimmed(_ words: String?) -> String? { words.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.flatMap { $0.isEmpty ? nil : $0 } } func said(_ column: String?) -> String? { guard let column else { return nil } return trimmed(onCard(column) ?? record[column].text) } markdown = slots.bodies.filter { !(record[$0].text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "").isEmpty }.map { definition.setsMarkdown($0) } bodies = slots.bodies.compactMap { record[$0].text?.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } if let named = said(slots.title) { title = [definition.card?.face == .notePage ? FaceMarkdown.plain(named) : named, said(slots.with)].compactMap { $0 }.joined(separator: " · ") } else if let date = slots.date { title = trimmed(onCard(date)) } else { title = nil } byline = definition.slip.byline.flatMap { line in record[line.column].text.flatMap { line.words[$0] } } } init(title: String?, byline: String? = nil, bodies: [String]) { self.title = title self.byline = byline self.bodies = bodies } } /// What a reading page was read from, so it can be written and read again. struct ReadSource { let record: TableRecord let card: DeckCard? let slots: ReadSlots let definition: TableDefinition /// The columns of the bodies the page reads, in its order: the slots' /// bodies that hold words on this record, as `ReadDocument` keeps them. var columns: [String] { slots.bodies.filter { !(record[$0].text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "").isEmpty } } /// The column body `index` is read from: the core says whether a person /// writes it on this record (`shell.input`'s ask refuses one they do not). func written(body index: Int) -> String? { let columns = columns return columns.indices.contains(index) ? columns[index] : nil } /// The record the editor writes. var target: DeckEditTarget { DeckEditTarget(table: definition.id, record: record.id, date: definition.whenColumn) } /// The page read again from `record` as written: its words new, its /// head the card's as it was (the head's columns are not written here). func reading(_ record: TableRecord) -> ReadDocument { var document = ReadDocument(record: record, card: card, slots: slots, definition: definition) document.source = ReadSource(record: record, card: card, slots: slots, definition: definition) return document } } // MARK: - The page /// Where a tap on the page goes: the deck's thirds (`DeckZones`) — the right /// third the next page, the left third the one before, the middle third /// nothing — never past either end. enum ReadTurn { static func page(after tap: CGFloat, width: CGFloat, at page: Int, of count: Int) -> Int { let step: Int switch DeckZones(width: width).zone(at: tap) { case .previous: step = -1 case .next: step = 1 case .own: step = 0 } return min(max(0, page + step), max(0, count - 1)) } /// How far through the reader is on page `at` of `count`: the pages read, /// this one counted, over the pages. static func progress(at page: Int, of count: Int) -> CGFloat { count > 0 ? CGFloat(min(page + 1, count)) / CGFloat(count) : 0 } } struct ReadPage: View { let opened: ReadDocument let close: () -> Void init(document: ReadDocument, close: @escaping () -> Void) { opened = document self.close = close } @State private var page = 0 /// The page read again after a long press wrote it. @State private var rewritten: ReadDocument? @Environment(\.theme) private var theme @Environment(\.deckEditor) private var editor @Environment(\.records) private var store @Environment(\.cottonCore) private var core @Environment(\.cottonHaptics) private var haptics private var document: ReadDocument { rewritten ?? opened } private var light: ReadLight { ReadLight.of(theme.appearance) } var body: some View { GeometryReader { box in let geometry = ReadGeometry(size: box.size, byline: document.byline != nil, titled: document.title != nil) let room = geometry.room let setBodies = document.bodies.enumerated().map { index, body in document.markdown.indices.contains(index) && document.markdown[index] ? FaceMarkdown.set(body, theme: theme) : AttributedString(body) } let reading = setBodies.map { String($0.characters) } let cuts = ReadPages.cuts(reading, words: ReadPages.words(width: room.width, height: room.height)) let pages = cuts.map(\.text) let at = min(page, max(0, pages.count - 1)) ZStack(alignment: .topLeading) { runningHead(in: geometry) if pages.indices.contains(at) { ReadBlockPlacement(geometry: geometry) { ReadText(text: pages[at], ink: light.ink, set: Self.setting(cuts[at], in: setBodies, before: Array(cuts.prefix(at)))) .accessibilityElement() .accessibilityLabel(pages[at]) .accessibilityIdentifier("read-page-text") .accessibilityAdjustableAction { direction in page = min(max(0, at + (direction == .increment ? 1 : -1)), pages.count - 1) } } .id(at) .transition(.opacity) } progress(at: at, of: pages.count) .frame(width: geometry.progress.width, height: geometry.progress.height) .offset(x: geometry.progress.minX, y: geometry.progress.minY) } .frame(width: box.size.width, height: box.size.height, alignment: .topLeading) .contentShape(Rectangle()) .onLongPressGesture(minimumDuration: DeckEditableKnobs.hold) { write(cuts.indices.contains(at) ? cuts[at].body : nil) } .onTapGesture { tap in page = ReadTurn.page(after: tap.x, width: box.size.width, at: at, of: pages.count) } .gesture( DragGesture(minimumDistance: 16).onEnded { drag in let dx = drag.translation.width, dy = drag.translation.height if abs(dx) > abs(dy), abs(dx) > ReadPageKnobs.turn { page = min(max(0, at + (dx < 0 ? 1 : -1)), max(0, pages.count - 1)) } else if dy > ReadPageKnobs.down, dy > abs(dx) { close() } }) .simultaneousGesture( MagnifyGesture().onEnded { pinch in if pinch.magnification < DeckWholeCardKnobs.closes { close() } }) .animation(.easeOut(duration: 0.18), value: page) } // The editor's keyboard, over the page, never shrinks the room: // the pages under it are cut as they were, and Done finds its page. .ignoresSafeArea(.keyboard) .overlay(alignment: .topLeading) { Button(action: close) { Image(systemName: "xmark") .font(CottonFonts.symbol(ReadPageKnobs.closeSize, weight: .light)) .foregroundStyle(light.marks.opacity(light.closeStrength)) .frame(width: ReadPageKnobs.closeBox, height: ReadPageKnobs.closeBox) .contentShape(Rectangle()) } .buttonStyle(.plain) .padding(.leading, ReadPageKnobs.closeInset) .offset(y: ReadPageKnobs.closeTop) .accessibilityLabel(CottonStrings.close) .accessibilityIdentifier("read-page-close") } .background { ReadGround(light: light).ignoresSafeArea() } // The shell's full-screen editor, over the reader that opened it: // the stack's own writing layer stands under this cover. .fullScreenCover(item: Binding( get: { editor?.writing?.overReader == true ? editor?.writing : nil }, set: { if $0 == nil, editor?.writing?.overReader == true { editor?.dismissWriting() } })) { writing in DeckLongTextEditor(title: writing.title, words: writing.words, voice: writing.voicePlan(surface: "note")) { text in if let text { editor?.commit(text) } else { editor?.dismissWriting() } } } #if os(iOS) .statusBarHidden() #endif .accessibilityElement(children: .contain) .accessibilityAddTraits(.isModal) .accessibilityIdentifier("read-page") } /// The reader cuts the set words, then keeps the original run attributes. /// The source document remains raw for the editor and the save path. static func setting(_ cut: ReadCut, in bodies: [AttributedString], before: [ReadCut] = []) -> AttributedString { let value = bodies[cut.body] let plain = String(value.characters) // ReadBlock normalises whitespace between sentences/paragraphs. Map // its characters back in order while retaining that page's spacing. var cursor = plain.startIndex for previous in before where previous.body == cut.body { for character in previous.text where !character.isWhitespace { if let found = plain[cursor...].firstIndex(of: character) { cursor = plain.index(after: found) } } } var out = AttributedString() for character in cut.text { if character.isWhitespace { var space = AttributedString(String(character)) if cursor < plain.endIndex, plain[cursor].isWhitespace { let from = value.characters.index(value.startIndex, offsetBy: plain.distance(from: plain.startIndex, to: cursor)) if let run = value[from.. some View { if let title = document.title { Text(title) .font(Font(ReadText.headFont)) .foregroundStyle(light.marks.opacity(light.headStrength)) .lineLimit(1) .truncationMode(.tail) .frame(width: geometry.head.width, height: geometry.head.height, alignment: .leading) .offset(x: geometry.head.minX, y: geometry.head.minY) .accessibilityIdentifier("read-page-title") } if let byline = document.byline { Text(byline) .font(Font(ReadText.bylineFont)) .foregroundStyle(light.marks.opacity(light.headStrength)) .lineLimit(1) .truncationMode(.tail) .frame(width: geometry.bylineLine.width, height: geometry.bylineLine.height, alignment: .leading) .offset(x: geometry.bylineLine.minX, y: geometry.bylineLine.minY) .accessibilityIdentifier("read-page-byline") } } /// The hair-thin line at the foot: the part read in ink, the rest a /// faint tint. VoiceOver hears the cards' page count from it. private func progress(at: Int, of count: Int) -> some View { GeometryReader { line in ZStack(alignment: .leading) { Rectangle().fill(light.marks.opacity(light.unreadStrength)) Rectangle().fill(light.marks.opacity(light.readStrength)) .frame(width: line.size.width * ReadTurn.progress(at: at, of: count)) } } .accessibilityElement() .accessibilityValue(ShellLines.line("cards", "note.page", ["at": String(at + 1), "of": String(count)])) .accessibilityIdentifier("read-page-progress") } } /// The page's words placed by `ReadGeometry`: as wide as the room, as tall /// as they are set, their top at the room's top. private struct ReadBlockPlacement: Layout { let geometry: ReadGeometry func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { proposal.replacingUnspecifiedDimensions() } func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { let room = geometry.room for words in subviews { let height = words.sizeThatFits(ProposedViewSize(width: room.width, height: nil)).height words.place(at: CGPoint(x: bounds.minX + room.minX, y: bounds.minY + geometry.blockTop(height)), anchor: .topLeading, proposal: ProposedViewSize(width: room.width, height: height)) } } }