Open source CapCut alternative.
TypeScript
feat(ios): rich text notes and a styled teleprompter
David Led718936ce373
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swiftindex b123469b..920beea3 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift@@ -115,11 +115,14 @@ nonisolated public struct Note: Identifiable, Equatable, Sendable {self.updatedAt = updatedAt}- /// The text a teleprompter reads for this note: what is written in it. A- /// title names the note, so it is read only when it is all the note has.+ /// The text a teleprompter reads for this note, in the body's own format:+ /// what is written in it. A title names the note, so it is read only when+ /// it is all the note has.public var script: String {- let written = body.trimmingCharacters(in: .whitespacesAndNewlines)- return written.isEmpty ? title.trimmingCharacters(in: .whitespacesAndNewlines) : written+ let written = NoteMarkdown.plainText(body).trimmingCharacters(in: .whitespacesAndNewlines)+ guard written.isEmpty else { return body }+ let title = title.trimmingCharacters(in: .whitespacesAndNewlines)+ return NoteMarkdown.serialize([NoteBlock(.paragraph, runs: [NoteRun(title)])])}}@@ -540,7 +543,7 @@ public final class IdeasModel {public var hasContent: Bool {!title.trimmingCharacters(in: .whitespaces).isEmpty- || !body.trimmingCharacters(in: .whitespaces).isEmpty+ || !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty}}@@ -574,13 +577,22 @@ public final class IdeasModel {self.draft = draft}- /// Saves the open draft. Returns the saved note, or nil when the draft was empty.+ /// Saves the open draft. Returns the saved note, or nil when the draft was+ /// empty. A draft nobody changed closes without a write, so opening a note+ /// to read it leaves it as the cloud has it.@discardableResultpublic func saveDraft() -> Note? {guard let draft, draft.hasContent else { return nil }let title = draft.title.trimmingCharacters(in: .whitespaces)- let body = draft.body.trimmingCharacters(in: .whitespaces)+ // The body is the editor's own output, and its spaces are markup: the+ // two at the head of a nested list item are its nesting.+ let body = draft.bodylet existing = notes.first(where: { $0.id == draft.id })+ if let existing, existing.title == title, existing.body == body, existing.color == draft.color,+ existing.folderId == draft.folderId, existing.labelIds == draft.labelIds {+ self.draft = nil+ return existing+ }// A stand-in title would be read out by the prompter, so an untitled// note stays untitled and the card shows the placeholder.let note = Note(diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/NoteMarkdown.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/NoteMarkdown.swiftnew file mode 100644index 00000000..a53f61cb--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/NoteMarkdown.swift@@ -0,0 +1,480 @@+import Foundation++// The note body's format: a line-per-block Markdown that the web editor, this+// phone's editor, its teleprompter and the chat all read and write.+//+// Every line is one block, so a note written as plain text — one thought to a+// line — reads exactly as it was typed. A line opens with its block's marker:+//+// # Heading ## Smaller ### Smallest+// - Bullet 1. Numbered - [ ] To-do - [x] Done+// > Quote+//+// List lines nest two spaces per level. Inside a line, **bold**, *italic*,+// ~~strikethrough~~, <u>underline</u> and <span color="red">color</span> style+// the words, and a backslash keeps the next character literal. The site's+// site/src/cut/lib/noteMarkdown.ts is the reference; this file follows it, and a+// change there changes this too.++/// Text colors, by name, with the ink each one takes on the note's paper and+/// on the dark teleprompter.+nonisolated public enum NoteTextColor: String, CaseIterable, Hashable, Sendable {+ case gray, brown, orange, yellow, green, blue, purple, pink, red++ public var name: String { rawValue.capitalized }++ public var paper: String {+ switch self {+ case .gray: "#787774"+ case .brown: "#9f6b53"+ case .orange: "#d9730d"+ case .yellow: "#cb912f"+ case .green: "#448361"+ case .blue: "#337ea9"+ case .purple: "#9065b0"+ case .pink: "#c14c8a"+ case .red: "#d44c47"+ }+ }++ public var dark: String {+ switch self {+ case .gray: "#9b9b9b"+ case .brown: "#ba856f"+ case .orange: "#c77d48"+ case .yellow: "#ca9849"+ case .green: "#529e72"+ case .blue: "#5e87c9"+ case .purple: "#9d68d3"+ case .pink: "#d15796"+ case .red: "#df5452"+ }+ }+}++nonisolated public enum NoteBlockKind: Hashable, Sendable {+ case paragraph+ /// Heading size, 1 to 3.+ case heading(Int)+ case bullet+ case number+ case todo(checked: Bool)+ case quote++ /// Bullets, numbers and to-dos: the kinds that nest.+ public var isList: Bool {+ switch self {+ case .bullet, .number, .todo: true+ case .paragraph, .heading, .quote: false+ }+ }+}++/// The styles a stretch of words wears.+nonisolated public struct NoteMarks: Hashable, Sendable {+ public var bold = false+ public var italic = false+ public var underline = false+ public var strike = false+ public var color: NoteTextColor?++ public init(+ bold: Bool = false,+ italic: Bool = false,+ underline: Bool = false,+ strike: Bool = false,+ color: NoteTextColor? = nil+ ) {+ self.bold = bold+ self.italic = italic+ self.underline = underline+ self.strike = strike+ self.color = color+ }++ public subscript(mark: NoteMark) -> Bool {+ get {+ switch mark {+ case .bold: bold+ case .italic: italic+ case .underline: underline+ case .strike: strike+ }+ }+ set {+ switch mark {+ case .bold: bold = newValue+ case .italic: italic = newValue+ case .underline: underline = newValue+ case .strike: strike = newValue+ }+ }+ }+}++/// The on-or-off styles, for code that flips one of them.+nonisolated public enum NoteMark: CaseIterable, Sendable {+ case bold, italic, underline, strike+}++nonisolated public struct NoteRun: Hashable, Sendable {+ public var text: String+ public var marks: NoteMarks++ public init(_ text: String, _ marks: NoteMarks = NoteMarks()) {+ self.text = text+ self.marks = marks+ }+}++nonisolated public struct NoteBlock: Hashable, Sendable {+ public var kind: NoteBlockKind+ /// List nesting, 0 at the margin. Only list kinds nest.+ public var indent: Int+ public var runs: [NoteRun]++ public init(_ kind: NoteBlockKind, indent: Int = 0, runs: [NoteRun] = []) {+ self.kind = kind+ self.indent = indent+ self.runs = runs+ }++ /// The block's words without their styles.+ public var text: String { runs.map(\.text).joined() }+}++nonisolated public enum NoteMarkdown {+ /// How deep a list nests.+ public static let indentMax = 5++ // MARK: Reading++ /// Read a body into its blocks.+ public static func parse(_ body: String) -> [NoteBlock] {+ body.components(separatedBy: "\n").map(parseLine)+ }++ /// The words of a body with its markup taken out.+ public static func plainText(_ body: String) -> String {+ parse(body).map(\.text).joined(separator: "\n")+ }++ private typealias Scalars = [Unicode.Scalar]++ /// A list line's opening: its nesting, its kind and how many scalars the+ /// marker takes. Mirrors `^((?: {2})*)(?:([-*•]) \[( |x|X)\] |([-*•]) |(\d+)\. )`.+ private static func listMarker(_ s: Scalars) -> (indent: Int, kind: NoteBlockKind, length: Int)? {+ var spaces = 0+ while spaces < s.count, s[spaces] == " " { spaces += 1 }+ // Pairs of spaces only: an odd one out leaves a space where the+ // marker has to be.+ guard spaces % 2 == 0 else { return nil }+ let at = spaces+ func scalar(_ i: Int) -> Unicode.Scalar? { i < s.count ? s[i] : nil }+ let bullets: Set<Unicode.Scalar> = ["-", "*", "•"]+ if let c = scalar(at), bullets.contains(c), scalar(at + 1) == " " {+ if scalar(at + 2) == "[", let box = scalar(at + 3), [" ", "x", "X"].contains(box),+ scalar(at + 4) == "]", scalar(at + 5) == " " {+ return (spaces / 2, .todo(checked: box != " "), at + 6)+ }+ return (spaces / 2, .bullet, at + 2)+ }+ var digits = at+ while let c = scalar(digits), ("0"..."9").contains(c) { digits += 1 }+ if digits > at, scalar(digits) == ".", scalar(digits + 1) == " " {+ return (spaces / 2, .number, digits + 2)+ }+ return nil+ }++ /// A heading line's level and marker length. Mirrors `^(#{1,3}) `.+ private static func headingMarker(_ s: Scalars) -> (level: Int, length: Int)? {+ var hashes = 0+ while hashes < s.count, s[hashes] == "#" { hashes += 1 }+ guard (1...3).contains(hashes), hashes < s.count, s[hashes] == " " else { return nil }+ return (hashes, hashes + 1)+ }++ private static func startsQuote(_ s: Scalars) -> Bool {+ s.count >= 2 && s[0] == ">" && s[1] == " "+ }++ private static func parseLine(_ line: String) -> NoteBlock {+ let s = Array(line.unicodeScalars)+ if let list = listMarker(s) {+ return NoteBlock(+ list.kind,+ indent: min(list.indent, indentMax),+ runs: parseInline(s, from: list.length)+ )+ }+ if let heading = headingMarker(s) {+ return NoteBlock(.heading(heading.level), runs: parseInline(s, from: heading.length))+ }+ if startsQuote(s) { return NoteBlock(.quote, runs: parseInline(s, from: 2)) }+ return NoteBlock(.paragraph, runs: parseInline(s, from: 0))+ }++ private enum Toggle { case bold, italic, strike }+ private enum Tagged { case underline, color }++ private enum Token {+ case text(String)+ case toggle(Toggle, String)+ case open(Tagged, NoteTextColor?, String)+ case close(Tagged, String)++ var source: String {+ switch self {+ case .text(let v), .toggle(_, let v), .open(_, _, let v), .close(_, let v): v+ }+ }+ }++ /// A tag at `i`: what it is and how many scalars it takes. Mirrors+ /// `^<(u|\/u|\/span|span color="([a-z]+)")>`.+ private static func tag(_ s: Scalars, at i: Int) -> (name: String, color: String?, length: Int)? {+ func matches(_ literal: String, at j: Int) -> Bool {+ let l = Array(literal.unicodeScalars)+ guard j + l.count <= s.count else { return false }+ return Array(s[j..<(j + l.count)]) == l+ }+ guard i < s.count, s[i] == "<" else { return nil }+ for name in ["u", "/u", "/span"] where matches(name + ">", at: i + 1) {+ return (name, nil, name.unicodeScalars.count + 2)+ }+ let open = "span color=\""+ guard matches(open, at: i + 1) else { return nil }+ var end = i + 1 + open.unicodeScalars.count+ let start = end+ while end < s.count, ("a"..."z").contains(s[end]) { end += 1 }+ guard end > start, matches("\">", at: end) else { return nil }+ var color = String.UnicodeScalarView()+ color.append(contentsOf: s[start..<end])+ return ("span", String(color), end + 2 - i)+ }++ private static func tokenize(_ s: Scalars, from: Int) -> [Token] {+ var out: [Token] = []+ var text = String.UnicodeScalarView()+ func flush() {+ if !text.isEmpty { out.append(.text(String(text))) }+ text = String.UnicodeScalarView()+ }+ func next(_ i: Int) -> Unicode.Scalar? { i < s.count ? s[i] : nil }+ var i = from+ while i < s.count {+ let c = s[i]+ if c == "\\", i + 1 < s.count {+ text.append(s[i + 1])+ i += 2+ } else if c == "*", next(i + 1) == "*" {+ flush()+ out.append(.toggle(.bold, "**"))+ i += 2+ } else if c == "*" {+ flush()+ out.append(.toggle(.italic, "*"))+ i += 1+ } else if c == "~", next(i + 1) == "~" {+ flush()+ out.append(.toggle(.strike, "~~"))+ i += 2+ } else if let tag = tag(s, at: i) {+ var source = String.UnicodeScalarView()+ source.append(contentsOf: s[i..<(i + tag.length)])+ let literal = String(source)+ if tag.name == "span", NoteTextColor(rawValue: tag.color ?? "") == nil {+ text.append(contentsOf: source)+ } else {+ flush()+ switch tag.name {+ case "u": out.append(.open(.underline, nil, literal))+ case "/u": out.append(.close(.underline, literal))+ case "/span": out.append(.close(.color, literal))+ default: out.append(.open(.color, NoteTextColor(rawValue: tag.color ?? ""), literal))+ }+ }+ i += tag.length+ } else {+ text.append(c)+ i += 1+ }+ }+ flush()+ return out+ }++ /// A line's styled runs. A delimiter with nothing to pair with — the lone+ /// star in "5 * 3" — is read as the text it is.+ public static func parseInline(_ line: String) -> [NoteRun] {+ parseInline(Array(line.unicodeScalars), from: 0)+ }++ private static func parseInline(_ s: Scalars, from: Int) -> [NoteRun] {+ var tokens = tokenize(s, from: from)+ // Toggles pair up in order; an odd one out is literal.+ for mark in [Toggle.bold, .italic, .strike] {+ let at = tokens.indices.filter {+ if case .toggle(let m, _) = tokens[$0] { return m == mark }+ return false+ }+ if at.count % 2 == 1, let last = at.last { tokens[last] = .text(tokens[last].source) }+ }+ // Tags pair open-to-close; a close with nothing open, or an open never+ // closed, is literal.+ for mark in [Tagged.underline, .color] {+ var open: [Int] = []+ for i in tokens.indices {+ switch tokens[i] {+ case .open(let m, _, _) where m == mark:+ open.append(i)+ case .close(let m, let v) where m == mark:+ if open.isEmpty { tokens[i] = .text(v) } else { open.removeLast() }+ default:+ break+ }+ }+ for i in open { tokens[i] = .text(tokens[i].source) }+ }+ var runs: [NoteRun] = []+ var marks = NoteMarks()+ var colors: [NoteTextColor] = []+ var underline = 0+ for token in tokens {+ switch token {+ case .text(let v):+ var now = marks+ now.underline = underline > 0+ now.color = colors.last+ if let last = runs.last, last.marks == now {+ runs[runs.count - 1].text += v+ } else {+ runs.append(NoteRun(v, now))+ }+ case .toggle(.bold, _): marks.bold.toggle()+ case .toggle(.italic, _): marks.italic.toggle()+ case .toggle(.strike, _): marks.strike.toggle()+ case .open(.underline, _, _): underline += 1+ case .open(.color, let color, _): if let color { colors.append(color) }+ case .close(.underline, _): underline -= 1+ case .close(.color, _): _ = colors.popLast()+ }+ }+ return runs+ }++ // MARK: Writing++ /// Write blocks back out as a body. Numbered items count up within their+ /// run at each level.+ public static func serialize(_ blocks: [NoteBlock]) -> String {+ let numbers = numbering(blocks)+ return zip(blocks, numbers).map { block, number in+ let indent = block.kind.isList ? min(max(block.indent, 0), indentMax) : 0+ let pad = String(repeating: " ", count: indent)+ let text = serializeInline(block.runs)+ switch block.kind {+ case .heading(let level):+ return String(repeating: "#", count: min(max(level, 1), 3)) + " " + text+ case .bullet:+ return pad + "- " + text+ case .number:+ return pad + "\(number). " + text+ case .todo(let checked):+ return pad + (checked ? "- [x] " : "- [ ] ") + text+ case .quote:+ return "> " + text+ case .paragraph:+ // A paragraph that starts like a marker keeps its first+ // character literal, so it reads back as the paragraph it is.+ let s = Array(text.unicodeScalars)+ return listMarker(s) != nil || headingMarker(s) != nil || startsQuote(s) ? "\\" + text : text+ }+ }+ .joined(separator: "\n")+ }++ /// The number each block shows: a numbered run restarts after anything+ /// that is not a deeper list line. Zero for blocks that are not numbered.+ public static func numbering(_ blocks: [NoteBlock]) -> [Int] {+ var counts: [Int] = []+ func resize(_ n: Int) {+ if counts.count > n { counts.removeLast(counts.count - n) }+ while counts.count < n { counts.append(0) }+ }+ return blocks.map { block in+ let indent = block.kind.isList ? min(max(block.indent, 0), indentMax) : 0+ if block.kind == .number {+ resize(indent + 1)+ counts[indent] += 1+ return counts[indent]+ }+ resize(block.kind.isList ? indent + 1 : 0)+ if block.kind.isList { counts[indent] = 0 }+ return 0+ }+ }++ private static func escapeText(_ s: String) -> String {+ var out = String.UnicodeScalarView()+ for c in s.unicodeScalars {+ if c == "\\" || c == "*" || c == "~" || c == "<" { out.append("\\") }+ out.append(c)+ }+ return String(out)+ }++ private enum Opened: Equatable {+ case color(NoteTextColor), underline, strike, bold, italic++ var open: String {+ switch self {+ case .color(let c): "<span color=\"\(c.rawValue)\">"+ case .underline: "<u>"+ case .strike: "~~"+ case .bold: "**"+ case .italic: "*"+ }+ }++ var close: String {+ switch self {+ case .color: "</span>"+ case .underline: "</u>"+ default: open+ }+ }+ }++ /// Marks open outside-in in this order and close inside-out, so a run that+ /// shares a mark with the one before it keeps it open across the seam.+ private static func wanted(_ marks: NoteMarks) -> [Opened] {+ var out: [Opened] = []+ if let color = marks.color { out.append(.color(color)) }+ if marks.underline { out.append(.underline) }+ if marks.strike { out.append(.strike) }+ if marks.bold { out.append(.bold) }+ if marks.italic { out.append(.italic) }+ return out+ }++ public static func serializeInline(_ runs: [NoteRun]) -> String {+ var out = ""+ var stack: [Opened] = []+ for run in runs where !run.text.isEmpty {+ let want = wanted(run.marks)+ // Keep the longest prefix of what is open that the run still wears.+ var keep = 0+ while keep < stack.count, keep < want.count, stack[keep] == want[keep] { keep += 1 }+ while stack.count > keep { out += stack.removeLast().close }+ for o in want[keep...] {+ out += o.open+ stack.append(o)+ }+ out += escapeText(run.text)+ }+ while let o = stack.popLast() { out += o.close }+ return out+ }+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/NoteRichText.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/NoteRichText.swiftnew file mode 100644index 00000000..77e3429f--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/NoteRichText.swift@@ -0,0 +1,412 @@+import Foundation++/// A note body as the phone's editor holds it: an attributed text with one+/// line per block, each list or quote line led by a marker the reader sees —+/// "• ", "1. ", "☐ ", "▎ " — and nested lists set in by an em space a level.+///+/// The blocks are the truth. The editor hands back whatever the keyboard made+/// of the text, and `edit(_:to:caret:)` reads that against the blocks it was+/// drawn from: lines the edit never reached keep their block, a new line+/// continues the list it was opened from, and a keystroke into a marker turns+/// the line back into text. What comes out is blocks again, so the body the+/// phone writes is always the dialect.+nonisolated public enum NoteRichText {+ /// One level of list nesting, as the editor shows it.+ public static let indentUnit: Character = "\u{2003}"++ /// What a line shows ahead of its words.+ public static func marker(for block: NoteBlock, number: Int) -> String {+ let pad = String(repeating: indentUnit, count: block.kind.isList ? clampedIndent(block.indent) : 0)+ switch block.kind {+ case .bullet: return pad + ["•", "◦", "▪"][clampedIndent(block.indent) % 3] + " "+ case .number: return pad + "\(number). "+ case .todo(let checked): return pad + (checked ? "☑\u{FE0E} " : "☐ ")+ case .quote: return "▎ "+ case .paragraph, .heading: return ""+ }+ }++ /// The editor's text for these blocks. Words carry `NoteMarksAttribute`;+ /// every character of a line — marker, words and the line break that ends+ /// it — carries `NoteLineAttribute`; marker characters also carry+ /// `NoteMarkerAttribute`.+ public static func attributedText(_ blocks: [NoteBlock]) -> AttributedString {+ var out = AttributedString()+ let numbers = NoteMarkdown.numbering(blocks)+ for (i, block) in blocks.enumerated() {+ let line = NoteLine(kind: block.kind, indent: block.kind.isList ? clampedIndent(block.indent) : 0)+ let marker = marker(for: block, number: numbers[i])+ if !marker.isEmpty {+ var piece = AttributedString(marker)+ piece[NoteLineAttribute.self] = line+ piece[NoteMarkerAttribute.self] = true+ out += piece+ }+ for run in block.runs where !run.text.isEmpty {+ var piece = AttributedString(run.text)+ piece[NoteLineAttribute.self] = line+ piece[NoteMarksAttribute.self] = run.marks+ out += piece+ }+ if i < blocks.count - 1 {+ var piece = AttributedString("\n")+ piece[NoteLineAttribute.self] = line+ out += piece+ }+ }+ return out+ }++ // MARK: Reading an edit++ /// Read the editor's text back into blocks. `blocks` is what the text was+ /// drawn from; `text` is what the keyboard made of it, with each+ /// character's styles already read into `NoteMarksAttribute`. `caret` is+ /// where the insertion point sits after the edit, which settles which of+ /// two identical characters was typed. The result's cursor is where the+ /// insertion point belongs in the text the new blocks draw.+ public static func edit(_ blocks: [NoteBlock], to text: AttributedString, caret: Int? = nil) -> NoteEdit {+ let old = blocks.isEmpty ? [NoteBlock(.paragraph)] : blocks+ let numbers = NoteMarkdown.numbering(old)+ var oldChars: [Character] = []+ var starts: [Int] = []+ var markerLengths: [Int] = []+ for (i, block) in old.enumerated() {+ if i > 0 { oldChars.append("\n") }+ starts.append(oldChars.count)+ let marker = Array(marker(for: block, number: numbers[i]))+ markerLengths.append(marker.count)+ oldChars += marker+ oldChars += Array(block.text)+ }+ func lineEnd(_ i: Int) -> Int { i + 1 < starts.count ? starts[i + 1] - 1 : oldChars.count }+ func line(at offset: Int) -> Int { starts.lastIndex(where: { $0 <= offset }) ?? 0 }++ var chars: [Character] = []+ var marks: [NoteMarks] = []+ for run in text.runs {+ let m = run[NoteMarksAttribute.self] ?? NoteMarks()+ for ch in text[run.range].characters {+ chars.append(isLineBreak(ch) ? "\n" : ch)+ marks.append(m)+ }+ }+ func runs(_ pieces: [Range<Int>]) -> [NoteRun] {+ var out: [NoteRun] = []+ for piece in pieces {+ for i in piece {+ if let last = out.last, last.marks == marks[i] {+ out[out.count - 1].text.append(chars[i])+ } else {+ out.append(NoteRun(String(chars[i]), marks[i]))+ }+ }+ }+ return out+ }++ let change = changedRange(old: oldChars, new: chars, caret: caret)+ let p = change.start, oldEnd = change.oldEnd, newEnd = change.newEnd+ let delta = chars.count - oldChars.count+ let first = line(at: p), last = line(at: oldEnd)+ let start0 = starts[first], markerEnd0 = start0 + markerLengths[first]+ let base = old[first]+ let inserted = chars[p..<newEnd]+ let pureInsertion = oldEnd == p++ func untouched(_ i: Int, shift: Int) -> NoteBlock {+ NoteBlock(old[i].kind, indent: old[i].indent, runs: runs([(starts[i] + markerLengths[i] + shift)..<(lineEnd(i) + shift)]))+ }+ let before = (0..<first).map { untouched($0, shift: 0) }+ let after = ((last + 1)..<old.count).map { untouched($0, shift: delta) }++ // Return on an empty list item or quote ends it: the line steps out a+ // level, or back to text at the margin, and no line is added.+ if pureInsertion, Array(inserted) == ["\n"], base.kind.isList || base.kind == .quote,+ first == last, lineEnd(first) == markerEnd0, p == markerEnd0 {+ let stepped = base.kind.isList && base.indent > 0+ ? NoteBlock(base.kind, indent: base.indent - 1)+ : NoteBlock(.paragraph)+ let result = before + [stepped] + after+ return NoteEdit(blocks: result, cursor: offset(line: first, content: 0, in: result))+ }++ // Typing a marker and a space at the head of a line makes the block it+ // names, the way the web editor does.+ if pureInsertion, Array(inserted) == [" "], first == last, p >= markerEnd0,+ let kind = shortcut(String(chars[markerEnd0..<newEnd]), on: base.kind) {+ let block = NoteBlock(+ kind,+ indent: base.kind.isList && kind.isList ? base.indent : 0,+ runs: runs([newEnd..<(lineEnd(first) + delta)])+ )+ let result = before + [block] + after+ return NoteEdit(blocks: result, cursor: offset(line: first, content: 0, in: result))+ }++ // Markers are drawn from the blocks, so the span's own are dropped:+ // the first line's, or what the edit left of its head, and what it+ // left of the tail of the last line's.+ let insideMarker = p < markerEnd0+ var dropped: [Range<Int>] = [start0..<min(p, markerEnd0)]+ let markerEndLast = starts[last] + markerLengths[last]+ if oldEnd < markerEndLast { dropped.append(newEnd..<(newEnd + markerEndLast - oldEnd)) }+ // Deleting into a marker steps a nested item out a level and takes+ // anything else back to text; typing inside one types at the head of+ // the line's words.+ var firstKind = base.kind, firstIndent = base.indent+ if insideMarker && !pureInsertion {+ if base.kind.isList, base.indent > 0, first == last, newEnd == p {+ firstIndent -= 1+ } else {+ firstKind = .paragraph+ firstIndent = 0+ }+ }++ let spanEnd = lineEnd(last) + delta+ var segments: [(range: Range<Int>, pieces: [Range<Int>])] = []+ var segmentStart = start0+ for i in start0...spanEnd where i == spanEnd || chars[i] == "\n" {+ let range = segmentStart..<i+ var pieces: [Range<Int>] = [range]+ for cut in dropped {+ pieces = pieces.flatMap { piece -> [Range<Int>] in+ guard piece.overlaps(cut) else { return [piece] }+ return [piece.lowerBound..<cut.lowerBound, cut.upperBound..<piece.upperBound].filter { !$0.isEmpty }+ }+ }+ segments.append((range, pieces))+ segmentStart = i + 1+ }++ // A line opened from a list item is another item; from anything else+ // it is text. A heading split in the middle stays a heading on both+ // sides.+ let continued: NoteBlockKind = switch firstKind {+ case .bullet, .number: firstKind+ case .todo: .todo(checked: false)+ case .quote: .quote+ case .heading, .paragraph: .paragraph+ }+ let splitMidHeading = first == last && oldEnd < lineEnd(first) && {+ if case .heading = firstKind { return true }+ return false+ }()+ var span: [NoteBlock] = []+ for (index, segment) in segments.enumerated() {+ let isFirst = index == 0+ let keepsHeading = index == segments.count - 1 && splitMidHeading+ let kind = isFirst || keepsHeading ? firstKind : continued+ span.append(NoteBlock(kind, indent: kind.isList ? firstIndent : 0, runs: runs(segment.pieces)))+ }+ let result = before + span + after++ // The insertion point lands after what was typed, counted in the words+ // that survive on its line.+ var cursorLine = first, cursorContent = 0+ for (index, segment) in segments.enumerated()+ where segment.range.lowerBound <= newEnd && newEnd <= segment.range.upperBound {+ cursorLine = first + index+ cursorContent = segment.pieces.reduce(0) { $0 + max(0, min($1.upperBound, newEnd) - $1.lowerBound) }+ break+ }+ return NoteEdit(blocks: result, cursor: offset(line: cursorLine, content: cursorContent, in: result))+ }++ /// The block a typed marker names: "- ", "1. ", "[ ] ", "# ", "> ".+ private static func shortcut(_ typed: String, on kind: NoteBlockKind) -> NoteBlockKind? {+ let todo: [String: NoteBlockKind] = [+ "[] ": .todo(checked: false), "[ ] ": .todo(checked: false),+ "[x] ": .todo(checked: true), "[X] ": .todo(checked: true),+ ]+ if kind == .bullet { return todo[typed] }+ guard kind == .paragraph else { return nil }+ if let found = todo[typed] { return found }+ switch typed {+ case "- ", "* ", "• ": return .bullet+ case "# ": return .heading(1)+ case "## ": return .heading(2)+ case "### ": return .heading(3)+ case "> ": return .quote+ default: break+ }+ let digits = typed.dropLast(2)+ if typed.hasSuffix(". "), !digits.isEmpty, digits.allSatisfy({ $0.isASCII && $0.isNumber }) { return .number }+ return nil+ }++ private static func isLineBreak(_ ch: Character) -> Bool {+ ch == "\n" || ch == "\r\n" || ch == "\r" || ch == "\u{2028}" || ch == "\u{2029}"+ }++ /// Where the old and new characters differ: from `start` to `oldEnd` in+ /// the old, to `newEnd` in the new. A pure insertion or deletion between+ /// repeated characters could sit at several places; the caret picks one,+ /// and without it the earliest stands.+ private static func changedRange(old: [Character], new: [Character], caret: Int?) -> (start: Int, oldEnd: Int, newEnd: Int) {+ var prefix = 0+ while prefix < old.count, prefix < new.count, old[prefix] == new[prefix] { prefix += 1 }+ var suffix = 0+ while suffix < old.count, suffix < new.count, old[old.count - 1 - suffix] == new[new.count - 1 - suffix] { suffix += 1 }+ let shorter = min(old.count, new.count)+ if prefix + suffix >= shorter, old.count != new.count {+ // One side is the other with a stretch added: any start from the+ // earliest the suffix allows to the latest the prefix allows.+ let length = abs(new.count - old.count)+ let earliest = max(0, shorter - suffix)+ let latest = min(prefix, shorter)+ var start = earliest+ if let caret {+ let wanted = new.count > old.count ? caret - length : caret+ if (earliest...latest).contains(wanted) { start = wanted }+ }+ return new.count > old.count+ ? (start, start, start + length)+ : (start, start + length, start)+ }+ let start = prefix+ let common = min(suffix, shorter - prefix)+ return (start, old.count - common, new.count - common)+ }++ // MARK: Positions++ private static func clampedIndent(_ indent: Int) -> Int { min(max(indent, 0), NoteMarkdown.indentMax) }++ /// The line an offset in the editor's text falls on, and how far into+ /// that line's words it sits. An offset inside a marker counts as the+ /// head of the words.+ public static func position(of offset: Int, in blocks: [NoteBlock]) -> (line: Int, content: Int) {+ let numbers = NoteMarkdown.numbering(blocks)+ var start = 0+ for (i, block) in blocks.enumerated() {+ let marker = marker(for: block, number: numbers[i]).count+ let length = block.text.count+ if offset <= start + marker + length || i == blocks.count - 1 {+ return (i, min(max(offset - start - marker, 0), length))+ }+ start += marker + length + 1+ }+ return (0, 0)+ }++ /// The offset in the editor's text of a point in a line's words.+ public static func offset(line: Int, content: Int, in blocks: [NoteBlock]) -> Int {+ let numbers = NoteMarkdown.numbering(blocks)+ var start = 0+ for (i, block) in blocks.enumerated() {+ let marker = marker(for: block, number: numbers[i]).count+ if i == line { return start + marker + min(max(content, 0), block.text.count) }+ start += marker + block.text.count + 1+ }+ return start+ }++ // MARK: Changing blocks++ /// Turn lines into another kind of block. Lists keep their nesting when+ /// they stay lists.+ public static func setting(_ kind: NoteBlockKind, lines: ClosedRange<Int>, of blocks: [NoteBlock]) -> [NoteBlock] {+ var out = blocks+ for i in lines where out.indices.contains(i) {+ out[i].indent = kind.isList && out[i].kind.isList ? out[i].indent : 0+ out[i].kind = kind+ }+ return out+ }++ /// Nest list lines a level deeper, or bring them a level out.+ public static func indenting(lines: ClosedRange<Int>, by step: Int, of blocks: [NoteBlock]) -> [NoteBlock] {+ var out = blocks+ for i in lines where out.indices.contains(i) && out[i].kind.isList {+ out[i].indent = clampedIndent(out[i].indent + step)+ }+ return out+ }++ /// The marks on every character between two offsets.+ public static func marks(from start: Int, to end: Int, in blocks: [NoteBlock]) -> [NoteMarks] {+ var out: [NoteMarks] = []+ forEachCharacter(from: start, to: end, in: blocks) { out.append($0) }+ return out+ }++ /// Restyle the words between two offsets. Markers and line breaks in the+ /// range are passed over.+ public static func restyling(+ from start: Int,+ to end: Int,+ in blocks: [NoteBlock],+ _ change: (inout NoteMarks) -> Void+ ) -> [NoteBlock] {+ let a = position(of: start, in: blocks), b = position(of: end, in: blocks)+ guard a.line < b.line || (a.line == b.line && a.content < b.content) else { return blocks }+ var out = blocks+ for line in a.line...b.line {+ let from = line == a.line ? a.content : 0+ let to = line == b.line ? b.content : out[line].text.count+ var chars: [(Character, NoteMarks)] = out[line].runs.flatMap { run in run.text.map { ($0, run.marks) } }+ for i in from..<min(to, chars.count) { change(&chars[i].1) }+ var runs: [NoteRun] = []+ for (ch, marks) in chars {+ if let last = runs.last, last.marks == marks {+ runs[runs.count - 1].text.append(ch)+ } else {+ runs.append(NoteRun(String(ch), marks))+ }+ }+ out[line].runs = runs+ }+ return out+ }++ private static func forEachCharacter(from start: Int, to end: Int, in blocks: [NoteBlock], _ body: (NoteMarks) -> Void) {+ let a = position(of: start, in: blocks), b = position(of: end, in: blocks)+ guard a.line <= b.line else { return }+ for line in a.line...b.line {+ let from = line == a.line ? a.content : 0+ let to = line == b.line ? b.content : blocks[line].text.count+ var index = 0+ for run in blocks[line].runs {+ for _ in run.text {+ if index >= from, index < to { body(run.marks) }+ index += 1+ }+ }+ }+ }+}++/// What an edit made of the note: its blocks, and where the insertion point+/// belongs in the text they draw.+nonisolated public struct NoteEdit: Equatable, Sendable {+ public var blocks: [NoteBlock]+ public var cursor: Int+}++/// A line's block, as the editor's text carries it.+nonisolated public struct NoteLine: Hashable, Sendable {+ public var kind: NoteBlockKind+ public var indent: Int++ public init(kind: NoteBlockKind, indent: Int) {+ self.kind = kind+ self.indent = indent+ }+}++nonisolated public enum NoteMarksAttribute: AttributedStringKey {+ public typealias Value = NoteMarks+ public static let name = "DonkeyNoteMarks"+}++nonisolated public enum NoteLineAttribute: AttributedStringKey {+ public typealias Value = NoteLine+ public static let name = "DonkeyNoteLine"+}++nonisolated public enum NoteMarkerAttribute: AttributedStringKey {+ public typealias Value = Bool+ public static let name = "DonkeyNoteMarker"+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swiftindex 2eb0040e..8cbd392b 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift@@ -16,59 +16,119 @@ nonisolated public struct TeleprompterSettings: Equatable, Codable, Sendable {}}-/// Prompter copy from a raw note, broken into the lines the screen draws.+/// One block of prompter copy, broken into the lines the screen draws. The+/// block's marker — a bullet, a number, a box — leads its first line.+nonisolated public struct PacedBlock: Equatable, Sendable {+ public var kind: NoteBlockKind+ public var lines: [[NoteRun]]++ public init(kind: NoteBlockKind, lines: [[NoteRun]]) {+ self.kind = kind+ self.lines = lines+ }+}++/// Prompter copy from a note's body, broken into the lines the screen draws.///-/// Spacing is the prompter's job: runs of spaces collapse and the writer's-/// own line breaks hold as paragraph breaks, so nobody has to format a note-/// to read it. Inside a paragraph, words stay together while they fit — a-/// line ends where the next word would run off the picture, and a short-/// clause shares its line with what follows it.+/// Spacing is the prompter's job: runs of spaces collapse and every block of+/// the note is its own paragraph, so nobody has to format a note to read it.+/// The words keep their styles. Inside a paragraph, words stay together while+/// they fit — a line ends where the next word would run off the picture, and a+/// short clause shares its line with what follows it. Blocks with no words in+/// them are left out.////// The measurer belongs to the caller, so the words are measured on the face-/// and the size they will be drawn in. `room` is the width they are drawn in,-/// in whatever unit that measurer answers in.+/// and the size they will be drawn in: it gets a line's runs and the block+/// they sit in. `room` is the width they are drawn in, in whatever unit that+/// measurer answers in.nonisolated public func pacedScript(- _ raw: String,+ _ script: String,room: Double,- measure: (String) -> Double-) -> String {- let paragraphs = raw- .trimmingCharacters(in: .whitespacesAndNewlines)- .split(separator: "\n", omittingEmptySubsequences: true)- .map { pacedParagraph(String($0), room: room, measure: measure) }- .filter { !$0.isEmpty }- return paragraphs.joined(separator: "\n\n")+ measure: ([NoteRun], NoteBlockKind) -> Double+) -> [PacedBlock] {+ let blocks = NoteMarkdown.parse(script)+ let numbers = NoteMarkdown.numbering(blocks)+ return zip(blocks, numbers).compactMap { block, number in+ let lines = pacedLines(+ block,+ marker: NoteRichText.marker(for: block, number: number),+ room: room,+ measure: { measure($0, block.kind) }+ )+ return lines.isEmpty ? nil : PacedBlock(kind: block.kind, lines: lines)+ }}-private nonisolated func pacedParagraph(- _ text: String,+private nonisolated func pacedLines(+ _ block: NoteBlock,+ marker: String,room: Double,- measure: (String) -> Double-) -> String {- let words = text.split(whereSeparator: { $0.isWhitespace }).map(String.init)- // No room to speak of: the paragraph is one line and the screen decides- // where it falls.- guard room > 0 else { return words.joined(separator: " ") }- var lines: [String] = []- var line = ""- for word in words {- let candidate = line.isEmpty ? word : "\(line) \(word)"- // A word wider than the room takes its own line whole; breaking it- // would leave the reader with half a word.- if !line.isEmpty, measure(candidate) > room {+ measure: ([NoteRun]) -> Double+) -> [[NoteRun]] {+ typealias Styled = [(Character, NoteMarks)]+ // The words, each with the marks of its characters, and the marks of the+ // space that went before each one.+ var words: [Styled] = []+ var gaps: [NoteMarks] = []+ var word: Styled = []+ var gap: NoteMarks?+ for run in block.runs {+ for ch in run.text {+ if ch.isWhitespace {+ if !word.isEmpty {+ words.append(word)+ word = []+ }+ if gap == nil { gap = run.marks }+ } else {+ if word.isEmpty {+ gaps.append(gap ?? NoteMarks())+ gap = nil+ }+ word.append((ch, run.marks))+ }+ }+ }+ if !word.isEmpty { words.append(word) }+ guard !words.isEmpty else { return [] }++ func runs(_ styled: Styled) -> [NoteRun] {+ var out: [NoteRun] = []+ for (ch, marks) in styled {+ if let last = out.last, last.marks == marks {+ out[out.count - 1].text.append(ch)+ } else {+ out.append(NoteRun(String(ch), marks))+ }+ }+ return out+ }++ let lead: Styled = marker.map { ($0, NoteMarks()) }+ var lines: [Styled] = []+ var line = lead+ var lineHasWords = false+ for (index, word) in words.enumerated() {+ let candidate = lineHasWords ? line + [(" ", gaps[index])] + word : line + word+ // No room to speak of: the paragraph is one line and the screen+ // decides where it falls. A word wider than the room takes its own+ // line whole; breaking it would leave the reader with half a word.+ if room > 0, lineHasWords, measure(runs(candidate)) > room {lines.append(line)line = word} else {line = candidate}+ lineHasWords = true}- if !line.isEmpty { lines.append(line) }- return lines.joined(separator: "\n")+ lines.append(line)+ return lines.map(runs)}-/// How long the script takes to read aloud at the given pace.+/// How long the script takes to read aloud at the given pace: its words, with+/// the markup taken out.nonisolated public func readDuration(of script: String, wordsPerMinute: Double) -> TimeInterval {- let words = script.split(whereSeparator: { $0.isWhitespace }).count+ let words = NoteMarkdown.plainText(script).split(whereSeparator: { $0.isWhitespace }).countguard words > 0, wordsPerMinute > 0 else { return 0 }return Double(words) / wordsPerMinute * 60}@@ -91,12 +151,12 @@ nonisolated public struct TeleprompterState: Equatable, Sendable {public init() {}public var hasScript: Bool {- !script.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ !NoteMarkdown.plainText(script).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty}- /// The text the overlay renders: the raw script, broken to the room the- /// screen gives it.- public func displayScript(room: Double, measure: (String) -> Double) -> String {+ /// The copy the overlay renders: the script's blocks, broken to the room+ /// the screen gives them.+ public func displayScript(room: Double, measure: ([NoteRun], NoteBlockKind) -> Double) -> [PacedBlock] {pacedScript(script, room: room, measure: measure)}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swiftindex 8582bba8..118babe5 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift@@ -659,6 +659,18 @@ struct TeleprompterCard: View {@Binding var showsSettings: Boollet onUseNote: () -> Void+ @State private var editing: NoteBodyEditing+ @FocusState private var editingScript: Bool++ init(camera: CameraModel, showsSettings: Binding<Bool>, onUseNote: @escaping () -> Void) {+ self.camera = camera+ _showsSettings = showsSettings+ self.onUseNote = onUseNote+ _editing = State(initialValue: NoteBodyEditing(body: camera.teleprompter.script, look: .scriptCard) { [camera] script in+ camera.teleprompter.script = script+ })+ }+var body: some View {VStack(alignment: .leading, spacing: 8) {// The card's controls ride the top row: the camera rail runs up the@@ -700,20 +712,24 @@ struct TeleprompterCard: View {}}.font(.body.weight(.semibold))- TextEditor(text: $camera.teleprompter.script)- .font(.system(size: 19, weight: .semibold))+ // The script is a note's body, styles and all, and edits the same+ // way the note does.+ NoteBodyEditor(editing: editing, placeholder: "Add your script here...").scrollContentBackground(.hidden).frame(minHeight: 96, maxHeight: 160)- .overlay(alignment: .topLeading) {- if camera.teleprompter.script.isEmpty {- Text("Add your script here...")- .font(.system(size: 19, weight: .semibold))- .foregroundStyle(.secondary)- .padding(.top, 8)- .padding(.leading, 5)- .allowsHitTesting(false)- }- }+ .focused($editingScript)+ }+ // A note picked while the card is up replaces the script under it.+ .onChange(of: camera.teleprompter.script) { _, script in+ if script != editing.body { editing.load(script) }+ }+ .toolbar {+ ToolbarItemGroup(placement: .keyboard) {+ NoteFormatControls(editing: editing)+ Spacer()+ Button("Done") { editingScript = false }+ .font(.body.weight(.bold))+ }}.foregroundStyle(.white).padding(14)@@ -766,24 +782,26 @@ struct TeleprompterOverlay: View {/// Margin each side of the script.private static var sidePadding: Double { 24 }+ /// The face the script draws in, at the reader's size. Headings draw+ /// larger, styled words in their own weight, slant and color.+ private var look: NoteLook { .prompter(size: camera.teleprompter.settings.textSize) }+/// The script broken to the width it is drawn in, measured on the very- /// face and size it will be drawn in. A line holds as many words as the+ /// faces and sizes it will be drawn in. A line holds as many words as the/// picture has room for, so a short clause reads on one line with what/// follows it. The last point of the width is left to the layout, so a/// line measured here as fitting is never broken again as it draws.- private func script(room: Double) -> String {- let font = UIFont.systemFont(- ofSize: camera.teleprompter.settings.textSize,- weight: .heavy- )- return camera.teleprompter.displayScript(room: room - 1) { line in- (line as NSString).size(withAttributes: [.font: font]).width+ private func script(room: Double) -> AttributedString {+ let look = look+ let paced = camera.teleprompter.displayScript(room: room - 1) { runs, kind in+ look.width(runs, kind)}+ return look.text(paced)}- private func scriptText(_ text: String) -> some View {+ private func scriptText(_ text: AttributedString) -> some View {Text(text)- .font(.system(size: camera.teleprompter.settings.textSize, weight: .heavy))+ .font(look.font(.paragraph, NoteMarks())).foregroundStyle(.white).lineSpacing(4).shadow(color: .black.opacity(0.7), radius: 6, y: 1)diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swiftindex 63ca3020..7528e093 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift@@ -612,7 +612,9 @@ struct NoteCard: View {Text(note.title).font(.subheadline.weight(.bold))}- Text(note.body)+ // The body in its own styles: headings, lists and colored words+ // read on the card as they do in the note.+ Text(NoteLook.card.text(NoteMarkdown.parse(note.body))).font(.footnote).opacity(0.75).lineLimit(8)diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteBodyEditor.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteBodyEditor.swiftnew file mode 100644index 00000000..e8118752--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteBodyEditor.swift@@ -0,0 +1,338 @@+#if os(iOS)+import SwiftUI+import DonkeyKitModels++/// The state of a note body being edited as rich text: the blocks, the+/// attributed text the editor shows for them, and the selection in it.+///+/// Every edit runs one way. The keyboard or the system's format menu changes+/// the text; the styles are read back off its fonts and decorations; the+/// blocks take the edit; and when the blocks draw differently from what the+/// editor holds — a marker to add, a face to put back — the text is redrawn+/// and the insertion point put where the edit left it. The body is written+/// from the blocks, so it is always the dialect. A body nobody changed is+/// handed back exactly as it came in, whatever the editor would have written.+@MainActor+@Observable+final class NoteBodyEditing {+ var text: AttributedString+ var selection = AttributedTextSelection()+ private(set) var blocks: [NoteBlock]+ /// The body as it stands, in the note format.+ private(set) var body: String++ let look: NoteLook+ @ObservationIgnored private let onChange: (String) -> Void+ /// The body as loaded, and what the editor writes for it untouched.+ @ObservationIgnored private var loaded = ""+ @ObservationIgnored private var loadedAsWritten = ""+ /// The text last drawn here, so a change that is only that drawing+ /// landing in the editor is not read back as an edit.+ @ObservationIgnored private var drawn = AttributedString()++ init(body: String, look: NoteLook, onChange: @escaping (String) -> Void) {+ self.look = look+ self.onChange = onChange+ self.body = body+ self.blocks = []+ self.text = AttributedString()+ load(body)+ }++ /// Show a body that came from elsewhere: a note picked into the+ /// prompter, say.+ func load(_ body: String) {+ loaded = body+ blocks = NoteMarkdown.parse(body)+ loadedAsWritten = NoteMarkdown.serialize(blocks)+ self.body = body+ drawn = look.text(blocks)+ text = drawn+ selection = AttributedTextSelection()+ // An empty body has no words to take a face from, so the first+ // keystroke is set to type in the body's own.+ if text.characters.isEmpty { place(caret: 0) }+ }++ /// The block the insertion point sits in.+ var currentBlock: NoteBlock? {+ let line = NoteRichText.position(of: selectedOffsets().upperBound, in: blocks).line+ return blocks.indices.contains(line) ? blocks[line] : nil+ }++ /// Read what the editor made of the text back into blocks.+ func textChanged(in context: Font.Context) {+ guard text != drawn else { return }+ var read = AttributedString()+ for run in text.runs {+ var piece = AttributedString(text[run.range])+ piece[NoteMarksAttribute.self] = look.marks(of: run.attributes, in: context)+ read += piece+ }+ let selected = selectedOffsets()+ let before = blocks.count+ let edit = NoteRichText.edit(blocks, to: read, caret: selected.upperBound)+ blocks = edit.blocks+ let fresh = look.text(blocks)+ let sameCharacters = String(fresh.characters) == String(text.characters)+ if sameCharacters, look.appearance(of: fresh, in: context) == look.appearance(of: text, in: context) {+ drawn = text+ // A line break leaves the next character to be typed in the face+ // of the line above; the new line's own face goes in its place.+ if blocks.count != before { place(caret: edit.cursor) }+ } else {+ drawn = fresh+ text = fresh+ if sameCharacters {+ select(selected)+ } else {+ place(caret: edit.cursor)+ }+ }+ publish()+ }++ // MARK: Formatting++ func setKind(_ kind: NoteBlockKind) {+ changeLines { NoteRichText.setting(kind, lines: $1, of: $0) }+ }++ func indent(by step: Int) {+ changeLines { NoteRichText.indenting(lines: $1, by: step, of: $0) }+ }++ /// Check a to-do off, or open it again.+ func toggleChecked() {+ changeLines { blocks, lines in+ var out = blocks+ for i in lines {+ if case .todo(let checked) = out[i].kind { out[i].kind = .todo(checked: !checked) }+ }+ return out+ }+ }++ /// Whether every selected character wears a mark — or, with nothing+ /// selected, whether the next one typed will.+ func isMarked(_ mark: NoteMark, in context: Font.Context) -> Bool {+ let range = selectedOffsets()+ if range.isEmpty { return typingMarks(in: context)[mark] }+ return NoteRichText.marks(from: range.lowerBound, to: range.upperBound, in: blocks).allSatisfy { $0[mark] }+ }++ func toggle(_ mark: NoteMark, in context: Font.Context) {+ let on = !isMarked(mark, in: context)+ restyle(in: context) { $0[mark] = on }+ }++ func setColor(_ color: NoteTextColor?, in context: Font.Context) {+ restyle(in: context) { $0.color = color }+ }++ private func restyle(in context: Font.Context, _ change: @escaping (inout NoteMarks) -> Void) {+ let range = selectedOffsets()+ if range.isEmpty {+ var marks = typingMarks(in: context)+ change(&marks)+ place(caret: range.lowerBound, marks: marks)+ return+ }+ blocks = NoteRichText.restyling(from: range.lowerBound, to: range.upperBound, in: blocks, change)+ redraw()+ select(range)+ publish()+ }++ /// Apply a change to the lines the selection touches, keeping the+ /// selection on the same words.+ private func changeLines(_ change: ([NoteBlock], ClosedRange<Int>) -> [NoteBlock]) {+ let range = selectedOffsets()+ let start = NoteRichText.position(of: range.lowerBound, in: blocks)+ let end = NoteRichText.position(of: range.upperBound, in: blocks)+ blocks = change(blocks, start.line...end.line)+ redraw()+ select(+ NoteRichText.offset(line: start.line, content: start.content, in: blocks)+ ..< NoteRichText.offset(line: end.line, content: end.content, in: blocks)+ )+ publish()+ }++ private func redraw() {+ drawn = look.text(blocks)+ text = drawn+ }++ private func publish() {+ let written = NoteMarkdown.serialize(blocks)+ body = written == loadedAsWritten ? loaded : written+ onChange(body)+ }++ // MARK: Selection++ private func offset(of index: AttributedString.Index) -> Int {+ text.characters.distance(from: text.startIndex, to: index)+ }++ private func index(at offset: Int) -> AttributedString.Index {+ text.characters.index(text.startIndex, offsetBy: min(max(offset, 0), text.characters.count))+ }++ private func selectedOffsets() -> Range<Int> {+ switch selection.indices(in: text) {+ case .insertionPoint(let index):+ let at = offset(of: index)+ return at..<at+ case .ranges(let ranges):+ guard let first = ranges.ranges.first, let last = ranges.ranges.last else { return 0..<0 }+ return offset(of: first.lowerBound)..<offset(of: last.upperBound)+ }+ }++ private func select(_ range: Range<Int>) {+ if range.isEmpty {+ place(caret: range.lowerBound)+ } else {+ selection = AttributedTextSelection(range: index(at: range.lowerBound)..<index(at: range.upperBound))+ }+ }++ /// Put the insertion point at an offset, set to type in the face of the+ /// words before it on its line — or plain, at the head of a line.+ private func place(caret: Int, marks: NoteMarks? = nil) {+ let position = NoteRichText.position(of: caret, in: blocks)+ guard blocks.indices.contains(position.line) else { return }+ let block = blocks[position.line]+ let typing = marks ?? (position.content > 0+ ? NoteRichText.marks(from: caret - 1, to: caret, in: blocks).first ?? NoteMarks()+ : NoteMarks())+ selection = AttributedTextSelection(+ insertionPoint: index(at: caret),+ typingAttributes: look.attributes(block.kind, typing)+ )+ }++ private func typingMarks(in context: Font.Context) -> NoteMarks {+ look.marks(of: selection.typingAttributes(in: text), in: context)+ }+}++/// The note body as rich text, over a placeholder while it is empty.+struct NoteBodyEditor: View {+ @Bindable var editing: NoteBodyEditing+ var placeholder: String++ @Environment(\.fontResolutionContext) private var fontContext++ var body: some View {+ TextEditor(text: $editing.text, selection: $editing.selection)+ .font(editing.look.font(.paragraph, NoteMarks()))+ .onChange(of: editing.text) { editing.textChanged(in: fontContext) }+ .overlay(alignment: .topLeading) {+ if editing.text.characters.isEmpty {+ Text(placeholder)+ .font(editing.look.font(.paragraph, NoteMarks()))+ .opacity(0.4)+ .padding(.horizontal, 5)+ .padding(.top, 8)+ .allowsHitTesting(false)+ }+ }+ }+}++/// The formatting controls for a note body: the block the lines are, the+/// styles the words wear, and their color. They ride the keyboard.+struct NoteFormatControls: View {+ var editing: NoteBodyEditing++ @Environment(\.fontResolutionContext) private var fontContext++ private struct Kind {+ var name: String+ var symbol: String+ var kind: NoteBlockKind+ }++ private static let kinds = [+ Kind(name: "Text", symbol: "text.alignleft", kind: .paragraph),+ Kind(name: "Heading 1", symbol: "textformat.size.larger", kind: .heading(1)),+ Kind(name: "Heading 2", symbol: "textformat.size", kind: .heading(2)),+ Kind(name: "Heading 3", symbol: "textformat.size.smaller", kind: .heading(3)),+ Kind(name: "Bulleted List", symbol: "list.bullet", kind: .bullet),+ Kind(name: "Numbered List", symbol: "list.number", kind: .number),+ Kind(name: "To-do", symbol: "checklist", kind: .todo(checked: false)),+ Kind(name: "Quote", symbol: "text.quote", kind: .quote),+ ]++ var body: some View {+ let block = editing.currentBlock+ Menu {+ ForEach(Self.kinds, id: \.name) { item in+ Button {+ editing.setKind(item.kind)+ } label: {+ Label(item.name, systemImage: Self.same(block?.kind, item.kind) ? "checkmark" : item.symbol)+ }+ }+ if let block, block.kind.isList {+ Divider()+ if case .todo(let checked) = block.kind {+ Button(checked ? "Mark Not Done" : "Mark Done", systemImage: checked ? "circle" : "checkmark.circle") {+ editing.toggleChecked()+ }+ }+ Button("Indent", systemImage: "increase.indent") { editing.indent(by: 1) }+ .disabled(block.indent >= NoteMarkdown.indentMax)+ Button("Outdent", systemImage: "decrease.indent") { editing.indent(by: -1) }+ .disabled(block.indent == 0)+ }+ } label: {+ Image(systemName: "textformat")+ }+ .accessibilityLabel("Block style")++ markButton(.bold, symbol: "bold", name: "Bold")+ markButton(.italic, symbol: "italic", name: "Italic")+ markButton(.underline, symbol: "underline", name: "Underline")+ markButton(.strike, symbol: "strikethrough", name: "Strikethrough")++ Menu {+ Button("Default") { editing.setColor(nil, in: fontContext) }+ ForEach(NoteTextColor.allCases, id: \.self) { color in+ Button {+ editing.setColor(color, in: fontContext)+ } label: {+ Label {+ Text(color.name)+ } icon: {+ Image(systemName: "circle.fill")+ .foregroundStyle(editing.look.color(color))+ }+ }+ }+ } label: {+ Image(systemName: "paintpalette")+ }+ .accessibilityLabel("Text color")+ }++ private func markButton(_ mark: NoteMark, symbol: String, name: String) -> some View {+ Button {+ editing.toggle(mark, in: fontContext)+ } label: {+ Image(systemName: symbol)+ }+ .accessibilityLabel(name)+ }++ /// Whether a line is the kind a menu item names. A to-do is a to-do,+ /// checked or not.+ private static func same(_ a: NoteBlockKind?, _ b: NoteBlockKind) -> Bool {+ if case .todo = a, case .todo = b { return true }+ return a == b+ }+}+#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swiftindex 046a652c..4961ab6b 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift@@ -11,6 +11,16 @@ struct NoteEditorView: View {@FocusState private var focused: Field?@State private var showingLabels = false+ @State private var editing: NoteBodyEditing++ init(app: AppModel, ideas: IdeasModel, onRecordNote: @escaping (Note) -> Void) {+ self.app = app+ self.ideas = ideas+ self.onRecordNote = onRecordNote+ _editing = State(initialValue: NoteBodyEditing(body: ideas.draft?.body ?? "", look: .paper) { [ideas] body in+ ideas.draft?.body = body+ })+ }var body: some View {let color = ideas.draft?.color ?? .butter@@ -67,22 +77,14 @@ struct NoteEditorView: View {.submitLabel(.next).onSubmit { focused = .body }- TextEditor(text: bodyBinding)- .font(.system(size: 20, weight: .medium))+ // The body edits as rich text: the keyboard's format controls+ // and the system's format menu style the words, and typing a+ // list marker starts a list.+ NoteBodyEditor(editing: editing, placeholder: "Write down an idea...").scrollContentBackground(.hidden).scrollDismissesKeyboard(.interactively).padding(.horizontal, 18).focused($focused, equals: .body)- .overlay(alignment: .topLeading) {- if (ideas.draft?.body ?? "").isEmpty {- Text("Write down an idea...")- .font(.system(size: 20, weight: .medium))- .opacity(0.4)- .padding(.horizontal, 23)- .padding(.top, 8)- .allowsHitTesting(false)- }- }// The labels the note wears. A tap on a chip takes it off; the// tag button opens the picker that adds, makes, renames and@@ -146,6 +148,9 @@ struct NoteEditorView: View {// Opening a note is reading it as often as writing it, so the// keyboard comes and goes on the writer's word.ToolbarItemGroup(placement: .keyboard) {+ if focused == .body {+ NoteFormatControls(editing: editing)+ }Spacer()Button("Done") { focused = nil }.font(.body.weight(.bold))@@ -161,13 +166,6 @@ struct NoteEditorView: View {set: { ideas.draft?.title = $0 })}-- private var bodyBinding: Binding<String> {- Binding(- get: { ideas.draft?.body ?? "" },- set: { ideas.draft?.body = $0 }- )- }}/// The label picker: every label on the account, the open note's checked. Adiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteLook.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteLook.swiftnew file mode 100644index 00000000..94299f28--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteLook.swift@@ -0,0 +1,263 @@+#if os(iOS)+import SwiftUI+import UIKit+import DonkeyKitModels++/// How a note's blocks and styles look on one surface: the size and weights+/// of its words, how much bigger headings draw, and which ink its colors take.+///+/// One face serves both the drawing and the measuring: the teleprompter breaks+/// lines with the same fonts it draws them in, and the editor reads bold and+/// italic back off the fonts it drew. Bold is read as a weight from bold up,+/// so every surface an editor reads keeps its plain weights below that.+struct NoteLook {+ var size: CGFloat+ var weight: Font.Weight+ var boldWeight: Font.Weight+ var headingWeight: Font.Weight+ var headingBoldWeight: Font.Weight+ /// How much bigger each heading level draws.+ var headingScale: [CGFloat] = [1.5, 1.3, 1.15]+ /// The ink of words with no color: the note paper's, or the stage's white.+ var ink: Color+ /// Whether colors take their dark-stage ink.+ var onDark: Bool++ /// The note editor, on its paper.+ static let paper = NoteLook(+ size: 20,+ weight: .medium,+ boldWeight: .bold,+ headingWeight: .semibold,+ headingBoldWeight: .bold,+ ink: .notePaperInk,+ onDark: false+ )++ /// A note card in the grid, at the size of footnote text.+ static var card: NoteLook {+ NoteLook(+ size: UIFont.preferredFont(forTextStyle: .footnote).pointSize,+ weight: .regular,+ boldWeight: .bold,+ headingWeight: .semibold,+ headingBoldWeight: .bold,+ headingScale: [1.25, 1.15, 1.05],+ ink: .notePaperInk,+ onDark: false+ )+ }++ /// The script editor on the teleprompter card, over the camera.+ static let scriptCard = NoteLook(+ size: 19,+ weight: .medium,+ boldWeight: .bold,+ headingWeight: .semibold,+ headingBoldWeight: .bold,+ headingScale: [1.35, 1.2, 1.1],+ ink: .white,+ onDark: true+ )++ /// The running prompter, at the reader's text size.+ static func prompter(size: CGFloat) -> NoteLook {+ NoteLook(+ size: size,+ weight: .heavy,+ boldWeight: .black,+ headingWeight: .heavy,+ headingBoldWeight: .black,+ headingScale: [1.4, 1.25, 1.12],+ ink: .white,+ onDark: true+ )+ }++ /// The weight from which a font reads as bold.+ private static let boldThreshold = (UIFont.Weight.semibold.rawValue + UIFont.Weight.bold.rawValue) / 2++ /// The size and the plain and bold weights of a block's words.+ private func face(_ kind: NoteBlockKind) -> (size: CGFloat, weight: Font.Weight, bold: Font.Weight) {+ guard case .heading(let level) = kind else { return (size, weight, boldWeight) }+ return (size * headingScale[min(max(level, 1), headingScale.count) - 1], headingWeight, headingBoldWeight)+ }++ /// The face words draw in. Bold and italic ride on the plain face as+ /// modifiers, the way the system's format menu writes them, so the menu+ /// can take them off again.+ func font(_ kind: NoteBlockKind, _ marks: NoteMarks) -> Font {+ let face = face(kind)+ var font = Font.system(size: face.size, weight: face.weight)+ if marks.bold { font = face.bold == .bold ? font.bold() : font.weight(face.bold) }+ if marks.italic { font = font.italic() }+ return font+ }++ /// The same face, for measuring.+ func uiFont(_ kind: NoteBlockKind, _ marks: NoteMarks) -> UIFont {+ let face = face(kind)+ let font = UIFont.systemFont(ofSize: face.size, weight: Self.uiWeight(marks.bold ? face.bold : face.weight))+ guard marks.italic,+ let italic = font.fontDescriptor.withSymbolicTraits(font.fontDescriptor.symbolicTraits.union(.traitItalic))+ else { return font }+ return UIFont(descriptor: italic, size: face.size)+ }++ private static func uiWeight(_ weight: Font.Weight) -> UIFont.Weight {+ let weights: [(Font.Weight, UIFont.Weight)] = [+ (.ultraLight, .ultraLight), (.thin, .thin), (.light, .light), (.regular, .regular),+ (.medium, .medium), (.semibold, .semibold), (.bold, .bold), (.heavy, .heavy), (.black, .black),+ ]+ return weights.first { $0.0 == weight }?.1 ?? .regular+ }++ func color(_ color: NoteTextColor) -> Color {+ Color(hex: onDark ? color.dark : color.paper)+ }++ /// The attributes a run draws with. Markers draw plain, in the line's face.+ func attributes(_ kind: NoteBlockKind, _ marks: NoteMarks, marker: Bool = false) -> AttributeContainer {+ let marks = marker ? NoteMarks() : marks+ var container = AttributeContainer()+ container[AttributeScopes.SwiftUIAttributes.FontAttribute.self] = font(kind, marks)+ if let color = marks.color {+ container[AttributeScopes.SwiftUIAttributes.ForegroundColorAttribute.self] = self.color(color)+ }+ if marks.underline {+ container[AttributeScopes.SwiftUIAttributes.UnderlineStyleAttribute.self] = Text.LineStyle.single+ }+ if marks.strike {+ container[AttributeScopes.SwiftUIAttributes.StrikethroughStyleAttribute.self] = Text.LineStyle.single+ }+ return container+ }++ /// The text of these blocks as this surface draws them, markers included.+ func text(_ blocks: [NoteBlock]) -> AttributedString {+ let source = NoteRichText.attributedText(blocks)+ var out = AttributedString()+ for run in source.runs {+ let kind = run[NoteLineAttribute.self]?.kind ?? .paragraph+ let marks = run[NoteMarksAttribute.self] ?? NoteMarks()+ let marker = run[NoteMarkerAttribute.self] ?? false+ out += AttributedString(+ String(source[run.range].characters),+ attributes: attributes(kind, marks, marker: marker)+ )+ }+ return out+ }++ /// Paced prompter copy as this surface draws it: a line break inside a+ /// block, a blank line between blocks.+ func text(_ paced: [PacedBlock]) -> AttributedString {+ var out = AttributedString()+ for (index, block) in paced.enumerated() {+ if index > 0 { out += AttributedString("\n\n", attributes: attributes(.paragraph, NoteMarks())) }+ for (number, line) in block.lines.enumerated() {+ if number > 0 { out += AttributedString("\n", attributes: attributes(block.kind, NoteMarks())) }+ for run in line {+ out += AttributedString(run.text, attributes: attributes(block.kind, run.marks))+ }+ }+ }+ return out+ }++ /// How wide a line of runs draws in this face.+ func width(_ runs: [NoteRun], _ kind: NoteBlockKind) -> Double {+ let line = NSMutableAttributedString()+ for run in runs {+ line.append(NSAttributedString(string: run.text, attributes: [.font: uiFont(kind, run.marks)]))+ }+ return line.size().width+ }++ // MARK: Reading the editor back++ /// The styles a run of the editor's text shows: bold and italic off its+ /// face, lines off its decorations, and its color as the nearest of the+ /// note colors — the system's format menu offers any color, and the note+ /// keeps the one it reads as.+ func marks(of attributes: AttributeContainer, in context: Font.Context) -> NoteMarks {+ var marks = NoteMarks()+ if let face = ctFont(of: attributes, in: context) {+ let traits = CTFontCopyTraits(face) as? [CFString: Any]+ let weight = (traits?[kCTFontWeightTrait] as? NSNumber)?.doubleValue ?? 0+ marks.bold = weight >= Self.boldThreshold+ marks.italic = CTFontGetSymbolicTraits(face).contains(.traitItalic)+ }+ marks.underline = attributes[AttributeScopes.SwiftUIAttributes.UnderlineStyleAttribute.self] != nil+ || (attributes[AttributeScopes.UIKitAttributes.UnderlineStyleAttribute.self].map { $0 != [] } ?? false)+ marks.strike = attributes[AttributeScopes.SwiftUIAttributes.StrikethroughStyleAttribute.self] != nil+ || (attributes[AttributeScopes.UIKitAttributes.StrikethroughStyleAttribute.self].map { $0 != [] } ?? false)+ marks.color = noteColor(of: attributes)+ return marks+ }++ /// The point size a run is drawn at, or zero when it names no face.+ func pointSize(of attributes: AttributeContainer, in context: Font.Context) -> Double {+ ctFont(of: attributes, in: context).map { Double(CTFontGetSize($0)) } ?? 0+ }++ private func ctFont(of attributes: AttributeContainer, in context: Font.Context) -> CTFont? {+ if let font = attributes[AttributeScopes.SwiftUIAttributes.FontAttribute.self] {+ return font.resolve(in: context).ctFont+ }+ if let font = attributes[AttributeScopes.UIKitAttributes.FontAttribute.self] {+ return font as CTFont+ }+ return nil+ }++ private func noteColor(of attributes: AttributeContainer) -> NoteTextColor? {+ let rgb: (Double, Double, Double)+ if let color = attributes[AttributeScopes.SwiftUIAttributes.ForegroundColorAttribute.self] {+ rgb = Self.components(color)+ } else if let color = attributes[AttributeScopes.UIKitAttributes.ForegroundColorAttribute.self] {+ rgb = Self.components(Color(uiColor: color))+ } else {+ return nil+ }+ func distance(_ other: Color) -> Double {+ let o = Self.components(other)+ return pow(rgb.0 - o.0, 2) + pow(rgb.1 - o.1, 2) + pow(rgb.2 - o.2, 2)+ }+ let nearest = NoteTextColor.allCases.min { distance(color($0)) < distance(color($1)) }+ guard let nearest, distance(color(nearest)) < distance(ink) else { return nil }+ return nearest+ }++ private static func components(_ color: Color) -> (Double, Double, Double) {+ let resolved = color.resolve(in: EnvironmentValues())+ return (Double(resolved.red), Double(resolved.green), Double(resolved.blue))+ }++ /// The text as a reader sees it: for each stretch, the styles it reads+ /// as and the size it draws at. Two texts that look alike compare equal+ /// however their attributes are spelled.+ func appearance(of text: AttributedString, in context: Font.Context) -> [NoteAppearance] {+ var out: [NoteAppearance] = []+ for run in text.runs {+ let look = NoteAppearance(+ marks: marks(of: run.attributes, in: context),+ pointSize: (pointSize(of: run.attributes, in: context) * 10).rounded(),+ length: text[run.range].characters.count+ )+ if let last = out.last, last.marks == look.marks, last.pointSize == look.pointSize {+ out[out.count - 1].length += look.length+ } else {+ out.append(look)+ }+ }+ return out+ }+}++struct NoteAppearance: Equatable {+ var marks: NoteMarks+ var pointSize: Double+ var length: Int+}+#endifdiff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swiftindex a1b02c5a..a96029b6 100644--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift@@ -231,28 +231,34 @@ import Testing/// Enough to pin down where a line ends without a screen.func measure(_ line: String) -> Double { Double(line.count) * 10 }+ /// The paced script as plain lines: a line break inside a block, a blank+ /// line between blocks.+ func paced(_ script: String, room: Double) -> String {+ pacedScript(script, room: room) { runs, _ in measure(runs.map(\.text).joined()) }+ .map { $0.lines.map { $0.map(\.text).joined() }.joined(separator: "\n") }+ .joined(separator: "\n\n")+ }+@Test func pacingRespectsUserNewlines() {- let paced = pacedScript("First thought\nSecond thought", room: 1000, measure: measure)- #expect(paced == "First thought\n\nSecond thought")+ #expect(paced("First thought\nSecond thought", room: 1000) == "First thought\n\nSecond thought")}@Test func pacingCollapsesSpaceRuns() {- #expect(pacedScript("hello there friend", room: 1000, measure: measure) == "hello there friend")+ #expect(paced("hello there friend", room: 1000) == "hello there friend")}@Test func wordsShareALineWhileThePictureHasRoom() {let script = "Hey everyone, welcome back"// 26 characters at ten points each, with room to spare.- #expect(pacedScript(script, room: 400, measure: measure) == script)+ #expect(paced(script, room: 400) == script)}@Test func aLineEndsWhereTheNextWordWouldRunOff() {- let paced = pacedScript(+ let text = paced("Hey everyone, welcome back to the channel where we talk about editing",- room: 200,- measure: measure+ room: 200)- let lines = paced.split(separator: "\n").map(String.init)+ let lines = text.split(separator: "\n").map(String.init)#expect(lines.allSatisfy { measure($0) <= 200 })// Each line is full: the first word of the next one would not have fit.for (line, next) in zip(lines, lines.dropFirst()) {@@ -260,16 +266,41 @@ import Testing#expect(measure("\(line) \(word)") > 200)}// Every word survives the wrap.- #expect(paced.split(whereSeparator: { $0.isWhitespace }).count == 12)+ #expect(text.split(whereSeparator: { $0.isWhitespace }).count == 12)}@Test func aWordWiderThanTheRoomKeepsItsOwnLine() {- let paced = pacedScript("a supercalifragilistic b", room: 60, measure: measure)- #expect(paced == "a\nsupercalifragilistic\nb")+ #expect(paced("a supercalifragilistic b", room: 60) == "a\nsupercalifragilistic\nb")}@Test func noRoomToSpeakOfLeavesTheParagraphWhole() {- #expect(pacedScript("keep me together", room: 0, measure: measure) == "keep me together")+ #expect(paced("keep me together", room: 0) == "keep me together")+ }++ @Test func pacingKeepsStylesAndMarkersAndDropsMarkup() {+ let blocks = pacedScript("# **Hi** there\n- one *two*\n2. three\n\n- [x] done", room: 1000) { runs, _ in+ measure(runs.map(\.text).joined())+ }+ #expect(blocks.map(\.kind) == [.heading(1), .bullet, .number, .todo(checked: true)])+ #expect(blocks[0].lines == [[NoteRun("Hi", NoteMarks(bold: true)), NoteRun(" there")]])+ #expect(blocks[1].lines == [[NoteRun("• one "), NoteRun("two", NoteMarks(italic: true))]])+ // Numbers count within their run, whatever the note wrote.+ #expect(blocks[2].lines == [[NoteRun("1. three")]])+ #expect(blocks[3].lines == [[NoteRun("☑\u{FE0E} done")]])+ }++ @Test func aStyledWordIsMeasuredWithTheBlockItSitsIn() {+ // Headings draw twice as wide here, so the same words break sooner.+ let blocks = pacedScript("# one two three\none two three", room: 100) { runs, kind in+ let width = measure(runs.map(\.text).joined())+ return kind == .heading(1) ? width * 2 : width+ }+ #expect(blocks[0].lines.count == 3)+ #expect(blocks[1].lines.count == 2)+ }++ @Test func readDurationCountsTheWordsNotTheMarkup() {+ #expect(readDuration(of: "- **one** two\n> three", wordsPerMinute: 60) == 3)}}diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/NoteMarkdownTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/NoteMarkdownTests.swiftnew file mode 100644index 00000000..804210bc--- /dev/null+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/NoteMarkdownTests.swift@@ -0,0 +1,293 @@+import Foundation+import Testing+@testable import DonkeyKitModels++/// The note body format. The cases follow the site's noteMarkdown tests, so+/// the phone and the web read and write the same bodies.+@Suite struct NoteMarkdownTests {+ func roundTrip(_ body: String) -> String { NoteMarkdown.serialize(NoteMarkdown.parse(body)) }++ @Test func aPlainTextNoteReadsOneParagraphPerLine() {+ let body = "Template\nfind a template to replicate\n\nCut Demo"+ #expect(NoteMarkdown.parse(body).map(\.kind) == [.paragraph, .paragraph, .paragraph, .paragraph])+ #expect(roundTrip(body) == body)+ }++ @Test func blockMarkersNestingAndToDosRoundTrip() {+ let body = [+ "# Title",+ "## Section",+ "### Sub",+ "- one",+ " - nested",+ " - deeper",+ "1. first",+ "2. second",+ " - aside",+ "3. third",+ "- [ ] open",+ "- [x] done",+ "> quoted",+ "",+ "plain",+ ].joined(separator: "\n")+ #expect(roundTrip(body) == body)+ let blocks = NoteMarkdown.parse(body)+ #expect(blocks[4].kind == .bullet && blocks[4].indent == 1)+ #expect(blocks[5].indent == 2)+ #expect(blocks[11].kind == .todo(checked: true))+ #expect(blocks[1].kind == .heading(2))+ }++ @Test func numberedRunsRenumberAndOtherBulletsReadAsBullets() {+ #expect(roundTrip("5. a\n9. b\ntext\n3. c") == "1. a\n2. b\ntext\n1. c")+ #expect(roundTrip("* a\n• b") == "- a\n- b")+ }++ @Test func nestingDeeperThanTheLimitClamps() {+ let blocks = NoteMarkdown.parse(String(repeating: " ", count: 8) + "- deep")+ #expect(blocks[0].indent == NoteMarkdown.indentMax)+ }++ @Test func oddSpacingAndUnspacedMarkersAreText() {+ #expect(NoteMarkdown.parse(" - three spaces")[0].kind == .paragraph)+ #expect(NoteMarkdown.parse("-no space")[0].kind == .paragraph)+ #expect(NoteMarkdown.parse("#### four")[0].kind == .paragraph)+ #expect(NoteMarkdown.parse(">quote")[0].kind == .paragraph)+ }++ @Test func inlineMarksParseAndNestAcrossSeams() {+ let runs = NoteMarkdown.parseInline("**bold *both* bold** <u>under</u> ~~gone~~ <span color=\"red\">red</span>")+ #expect(runs == [+ NoteRun("bold ", NoteMarks(bold: true)),+ NoteRun("both", NoteMarks(bold: true, italic: true)),+ NoteRun(" bold", NoteMarks(bold: true)),+ NoteRun(" "),+ NoteRun("under", NoteMarks(underline: true)),+ NoteRun(" "),+ NoteRun("gone", NoteMarks(strike: true)),+ NoteRun(" "),+ NoteRun("red", NoteMarks(color: .red)),+ ])+ for body in ["**bold *both* bold**", "<span color=\"blue\"><u>**a**</u></span>b", "*a***b**"] {+ #expect(roundTrip(roundTrip(body)) == roundTrip(body))+ #expect(NoteMarkdown.parse(roundTrip(body)) == NoteMarkdown.parse(body))+ }+ }++ @Test func canonicalBodiesSerializeToThemselves() {+ for body in [+ "",+ "plain\n\nlines",+ "# Title\n- a\n - b\n 1. c\n 2. d\n- e\n- [ ] f\n - [x] g\n> q1\n> q2\ntext",+ "**bold** *it* <u>u</u> ~~s~~ <span color=\"green\">**g**</span>",+ "<span color=\"red\"><u>~~***all***~~</u></span>",+ "a \\* b \\\\ c \\~\\~ d \\<u>",+ ] {+ #expect(roundTrip(body) == body)+ }+ }++ @Test func strayDelimitersAndUnknownTagsStayLiteral() {+ #expect(NoteMarkdown.plainText("5 * 3 = 15") == "5 * 3 = 15")+ #expect(NoteMarkdown.plainText("a <b>tag</b> and <span color=\"teal\">x</span>") == "a <b>tag</b> and <span color=\"teal\">x</span>")+ #expect(NoteMarkdown.plainText("close </u> first") == "close </u> first")+ #expect(NoteMarkdown.plainText("**one** **two** **three") == "one two **three")+ #expect(NoteMarkdown.plainText("<u>open never closed") == "<u>open never closed")+ }++ @Test func aLoneStarIsWrittenBackEscaped() {+ // The words survive; the star picks up the backslash that keeps it a+ // star from here on.+ #expect(roundTrip("5 * 3 = 15") == "5 \\* 3 = 15")+ #expect(NoteMarkdown.plainText(roundTrip("5 * 3 = 15")) == "5 * 3 = 15")+ }++ @Test func backslashKeepsTheNextCharacterLiteral() {+ #expect(NoteMarkdown.parseInline("\\*not italic\\*") == [NoteRun("*not italic*")])+ #expect(NoteMarkdown.parseInline("ends in \\") == [NoteRun("ends in \\")])+ #expect(NoteMarkdown.parse("\\- text")[0] == NoteBlock(.paragraph, runs: [NoteRun("- text")]))+ }++ @Test func literalTextThatLooksLikeMarkupIsEscapedAndReadsBack() {+ let blocks = [+ NoteBlock(.paragraph, runs: [NoteRun("- not a bullet *or* <u>tag</u> \\ ~~")]),+ NoteBlock(.paragraph, runs: [NoteRun("1. not a number")]),+ NoteBlock(.paragraph, runs: [NoteRun("# not a heading")]),+ NoteBlock(.paragraph, runs: [NoteRun("> not a quote")]),+ NoteBlock(.paragraph, runs: [NoteRun(" - not nested")]),+ ]+ #expect(NoteMarkdown.parse(NoteMarkdown.serialize(blocks)) == blocks)+ }++ @Test func colorsCarryBothInks() {+ #expect(NoteTextColor.allCases.count == 9)+ #expect(NoteTextColor.red.paper == "#d44c47")+ #expect(NoteTextColor.red.dark == "#df5452")+ #expect(NoteTextColor.gray.name == "Gray")+ }+}++/// The phone editor's attributed text and how edits read back into blocks.+@Suite struct NoteRichTextTests {+ let body = "# Title\n- a\n - b\n1. one\n2. two\n- [ ] open\n- [x] done\n> quote\n\n**bold** <span color=\"blue\">blue</span>"++ /// The editor's text after the keyboard has had it: the drawn text with+ /// `change` applied to its characters.+ func typed(_ blocks: [NoteBlock], _ change: (inout String) -> Void) -> AttributedString {+ let drawn = NoteRichText.attributedText(blocks)+ var chars = String(drawn.characters)+ change(&chars)+ // Styles ride along on the characters that stayed; anything new is+ // plain, which is what a keyboard types after plain words.+ let old = Array(drawn.characters)+ let new = Array(chars)+ var prefix = 0+ while prefix < old.count, prefix < new.count, old[prefix] == new[prefix] { prefix += 1 }+ var out = AttributedString(chars)+ if prefix > 0 {+ let end = out.characters.index(out.startIndex, offsetBy: prefix)+ let source = drawn.characters.index(drawn.startIndex, offsetBy: prefix)+ out.replaceSubrange(out.startIndex..<end, with: drawn[drawn.startIndex..<source])+ }+ return out+ }++ func body(after blocks: [NoteBlock], _ change: (inout String) -> Void, caret: Int? = nil) -> String {+ NoteMarkdown.serialize(NoteRichText.edit(blocks, to: typed(blocks, change), caret: caret).blocks)+ }++ @Test func drawnTextShowsMarkersAndWords() {+ let text = NoteRichText.attributedText(NoteMarkdown.parse(body))+ #expect(String(text.characters) == "Title\n• a\n\u{2003}◦ b\n1. one\n2. two\n☐ open\n☑\u{FE0E} done\n▎ quote\n\nbold blue")+ }++ @Test func anUneditedTextReadsBackToTheSameBody() {+ for body in [body, "", "plain\n\nlines", "5 \\* 3", "# \n- \n1. ", " - first line nested"] {+ let blocks = NoteMarkdown.parse(body)+ let edit = NoteRichText.edit(blocks, to: NoteRichText.attributedText(blocks))+ #expect(edit.blocks == blocks)+ #expect(NoteMarkdown.serialize(edit.blocks) == body)+ }+ }++ @Test func marksRideTheAttributedText() {+ let blocks = NoteMarkdown.parse("plain **bold**")+ var text = NoteRichText.attributedText(blocks)+ // The editor turned "plain" italic.+ let end = text.characters.index(text.startIndex, offsetBy: 5)+ text[text.startIndex..<end][NoteMarksAttribute.self] = NoteMarks(italic: true)+ let edit = NoteRichText.edit(blocks, to: text)+ #expect(NoteMarkdown.serialize(edit.blocks) == "*plain* **bold**")+ }++ @Test func typingInsideAWordKeepsTheLine() {+ let blocks = NoteMarkdown.parse("- milk\n- eggs")+ #expect(body(after: blocks, { $0 = $0.replacingOccurrences(of: "milk", with: "milky") }) == "- milky\n- eggs")+ }++ @Test func returnAtTheEndOfAnItemOpensAnother() {+ let blocks = NoteMarkdown.parse("1. one\n- [x] done")+ #expect(body(after: blocks, { $0 = $0.replacingOccurrences(of: "1. one", with: "1. one\nnext") }) == "1. one\n2. next\n- [x] done")+ let todo = NoteMarkdown.parse("- [x] done")+ #expect(body(after: todo, { $0 += "\nmore" }) == "- [x] done\n- [ ] more")+ }++ @Test func returnOnAnEmptyItemEndsTheList() {+ let blocks = NoteMarkdown.parse("- a\n- ")+ let edit = NoteRichText.edit(blocks, to: typed(blocks) { $0 += "\n" })+ #expect(NoteMarkdown.serialize(edit.blocks) == "- a\n")+ #expect(edit.cursor == String(NoteRichText.attributedText(edit.blocks).characters).count)+ let nested = NoteMarkdown.parse("- a\n - ")+ #expect(body(after: nested, { $0 += "\n" }) == "- a\n- ")+ }++ @Test func returnAfterAHeadingWritesText() {+ let blocks = NoteMarkdown.parse("# Title\n- x")+ // The new line could be read on either side of the line break; the+ // caret says it went after the title.+ #expect(body(after: blocks, { $0 = $0.replacingOccurrences(of: "Title", with: "Title\n") }, caret: 6) == "# Title\n\n- x")+ // Without the caret, the earliest reading stands, which is the same.+ #expect(body(after: blocks, { $0 = $0.replacingOccurrences(of: "Title", with: "Title\n") }) == "# Title\n\n- x")+ // Split in the middle, both halves stay headings.+ #expect(body(after: blocks, { $0 = $0.replacingOccurrences(of: "Title", with: "Ti\ntle") }) == "# Ti\n# tle\n- x")+ }++ @Test func backspaceIntoAMarkerTurnsTheLineBackToText() {+ let blocks = NoteMarkdown.parse("- milk")+ let edit = NoteRichText.edit(blocks, to: typed(blocks) { $0 = "•milk" })+ #expect(NoteMarkdown.serialize(edit.blocks) == "milk")+ #expect(edit.cursor == 0)+ // A nested item steps out a level instead.+ let nested = NoteMarkdown.parse("- a\n - b")+ #expect(body(after: nested, { $0 = $0.replacingOccurrences(of: "◦ b", with: "◦b") }) == "- a\n- b")+ }++ @Test func typingAMarkerMakesTheBlock() {+ let cases: [(String, String)] = [+ ("- ", "- x"), ("* ", "- x"), ("1. ", "1. x"), ("# ", "# x"), ("### ", "### x"),+ ("> ", "> x"), ("[ ] ", "- [ ] x"), ("[x] ", "- [x] x"),+ ]+ for (marker, expected) in cases {+ let blocks = NoteMarkdown.parse(String(marker.dropLast()) + "x")+ let caret = marker.count+ let edit = NoteRichText.edit(blocks, to: typed(blocks) { $0 = marker + "x" }, caret: caret)+ #expect(NoteMarkdown.serialize(edit.blocks) == expected)+ }+ // A to-do box typed at the head of a bullet makes it a to-do.+ let bullet = NoteMarkdown.parse("- [ ]x")+ #expect(body(after: bullet, { $0 = "• [ ] x" }) == "- [ ] x")+ }++ @Test func aMarkerTypedMidLineIsText() {+ let blocks = NoteMarkdown.parse("a -")+ #expect(body(after: blocks, { $0 = "a - " }) == "a - ")+ }++ @Test func deletingAcrossLinesKeepsTheFirstLinesBlock() {+ let blocks = NoteMarkdown.parse("# Head\n- item")+ #expect(body(after: blocks, { $0 = "Heitem" }) == "# Heitem")+ }++ @Test func pastedLinesContinueTheList() {+ let blocks = NoteMarkdown.parse("- a")+ #expect(body(after: blocks, { $0 += "\r\nb\nc" }) == "- a\n- b\n- c")+ }++ @Test func typedMarkupIsWrittenAsText() {+ let blocks = NoteMarkdown.parse("")+ #expect(body(after: blocks, { $0 = "5 * 3 <u>" }) == "5 \\* 3 \\<u>")+ // A line typed to look like a list without the space shortcut stays+ // the text it is.+ #expect(body(after: blocks, { $0 = "-x" }) == "-x")+ }++ @Test func positionsMapThroughMarkers() {+ let blocks = NoteMarkdown.parse("# T\n- ab")+ func at(_ offset: Int) -> [Int] {+ let position = NoteRichText.position(of: offset, in: blocks)+ return [position.line, position.content]+ }+ #expect(at(0) == [0, 0])+ // Inside the bullet counts as the head of its words.+ #expect(at(2) == [1, 0])+ #expect(at(4) == [1, 0])+ #expect(at(5) == [1, 1])+ #expect(NoteRichText.offset(line: 1, content: 2, in: blocks) == 6)+ }++ @Test func restylingAndBlockChanges() {+ let blocks = NoteMarkdown.parse("hello world\nnext")+ let bold = NoteRichText.restyling(from: 6, to: 11, in: blocks) { $0.bold = true }+ #expect(NoteMarkdown.serialize(bold) == "hello **world**\nnext")+ let red = NoteRichText.restyling(from: 0, to: 16, in: blocks) { $0.color = .red }+ #expect(NoteMarkdown.serialize(red) == "<span color=\"red\">hello world</span>\n<span color=\"red\">next</span>")+ #expect(NoteRichText.marks(from: 6, to: 11, in: bold).allSatisfy { $0.bold })+ let listed = NoteRichText.setting(.number, lines: 0...1, of: blocks)+ #expect(NoteMarkdown.serialize(listed) == "1. hello world\n2. next")+ let nested = NoteRichText.indenting(lines: 1...1, by: 1, of: listed)+ #expect(NoteMarkdown.serialize(nested) == "1. hello world\n 1. next")+ let heading = NoteRichText.setting(.heading(2), lines: 1...1, of: nested)+ #expect(NoteMarkdown.serialize(heading) == "1. hello world\n## next")+ }+}