Repository Public License
1import Foundation2import Testing3import PrismComponentCatalog4import PrismComponentSDK5import PrismCore6import PrismDataRuntime7import PrismObjectModel8@testable import PrismRenderer910/// A one-page app holding the given components and a `tasks` table, for driving family B logic through the real runtime.11@MainActor12private func familyBApp(_ components: [PrismObject], state: [String: JSONValue] = [:]) throws -> AppRuntime {13 var bp = AppBlueprint(id: "app_fb", name: "Family B", entrypoint: "home")14 bp.state = state15 bp.permissions = [Permission.storageLocal]16 bp.objects = [17 PrismObject(id: "home", type: ObjectType.page, name: "Home", children: ["root"]),18 PrismObject(id: "root", type: "prism.stack", children: components.map(\.id)),19 PrismObject(id: "tasks", type: ObjectType.dataTable, props: [20 "columns": [21 ["name": "title", "type": "text", "required": true], ["name": "done", "type": "boolean"],22 ["name": "status", "type": "text", "options": ["To do", "Doing", "Done"]], ["name": "due", "type": "date"],23 ],24 "seed": [25 ["title": "Draft", "done": true, "status": "Done", "due": "2026-01-05"],26 ["title": "Review", "done": false, "status": "Doing", "due": "2026-01-07"],27 ["title": "Ship", "done": false, "status": "To do", "due": "2026-01-07"],28 ],29 ]),30 ] + components31 let issues = BlueprintValidator.validate(bp, registry: Catalog.registry)32 #expect(issues.errors.isEmpty, "\(issues.errors)")33 return try makeRuntime(bp)34}3536@MainActor37@Suite struct FamilyBTests {38 // MARK: Catalog and router3940 @Test func rendererCoversExactlyTheFamilyBManifests() {41 let manifestTypes = Set(Catalog.manifests.map(\.type)).intersection(FamilyBComponents.types)42 #expect(FamilyBComponents.types.count == 53)43 #expect(manifestTypes == FamilyBComponents.types, "missing manifests: \(FamilyBComponents.types.subtracting(manifestTypes).sorted())")44 let categories: Set<String> = ["input", "forms", "productivity", "time"]45 for type in FamilyBComponents.types {46 let m = Catalog.registry.manifest(type)47 #expect(m != nil, "\(type) is not registered")48 #expect(m.map { categories.contains($0.category) } == true, "\(type) has an unexpected category")49 #expect((m?.keywords.count ?? 0) >= 4, "\(type) needs four keywords")50 }51 }5253 @Test func tableComponentsDeclareStorage() {54 for type in FamilyBComponents.types {55 guard let m = Catalog.registry.manifest(type) else { continue }56 let readsTable = m.props.contains { $0.name == "table" }57 #expect(!readsTable || m.permissions.contains(Permission.storageLocal), "\(type) reads a table without the storage permission")58 }59 }6061 @Test func requiredBindingsAreDeclaredForEveryInput() {62 for type in FamilyBComponents.inputTypes {63 guard let m = Catalog.registry.manifest(type) else { continue }64 #expect(m.props.contains { $0.binding == .required }, "\(type) has no required binding")65 #expect(m.events.contains("change"), "\(type) does not fire change")66 }67 }6869 // MARK: Validation of typed fields7071 @Test func emailValidation() {72 for good in ["maya@example.com", "first.last+tag@sub.example.co", " leo@uqo.ca "] { #expect(FBValidate.email(good), "\(good)") }73 for bad in ["", "maya", "maya@", "@example.com", "maya@example", "ma ya@example.com", "maya@@example.com", "maya@exa_mple.com", ".maya@example.com", "maya@example.c", "maya@-example.com"] {74 #expect(!FBValidate.email(bad), "\(bad)")75 }76 #expect(FBValidate.message(.email, "") == nil)77 #expect(FBValidate.message(.email, "maya@example") != nil)78 #expect(FBValidate.message(.email, "maya@example.com") == nil)79 }8081 @Test func urlValidationAcceptsOnlyWebAddresses() {82 for good in ["https://example.com", "http://example.com/a?b=1#c", "https://sub.example.co.uk:8443/path", "http://localhost:3000"] { #expect(FBValidate.url(good), "\(good)") }83 for bad in ["", "example.com", "ftp://example.com", "file:///etc/passwd", "javascript:alert(1)", "https://", "https://exa mple.com", "mailto:a@b.co", "https://nodot"] {84 #expect(!FBValidate.url(bad), "\(bad)")85 }86 #expect(FBValidate.webURL("HTTPS://Example.com/x")?.host == "Example.com" || FBValidate.webURL("HTTPS://Example.com/x")?.host == "example.com")87 #expect(FBValidate.webURL("file:///Applications") == nil)88 #expect(FBValidate.webURL("x-apple.systempreferences:com.apple.preference") == nil)89 #expect(FBValidate.webURL("https://user:secret@example.com") == nil)90 #expect(FBValidate.message(.url, "example.com") != nil)91 }9293 @Test func phoneValidation() {94 for good in ["+1 (819) 555-0142", "819 555 0142", "5550142", "+33.1.23.45.67.89"] { #expect(FBValidate.phone(good), "\(good)") }95 for bad in ["", "12345", "call me", "+1 819 555 0142 ext 5", "1234567890123456", "555-O142"] { #expect(!FBValidate.phone(bad), "\(bad)") }96 #expect(FBValidate.message(.phone, "12345") != nil)97 #expect(FBValidate.message(.phone, " ") == nil)98 }99100 @Test func percentAndNumberParsing() {101 #expect(FBValidate.percent("12.5") == 12.5)102 #expect(FBValidate.percent("12,5 %") == 12.5)103 #expect(FBValidate.percent("100") == 100)104 #expect(FBValidate.percent("101") == nil)105 #expect(FBValidate.percent("-1") == nil)106 #expect(FBValidate.percent("abc") == nil)107 #expect(FBValidate.percent("25", min: 0, max: 20) == nil)108 #expect(FBValidate.number("72.5") == 72.5)109 #expect(FBValidate.number("1e5") == nil)110 #expect(FBValidate.number("") == nil)111 #expect(FBValidate.number("nan") == nil)112 }113114 // MARK: Numbers, time, colors115116 @Test func boundsClampSnapAndRepairBadRanges() {117 let b = FBBounds(["min": 0, "max": 10, "step": 0.1])118 #expect(b.snap(0.30000000000000004) == 0.3)119 #expect(b.snap(11) == 10)120 #expect(b.snap(-4) == 0)121 #expect(b.fraction(2.5) == 0.25)122 #expect(b.value(fraction: 0.5) == 5)123 let reversed = FBBounds(lo: 5, hi: 5, step: 0)124 #expect(reversed.hi > reversed.lo && reversed.step > 0)125 #expect(JSONValue.fbNumber(3) == .int(3))126 #expect(JSONValue.fbNumber(3.5) == .double(3.5))127 #expect(JSONValue.fbNumber(.nan) == .int(0))128 }129130 @Test func timeFormatting() {131 #expect(FBTime.clock(0) == "00:00")132 #expect(FBTime.clock(75) == "01:15")133 #expect(FBTime.clock(3599) == "59:59")134 #expect(FBTime.clock(3661) == "1:01:01")135 #expect(FBTime.clock(-5) == "00:00")136 #expect(FBTime.stopwatch(0) == "00:00.0")137 #expect(FBTime.stopwatch(65.47) == "01:05.4")138 #expect(FBTime.hhmm(hour: 9, minute: 5) == "09:05")139 #expect(FBTime.hhmm(hour: 27, minute: 70) == "23:59")140 #expect(FBTime.parseHHmm("09:30")?.hour == 9 && FBTime.parseHHmm("09:30")?.minute == 30)141 #expect(FBTime.parseHHmm("23:59:10")?.minute == 59)142 #expect(FBTime.parseHHmm("24:00") == nil)143 #expect(FBTime.parseHHmm("noon") == nil)144 }145146 @Test func colorHex() {147 #expect(FBColor.hex(red: 1, green: 0, blue: 0) == "#FF0000")148 #expect(FBColor.hex(red: 0.2, green: 0.78, blue: 0.35) == "#33C759")149 #expect(FBColor.hex(red: 2, green: -1, blue: 0.5) == "#FF0080")150 #expect(FBColor.normalized("34c759") == "#34C759")151 #expect(FBColor.normalized("#12345") == nil)152 #expect(FBColor.normalized("#GGGGGG") == nil)153 #expect(FBColor.presets.allSatisfy { FBColor.normalized($0) == $0 })154 }155156 @Test func stopwatchAccumulatesAcrossStops() {157 let t0 = Date(timeIntervalSince1970: 1_000)158 var watch = StopwatchState()159 #expect(!watch.isRunning && watch.elapsed(at: t0) == 0)160 watch.start(at: t0)161 #expect(watch.elapsed(at: t0.addingTimeInterval(2.5)) == 2.5)162 watch.stop(at: t0.addingTimeInterval(3))163 #expect(!watch.isRunning && watch.elapsed(at: t0.addingTimeInterval(60)) == 3)164 watch.start(at: t0.addingTimeInterval(100))165 watch.start(at: t0.addingTimeInterval(101)) // starting twice does not restart166 #expect(watch.elapsed(at: t0.addingTimeInterval(104)) == 7)167 watch.reset()168 #expect(!watch.isRunning && watch.elapsed(at: t0.addingTimeInterval(200)) == 0)169 }170171 @Test func countdownReachesZeroOnce() {172 var timer = CountdownState(duration: 5)173 #expect(timer.fraction == 1)174 let early = timer.tick(2)175 #expect(!early && timer.remaining == 3)176 let finished = timer.tick(10)177 #expect(finished && timer.remaining == 0 && timer.isFinished)178 let again = timer.tick()179 #expect(!again, "a finished countdown does not complete again")180 timer.reset()181 #expect(timer.remaining == 5)182 timer.setDuration(0)183 #expect(timer.duration == 1, "the duration never drops below one second")184 }185186 @Test func pomodoroPhaseMachine() {187 var p = PomodoroMachine(work: 10, shortBreak: 3, longBreak: 6, cyclesBeforeLongBreak: 2)188 #expect(p.phase == .work && p.remaining == 10)189 var done = p.tick(9)190 #expect(done == 0 && p.phase == .work && p.remaining == 1)191 done = p.tick(1)192 #expect(done == 1 && p.phase == .shortBreak && p.remaining == 3 && p.completedCycles == 1)193 done = p.tick(3)194 #expect(done == 0 && p.phase == .work && p.remaining == 10)195 done = p.tick(10)196 #expect(done == 1 && p.phase == .longBreak && p.remaining == 6 && p.completedCycles == 2)197 done = p.tick(6)198 #expect(done == 0 && p.phase == .work)199 // A long sleep crosses several phases and counts every finished focus session.200 done = p.tick(10 + 3 + 10 + 6 + 4)201 #expect(done == 2 && p.phase == .work && p.remaining == 6 && p.completedCycles == 4)202 var wasWork = p.skip()203 #expect(wasWork && p.phase == .shortBreak && p.completedCycles == 5)204 wasWork = p.skip()205 #expect(!wasWork && p.phase == .work)206 p.reset()207 #expect(p.phase == .work && p.remaining == 10 && p.completedCycles == 0)208 var degenerate = PomodoroMachine(work: 0, shortBreak: -4, longBreak: 0, cyclesBeforeLongBreak: 0)209 done = degenerate.tick(1)210 #expect(done == 1, "degenerate durations are repaired, not looped on")211 }212213 // MARK: Calculator, keypad, dial, pin214215 private func calc(_ keys: String...) -> String {216 var c = CalculatorEngine()217 c.press(keys: keys)218 return c.display219 }220221 @Test func calculatorArithmetic() {222 #expect(calc("1", "2", "+", "3", "=") == "15")223 #expect(calc("7", "−", "1", "0", "=") == "-3")224 #expect(calc("6", "×", "7", "=") == "42")225 #expect(calc("9", "÷", "4", "=") == "2.25")226 #expect(calc("0", ".", "1", "+", "0", ".", "2", "=") == "0.3")227 #expect(calc("2", "+", "3", "×", "4", "=") == "20", "operators apply left to right, like a pocket calculator")228 #expect(calc("5", "+", "=") == "10")229 #expect(calc("5", "+", "×", "3", "=") == "15", "the last operator pressed wins")230 #expect(calc("8", "÷", "0", "=") == "Error")231 #expect(calc("8", "÷", "0", "=", "4") == "4", "typing after an error starts over")232 #expect(calc("5", "0", "%") == "0.5")233 #expect(calc("9", "±") == "-9")234 #expect(calc("9", "±", "±") == "9")235 #expect(calc("1", "2", "3", "⌫") == "12")236 #expect(calc("7", "⌫") == "0")237 #expect(calc("1", ".", ".", "5") == "1.5")238 #expect(calc("0", "0", "7") == "7")239 #expect(calc("4", "+", "4", "=", "C") == "0")240 #expect(calc("2", "+", "2", "=", "+", "1", "=") == "5", "a result can be continued")241 #expect(calc("2", "+", "2", "=", "9") == "9", "a digit after a result starts a new number")242 }243244 @Test func calculatorStateAndFormatting() {245 var c = CalculatorEngine()246 c.press(keys: ["3", "×"])247 #expect(c.pendingOperator == "×" && c.value == 3)248 c.press(keys: ["8", "÷", "0", "="])249 #expect(c.isError)250 c.press("C")251 #expect(!c.isError && c.display == "0" && c.pendingOperator == nil)252 #expect(CalculatorEngine.format(1e20) == "1e+20")253 #expect(CalculatorEngine.format(-0.5) == "-0.5")254 #expect(CalculatorEngine.format(.infinity) == "Error")255 #expect(CalculatorEngine.keys.count == 20)256 }257258 @Test func keypadEditing() {259 #expect(FBKeypad.press("", key: "5") == "5")260 #expect(FBKeypad.press("0", key: "5") == "5")261 #expect(FBKeypad.press("12", key: ".") == "12.")262 #expect(FBKeypad.press("12.", key: ".") == "12.")263 #expect(FBKeypad.press("", key: ".") == "0.")264 #expect(FBKeypad.press("12", key: ".", decimal: false) == "12")265 #expect(FBKeypad.press("12", key: "⌫") == "1")266 #expect(FBKeypad.press("", key: "⌫") == "")267 #expect(FBKeypad.press("123", key: "C") == "")268 #expect(FBKeypad.press("123", key: "4", maxLength: 3) == "123")269 #expect(FBKeypad.press("1", key: "x") == "1")270 #expect(FBKeypad.keys.count == 12)271 }272273 @Test func dialAngles() {274 #expect(abs(FBDial.fraction(dx: -1, dy: 1) - 0) < 1e-9, "bottom left is the minimum")275 #expect(abs(FBDial.fraction(dx: 0, dy: -1) - 0.5) < 1e-9, "the top is the middle")276 #expect(abs(FBDial.fraction(dx: 1, dy: 1) - 1) < 1e-9, "bottom right is the maximum")277 #expect(abs(FBDial.fraction(dx: -1, dy: 0) - 1.0 / 6) < 1e-9)278 #expect(FBDial.fraction(dx: 0.2, dy: 1) == 1, "the gap snaps to the nearest end")279 #expect(FBDial.fraction(dx: -0.2, dy: 1) == 0)280 }281282 @Test func pinCompletion() {283 #expect(FBPin.sanitize("12a3 4567", length: 4) == "1234")284 #expect(FBPin.sanitize("", length: 4) == "")285 #expect(FBPin.isComplete("1234", length: 4))286 #expect(!FBPin.isComplete("123", length: 4))287 #expect(!FBPin.isComplete("12345", length: 4))288 #expect(!FBPin.isComplete("12a4", length: 4))289 }290291 // MARK: Lists, suggestions, drawing292293 @Test func tagsAndToggles() {294 #expect(FBTags.adding(" new ", to: ["a"]) == ["a", "new"])295 #expect(FBTags.adding("A", to: ["a"]) == nil)296 #expect(FBTags.adding(" ", to: []) == nil)297 #expect(FBTags.toggling("B", in: ["C"], order: ["A", "B", "C"]) == ["B", "C"])298 #expect(FBTags.toggling("C", in: ["B", "C"], order: ["A", "B", "C"]) == ["B"])299 }300301 @Test func suggestionsAndCommands() {302 let options = ["Rent", "Restaurant", "Groceries", "Car rental"]303 #expect(FBSuggest.filter(options, text: "re") == ["Rent", "Restaurant", "Car rental"])304 #expect(FBSuggest.filter(options, text: "rent") == ["Car rental"], "an exact match is not suggested back")305 #expect(FBSuggest.filter(options, text: "") == [])306 #expect(FBSuggest.filter(options, text: "r", limit: 2).count == 2)307 #expect(FBSuggest.remember("desk", in: ["lamp", "Desk", "chair"], max: 3) == ["desk", "lamp", "chair"])308 #expect(FBSuggest.remember("x", in: ["a", "b", "c"], max: 3) == ["x", "a", "b"])309 #expect(FBSuggest.remember(" ", in: ["a"]) == ["a"])310 let items: [JSONValue] = [["title": "New task"], ["title": "Show completed tasks"], ["title": "Hide completed tasks"]]311 #expect(FBSuggest.commands(items, query: "task comp").count == 2)312 #expect(FBSuggest.commands(items, query: "NEW").first?["title"]?.stringValue == "New task")313 #expect(FBSuggest.commands(items, query: " ").count == 3)314 #expect(FBSuggest.commands(items, query: "zzz").isEmpty)315 }316317 @Test func drawingRoundTrip() {318 let strokes = [[CGPoint(x: 1.04, y: 2), CGPoint(x: 10.26, y: 20.5)], [CGPoint(x: 5, y: 5)]]319 let json = FBDrawing.encode(strokes)320 #expect(json == [[[1, 2], [10.3, 20.5]], [[5, 5]]])321 #expect(FBDrawing.decode(json) == [[CGPoint(x: 1, y: 2), CGPoint(x: 10.3, y: 20.5)], [CGPoint(x: 5, y: 5)]])322 #expect(FBDrawing.decode("nonsense") == [])323 #expect(FBDrawing.decode([[["x", 1], [2, 3]]]) == [[CGPoint(x: 2, y: 3)]])324 let dense = (0..<50).map { CGPoint(x: Double($0) * 0.2, y: 0) }325 let thin = FBDrawing.thinned(dense)326 #expect(thin.count < 12 && thin.first == dense.first && thin.last == dense.last)327 #expect(FBDrawing.thinned([CGPoint(x: 3, y: 3)]) == [CGPoint(x: 3, y: 3)])328 }329330 // MARK: Dates and record views331332 @Test func dayArithmetic() {333 #expect(FBDay.adding(1, to: "2026-02-28") == "2026-03-01")334 #expect(FBDay.adding(-1, to: "2024-03-01") == "2024-02-29")335 #expect(FBDay.weekday("2026-01-01") == 5, "1 January 2026 is a Thursday")336 #expect(FBDay.weekStart("2026-01-07", firstWeekday: 1) == "2026-01-04")337 #expect(FBDay.weekStart("2026-01-07", firstWeekday: 2) == "2026-01-05")338 #expect(FBDay.weekStart("2026-01-04", firstWeekday: 2) == "2025-12-29")339 #expect(FBDay.daysInMonth(year: 2024, month: 2) == 29)340 #expect(FBDay.daysInMonth(year: 2026, month: 2) == 28)341 #expect(FBDay.shiftMonth(year: 2026, month: 1, by: -1) == (2025, 12))342 #expect(FBDay.shiftMonth(year: 2026, month: 12, by: 1) == (2027, 1))343 #expect(FBDay.shiftMonth(year: 2026, month: 6, by: 30) == (2028, 12))344 #expect(FBDay.normalized("2026-01-05T10:00:00Z") == "2026-01-05")345 #expect(FBDay.normalized("2026-02-30") == nil)346 #expect(FBDay.normalized("soon") == nil)347 #expect(FBDay.parts("2026-11-22")?.month == 11)348 }349350 @Test func calendarMonthGrid() {351 let january = MonthGrid(year: 2026, month: 1, firstWeekday: 1)352 #expect(january.cells.count == 35 && january.weeks == 5)353 #expect(Array(january.cells.prefix(5)) == [nil, nil, nil, nil, 1], "January 2026 starts on a Thursday")354 #expect(january.cells.last == 31)355 #expect(january.iso(5) == "2026-01-05")356 let mondayFirst = MonthGrid(year: 2026, month: 1, firstWeekday: 2)357 #expect(Array(mondayFirst.cells.prefix(4)) == [nil, nil, nil, 1])358 let february = MonthGrid(year: 2026, month: 2, firstWeekday: 1)359 #expect(february.cells.count == 28 && february.cells.first == 1 && february.cells.last == 28, "February 2026 fills exactly four weeks")360 let leap = MonthGrid(year: 2024, month: 2, firstWeekday: 1)361 #expect(leap.cells.compactMap { $0 }.count == 29)362 let august = MonthGrid(year: 2026, month: 8, firstWeekday: 1)363 #expect(august.weeks == 6 && august.cells.compactMap { $0 } == Array(1...31))364 }365366 @Test func agendaPutsUpcomingDaysFirst() {367 let rows: [[String: JSONValue]] = [368 ["id": 1, "date": "2026-01-05", "title": "Past A"], ["id": 2, "date": "2026-03-02", "title": "Later"],369 ["id": 3, "date": "2026-02-03", "title": "Soon 1"], ["id": 4, "date": "2026-02-03", "title": "Soon 2"],370 ["id": 5, "date": "2026-01-20", "title": "Past B"], ["id": 6, "date": "", "title": "Undated"],371 ]372 let upcoming = FBRecords.agenda(rows, column: "date", today: "2026-02-01", includePast: false)373 #expect(upcoming.map(\.day) == ["2026-02-03", "2026-03-02"])374 #expect(upcoming[0].rows.count == 2)375 let all = FBRecords.agenda(rows, column: "date", today: "2026-02-01", includePast: true)376 #expect(all.map(\.day) == ["2026-02-03", "2026-03-02", "2026-01-20", "2026-01-05"])377 #expect(FBRecords.agenda(rows, column: "date", today: "2026-02-03", includePast: false).first?.day == "2026-02-03", "today counts as upcoming")378 let limited = FBRecords.agenda(rows, column: "date", today: "2026-02-01", includePast: true, limit: 3)379 #expect(limited.flatMap(\.rows).count == 3)380 #expect(FBRecords.byDay(rows, column: "date")["2026-02-03"]?.count == 2)381 #expect(FBRecords.counts(rows, column: "date") == ["2026-01-05": 1, "2026-03-02": 1, "2026-02-03": 2, "2026-01-20": 1])382 }383384 @Test func habitGridWeeksAndLevels() {385 let weeks = FBRecords.heatWeeks(end: "2026-01-07", weeks: 3, firstWeekday: 1)386 #expect(weeks.count == 3)387 #expect(weeks[0].first == "2025-12-21")388 #expect(weeks[2] == ["2026-01-04", "2026-01-05", "2026-01-06", "2026-01-07", nil, nil, nil], "days after the end are blank")389 #expect(FBRecords.heatWeeks(end: "2026-01-07", weeks: 500).count == 53)390 #expect(FBRecords.level(0, max: 8) == 0)391 #expect(FBRecords.level(1, max: 8) == 1)392 #expect(FBRecords.level(4, max: 8) == 2)393 #expect(FBRecords.level(8, max: 8) == 4)394 #expect(FBRecords.level(3, max: 0) == 0)395 }396397 @Test func kanbanColumnsAndGrouping() {398 #expect(FBRecords.columns(preferred: ["To do", "Doing", "Done"], values: ["Done", "Blocked", "To do"]) == ["To do", "Doing", "Done", "Blocked"])399 #expect(FBRecords.columns(preferred: [], values: ["B", "A", "B", ""]) == ["B", "A", ""])400 #expect(FBRecords.columns(preferred: ["A"], values: ["A"]) == ["A"])401 let groups = FBRecords.grouped([["id": 1, "s": "A"], ["id": 2, "s": "B"], ["id": 3, "s": "A"], ["id": 4]], by: "s")402 #expect(groups["A"]?.count == 2 && groups["B"]?.count == 1 && groups[""]?.count == 1)403 }404405 @Test func kanbanMoveUpdatesTheRecordAndFiresDrop() throws {406 let board = PrismObject(id: "board", type: "prism.kanban", props: ["table": "tasks", "statusColumn": "status", "titleColumn": "title"],407 events: ["drop": [["type": "setState", "key": "lastDrop", "value": ["$expr": "concat(row.title, ' → ', value)"]]]])408 let rt = try familyBApp([board], state: ["lastDrop": ""])409 let ship = try #require(rt.fbRows("tasks").first { $0["title"] == "Ship" }?["id"]?.intValue)410 #expect(rt.fbMoveCard(board, id: ship, to: "Doing"))411 #expect(try rt.store.record("tasks", id: ship)?["status"] == "Doing")412 #expect(rt.state["lastDrop"] == "Ship → Doing")413 #expect(FBRecords.grouped(rt.fbRows("tasks"), by: "status")["Doing"]?.count == 2, "the board re-reads the table after the move")414 #expect(!rt.fbMoveCard(board, id: ship, to: "Doing"), "dropping a card on its own column changes nothing")415 #expect(!rt.fbMoveCard(board, id: 9_999, to: "Done"), "an unknown record is refused")416 #expect(!rt.logs.contains { $0.level == .error })417 }418419 @Test func checklistTogglesAndAddsRecords() throws {420 let list = PrismObject(id: "list", type: "prism.checklist", props: ["table": "tasks", "doneColumn": "done"],421 events: ["toggle": [["type": "setState", "key": "toggled", "value": ["$expr": "row.title"]]], "add": [["type": "setState", "key": "added", "value": ["$expr": "value"]]]])422 let rt = try familyBApp([list], state: ["toggled": "", "added": 0])423 let review = try #require(rt.fbRows("tasks").first { $0["title"] == "Review" }?["id"]?.intValue)424 #expect(rt.fbToggleItem(list, id: review, to: true))425 #expect(try rt.store.record("tasks", id: review)?["done"]?.isTruthy == true)426 #expect(rt.state["toggled"] == "Review")427 #expect(rt.fbToggleItem(list, id: review, to: false))428 #expect(try rt.store.record("tasks", id: review)?["done"]?.isTruthy == false)429 #expect(rt.fbTitleColumn("tasks", preferred: nil, excluding: ["done"]) == "title")430 #expect(rt.fbAddItem(list, title: " Celebrate "))431 let added = try #require(rt.fbRows("tasks").last)432 #expect(added["title"] == "Celebrate" && added["done"]?.isTruthy == false)433 #expect(rt.state["added"] == added["id"])434 #expect(!rt.fbAddItem(list, title: " "), "a blank item is not added")435 #expect(try rt.store.count("tasks") == 4)436 }437438 @Test func formSubmitsOnlyWhenNoRuleFails() throws {439 let form = PrismObject(id: "form", type: "prism.form", props: ["title": "Sign up", "rules": [440 ["when": ["$expr": "isEmpty(state.email)"], "message": "Email is required."],441 ["when": ["$expr": "state.age < 18"], "message": "You must be an adult."],442 ]], events: ["submit": [["type": "setState", "key": "submitted", "value": ["$expr": "state.submitted + 1"]]]])443 let rt = try familyBApp([form], state: ["email": "", "age": 30, "submitted": 0])444 #expect(rt.fbSubmit(form: form) == ["Email is required."])445 #expect(rt.state["submitted"] == 0)446 rt.setState("email", "maya@example.com")447 #expect(rt.fbSubmit(form: form).isEmpty)448 #expect(rt.state["submitted"] == 1)449 rt.setState("age", 12)450 #expect(rt.fbSubmit(form: form) == ["You must be an adult."])451 #expect(rt.state["submitted"] == 1)452 }453454 @Test func linkButtonRefusesEverythingButWebAddresses() throws {455 func link(_ id: String, _ url: String) -> PrismObject {456 PrismObject(id: id, type: "prism.linkButton", props: ["title": "Open", "url": .string(url)], events: ["open": [["type": "setState", "key": "opened", "value": ["$expr": "value"]]]])457 }458 let good = link("good", "https://example.com/guide"), file = link("file", "file:///etc/passwd"), script = link("script", "javascript:alert(1)")459 let rt = try familyBApp([good, file, script], state: ["opened": ""])460 var opened: [URL] = []461 #expect(rt.fbOpenLink(good) { opened.append($0) })462 #expect(opened.map(\.absoluteString) == ["https://example.com/guide"])463 #expect(rt.state["opened"] == "https://example.com/guide")464 #expect(!rt.fbOpenLink(file) { opened.append($0) })465 #expect(!rt.fbOpenLink(script) { opened.append($0) })466 #expect(opened.count == 1, "nothing but the web address reached the opener")467 #expect(rt.notices.count == 2 && rt.notices.allSatisfy { $0.tone == "warning" })468 }469470 @Test func bindingHelpersWriteStateAndFireChange() throws {471 let slider = PrismObject(id: "s", type: "prism.slider", props: ["label": "Volume", "value": ["$bind": "volume"]],472 events: ["change": [["type": "setState", "key": "changes", "value": ["$expr": "state.changes + 1"]]]])473 let chips = PrismObject(id: "c", type: "prism.chipSelect", props: ["value": ["$bind": "picked"], "options": ["A", "B"], "optionsFrom": ["table": "tasks", "column": "status"], "multiple": true])474 let rt = try familyBApp([slider, chips], state: ["volume": 10, "changes": 0, "picked": []])475 rt.fbSet(slider, "value", .fbNumber(35))476 #expect(rt.state["volume"] == 35 && rt.state["changes"] == 1)477 #expect(rt.fbOptions(chips) == ["A", "B", "Doing", "Done", "To do"] || Set(rt.fbOptions(chips)) == ["A", "B", "Doing", "Done", "To do"])478 rt.fbSet(chips, "value", ["A", "Done"])479 #expect(rt.fbStrings(chips.props["value"]) == ["A", "Done"])480 #expect(rt.fbText(slider, "label") == "Volume" && rt.fbText(slider, "placeholder", "fallback") == "fallback")481 }482483 // MARK: Tree, pagination, wizard484485 @Test func treeFlattening() {486 let items: [JSONValue] = [487 ["id": "inbox", "title": "Inbox"],488 ["id": "projects", "title": "Projects", "icon": "folder", "children": [["id": "alpha", "title": "Alpha"], ["id": "beta", "title": "Beta", "children": [["title": "Unnamed"]]]]],489 ]490 #expect(FBTree.parents(items) == ["projects", "beta"])491 #expect(FBTree.flatten(items, expanded: []).map(\.id) == ["inbox", "projects"])492 let open = FBTree.flatten(items, expanded: ["projects"])493 #expect(open.map(\.id) == ["inbox", "projects", "alpha", "beta"])494 #expect(open.map(\.depth) == [0, 0, 1, 1])495 #expect(open[1].hasChildren && open[1].icon == "folder" && !open[2].hasChildren)496 let all = FBTree.flatten(items, expanded: FBTree.parents(items))497 #expect(all.count == 5 && all.last?.depth == 2 && all.last?.title == "Unnamed" && all.last?.id == "beta.0", "a node without an id gets a stable path id")498 #expect(Set(all.map(\.id)).count == all.count)499 }500501 @Test func paginationWindow() {502 #expect(FBPagination.window(page: 1, count: 5) == [1, 2, 3, 4, 5])503 #expect(FBPagination.window(page: 5, count: 12) == [1, nil, 4, 5, 6, nil, 12])504 #expect(FBPagination.window(page: 1, count: 12) == [1, 2, nil, 12])505 #expect(FBPagination.window(page: 12, count: 12) == [1, nil, 11, 12])506 #expect(FBPagination.window(page: 2, count: 12) == [1, 2, 3, nil, 12])507 #expect(FBPagination.window(page: 99, count: 0) == [1])508 #expect(FBPagination.clamp(0, count: 7) == 1 && FBPagination.clamp(9, count: 7) == 7 && FBPagination.clamp(3, count: 7) == 3)509 #expect(FBWizard.clamp(-1, count: 3) == 0 && FBWizard.clamp(5, count: 3) == 2 && FBWizard.clamp(2, count: 0) == 0)510 }511512 // MARK: Rendering with live data513514 @Test func recordViewsRenderTheirTableWithoutErrors() throws {515 let rt = try familyBApp([516 PrismObject(id: "board", type: "prism.kanban", props: ["table": "tasks", "statusColumn": "status"]),517 PrismObject(id: "cal", type: "prism.calendar", props: ["table": "tasks", "dateColumn": "due", "selection": ["$bind": "day"]]),518 PrismObject(id: "list", type: "prism.checklist", props: ["table": "tasks", "doneColumn": "done", "title": "Tasks"]),519 PrismObject(id: "week", type: "prism.weekPlanner", props: ["table": "tasks", "dateColumn": "due", "week": "2026-01-07"]),520 PrismObject(id: "heat", type: "prism.habitGrid", props: ["table": "tasks", "dateColumn": "due", "endDate": "2026-01-31"]),521 PrismObject(id: "agenda", type: "prism.agenda", props: ["table": "tasks", "dateColumn": "due", "from": "2026-01-06"]),522 ], state: ["day": "2026-01-07"])523 let rep = try #require(renderBitmap(AppView(runtime: rt), size: CGSize(width: 900, height: 1400)))524 saveSnapshot(rep, "family-b-record-views")525 #expect(distinctColors(rep) > 6)526 #expect(!rt.logs.contains { $0.level != .info }, "\(rt.logs.filter { $0.level != .info }.map(\.message))")527 }528529 @Test func misconfiguredTableComponentsDegradeToAMessage() throws {530 // A column that does not exist must not crash or log a query error: the component explains itself instead.531 let rt = try familyBApp([532 PrismObject(id: "board", type: "prism.kanban", props: ["table": "tasks", "statusColumn": "ghost"]),533 PrismObject(id: "cal", type: "prism.calendar", props: ["table": "tasks", "dateColumn": "ghost"]),534 PrismObject(id: "list", type: "prism.checklist", props: ["table": "tasks", "doneColumn": "ghost", "allowAdd": false]),535 ])536 let rep = try #require(renderBitmap(AppView(runtime: rt), size: CGSize(width: 900, height: 700)))537 #expect(distinctColors(rep) > 1)538 #expect(!rt.logs.contains { $0.level == .error })539 #expect(!rt.fbMoveCard(try #require(rt.blueprint.object("board")), id: 1, to: "Done"))540 }541}542