Cotton code
58 lines · 2.7 KB · SwiftRaw
// A name or a title set in whole words, the rolodex's rule (People, 2026)// that the hardback's blank jacket takes too: wrapped at word boundaries,// taken down a size at a time before any word is split, and only at the// least size may a word wider than the line split, with an explicit hyphen// at the last grapheme that fits — never a bare break inside a word.import CoreGraphicspublic enum NameFit {    /// `words` laid greedily at each of `sizes`, largest first, until they    /// stand whole in at most `limit` lines. `measure(size)` answers whether    /// a line fits the room at that size. A word wider than the line moves    /// on to the next size; at the last size it splits, hyphenated. The    /// lines are all of them — a face cuts what runs past `limit` its own    /// way — with the size they are set at and whether a word was split.    public static func lines(        _ words: [String], sizes: [CGFloat], limit: Int, measure: (CGFloat) -> (String) -> Bool    ) -> (lines: [String], size: CGFloat, split: Bool) {        var lines: [String] = []        var split = false        guard let least = sizes.last else { return ([], 0, false) }        var size = least        for (index, step) in sizes.enumerated() {            size = step            let fits = measure(step)            lines = []            split = false            let atFloor = index == sizes.count - 1            var oversized = false            for word in words {                var remaining = word                if !fits(word) {                    oversized = true                    if !atFloor { break }                    // Only at the floor may a word split, with an explicit                    // hyphen at the last fitting grapheme (never a bare break).                    while !fits(remaining), remaining.count > 1 {                        var prefix = ""                        for character in remaining.dropLast() {                            let next = prefix + String(character)                            guard fits(next + "-") else { break }                            prefix = next                        }                        guard !prefix.isEmpty else { break }                        lines.append(prefix + "-")                        split = true                        remaining.removeFirst(prefix.count)                    }                }                if let last = lines.last, !last.hasSuffix("-"), fits(last + " " + remaining) {                    lines[lines.count - 1] = last + " " + remaining                } else { lines.append(remaining) }            }            if (!oversized || atFloor) && lines.count <= limit { break }        }        return (lines, size, split)    }}