// The verbs answered in memory, from the bundled synthetic records — for // tests and previews only; the root's records are the core's // (`CoreRecords`). Every write answers a change with a byline and can be // undone, as the real verbs do: `undo(change:)` sends the change's id through // the generic verb (`GenericVerbs.undo(changeId:)`), which this actor answers // in memory — the fixture side of the seam `CoreRecords` answers over // cotton-ffi. Made with `answersUndo: false` it stands for a build whose core // lacks the verb: every change is minted not undoable and undo is refused. import CottonValues import Foundation import CottonKit public actor FixtureRecords: Records, GenericVerbs, ThoughtKeepingRecords { public static let pageSize = 50 /// Where thoughts are kept when no table plays the thought role. static let undeclaredThoughts = "Kept thoughts" private let tools: [ToolDefinition] private let definitions: [String: TableDefinition] private var tables: [String: [TableRecord]] private var changes: [String: (table: String, change: ChangeRecord, order: [String]?)] = [:] private var nextChange = 1 private let byline: String public nonisolated let answersUndo: Bool /// Whether words a table does not take are kept as a thought here. public nonisolated let thoughtsKept: Bool public init( definitions: [TableDefinition], records: [String: [TableRecord]], byline: String = "You", tools: [ToolDefinition] = [], answersUndo: Bool = true, thoughtsKept: Bool = false ) { self.thoughtsKept = thoughtsKept self.definitions = Dictionary(definitions.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) self.tables = records self.byline = byline self.tools = tools self.answersUndo = answersUndo } /// The built-in definitions and every table's synthetic records. public static func bundled() -> FixtureRecords { bundled(FixtureDefinitions.load().definitions, from: CottonUIResources.bundle) } static func bundled(from bundle: Bundle?) -> FixtureRecords { bundled(FixtureDefinitions.load(from: bundle).definitions, from: bundle) } private static func bundled(_ definitions: [TableDefinition], from bundle: Bundle?) -> FixtureRecords { var records: [String: [TableRecord]] = [:] for definition in definitions { records[definition.id] = (try? FixtureDefinitions.fixtureRecords(for: definition.id, bundle: bundle)) ?? [] } return FixtureRecords(definitions: definitions, records: records) } public func toolDefinitions() async throws -> [ToolDefinition] { tools } public func tableDefinitions() async throws -> [TableDefinition] { definitions.values.sorted { $0.id < $1.id } } public func count(table: String) async throws -> Int { _ = try definition(table) return tables[table]?.count ?? 0 } public func lastChanged(table: String) async throws -> String? { _ = try definition(table) return tables[table]?.compactMap { $0["updated_at"].text }.max() } public func list( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue] ) async throws -> RecordPage { let definition = try self.definition(table) var rows = tables[table] ?? [] if !filter.isEmpty { rows = rows.filter { record in filter.allSatisfy { Self.holds(record[$0.key], $0.value) } } } if let project, let key = definition.project { rows = rows.filter { FaceText.linkIDs($0[key]).contains(project) } } if let needle = query?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), !needle.isEmpty { // The definition's own `search` columns when it names them, else // every text-like column — by any part of a word. let searched = definition.search.isEmpty ? definition.columns.filter { [.text, .longtext, .choice].contains($0.type) }.map(\.key) : definition.search rows = rows.filter { record in searched.contains { key in record[key].text?.lowercased().contains(needle) ?? false } } } rows = Self.ordered(rows, by: definition) let start = max(0, page) * Self.pageSize guard start < rows.count else { return RecordPage(records: [], next: nil, total: rows.count) } let end = min(rows.count, start + Self.pageSize) return RecordPage(records: Array(rows[start.. LinkTitles { var titles: [String: String] = [:] var pictures: [String: String] = [:] for table in Set(links.map(\.table)) { guard let definition = definitions[table] else { continue } let ids = Set(links.filter { $0.table == table }.map(\.id)) for row in tables[table] ?? [] where ids.contains(row.id) { titles[row.id] = row.said?.slip.name ?? row[definition.title].text pictures[row.id] = LinkTitles.picture(of: row, in: definition) } } return LinkTitles(titles, pictures: pictures) } public func get(table: String, id: String) async throws -> TableRecord? { _ = try definition(table) if readsHeld { throw ActionRefused(ShellLines.line("definitions", "fixture.still_reading")) } return tables[table]?.first { $0.id == id } } /// While held, a record is not read back (a large database still /// answering): what a page shows meanwhile is what it already knows. private var readsHeld = false public func holdReads(_ held: Bool) { readsHeld = held } public func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord { _ = try definition(table) var stamped = data stamped["updated_at"] = .text(CottonDate.format(Date())) let record = TableRecord(id: "fixture-\(table)-\(UUID().uuidString.lowercased())", values: stamped) tables[table, default: []].append(record) return remember(table: table, before: nil, after: record) } public nonisolated func keepsThoughts(table: String) -> Bool { thoughtsKept } /// A thought, with where it was said, among the `thought` records — made /// whether or not this store declares a thought table, as the core's is. /// The file's record among the `photo`, `video` or `document` records; /// no bytes are kept. A fixture is one database, so a thought's picture /// is kept where any other is. public func captureMedia( file: URL, mime: String, kind: CaptureMediaKind, filename: String?, forThought: Bool ) async throws -> MediaCaptured { let id = "fixture-\(kind.rawValue)-\(UUID().uuidString.lowercased())" let values: [String: RecordValue] = ["filename": filename.map(RecordValue.text) ?? .null, "mime": .text(mime)] tables[kind.rawValue, default: []].append(TableRecord(id: id, values: values)) return MediaCaptured(key: "media/\(id)", recordId: id) } public func keepThought( _ words: String, table: String?, recordId: String?, attachments: [CaptureAttachment] ) async throws -> ChangeRecord { var values: [String: RecordValue] = ["raw_text": .text(words)] if let table { values["said_table"] = .text(table) } if let recordId, table != nil { values["said_record_id"] = .text(recordId) } if !attachments.isEmpty { values["attachments"] = .list(attachments.map { .object(["kind": .text($0.kind), "id": .text($0.id)]) }) } let record = TableRecord(id: "fixture-thought-\(UUID().uuidString.lowercased())", values: values) // The core keeps a thought whether or not the store declares the // table playing the thought role; undeclared, it is kept apart. let thoughts = definitions.values.first(where: { $0.role == .thought })?.id ?? Self.undeclaredThoughts tables[thoughts, default: []].append(record) return remember(table: thoughts, before: nil, after: record) } public func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord { _ = try definition(table) guard let index = tables[table]?.firstIndex(where: { $0.id == id }) else { throw RecordsError.unknownRecord(id) } let before = tables[table]![index] var after = before for (key, value) in patch { after.values[key] = value } after.values["updated_at"] = .text(CottonDate.format(Date())) tables[table]![index] = after return remember(table: table, before: before, after: after) } public func delete(table: String, id: String) async throws -> ChangeRecord { _ = try definition(table) guard let index = tables[table]?.firstIndex(where: { $0.id == id }) else { throw RecordsError.unknownRecord(id) } let before = tables[table]!.remove(at: index) return remember(table: table, before: before, after: nil) } /// Writes the order column so the ids given come first, in that order, /// numbered 1, 2, 3…; records not named keep their places after them. public func reorder(table: String, ids: [String]) async throws -> ChangeRecord { let definition = try self.definition(table) guard let key = definition.order else { throw RecordsError.noOrderColumn(table) } let previous = Self.ordered(tables[table] ?? [], by: definition).map(\.id) let named = Set(ids) let sequence = ids + previous.filter { !named.contains($0) } for (position, id) in sequence.enumerated() { if let index = tables[table]?.firstIndex(where: { $0.id == id }) { tables[table]![index].values[key] = .number(Double(position + 1)) } } return remember(table: table, before: nil, after: nil, order: previous) } public func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord { try await update(table: table, id: id, patch: [column: .text(target)]) } /// The Records verb: the change's id, sent through the generic verb. public func undo(change id: String) async throws -> ChangeRecord { try await undo(changeId: id) } /// The generic verb, in memory: puts `before` back. The undoing change is /// not itself kept for undo (no redo here), so it says so. Absent in a /// build that says it lacks the verb, however it is reached. public func undo(changeId id: String) async throws -> ChangeRecord { guard answersUndo else { throw GenericVerbsError.absent(verb: "undo") } guard let entry = changes.removeValue(forKey: id) else { throw RecordsError.unknownChange(id) } let table = entry.table if let order = entry.order { return try await reorder(table: table, ids: order) } let before = entry.change.before, after = entry.change.after switch (before, after) { case (nil, let created?): tables[table]?.removeAll { $0.id == created.id } case (let old?, nil): tables[table, default: []].append(old) case (let old?, let new?): if let index = tables[table]?.firstIndex(where: { $0.id == new.id }) { tables[table]![index] = old } case (nil, nil): break } return ChangeRecord( id: "undo-\(id)", byline: byline, before: after, after: before, undoable: false, reason: ShellLines.line("definitions", "fixture.undo_itself")) } /// Whether a column's value matches a filter's: equal, or — a column /// holding several values (a person's `people` links) — one of them. static func holds(_ value: RecordValue, _ wanted: RecordValue) -> Bool { if value == wanted { return true } // An array asked for is any of its values, as the core reads it. if case .list(let any) = wanted { return any.contains { holds(value, $0) } } if case .list(let items) = value { return items.contains(wanted) } return false } private func definition(_ table: String) throws -> TableDefinition { guard let definition = definitions[table] else { throw RecordsError.unknownTable(table) } return definition } private func remember(table: String, before: TableRecord?, after: TableRecord?, order: [String]? = nil) -> ChangeRecord { let change = ChangeRecord( id: "change-\(nextChange)", byline: byline, before: before, after: after, undoable: answersUndo, reason: answersUndo ? nil : GenericVerbsWords.undoAbsent) nextChange += 1 changes[change.id] = (table, change, order) return change } /// The order column when the table has one, else the definition's list /// order, else the date column newest first, else the title. static func ordered(_ rows: [TableRecord], by definition: TableDefinition) -> [TableRecord] { if let key = definition.order { return rows.sorted { ($0[key].number ?? .infinity) < ($1[key].number ?? .infinity) } } if definition.sort != nil { return definition.sorted(rows) } if let key = definition.date { return rows.sorted { ($0[key].text ?? "") > ($1[key].text ?? "") } } return rows.sorted { ($0[definition.title].text ?? "") < ($1[definition.title].text ?? "") } } } // A Settings source and a fixture answer their own rows, in the definition's order. extension TableDefinition { /// `records` in the definition's `sort` order, or as they came when the /// table has a drag order or no sort. public func sorted(_ records: [TableRecord]) -> [TableRecord] { guard order == nil, let sort else { return records } return records.enumerated().sorted { a, b in var (x, y) = (a.element[sort.column], b.element[sort.column]) if !Self.precedes(x, y) && !Self.precedes(y, x), let tie = sort.tie { (x, y) = (a.element[tie], b.element[tie]) } // An empty value goes last either way round. switch (RecordValue.isBlank(x), RecordValue.isBlank(y)) { case (false, true): return true case (true, false): return false case (true, true): return a.offset < b.offset case (false, false): if !Self.precedes(x, y) && !Self.precedes(y, x) { return a.offset < b.offset } return sort.descending ? Self.precedes(y, x) : Self.precedes(x, y) } }.map(\.element) } /// Ascending order of two written column values: numbers by size, text /// as text (an ISO date sorts as its day). static func precedes(_ x: RecordValue, _ y: RecordValue) -> Bool { switch (x, y) { case (.number(let a), .number(let b)): return a < b case (.bool(let a), .bool(let b)): return !a && b // Text as a person reads it: case and accents folded, numbers by // size ("anil" beside "Anand", "9" before "10"); an ISO day sorts as // its day either way. default: return (x.text ?? "").localizedStandardCompare(y.text ?? "") == .orderedAscending } } }