Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Work/Database/DatabaseDrafts.swift3// Description: The pure pieces of the database screen: the editable filter tree (⇄ `DatabaseViewFilter`), the operators4// each property type accepts, the merge of a draft into a view's config, the French display of cell values5// (stored and server-computed), and the geometry of the calendar and timeline views (days of the server's6// time zone).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPNotesAPI12import SPNotesDocument13import SPNotesSync1415// MARK: - Filter draft1617/// An editable copy of a view's filter tree. Node ids are local (stable while editing).18public struct DatabaseFilterDraft: Equatable, Sendable {19 public enum Conjunction: String, Sendable, Equatable { case all, any }2021 public struct Rule: Identifiable, Equatable, Sendable {22 public var id = UUID()23 public var property: String24 public var op: String25 public var value: JSONValue?2627 public init(property: String, op: String, value: JSONValue? = nil) {28 self.property = property29 self.op = op30 self.value = value31 }32 }3334 public struct Group: Identifiable, Equatable, Sendable {35 public var id = UUID()36 public var conjunction: Conjunction37 public var nodes: [Node]3839 public init(conjunction: Conjunction = .all, nodes: [Node] = []) {40 self.conjunction = conjunction41 self.nodes = nodes42 }43 }4445 public indirect enum Node: Identifiable, Equatable, Sendable {46 case rule(Rule)47 case group(Group)4849 public var id: UUID {50 switch self {51 case .rule(let rule): return rule.id52 case .group(let group): return group.id53 }54 }55 }5657 public var root: Group5859 public init() { root = Group() }6061 /// From a stored filter. A bare rule at the top becomes a one-rule « all » group (what the server requires).62 public init(filter: DatabaseViewFilter?) {63 switch filter {64 case nil: root = Group()65 case .rule?: root = Group(conjunction: .all, nodes: [Self.node(filter!)])66 case .all(let nodes)?: root = Group(conjunction: .all, nodes: nodes.map(Self.node))67 case .any(let nodes)?: root = Group(conjunction: .any, nodes: nodes.map(Self.node))68 }69 }7071 private static func node(_ filter: DatabaseViewFilter) -> Node {72 switch filter {73 case .rule(let property, let op, let value): return .rule(Rule(property: property, op: op, value: value))74 case .all(let nodes): return .group(Group(conjunction: .all, nodes: nodes.map(node)))75 case .any(let nodes): return .group(Group(conjunction: .any, nodes: nodes.map(node)))76 }77 }7879 /// The filter to evaluate / send (nil when there is no rule at all). Empty nested groups are dropped.80 public var filter: DatabaseViewFilter? { Self.filter(root, isRoot: true) }8182 private static func filter(_ group: Group, isRoot: Bool) -> DatabaseViewFilter? {83 let nodes: [DatabaseViewFilter] = group.nodes.compactMap { node in84 switch node {85 case .rule(let rule): return .rule(property: rule.property, op: rule.op, value: DatabaseFilterOps.needsValue(rule.op) ? rule.value : nil)86 case .group(let inner): return filter(inner, isRoot: false)87 }88 }89 guard !nodes.isEmpty else { return nil }90 return group.conjunction == .all ? .all(nodes) : .any(nodes)91 }9293 public var ruleCount: Int { Self.count(root) }9495 private static func count(_ group: Group) -> Int {96 group.nodes.reduce(0) { total, node in97 switch node {98 case .rule: return total + 199 case .group(let inner): return total + count(inner)100 }101 }102 }103104 // MARK: edits by id105106 public mutating func addRule(_ rule: Rule, to groupId: UUID? = nil) {107 Self.mutate(&root, groupId ?? root.id) { $0.nodes.append(.rule(rule)) }108 }109110 public mutating func addGroup(to groupId: UUID? = nil, conjunction: Conjunction = .any) {111 Self.mutate(&root, groupId ?? root.id) { $0.nodes.append(.group(Group(conjunction: conjunction))) }112 }113114 public mutating func setConjunction(_ conjunction: Conjunction, of groupId: UUID) {115 Self.mutate(&root, groupId) { $0.conjunction = conjunction }116 }117118 public mutating func remove(_ id: UUID) { Self.remove(&root, id) }119120 public mutating func update(_ id: UUID, _ change: (inout Rule) -> Void) { Self.update(&root, id, change) }121122 public func rule(_ id: UUID) -> Rule? { Self.find(root, id) }123124 private static func mutate(_ group: inout Group, _ id: UUID, _ change: (inout Group) -> Void) {125 if group.id == id { change(&group); return }126 for index in group.nodes.indices {127 if case .group(var inner) = group.nodes[index] {128 mutate(&inner, id, change)129 group.nodes[index] = .group(inner)130 }131 }132 }133134 private static func remove(_ group: inout Group, _ id: UUID) {135 group.nodes.removeAll { $0.id == id }136 for index in group.nodes.indices {137 if case .group(var inner) = group.nodes[index] {138 remove(&inner, id)139 group.nodes[index] = .group(inner)140 }141 }142 }143144 private static func update(_ group: inout Group, _ id: UUID, _ change: (inout Rule) -> Void) {145 for index in group.nodes.indices {146 switch group.nodes[index] {147 case .rule(var rule) where rule.id == id:148 change(&rule)149 group.nodes[index] = .rule(rule)150 case .group(var inner):151 update(&inner, id, change)152 group.nodes[index] = .group(inner)153 default: break154 }155 }156 }157158 private static func find(_ group: Group, _ id: UUID) -> Rule? {159 for node in group.nodes {160 switch node {161 case .rule(let rule) where rule.id == id: return rule162 case .group(let inner): if let found = find(inner, id) { return found }163 default: break164 }165 }166 return nil167 }168}169170/// The operators of the server's filter engine, per property type.171public enum DatabaseFilterOps {172 public static func ops(for type: String) -> [String] {173 typealias O = DatabaseFilterOp174 switch type {175 case DatabasePropertyType.number: return [O.eq, O.neq, O.gt, O.gte, O.lt, O.lte, O.empty, O.notEmpty]176 case DatabasePropertyType.date, DatabasePropertyType.createdTime, DatabasePropertyType.lastEditedTime: return [O.on, O.before, O.after, O.empty, O.notEmpty]177 case DatabasePropertyType.checkbox: return [O.eq]178 case DatabasePropertyType.select, DatabasePropertyType.status: return [O.eq, O.neq, O.empty, O.notEmpty]179 case DatabasePropertyType.multiSelect: return [O.contains, O.notContains, O.empty, O.notEmpty]180 default: return [O.contains, O.notContains, O.eq, O.neq, O.startsWith, O.endsWith, O.empty, O.notEmpty]181 }182 }183184 public static func needsValue(_ op: String) -> Bool { op != DatabaseFilterOp.empty && op != DatabaseFilterOp.notEmpty }185186 public static func label(_ op: String) -> String {187 typealias O = DatabaseFilterOp188 switch op {189 case O.eq: return L("est")190 case O.neq: return L("n'est pas")191 case O.contains: return L("contient")192 case O.notContains: return L("ne contient pas")193 case O.startsWith: return L("commence par")194 case O.endsWith: return L("finit par")195 case O.empty: return L("est vide")196 case O.notEmpty: return L("n'est pas vide")197 case O.gt: return ">"198 case O.gte: return "≥"199 case O.lt: return "<"200 case O.lte: return "≤"201 case O.before: return L("avant le")202 case O.after: return L("après le")203 case O.on: return L("le")204 default: return op205 }206 }207208 /// A sensible first rule for a property.209 public static func defaultRule(for property: DatabaseProperty) -> DatabaseFilterDraft.Rule {210 let op = ops(for: property.type).first ?? DatabaseFilterOp.contains211 var value: JSONValue?212 switch property.type {213 case DatabasePropertyType.checkbox: value = .bool(true)214 case DatabasePropertyType.select, DatabasePropertyType.status: value = property.options.first.map { .string($0.id) }215 case DatabasePropertyType.multiSelect: value = property.options.first.map { .string($0.id) }216 default: value = nil217 }218 return DatabaseFilterDraft.Rule(property: property.id, op: op, value: value)219 }220}221222// MARK: - Draft of a view's query223224/// What the builders edit: filter, sorts, grouping. Compared with the saved view to know whether it is a local preview.225public struct DatabaseQueryDraft: Equatable, Sendable {226 public var filter = DatabaseFilterDraft()227 public var sorts: [DatabaseViewSort] = []228 public var groupBy: String?229230 public init() {}231232 public init(config: JSONValue?) {233 let query = DatabaseViewQuery(viewConfig: config)234 filter = DatabaseFilterDraft(filter: query.filter)235 sorts = query.sorts236 groupBy = query.groupBy237 }238239 /// Same query (the local node ids do not count).240 public func isSameQuery(as other: DatabaseQueryDraft) -> Bool {241 filter.filter == other.filter.filter && sorts == other.sorts && groupBy == other.groupBy242 }243244 /// The view config with this draft written in, every other key (hidden, widths, dateProperty…) untouched.245 public func merged(into config: JSONValue?) -> JSONValue {246 var object = config?.objectValue ?? [:]247 if let filter = filter.filter { object["filter"] = filter.topLevelJSON } else { object["filter"] = nil }248 if sorts.isEmpty { object["sorts"] = nil } else { object["sorts"] = .array(sorts.map(\.json)) }249 if let groupBy { object["groupBy"] = .string(groupBy) } else { object["groupBy"] = nil }250 return .object(object)251 }252253 public var query: DatabaseViewQuery { DatabaseViewQuery(filter: filter.filter, sorts: sorts, groupBy: groupBy) }254}255256// MARK: - Cells257258/// How a cell is shown. `text` is always filled (VoiceOver, search); the other cases refine the rendering.259public struct DatabaseCellDisplay: Equatable, Sendable {260 public enum Kind: Equatable, Sendable {261 case empty262 case text263 case number264 case checkbox(Bool)265 /// (name, colour name) of each option.266 case options([Option])267 case url(String)268 case relations([String])269 /// The server reported an error for this computed cell.270 case error271 /// An AI cell being computed.272 case pending273 }274275 public struct Option: Equatable, Sendable {276 public var name: String277 public var color: String?278 }279280 public var kind: Kind281 public var text: String282 /// The value was produced by a model (property type `ai`): show it under the AI mark.283 public var isAI = false284}285286public enum DatabaseCellFormat {287 /// The value the server sees for a property of a row (title and creation time come from the row itself).288 public static func value(_ property: DatabaseProperty, _ row: DatabaseRowValues) -> JSONValue? {289 switch property.type {290 case DatabasePropertyType.title: return .string(row.title)291 case DatabasePropertyType.createdTime: return row.values[property.id] ?? row.createdAt.map { .string(APIDate.string(from: $0)) }292 case DatabasePropertyType.lastEditedTime: return row.values[property.id] ?? row.updatedAt.map { .string(APIDate.string(from: $0)) }293 default: return row.values[property.id]294 }295 }296297 public static func display(_ property: DatabaseProperty, _ row: DatabaseRowValues, timeZone: TimeZone = DatabaseEvaluator.serverTimeZone) -> DatabaseCellDisplay {298 var display = display(property, value(property, row), timeZone: timeZone)299 display.isAI = property.type == DatabasePropertyType.ai && display.kind != .empty300 return display301 }302303 public static func display(_ property: DatabaseProperty, _ value: JSONValue?, timeZone: TimeZone = DatabaseEvaluator.serverTimeZone) -> DatabaseCellDisplay {304 guard let value, !value.isNull else { return DatabaseCellDisplay(kind: .empty, text: "") }305 if case .object(let object) = value {306 if object["pending"]?.boolValue == true { return DatabaseCellDisplay(kind: .pending, text: L("Calcul en cours…")) }307 if let error = object["error"]?.stringValue { return DatabaseCellDisplay(kind: .error, text: LF("Erreur : %@", error)) }308 }309 if case .string(let text) = value, text.isEmpty { return DatabaseCellDisplay(kind: .empty, text: "") }310 if case .array(let items) = value, items.isEmpty { return DatabaseCellDisplay(kind: .empty, text: "") }311 switch property.type {312 case DatabasePropertyType.number:313 guard let number = number(value) else { return DatabaseCellDisplay(kind: .text, text: scalar(value)) }314 return DatabaseCellDisplay(kind: .number, text: formatNumber(number, property.typedConfig.format))315 case DatabasePropertyType.date, DatabasePropertyType.createdTime, DatabasePropertyType.lastEditedTime:316 guard let text = value.stringValue else { return DatabaseCellDisplay(kind: .text, text: scalar(value)) }317 return DatabaseCellDisplay(kind: .text, text: dateText(text, includeTime: property.typedConfig.includeTime ?? (property.type != DatabasePropertyType.date), timeZone: timeZone))318 case DatabasePropertyType.checkbox:319 let on = truthy(value)320 return DatabaseCellDisplay(kind: .checkbox(on), text: on ? L("Oui") : L("Non"))321 case DatabasePropertyType.select, DatabasePropertyType.status, DatabasePropertyType.multiSelect:322 let items = value.arrayValue ?? [value]323 let options = items.map { item -> DatabaseCellDisplay.Option in324 let option = property.options.first { $0.id == item.stringValue } ?? property.options.first { $0.name == item.stringValue }325 return .init(name: option?.name ?? scalar(item), color: option?.color)326 }327 return DatabaseCellDisplay(kind: .options(options), text: options.map(\.name).joined(separator: ", "))328 case DatabasePropertyType.url:329 let text = scalar(value)330 return DatabaseCellDisplay(kind: .url(text), text: text)331 case DatabasePropertyType.relation:332 let titles = (value.arrayValue ?? []).compactMap { $0["title"]?.stringValue ?? $0.stringValue }333 return titles.isEmpty ? DatabaseCellDisplay(kind: .empty, text: "") : DatabaseCellDisplay(kind: .relations(titles), text: titles.joined(separator: ", "))334 case DatabasePropertyType.file:335 let names = (value.arrayValue ?? []).compactMap { $0["name"]?.stringValue }336 return DatabaseCellDisplay(kind: names.isEmpty ? .empty : .text, text: names.joined(separator: ", "))337 default:338 // Formulas and rollups: whatever the server computed.339 switch value {340 case .bool(let flag): return DatabaseCellDisplay(kind: .checkbox(flag), text: flag ? L("Oui") : L("Non"))341 case .int, .double: return DatabaseCellDisplay(kind: .number, text: formatNumber(number(value) ?? 0, property.typedConfig.format))342 case .array(let items): return DatabaseCellDisplay(kind: .text, text: items.map(scalar).joined(separator: ", "))343 default: return DatabaseCellDisplay(kind: .text, text: scalar(value))344 }345 }346 }347348 static func scalar(_ value: JSONValue) -> String {349 switch value {350 case .string(let text): return text351 case .int(let number): return String(number)352 case .double(let number): return formatNumber(number, nil)353 case .bool(let flag): return flag ? L("Oui") : L("Non")354 case .null: return ""355 default: return value.canonicalString()356 }357 }358359 static func number(_ value: JSONValue) -> Double? {360 switch value {361 case .int(let number): return Double(number)362 case .double(let number): return number.isFinite ? number : nil363 case .string(let text): return Double(text.filter { !$0.isWhitespace && $0 != "," && $0 != "$" && $0 != "%" })364 default: return nil365 }366 }367368 static func truthy(_ value: JSONValue) -> Bool {369 switch value {370 case .bool(let flag): return flag371 case .int(let number): return number != 0372 case .double(let number): return number != 0373 case .string(let text): return !text.isEmpty && text != "false"374 case .null: return false375 default: return true376 }377 }378379 public static func formatNumber(_ number: Double, _ format: String?) -> String {380 let formatter = NumberFormatter()381 formatter.locale = FeatureStrings.locale382 switch format {383 case "integer": formatter.numberStyle = .decimal; formatter.maximumFractionDigits = 0384 case "percent": formatter.numberStyle = .percent; formatter.maximumFractionDigits = 1; return formatter.string(from: NSNumber(value: number / 100)) ?? ""385 case "currency": formatter.numberStyle = .currency; formatter.currencyCode = "CAD"; formatter.maximumFractionDigits = number == number.rounded() ? 0 : 2386 default: formatter.numberStyle = .decimal; formatter.maximumFractionDigits = 6387 }388 return formatter.string(from: NSNumber(value: number)) ?? ""389 }390391 /// The instant of a stored date value: a bare `YYYY-MM-DD` is midnight in the server's time zone.392 public static func date(_ text: String, timeZone: TimeZone = DatabaseEvaluator.serverTimeZone) -> Date? {393 if isBareDay(text) { return WorkDay.date(text, timeZone: timeZone) }394 return APIDate.parse(text)395 }396397 public static func isBareDay(_ text: String) -> Bool { text.range(of: #"^\d{4}-\d{2}-\d{2}$"#, options: .regularExpression) != nil }398399 /// The calendar day (`YYYY-MM-DD`, server time zone) of a stored date value.400 public static func day(_ value: JSONValue?, timeZone: TimeZone = DatabaseEvaluator.serverTimeZone) -> String? {401 guard let text = value?.stringValue, !text.isEmpty else { return nil }402 if isBareDay(text) { return text }403 return APIDate.parse(text).map { WorkDay.string($0, timeZone: timeZone) }404 }405406 static func dateText(_ text: String, includeTime: Bool, timeZone: TimeZone) -> String {407 guard let date = date(text, timeZone: timeZone) else { return text }408 return includeTime && !isBareDay(text) ? FeatureFormat.dayTime(date, timeZone: timeZone) : FeatureFormat.day(date, timeZone: timeZone)409 }410411 public static func typeLabel(_ type: String) -> String {412 switch type {413 case DatabasePropertyType.title: return L("Titre")414 case DatabasePropertyType.text: return L("Texte")415 case DatabasePropertyType.number: return L("Nombre")416 case DatabasePropertyType.date: return L("Date")417 case DatabasePropertyType.checkbox: return L("Case à cocher")418 case DatabasePropertyType.status: return L("Statut")419 case DatabasePropertyType.select: return L("Choix")420 case DatabasePropertyType.multiSelect: return L("Choix multiples")421 case DatabasePropertyType.url: return L("Lien")422 case DatabasePropertyType.file: return L("Fichier")423 case DatabasePropertyType.relation: return L("Relation")424 case DatabasePropertyType.rollup: return L("Agrégat")425 case DatabasePropertyType.formula: return L("Formule")426 case DatabasePropertyType.createdTime: return L("Date de création")427 case DatabasePropertyType.lastEditedTime: return L("Dernière modification")428 case DatabasePropertyType.ai: return L("IA")429 default: return type430 }431 }432433 public static func typeSymbol(_ type: String) -> String {434 switch type {435 case DatabasePropertyType.title: return "textformat"436 case DatabasePropertyType.text: return "text.alignleft"437 case DatabasePropertyType.number: return "number"438 case DatabasePropertyType.date, DatabasePropertyType.createdTime, DatabasePropertyType.lastEditedTime: return "calendar"439 case DatabasePropertyType.checkbox: return "checkmark.square"440 case DatabasePropertyType.status: return "circle.dotted"441 case DatabasePropertyType.select: return "chevron.down.circle"442 case DatabasePropertyType.multiSelect: return "tag"443 case DatabasePropertyType.url: return "link"444 case DatabasePropertyType.file: return "paperclip"445 case DatabasePropertyType.relation: return "arrow.up.right"446 case DatabasePropertyType.rollup: return "sum"447 case DatabasePropertyType.formula: return "function"448 case DatabasePropertyType.ai: return "sparkles"449 default: return "questionmark.square"450 }451 }452453 public static func viewTypeLabel(_ type: String) -> String {454 switch type {455 case DatabaseViewType.board: return L("Tableau kanban")456 case DatabaseViewType.list: return L("Liste")457 case DatabaseViewType.gallery: return L("Galerie")458 case DatabaseViewType.calendar: return L("Calendrier")459 case DatabaseViewType.timeline: return L("Chronologie")460 default: return L("Table")461 }462 }463464 public static func viewTypeSymbol(_ type: String) -> String {465 switch type {466 case DatabaseViewType.board: return "rectangle.split.3x1"467 case DatabaseViewType.list: return "list.bullet"468 case DatabaseViewType.gallery: return "square.grid.2x2"469 case DatabaseViewType.calendar: return "calendar"470 case DatabaseViewType.timeline: return "chart.bar.xaxis"471 default: return "tablecells"472 }473 }474}475476// MARK: - Calendar and timeline geometry477478/// A month of the calendar view.479public struct DatabaseMonth: Equatable, Hashable, Sendable {480 public var year: Int481 public var month: Int482483 public init(year: Int, month: Int) {484 self.year = year485 self.month = month486 }487488 /// The month of an instant in a time zone.489 public init(_ date: Date, timeZone: TimeZone) {490 var calendar = Calendar(identifier: .gregorian)491 calendar.timeZone = timeZone492 let c = calendar.dateComponents([.year, .month], from: date)493 year = c.year ?? 2000494 month = c.month ?? 1495 }496497 public init?(day: String) {498 let parts = day.split(separator: "-").compactMap { Int($0) }499 guard parts.count == 3 else { return nil }500 year = parts[0]501 month = parts[1]502 }503504 public func adding(_ months: Int) -> DatabaseMonth {505 let index = year * 12 + (month - 1) + months506 return DatabaseMonth(year: index / 12, month: index % 12 + 1)507 }508509 public func key(day: Int) -> String { String(format: "%04d-%02d-%02d", year, month, day) }510511 public var title: String {512 var calendar = Calendar(identifier: .gregorian)513 calendar.timeZone = WorkDay.utc514 guard let date = calendar.date(from: DateComponents(year: year, month: month, day: 15, hour: 12)) else { return "" }515 let formatter = DateFormatter()516 formatter.locale = FeatureStrings.locale517 formatter.timeZone = WorkDay.utc518 formatter.setLocalizedDateFormatFromTemplate("MMMM yyyy")519 return formatter.string(from: date).prefix(1).uppercased() + formatter.string(from: date).dropFirst()520 }521522 public var dayCount: Int {523 var calendar = Calendar(identifier: .gregorian)524 calendar.timeZone = WorkDay.utc525 guard let date = calendar.date(from: DateComponents(year: year, month: month, day: 1)) else { return 30 }526 return calendar.range(of: .day, in: .month, for: date)?.count ?? 30527 }528529 /// Weeks of the month: 7 slots each, `nil` outside the month. `firstWeekday`: 1 = Sunday, 2 = Monday.530 public func weeks(firstWeekday: Int = 2) -> [[Int?]] {531 var calendar = Calendar(identifier: .gregorian)532 calendar.timeZone = WorkDay.utc533 guard let first = calendar.date(from: DateComponents(year: year, month: month, day: 1)) else { return [] }534 let weekday = calendar.component(.weekday, from: first) // 1 = Sunday535 let lead = (weekday - firstWeekday + 7) % 7536 var slots: [Int?] = Array(repeating: nil, count: lead) + (1...dayCount).map { Optional($0) }537 while slots.count % 7 != 0 { slots.append(nil) }538 return stride(from: 0, to: slots.count, by: 7).map { Array(slots[$0..<$0 + 7]) }539 }540541 /// Short weekday names in the order of `weeks(firstWeekday:)`.542 public static func weekdaySymbols(firstWeekday: Int = 2) -> [String] {543 var calendar = Calendar(identifier: .gregorian)544 calendar.locale = FeatureStrings.locale545 let symbols = calendar.veryShortStandaloneWeekdaySymbols546 return (0..<7).map { symbols[($0 + firstWeekday - 1) % 7] }547 }548}549550public enum DatabaseCalendarLayout {551 /// The rows of each day (`YYYY-MM-DD` in the server's time zone) for a date property; rows without a date are left out.552 public static func rowsByDay(_ rows: [DatabaseRowValues], property: DatabaseProperty, timeZone: TimeZone = DatabaseEvaluator.serverTimeZone) -> [String: [DatabaseRowValues]] {553 var out: [String: [DatabaseRowValues]] = [:]554 for row in rows {555 guard let day = DatabaseCellFormat.day(DatabaseCellFormat.value(property, row), timeZone: timeZone) else { continue }556 out[day, default: []].append(row)557 }558 return out559 }560}561562public enum DatabaseTimelineLayout {563 public struct Bar: Equatable, Identifiable, Sendable {564 public var id: String565 public var title: String566 public var startDay: String567 public var endDay: String568 /// 0…1 across the range.569 public var start: Double570 public var width: Double571 }572573 public struct Result: Equatable, Sendable {574 public var bars: [Bar]575 /// Rows with no start date.576 public var undated: [String]577 public var firstDay: String?578 public var lastDay: String?579 public var dayCount: Int580 /// (label, 0…1 position) of each month start in the range.581 public var ticks: [Tick]582 }583584 public struct Tick: Equatable, Sendable {585 public var label: String586 public var position: Double587 }588589 static func ordinal(_ day: String) -> Int? {590 WorkDay.date(day, hour: 12, timeZone: WorkDay.utc).map { Int(($0.timeIntervalSince1970 / 86_400).rounded(.down)) }591 }592593 /// Bars of the rows between the first start and the last end (inclusive days). An end before its start is drawn as594 /// a one-day bar at the start.595 public static func layout(_ rows: [DatabaseRowValues], start: DatabaseProperty, end: DatabaseProperty?, timeZone: TimeZone = DatabaseEvaluator.serverTimeZone) -> Result {596 var spans: [(row: DatabaseRowValues, startDay: String, endDay: String, a: Int, b: Int)] = []597 var undated: [String] = []598 for row in rows {599 guard let startDay = DatabaseCellFormat.day(DatabaseCellFormat.value(start, row), timeZone: timeZone), let a = ordinal(startDay) else { undated.append(row.id); continue }600 var endDay = end.flatMap { DatabaseCellFormat.day(DatabaseCellFormat.value($0, row), timeZone: timeZone) } ?? startDay601 var b = ordinal(endDay) ?? a602 if b < a { b = a; endDay = startDay }603 spans.append((row, startDay, endDay, a, b))604 }605 guard let first = spans.map(\.a).min(), let last = spans.map(\.b).max() else {606 return Result(bars: [], undated: undated, firstDay: nil, lastDay: nil, dayCount: 0, ticks: [])607 }608 let count = last - first + 1609 let bars = spans.sorted { ($0.a, $0.b, $0.row.id) < ($1.a, $1.b, $1.row.id) }.map { span in610 Bar(id: span.row.id, title: span.row.title, startDay: span.startDay, endDay: span.endDay,611 start: Double(span.a - first) / Double(count), width: Double(span.b - span.a + 1) / Double(count))612 }613 let firstDay = spans.first { $0.a == first }?.startDay614 let lastDay = spans.first { $0.b == last }?.endDay615 var ticks: [Tick] = []616 if let firstDay, var month = DatabaseMonth(day: firstDay) {617 for _ in 0..<36 {618 if let ordinal = ordinal(month.key(day: 1)), ordinal >= first, ordinal <= last {619 ticks.append(Tick(label: month.title, position: Double(ordinal - first) / Double(count)))620 }621 month = month.adding(1)622 if let next = ordinal(month.key(day: 1)), next > last { break }623 }624 }625 return Result(bars: bars, undated: undated, firstDay: firstDay, lastDay: lastDay, dayCount: count, ticks: ticks)626 }627}628