Cotton code
38 lines · 2.0 KB · SwiftRaw
// WHAT THE EDITOR LAYS OVER THE CORE'S RUNS: the phone's own state drawn in// the core's shape. Where a text folds, what Find found and which note a link// names are the core's answers (`folds`, `notes.find`, `links`, CONTRACT.md// §4, §6); which folds are shut and which match stands are the phone's. Each// is a run, so the text view draws it as any other.//// - `fold_mark`: a line that folds (its first character), `glyph` `open` or//   `closed`: the chevron beside it.// - `folded`: words hidden with their lines (a folded section).// - `found` / `found_now`: a match of Find, and the one standing.//// Offsets are UTF-16 code units, as NSString counts.import Foundationpublic enum WritingOverlay {    /// The runs laid over the core's: the chevrons of the core's `folds`, the `folded` lines' sections hidden,    /// and Find's `found` with the current one.    static func spans(length: Int, folds: [WritingFold], folded: Set<Int>, found: [NSRange], current: Int) -> [WritingSpan] {        var out: [WritingSpan] = []        for (i, r) in found.enumerated() {            out.append(WritingSpan(start: r.location, end: NSMaxRange(r), style: i == current ? "found_now" : "found"))        }        for f in folds {            let shut = folded.contains(f.line)            if f.line < length { out.append(WritingSpan(start: f.line, end: f.line + 1, style: "fold_mark", glyph: shut ? "closed" : "open")) }            if shut, f.end > f.start { out.append(WritingSpan(start: f.start, end: min(f.end, length), style: "folded")) }        }        return out    }    /// What a cursor at `at` stands in: a `[[note link]]` (as `note:<target>`), or a link's address.    public static func linkAt(_ styled: WritingStyled?, at: Int) -> String? {        guard let styled else { return nil }        if let link = styled.links.first(where: { at > $0.start && at <= $0.end }) { return "note:" + link.target }        return styled.spans.first { $0.style == "link" && $0.url != nil && at >= $0.start && at <= $0.end }?.url    }}