// The NOTE as a TORN PAGE (the owner's pick, 29 Oct 2026; the note picture// `note-look/3-torn-page`): a ruled cream page torn out of a spiral notebook,// its binding edge ragged with the perforation holes, a paperclip at its top,// lying bare on the notes' burnt-orange felt (`FaceGround.feltOrange`) with no// paper and no rule of the deck's. The page, its shadow on the cloth, the clip// are PAINTED (`Media.xcassets`, cut and imported by// `scripts/import-notebook-materials.py`), the rules and the red margin with// them; the face draws live only what the card decides, written on the// painted rules://// the title in Libre Caslon, one line or two and no further — a title that// wants a third stops at the second's last whole word, with no ellipsis: a// page just stops. A note with no title sets its first sentence as one,// and the opening goes on after it.// the date typed under it in Courier Prime, in grey: the card's date words// as the core says them, the year among them for a note from another year.// The note's corner is this line; there is no plate.// the OPENING of the body in Caslon, a line on each rule after a rule left// bare, as many whole lines as the page holds, stopping at the last whole// word that fits: nothing scrolls, no pages, no "and more". A paragraph// after the first starts indented, as a book's does. The object shows the// title and the opening; the reader shows the rest.//// Nothing on the page is a tagged part, and it keeps no tap of its own: the// whole page is the deck's to tap — a side third steps the deck, the middle// opens the reader (owner, 29 Oct 2026: "instant switching to the next note// when you keep tapping"); a note is edited from the action fan. Stepped by a// tap, it cuts (`FaceStep.cut`): the next page is simply there.//// Every word is the core's (`DeckCard`): the face only sets them on the rules.importCottonPaperimportCottonValuesimportCoreTextimportSwiftUIenumNotePageFaceKnobs {// THE PAGE, as painted (`note-page`, 1065 by 1407 pixels): its width// over its height, each rule's height and the margin line's place as// shares of it, and how far its shadow (`note-page-shadow`) reaches past// it on every side, as a share of its width — measured off the painting// by the cut that made the layers (`cut.py` beside them), so a repainted// page owes new knobs.staticlet aspect: CGFloat = 1065.0 / 1407.0staticlet rules: [CGFloat] = [0.0925, 0.1331, 0.1736, 0.2145, 0.2553, 0.2962, 0.3370, 0.3779, 0.4187, 0.4597, 0.5014,0.5421, 0.5832, 0.6240, 0.6662, 0.7076, 0.7483, 0.7895, 0.8305, 0.8713, 0.9128, 0.9556, ]staticlet margin: CGFloat = 0.2014staticlet shadowReach: CGFloat = 0.0845/// The page in the card's room: the most of its height the page and the/// clip standing over its top take together, and of its width.staticlet fillHeight: CGFloat = 0.97staticlet fillWidth: CGFloat = 0.96/// The clip (`note-clip`): its width over its height as painted; its/// length, its middle's place across the page and its top's above the/// page's edge, as shares of the page; the turn it lies askew at.staticlet clipAspect: CGFloat = 192.0 / 701.0staticlet clipLength: CGFloat = 0.17staticlet clipAcross: CGFloat = 0.31staticlet clipTop: CGFloat = -0.045staticlet clipTurn: Double = -7/// The writing's room: from this far past the margin line to this far/// in from the page's right edge, as shares of its width.staticlet lead: CGFloat = 0.025staticlet trail: CGFloat = 0.045/// The type, as shares of the page's height (at a phone's page, about/// 17, 11 and 13 points on rules 17 apart): print on an object scales/// with the object, never with Dynamic Type.staticlet titleSize: CGFloat = 0.042staticlet dateSize: CGFloat = 0.026staticlet openingSize: CGFloat = 0.031/// The rule the title's first line is written on, the rules between/// its lines, and how many lines it may take.staticlet titleRule = 2staticlet titleStep = 2staticlet titleLines = 2/// A paragraph after the first starts this many of the opening's/// points in.staticlet indent: CGFloat = 1.4}/// One line written on the page: its words, and whether it opens a/// paragraph after the first (indented).publicstructTornLine: Equatable, Sendable {publicvar words: Stringpublicvar indented: Boolpublicvar setWords: AttributedString? = nilpublicinit(_ words: String, indented: Bool = false) {self.words = wordsself.indented = indented }}/// A note's card as the torn page writes it: the title's lines, the date,/// the opening's lines, and the rule each is written on.publicstructTornPage: Equatable, Sendable {publicvar title: [TornLine]publicvar date: String?publicvar opening: [TornLine]publicvar titleRules: [Int]publicvar dateRule: Int?publicvar openingRule: Int/// The rules the opening is written on, one a line.publicvar openingRules: Range<Int> { openingRule..<(openingRule + opening.count) }}/// How a note's card is set on the page.publicenumTornPageSetting {/// The title and the words after it: the card's title and body, or, for/// a note with no title, its first sentence and the rest.publicstaticfunc words(_ card: DeckCard) -> (title: String?, body: String) {let body = FaceMarkdown.plain(card.text("body") ?? "").trimmingCharacters(in: .whitespacesAndNewlines)let title = FaceMarkdown.plain(card.text("title") ?? "").trimmingCharacters(in: .whitespacesAndNewlines)if !title.isEmpty { return (title, body) }guardlet first = firstSentence(body) else { return (nil, body) }return (first.sentence, first.rest) }/// The first sentence of `text` and what follows it: up to the first/// full stop, question or exclamation that ends a word, or the first/// line's end, whichever comes first; a full stop is let go (a title/// carries none), a question or an exclamation kept. Nil for no words.publicstaticfunc firstSentence(_ text: String) -> (sentence: String, rest: String)? {let text = text.trimmingCharacters(in: .whitespacesAndNewlines)guard !text.isEmpty else { returnnil }var end = text.endIndexvar index = text.startIndexwhile index < text.endIndex {let character = text[index]if character.isNewline { end = indexbreak }let next = text.index(after: index)if".!?".contains(character), next == text.endIndex || text[next].isWhitespace { end = nextbreak } index = next }var sentence = String(text[..<end]).trimmingCharacters(in: .whitespaces)if sentence.hasSuffix(".") { sentence.removeLast() }let rest = String(text[end...]).trimmingCharacters(in: .whitespacesAndNewlines)return (sentence, rest) }/// `text` set in `font` at `width`, at most `limit` lines, each ending/// on a whole word (a word wider than the line alone is broken), its/// paragraphs one a line break, empty ones let go, each after the first/// starting `indent` in.publicstaticfunc lines(_ text: String, font: CTFont, width: CGFloat, limit: Int, indent: CGFloat = 0, set: AttributedString? = nil) -> [TornLine] {let paragraphs = text.split(whereSeparator: \.isNewline) .map { set == nil ? $0.trimmingCharacters(in: .whitespaces) : String($0) } .filter { !$0.isEmpty }guard limit > 0, width > 0, !paragraphs.isEmpty else { return [] }let joined = paragraphs.joined(separator: "\n") as NSStringlet rendered = set.map { value -> AttributedStringinlet plain = String(value.characters)var cursor = plain.startIndexvar out = AttributedString()for paragraph in paragraphs {guardlet range = plain.range(of: paragraph, range: cursor..<plain.endIndex) else { continue }if !out.characters.isEmpty { out += AttributedString("\n") }let from = value.characters.index(value.startIndex, offsetBy: plain.distance(from: plain.startIndex, to: range.lowerBound))let to = value.characters.index(from, offsetBy: plain[range].count) out += AttributedString(value[from..<to]) cursor = range.upperBound }return out }let string = rendered.map { FaceMarkdown.native($0, font: font) } ?? NSAttributedString( string: joined asString, attributes: [NSAttributedString.Key(kCTFontAttributeName asString): font])let setter = CTTypesetterCreateWithAttributedString(string)var lines: [TornLine] = []var start = 0while start < joined.length, lines.count < limit {let opens = start > 0 && joined.character(at: start - 1) == 0x0Alet count = CTTypesetterSuggestLineBreak(setter, start, Double(max(1, width - (opens ? indent : 0))))guard count > 0else { break }let words = joined.substring(with: NSRange(location: start, length: count)).replacingOccurrences(of: #"\s+$"#, with: "", options: .regularExpression)if !words.isEmpty {var line = TornLine(words, indented: opens)iflet rendered {let raw = joined.substring(with: NSRange(location: start, length: count))let skipped = raw.range(of: words).map { raw[..<$0.lowerBound].utf16.count } ?? 0let lower = String.Index(utf16Offset: start + skipped, in: joined asString)let upper = String.Index(utf16Offset: start + skipped + words.utf16.count, in: joined asString)let from = rendered.characters.index(rendered.startIndex, offsetBy: (joined asString).distance(from: (joined asString).startIndex, to: lower))let to = rendered.characters.index(from, offsetBy: (joined asString)[lower..<upper].count) line.setWords = AttributedString(rendered[from..<to]) } lines.append(line) } start += count }return lines }/// The faces the page is written in, at a page `height` points tall.staticfunc fonts(height: CGFloat) -> (title: CTFont, opening: CTFont) {let knobs = NotePageFaceKnobs.self// Asked of CottonFonts first, so the bundled faces are registered// before CoreText is asked for them by name. _ = CottonFonts.caslon(1)return ( CTFontCreateWithName(CottonFonts.caslonFace as CFString, drawable(knobs.titleSize * height), nil), CTFontCreateWithName(CottonFonts.caslonFace as CFString, drawable(knobs.openingSize * height), nil) ) }/// The writing's room across a page `size` points: where it starts and/// how wide it is.staticfunc column(_ size: CGSize) -> (lead: CGFloat, width: CGFloat) {let knobs = NotePageFaceKnobs.selflet lead = (knobs.margin + knobs.lead) * size.widthreturn (lead, size.width * (1 - knobs.trail) - lead) }/// `card` set on a page `size` points: the title on its rules, the date/// on the next, then a rule left bare, then the opening to the last rule.publicstaticfunc set(_ card: DeckCard, size: CGSize, theme: Theme) -> TornPage {let knobs = NotePageFaceKnobs.selflet (title, body) = words(card)let raw = card.text("body") ?? ""let set = FaceMarkdown.set(raw, theme: theme)let marked = String(set.characters) != rawlet setBody = marked ? set : nillet faces = fonts(height: size.height)let column = column(size)let flat = title?.split(whereSeparator: \.isNewline).joined(separator: " ") ?? ""let titleLines = lines(flat, font: faces.title, width: column.width, limit: knobs.titleLines)let titleRules = titleLines.indices.map { knobs.titleRule + $0 * knobs.titleStep }let date = card.text("date").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.flatMap { $0.isEmpty ? nil : $0 }let dateRule = date.map { _ in (titleRules.last ?? knobs.titleRule - 1) + 1 }let openingRule = (dateRule ?? titleRules.last ?? knobs.titleRule - 2) + 2let opening = lines( body, font: faces.opening, width: column.width, limit: max(0, knobs.rules.count - openingRule), indent: knobs.indent * knobs.openingSize * size.height, set: setBody)returnTornPage(title: titleLines, date: date, opening: opening, titleRules: titleRules, dateRule: dateRule, openingRule: openingRule) }}/// The size CottonFonts draws a face at, which a font measured by name must/// match: never under a point.privatefunc drawable(_ points: CGFloat) -> CGFloat { points.isFinite ? max(points, 1) : 1}publicstructNotePageFace: View { @Environment(\.theme) privatevar themelet card: DeckCardpublicinit(card: DeckCard) {self.card = card }publicvar body: someView {let knobs = NotePageFaceKnobs.selfGeometryReader { box in// The clip stands over the page's top: the two are centred// together, so the clip is never cut by the card's room.let over = -knobs.clipToplet height = min(box.size.height * knobs.fillHeight / (1 + over), box.size.width * knobs.fillWidth / knobs.aspect)let size = CGSize(width: height * knobs.aspect, height: height)TornPageSheet(card: card, page: TornPageSetting.set(card, size: size, theme: theme), size: size) .frame(width: size.width, height: size.height) .padding(.top, over * height) .frame(width: box.size.width, height: box.size.height) } }}/// A painted layer of the page, by its catalogue name, at the scale it was/// painted for; nil where this build carries no pictures.privatefunc painted(_ name: String) -> Image? {CottonMedia.image(name, scale: 3)}/// The page lying on the cloth: its shadow, the painted page (or its/// stand-in), the words on its rules, and the clip over its top.privatestructTornPageSheet: View {let card: DeckCardlet page: TornPagelet size: CGSizevar body: someView {let knobs = NotePageFaceKnobs.selflet w = size.widthlet h = size.heightlet reach = knobs.shadowReach * wlet clipHeight = knobs.clipLength * hlet clipWidth = clipHeight * knobs.clipAspectlet column = TornPageSetting.column(size)let rule = { (index: Int) in knobs.rules[min(max(0, index), knobs.rules.count - 1)] * h } ZStack(alignment: .topLeading) {iflet shadow = painted("note-page-shadow") { shadow.resizable().interpolation(.high) .frame(width: w + 2 * reach, height: h + 2 * reach) .offset(x: -reach, y: -reach) .accessibilityHidden(true) }iflet paper = painted("note-page") { paper.resizable().interpolation(.high) .frame(width: w, height: h) .cardPaperLaid() .accessibilityHidden(true) } else {StandInPage(size: size) }Group {if !page.title.isEmpty {Written( lines: page.title, rules: page.titleRules.map(rule), font: CottonFonts.caslon(knobs.titleSize * h), size: knobs.titleSize * h, ink: NotebookMaterial.ink.colour, width: column.width) .accessibilityRepresentation { Text(page.title.map(\.words).joined(separator: " ")) } .accessibilityIdentifier("deck-title") .padding(.leading, column.lead) .padding(.top, rule(page.titleRules[0]) - knobs.titleSize * h * 1.1) }iflet date = page.date, let at = page.dateRule {Written( lines: [TornLine(date)], rules: [rule(at)], font: CottonFonts.type(knobs.dateSize * h), size: knobs.dateSize * h, ink: NotebookMaterial.date.colour, width: column.width, fits: true) .accessibilityRepresentation { Text(date) } .accessibilityIdentifier("note-page-date") .padding(.leading, column.lead) .padding(.top, rule(at) - knobs.dateSize * h * 1.1) }if !page.opening.isEmpty {let indent = knobs.indent * knobs.openingSize * hWritten( lines: page.opening, rules: page.openingRules.map(rule), font: CottonFonts.caslon(knobs.openingSize * h), size: knobs.openingSize * h, ink: NotebookMaterial.ink.colour, width: column.width, indent: indent, setFont: TornPageSetting.fonts(height: h).opening) .accessibilityRepresentation { Text(page.opening.map(\.words).joined(separator: " ")) } .accessibilityIdentifier("note-page-opening") .padding(.leading, column.lead) .padding(.top, rule(page.openingRule) - knobs.openingSize * h * 1.1) } }// Ink soaks into the paper: the words multiply over the paint. .blendMode(.multiply)iflet clip = painted("note-clip") { clip.resizable().interpolation(.high) .frame(width: clipWidth, height: clipHeight) .shadow(color: NotebookMaterial.ink.colour.opacity(0.45), radius: clipWidth * 0.06, x: clipWidth * 0.08, y: clipWidth * 0.12) .rotationEffect(.degrees(knobs.clipTurn)) .offset(x: knobs.clipAcross * w - clipWidth / 2, y: knobs.clipTop * h) .accessibilityHidden(true) } } .frame(width: w, height: h, alignment: .topLeading) .accessibilityElement(children: .contain) .accessibilityIdentifier("note-page") }}/// Lines written on the page's rules: each line's baseline on its rule,/// drawn into a room from just above the first line's letters to just/// under the last's. The diary's page is written with it too.structWritten: View {let lines: [TornLine]/// Each line's rule, from the page's top.let rules: [CGFloat]let font: Fontlet size: CGFloatlet ink: Colorlet width: CGFloatvar indent: CGFloat = 0var setFont: CTFont? = nil/// One line squeezed to the room rather than cut: a date.var fits = falsevar body: someView {let top = (rules.first ?? 0) - size * 1.1let height = (rules.last ?? 0) - top + size * 0.4Canvas { context, room infor (line, rule) in zip(lines, rules) {iflet words = line.setWords, let face = setFont { context.withCGContext { canvas inFaceMarkdown.draw(words, font: face, ink: ink, in: canvas, at: CGPoint(x: line.indented ? indent : 0, y: rule - top - CTFontGetAscent(face))) }continue }let text = context.resolve(Text(line.setWords.map { FaceMarkdown.print($0, size: size, font: font) } ?? AttributedString(line.words)).font(font).foregroundStyle(ink))let ideal = text.measure(in: CGSize(width: 10_000, height: 10_000))var scale: CGFloat = 1if fits, ideal.width > room.width { scale = room.width / ideal.width }let base = text.firstBaseline(in: CGSize(width: 10_000, height: 10_000))let x = line.indented ? indent : 0if scale < 1 { context.translateBy(x: x, y: rule - top) context.scaleBy(x: scale, y: scale) context.draw(text, at: CGPoint(x: 0, y: -base), anchor: .topLeading) context.scaleBy(x: 1 / scale, y: 1 / scale) context.translateBy(x: -x, y: -(rule - top)) } else { context.draw(text, at: CGPoint(x: x, y: rule - top - base), anchor: .topLeading) } } } .frame(width: width, height: max(height, 1)) }}/// The page where this build carries no pictures: its cream, its rules and/// its margin, flat.privatestructStandInPage: View {let size: CGSizevar body: someView {let knobs = NotePageFaceKnobs.selfCanvas { context, room in context.fill(Path(roundedRect: CGRect(origin: .zero, size: room), cornerRadius: room.width * 0.02), with: .color(NotebookMaterial.paper.colour))for share in knobs.rules {let y = share * room.height context.stroke(Path { $0.move(to: CGPoint(x: 0, y: y)); $0.addLine(to: CGPoint(x: room.width, y: y)) }, with: .color(NotebookMaterial.rule.colour), lineWidth: 0.5) }let x = knobs.margin * room.width context.stroke(Path { $0.move(to: CGPoint(x: x, y: 0)); $0.addLine(to: CGPoint(x: x, y: room.height)) }, with: .color(NotebookMaterial.margin.colour), lineWidth: 0.6) } .frame(width: size.width, height: size.height) .accessibilityHidden(true) }}/// The torn page, by its id beside the note's own face, and the notes it is/// reviewed in: invented words only. The specimen world's today is Thursday/// 29 October 2026; a note's date is when it was last written, said as the/// core says it (`weekday_date`), the year only for another year's.publicenumNotePageFaceCatalogue {publicstaticlet stock: FaceStock = .ownpublicstaticlet ground: FaceGround = .feltOrangepublicstaticlet face = Face(id: "note.page", specimens: [Specimen("lake", lake), Specimen("short", short), Specimen("untitled", untitled),Specimen("long-title", longTitle), Specimen("old", old), ], steps: .cut, tagsNoPart: true) { card, _, _ inNotePageFace(card: card) }staticfunc note(_ fields: [String: RecordValue]) -> DeckCard {DeckCard(face: "note.page", corner: nil, pressing: false, pace: nil, plate: nil, fields: fields) }staticfunc date(_ day: String, _ clock: String) -> RecordValue { .text(day + EventWhen.join + clock) }publicstaticlet lake = note(["title": .text("Things the lake taught me"),"date": date("Sun 11 Oct", "7:12 am"),"body": .text(""" I went down to the lake before anyone else was awake, the way I used to when I was small. The water was so still that the far hills stood in it upside down, and for a while I could not tell where the shore ended. I sat on the cold boards of the jetty and did nothing at all. The first thing the lake taught me is that stillness is not the same as emptiness. Under that flat grey skin there was everything: weed leaning in the slow current, small fish turning together, the old posts going down into the dark. The surface only looked empty because it was calm enough to hold the sky. The second thing is that it does not hurry. A heron stood in the shallows for the whole time I was there, and in all that time it moved perhaps three steps. It was not waiting for anything. It was simply where it was, and when the moment came it would know. I want to go back next Sunday, earlier still, and bring nothing to write with. """), ])/// Two sentences: most of the rules left bare.publicstaticlet short = note(["title": .text("Spare key"),"date": date("Wed 28 Oct", "9:40 pm"),"body": .text("The spare key is under the blue pot by the back door, not the green one. Tell Ravi before he leaves on Friday."), ])/// No title: the first sentence stands as one.publicstaticlet untitled = note(["date": date("Tue 27 Oct", "6:05 pm"),"body": .text(""" Buy the blue-black ink before Friday. The shop by the station shuts early for the holidays, so go at lunch. The nib on the old pen is fine, it only wants a night in warm water and a soft cloth. Ask about the converter too, the one that screws in, because the cartridges keep running dry halfway down a page. And a new notebook, ruled, with the paper that does not let the ink through. """), ])/// A title that takes the page's two title lines.publicstaticlet longTitle = note(["title": .text("What the garden needs before the rains come back"),"date": date("Mon 26 Oct", "11:20 am"),"body": .text(""" The roses by the gate want cutting hard, back to three buds on each cane, and the bed under them wants the old mulch raked off. The tap behind the shed drips; a new washer, not a new tap. Move the curry leaf into the big pot before its roots find the drain. Seeds to sow in the first week: coriander, fenugreek, the long beans along the wall. """), ])/// A note from a year ago: its date says the year.publicstaticlet old = note(["title": .text("First week in the new flat"),"date": date("Mon 27 Oct 2025", "8:15 am"),"body": .text(""" The light comes into the kitchen at seven and stays on the table until nine, which is the best thing about this place so far. The second best is the neem outside the bedroom window, full of mynas every evening. Still to do: curtains for the front room, a shelf for the books still in their boxes, and a lamp for the corner where the chair will go. """), ])}