updates plug with all sorts of awesome improvements

This commit is contained in:
2026-11-09 13:09:09 +01:00
parent a92d6f8871
commit 3afdb6d67f
553 changed files with 22780 additions and 13155 deletions
+40
View File
@@ -0,0 +1,40 @@
import Foundation
/// A line of the page that starts with one `=` directly followed by a title, as `=update on this`.
public struct Bookmark: Equatable, Sendable {
/// The text after the `=`, without the spaces at its end.
public var title: String
/// The whole line, the `=` included, without its newline.
public var range: NSRange
public init(title: String, range: NSRange) {
self.title = title
self.range = range
}
/// The bookmarks of a text, top to bottom.
public static func find(in text: NSString) -> [Bookmark] {
var bookmarks: [Bookmark] = []
var start = 0
while start < text.length {
if text.character(at: start) == 0x3D, let bookmark = bookmark(in: text, at: start) {
bookmarks.append(bookmark)
}
let next = text.range(of: "\n=", range: NSRange(location: start, length: text.length - start))
guard next.location != NSNotFound else { break }
start = next.location + 1
}
return bookmarks
}
private static func bookmark(in text: NSString, at start: Int) -> Bookmark? {
guard start + 1 < text.length else { return nil }
let first = text.character(at: start + 1)
guard first != 0x3D, let scalar = Unicode.Scalar(first), !CharacterSet.whitespacesAndNewlines.contains(scalar) else { return nil }
let newline = text.range(of: "\n", range: NSRange(location: start, length: text.length - start))
let end = newline.location == NSNotFound ? text.length : newline.location
let range = NSRange(location: start, length: end - start)
let title = text.substring(with: NSRange(location: start + 1, length: end - start - 1)).trimmingCharacters(in: .whitespaces)
return title.isEmpty ? nil : Bookmark(title: title, range: range)
}
}
+121
View File
@@ -0,0 +1,121 @@
import Foundation
/// The names that contact samples are made from, read from contacts.json.
public struct ContactNames: Codable, Equatable, Sendable {
public var streets: [String]
public var cities: [String]
public var firstNames: [String]
public var lastNames: [String]
public init(streets: [String], cities: [String], firstNames: [String], lastNames: [String]) {
self.streets = streets
self.cities = cities
self.firstNames = firstNames
self.lastNames = lastNames
}
public var isComplete: Bool {
![streets, cities, firstNames, lastNames].contains { $0.isEmpty }
}
/// The names of contacts.json; empty lists when the file is missing or unreadable.
public static let bundled: ContactNames = {
let empty = ContactNames(streets: [], cities: [], firstNames: [], lastNames: [])
guard let url = LoremText.fileURL(named: "contacts.json"), let data = try? Data(contentsOf: url) else { return empty }
return (try? JSONDecoder().decode(ContactNames.self, from: data)) ?? empty
}()
}
/// The telephone numbers, addresses and e-mail addresses at the end of lorem text.
public struct ContactSample: Equatable, Sendable {
public static let count = 4
public static let emailDomains = ["example.nl", "example.com", "example.org"]
public static let excludedPostcodeLetters: Set<String> = ["SS", "SD", "SA"]
static let areaCodes3 = ["010", "020", "023", "024", "026", "030", "033", "035", "036", "038", "040", "043",
"045", "046", "050", "053", "055", "058", "070", "071", "072", "073", "075", "076"]
static let areaCodes4 = ["0118", "0162", "0172", "0222", "0251", "0294", "0313", "0318", "0341", "0413",
"0475", "0488", "0513", "0546", "0591"]
public var phones: [String]
public var addresses: [String]
public var emails: [String]
public init(phones: [String], addresses: [String], emails: [String]) {
self.phones = phones
self.addresses = addresses
self.emails = emails
}
/// The three groups, each one item per line.
public var blocks: [String] {
[phones, addresses, emails].map { $0.joined(separator: "\n") }
}
/// Four distinct items per group; nil when `names` has an empty list or too few names for four e-mails.
public static func pick<G: RandomNumberGenerator>(from names: ContactNames, using generator: inout G) -> ContactSample? {
guard names.isComplete else { return nil }
let kinds = (PhoneKind.allCases + [PhoneKind.allCases.randomElement(using: &generator)!]).shuffled(using: &generator)
var kind = kinds.makeIterator()
guard let phones = distinct(using: &generator, { phone(kind: kind.next() ?? .mobile, using: &$0) }),
let addresses = distinct(using: &generator, { address(from: names, using: &$0) }),
let emails = distinct(using: &generator, { email(from: names, using: &$0) })
else { return nil }
return ContactSample(phones: phones, addresses: addresses, emails: emails)
}
private static func distinct<G: RandomNumberGenerator>(using generator: inout G, _ make: (inout G) -> String) -> [String]? {
var items: [String] = []
for _ in 0..<200 where items.count < count {
let item = make(&generator)
if !items.contains(item) { items.append(item) }
}
return items.count == count ? items : nil
}
private static func digits<G: RandomNumberGenerator>(_ length: Int, using generator: inout G) -> String {
String(Int.random(in: 1...9, using: &generator)) + (1..<length).map { _ in String(Int.random(in: 0...9, using: &generator)) }.joined()
}
private enum PhoneKind: CaseIterable {
case mobile, landline, international
}
private static func phone<G: RandomNumberGenerator>(kind: PhoneKind, using generator: inout G) -> String {
switch kind {
case .landline:
if Bool.random(using: &generator) {
return "\(areaCodes3.randomElement(using: &generator)!)-\(digits(7, using: &generator))"
}
return "\(areaCodes4.randomElement(using: &generator)!)-\(digits(6, using: &generator))"
case .international:
return "+31 6 \(digits(8, using: &generator))"
case .mobile:
return "06-\(digits(8, using: &generator))"
}
}
private static func address<G: RandomNumberGenerator>(from names: ContactNames, using generator: inout G) -> String {
let street = names.streets.randomElement(using: &generator)!
let number = Int.random(in: 1...250, using: &generator)
let suffix = Int.random(in: 0..<5, using: &generator) == 0 ? String("abc".randomElement(using: &generator)!) : ""
let letters = Array("ABCDEGHJKLMNPRSTVWXZ")
var pair = ""
repeat {
pair = String([letters.randomElement(using: &generator)!, letters.randomElement(using: &generator)!])
} while excludedPostcodeLetters.contains(pair)
let city = names.cities.randomElement(using: &generator)!
return "\(street) \(number)\(suffix), \(Int.random(in: 1000...9999, using: &generator)) \(pair) \(city)"
}
private static func email<G: RandomNumberGenerator>(from names: ContactNames, using generator: inout G) -> String {
let first = mailPart(names.firstNames.randomElement(using: &generator)!)
let last = mailPart(names.lastNames.randomElement(using: &generator)!)
return "\(first).\(last)@\(emailDomains.randomElement(using: &generator)!)"
}
/// Lower case ASCII letters only: `van den Berg` becomes `vandenberg`, `Zoë` becomes `zoe`.
static func mailPart(_ name: String) -> String {
let folded = name.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Locale(identifier: "en_US_POSIX"))
return String(folded.lowercased().unicodeScalars.filter { ("a"..."z").contains($0) }.map(Character.init))
}
}
+10
View File
@@ -0,0 +1,10 @@
import Foundation
/// The help text: the docs, tricks and shortcuts that Plak Help appends, read from `help.md` in the page file format.
public enum HelpText {
/// The text of help.md; empty when the file is missing.
public static let text: String = {
guard let url = LoremText.fileURL(named: "help.md"), let text = try? String(contentsOf: url, encoding: .utf8) else { return "" }
return text
}()
}
+75
View File
@@ -0,0 +1,75 @@
import Foundation
/// The lorem text that `#lorem` puts in the page: an opening sentence of 16 words, two paragraphs and a contact sample.
public struct LoremText: Equatable, Sendable {
public static let trigger = "#lorem"
public static let openingWords = 16
public static let paragraphSentences = 3...5
public static let resourceBundleName = "Plak_PlakCore.bundle"
public var opening: String
public var paragraphs: [[String]]
public var contacts: ContactSample
public init(opening: String, paragraphs: [[String]], contacts: ContactSample) {
self.opening = opening
self.paragraphs = paragraphs
self.contacts = contacts
}
/// The sentence, the two paragraphs, the phones, the addresses and the e-mails, with a blank line between each.
public var text: String {
([opening] + paragraphs.map { $0.joined(separator: " ") } + contacts.blocks).joined(separator: "\n\n")
}
public static func wordCount(_ sentence: String) -> Int {
sentence.split(whereSeparator: \.isWhitespace).count
}
/// Picks random sentences, no sentence twice; nil when `sentences` has no line of 16 words or too few lines.
public static func pick<G: RandomNumberGenerator>(
from sentences: [String], names: ContactNames = .bundled, using generator: inout G
) -> LoremText? {
let openings = sentences.indices.filter { wordCount(sentences[$0]) == openingWords }
guard let opening = openings.randomElement(using: &generator) else { return nil }
let counts = (0..<2).map { _ in Int.random(in: paragraphSentences, using: &generator) }
let rest = sentences.indices.filter { $0 != opening }.shuffled(using: &generator)
guard rest.count >= counts.reduce(0, +) else { return nil }
let second = rest.dropFirst(counts[0]).prefix(counts[1])
let paragraphs = [rest.prefix(counts[0]), second].map { $0.map { sentences[$0] } }
guard let contacts = ContactSample.pick(from: names, using: &generator) else { return nil }
return LoremText(opening: sentences[opening], paragraphs: paragraphs, contacts: contacts)
}
public static func pick(from sentences: [String], names: ContactNames = .bundled) -> LoremText? {
var generator = SystemRandomNumberGenerator()
return pick(from: sentences, names: names, using: &generator)
}
/// The sentences of lorem.txt, one per line; empty when the file is missing.
public static let sentences: [String] = {
guard let url = fileURL(), let text = try? String(contentsOf: url, encoding: .utf8) else { return [] }
return text.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
}()
/// A resource of PlakCore, found without `Bundle.module`: its generated accessor looks next to the .app
/// (not in Contents/Resources) and falls back to an absolute build path.
public static func fileURL(named name: String = "lorem.txt") -> URL? {
let candidates = [
Bundle.main.resourceURL,
Bundle.main.bundleURL,
Bundle.main.executableURL?.deletingLastPathComponent(),
Bundle(for: BundleToken.self).bundleURL.deletingLastPathComponent(),
]
for base in candidates.compactMap({ $0 }) {
let bundle = base.appendingPathComponent(resourceBundleName)
for path in [name, "Contents/Resources/\(name)"] {
let url = bundle.appendingPathComponent(path)
if FileManager.default.fileExists(atPath: url.path) { return url }
}
}
return nil
}
private final class BundleToken {}
}
+15
View File
@@ -0,0 +1,15 @@
import Foundation
/// A web or mail address in the plain text of the page.
public enum PageLink {
/// The address that covers the character at `index`, and its range; nil when no address is there.
public static func link(in text: NSString, at index: Int) -> (url: URL, range: NSRange)? {
guard index >= 0, index < text.length,
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { return nil }
let line = text.lineRange(for: NSRange(location: index, length: 0))
for match in detector.matches(in: text as String, range: line) where NSLocationInRange(index, match.range) {
if let url = match.url { return (url, match.range) }
}
return nil
}
}
+13
View File
@@ -0,0 +1,13 @@
import Foundation
/// The welcome text: the one line the page holds at the first startup.
public enum WelcomeText {
public static let text = "Welcome to plak. For the docs, the tricks and the shortcuts, choose Plak Help in the menu bar icon."
/// The welcome text as a page of one block created at `now`.
public static func page(createdAt now: Date) -> PageFile {
var page = PageFile(text: text)
page.dates = Dictionary(uniqueKeysWithValues: page.blocks.map { ($0.lowerBound, now) })
return page
}
}