// The core's cut of a face's words into pages (`cards.pages`): the page // cutter the app hands every face (`facePageCutter`, CottonFaces' // `FacePages`), installed wherever the core is (`cottonCore`), and the // note's own cut for the room `NoteRoom` measures (CottonFaces' `NoteCard`). import CottonFaces import CottonKit import SwiftUI /// The core's cut, as a face asks it (`FacePageCutter`). struct CorePageCutter: FacePageCutter { let core: any CottonCalling func cut(_ text: String, columns: Int, first: Int, rest: Int) async -> [NotePage] { await NotePages.cut(core, text: text, columns: columns, first: first, rest: rest) } } /// The core's cut of a note into pages (`cards.pages`) for the room the face /// measured. A core that refuses leaves the whole text as one page. enum NotePages { static func cut(_ core: any CottonCalling, text: String, width: CGFloat, height: CGFloat) async -> [NotePage] { let room = NoteRoom.measure(width: width, height: height) return await cut(core, text: text, columns: room.columns, first: room.first, rest: room.rest) } /// Cut into pages of `first` lines, then `rest`, of `columns` characters /// — never leaving a last page of one lone line: such a cut is asked /// again a line shorter a page, each page handing one on (real-data walk: /// page 3 of a long todo held only "unreviewed."). static func cut(_ core: any CottonCalling, text: String, columns: Int, first: Int, rest: Int) async -> [NotePage] { let pages = await ask(core, text: text, columns: columns, first: first, rest: rest) guard lone(pages, columns: columns), first > 2, rest > 2 else { return pages } let kept = await ask(core, text: text, columns: columns, first: first - 1, rest: rest - 1) return lone(kept, columns: columns) ? pages : kept } /// The last of several pages is a single line. static func lone(_ pages: [NotePage], columns: Int) -> Bool { guard pages.count > 1, let last = pages.last?.text.trimmingCharacters(in: .whitespacesAndNewlines) else { return false } return !last.contains("\n") && last.count <= columns } private static func ask(_ core: any CottonCalling, text: String, columns: Int, first: Int, rest: Int) async -> [NotePage] { let request: [String: Any] = ["text": text, "columns": columns, "first": first, "rest": rest] guard let body = try? JSONSerialization.data(withJSONObject: request), let raw = try? await core.callRaw(CottonMethod.cardsPages, requestJSON: String(decoding: body, as: UTF8.self)), let envelope = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any], envelope["ok"] as? Bool == true, let data = envelope["data"] as? [String: Any], let pages = data["pages"] as? [[String: Any]] else { return [NotePage(text: text, label: "")] } return pages.map { NotePage(text: $0["text"] as? String ?? "", label: $0["label"] as? String ?? "") } } }