// 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.importCottonFacesimportCottonKitimportCottonPaperimportCottonValuesimportNaturalLanguageimportSwiftUIenumReadPageKnobs {/// 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.staticlet bodySize: CGFloat = 22staticlet bodyPitch: CGFloat = 1.45/// The running head: the typewriter, small, read off the picture.staticlet headSize: CGFloat = 11/// The byline under the head, a fact: the typewriter, small.staticlet bylineSize: CGFloat = 12/// The text block's margin at either side: the page is centred, so the/// two are one.staticlet margin: CGFloat = 32/// The least room between the head (or the byline) and the words, and/// between the words and the progress line.staticlet gap: CGFloat = 34staticlet bylineGap: CGFloat = 4/// The progress line: its weight, and its place above the bottom of the/// safe area.staticlet progress: CGFloat = 1.5staticlet 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.staticlet closeSize: CGFloat = 17staticlet closeBox: CGFloat = 44staticlet closeInset: CGFloat = 10staticlet 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.staticlet 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.staticlet comfort: Double = 0.5/// How far a swipe travels before it turns the page, or closes it.staticlet turn: CGFloat = 40staticlet 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.structReadGeometry: Equatable {let size: CGSize/// Whether a byline stands under the head.let byline: Boolvar 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.marginlet bottom = progress.minY - ReadPageKnobs.gapreturn 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.enumReadPages {/// 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`).staticfunc 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.staticfunc words(width: CGFloat, height: CGFloat) -> Int {let pitch = ReadText.pitchlet 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.staticfunc 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.staticfunc 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.staticfunc 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 = 0func turn() {if !page.isEmpty { pages.append(page.joined(separator: "\n\n")) } page = [] held = 0 }for block in blocks {let count = block.wordsif held + count <= cap { page.append(block.text) held += countcontinue }if count <= cap { turn() page = [block.text] held = countcontinue }// 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`.staticfunc count(_ text: String) -> Int { text.split(whereSeparator: \.isWhitespace).count }}/// One page's words and the body they were cut from.structReadCut: Equatable {let body: Intlet text: String}/// A paragraph of a body, or a list: what a page keeps whole while it can.structReadBlock: 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: Stringvar 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.staticfunc 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 inlet text = lines.joined(separator: "\n")if lines.contains(where: isItem) {returnReadBlock(text: text, units: items(lines), join: "\n") }returnReadBlock(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.staticfunc 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.staticfunc 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.staticfunc sentences(_ text: String) -> [String] {let tokenizer = NLTokenizer(unit: .sentence) tokenizer.string = textvar found: [String] = [] tokenizer.enumerateTokens(in: text.startIndex..<text.endIndex) { range, _ inlet sentence = text[range].trimmingCharacters(in: .whitespacesAndNewlines)if !sentence.isEmpty { found.append(sentence) }returntrue }return found.isEmpty ? [text] : found }}// MARK: - The slots/// The columns a reading page reads, from the record's definition.structReadSlots: Equatable {/// The column whose words are the running head.let title: String?/// A column said after the head's, " · " between them: a book's author.let with: String?/// The column whose card words stand as the head when the title says/// nothing: a memory's date, when it has no project.let date: String?/// The columns read, in order, each starting its own pages.let bodies: [String]init(title: String?, with: String? = nil, date: String? = nil, bodies: [String]) {self.title = titleself.with = withself.date = dateself.bodies = bodies }/// The kinds of card that are their own words: a note, a memory, and a/// book, whose notes and favourite quote are.staticlet kinds: Set<DefinitionCardKind> = [.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.staticfunc of(_ definition: TableDefinition) -> ReadSlots? {guardlet card = definition.card, kinds.contains(card.face), card.face == .bookHardback || !card.fields.contains(where: { $0.slot == .photo })else { returnnil }func column(_ slot: DefinitionCardSlot) -> String? { card.fields.first { $0.slot == slot }?.column }let titleIsBody = definition.column(definition.title)?.type == .longtextvar bodies: [String] = titleIsBody ? [definition.title] : []for slot in [DefinitionCardSlot.body, .quote] {iflet body = column(slot), !bodies.contains(body), definition.column(body)?.type == .longtext { bodies.append(body) } }guard !bodies.isEmpty else { returnnil }if titleIsBody { returnReadSlots(title: column(.subtitle), date: column(.date), bodies: bodies) }returnReadSlots(title: definition.title, with: column(.subtitle), bodies: bodies) }}/// One record's reading page: its words, as the slots read them.structReadDocument: 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?staticfunc == (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? {guardlet column else { returnnil }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 }iflet named = said(slots.title) { title = [definition.card?.face == .notePage ? FaceMarkdown.plain(named) : named, said(slots.with)].compactMap { $0 }.joined(separator: " · ") } elseiflet 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 = titleself.byline = bylineself.bodies = bodies }}/// What a reading page was read from, so it can be written and read again.structReadSource {let record: TableRecordlet card: DeckCard?let slots: ReadSlotslet 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 = columnsreturn 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.enumReadTurn {staticfunc page(after tap: CGFloat, width: CGFloat, at page: Int, of count: Int) -> Int {let step: IntswitchDeckZones(width: width).zone(at: tap) {case .previous: step = -1case .next: step = 1case .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.staticfunc progress(at page: Int, of count: Int) -> CGFloat { count > 0 ? CGFloat(min(page + 1, count)) / CGFloat(count) : 0 }}structReadPage: View {let opened: ReadDocumentlet close: () -> Voidinit(document: ReadDocument, close: @escaping () -> Void) { opened = documentself.close = close } @State privatevar page = 0/// The page read again after a long press wrote it. @State privatevar rewritten: ReadDocument? @Environment(\.theme) privatevar theme @Environment(\.deckEditor) privatevar editor @Environment(\.records) privatevar store @Environment(\.cottonCore) privatevar core @Environment(\.cottonHaptics) privatevar hapticsprivatevar document: ReadDocument { rewritten ?? opened }privatevar light: ReadLight { ReadLight.of(theme.appearance) }var body: someView {GeometryReader { box inlet geometry = ReadGeometry(size: box.size, byline: document.byline != nil, titled: document.title != nil)let room = geometry.roomlet 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 inlet dx = drag.translation.width, dy = drag.translation.heightif abs(dx) > abs(dy), abs(dx) > ReadPageKnobs.turn { page = min(max(0, at + (dx < 0 ? 1 : -1)), max(0, pages.count - 1)) } elseif dy > ReadPageKnobs.down, dy > abs(dx) { close() } }) .simultaneousGesture(MagnifyGesture().onEnded { pinch inif 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 inDeckLongTextEditor(title: writing.title, words: writing.words, voice: writing.voicePlan(surface: "note")) { text iniflet 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.staticfunc 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.startIndexfor previous in before where previous.body == cut.body {for character in previous.text where !character.isWhitespace {iflet 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))iflet run = value[from..<value.characters.index(after: from)].runs.first { space.mergeAttributes(run.attributes) } cursor = plain.index(after: cursor) } out += spacecontinue }guardlet found = plain[cursor...].firstIndex(of: character) else { continue }let from = value.characters.index(value.startIndex, offsetBy: plain.distance(from: plain.startIndex, to: found)) out += AttributedString(value[from..<value.characters.index(after: from)]) cursor = plain.index(after: found) }return out }/// A long press on a page cut from body `body`: its column written in the/// shell's editor, where a person writes it; else nothing happens.privatefunc write(_ body: Int?) {guardlet body, let editor, let source = document.source, let column = source.written(body: body) else { return } haptics.press() editor.write(source.target, column: column, store: store, core: core) { after in rewritten = source.reading(after) } }/// The running head centred at the top, level with the ×, in the/// typewriter, and the byline centred under it when there is one. @ViewBuilderprivatefunc runningHead(in geometry: ReadGeometry) -> someView {iflet 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") }iflet 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.privatefunc progress(at: Int, of count: Int) -> someView {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.privatestructReadBlockPlacement: Layout {let geometry: ReadGeometryfunc sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { proposal.replacingUnspecifiedDimensions() }func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {let room = geometry.roomfor 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)) } }}