SPB Git

Repository Public License

Components+FamilyBProductivity.swift 37.5 KB 703 lines swift

1import AppKit2import PrismCore3import PrismDataRuntime4import PrismLogicRuntime5import PrismObjectModel6import SwiftUI78// Family B, part 3: record-backed productivity views and navigation helpers.910@MainActor11private func fbDayTitle(_ iso: String, runtime: AppRuntime, weekday: Bool = true) -> String {12    guard let date = LocalDate.date(iso) else { return iso }13    let style = weekday ? Date.FormatStyle().weekday(.wide).month(.abbreviated).day().year() : Date.FormatStyle().month(.abbreviated).day().year()14    return date.formatted(style.locale(runtime.locale))15}1617/// Weekday symbols starting at the calendar's first weekday.18@MainActor19private func fbWeekdaySymbols(_ runtime: AppRuntime, firstWeekday: Int) -> [String] {20    var calendar = Calendar(identifier: .gregorian)21    calendar.locale = runtime.locale22    let symbols = calendar.shortStandaloneWeekdaySymbols23    return (0..<7).map { symbols[($0 + firstWeekday - 1) % 7] }24}2526private struct FBMissingTable: View {27    let table: String28    var body: some View {29        Label(table.isEmpty ? "No table is set." : "Table “\(table)” does not exist.", systemImage: "exclamationmark.triangle").foregroundStyle(.orange)30    }31}3233struct FBKanbanComponent: View {34    @Environment(AppRuntime.self) private var runtime35    @Environment(\.prismTheme) private var theme36    let o: PrismObject37    @State private var targeted: String?3839    var body: some View {40        let table = o.props["table"]?.stringValue ?? ""41        let status = o.props["statusColumn"]?.stringValue ?? ""42        if let schema = runtime.schema(table), schema.column(status) != nil {43            let rows = runtime.fbRows(table)44            let preferred = o.props["options"].map { runtime.fbStrings($0) } ?? schema.column(status)?.options ?? []45            let columns = FBRecords.columns(preferred: preferred, values: rows.map { $0[status]?.displayString ?? "" })46            let groups = FBRecords.grouped(rows, by: status)47            let titleColumn = runtime.fbTitleColumn(table, preferred: o.props["titleColumn"]?.stringValue, excluding: [status])48            let subtitle = o.props["subtitleColumn"]?.stringValue.flatMap { schema.column($0)?.name }49            let selected = runtime.resolve(o.props["selection"]).intValue50            ScrollView(.horizontal) {51                HStack(alignment: .top, spacing: 10) {52                    ForEach(columns, id: \.self) { column in53                        let cards = groups[column] ?? []54                        VStack(alignment: .leading, spacing: 6) {55                            HStack {56                                Text(column.isEmpty ? "No status" : column).font(.callout.weight(.semibold)).lineLimit(1)57                                Spacer(minLength: 4)58                                Text("\(cards.count)").font(.caption.monospacedDigit()).foregroundStyle(.secondary).accessibilityLabel("\(cards.count) cards")59                            }60                            ForEach(cards, id: \.self) { row in61                                card(row, column: column, columns: columns, table: table, titleColumn: titleColumn, subtitle: subtitle, selected: selected)62                            }63                        }64                        .padding(8)65                        .frame(width: 190, alignment: .topLeading)66                        .frame(minHeight: 130, maxHeight: .infinity, alignment: .top)67                        .background(targeted == column ? AnyShapeStyle(theme.accent.opacity(0.16)) : AnyShapeStyle(.quaternary.opacity(0.4)), in: RoundedRectangle(cornerRadius: 8))68                        .dropDestination(for: String.self) { items, _ in69                            guard let id = items.first.flatMap({ Int($0) }) else { return false }70                            return runtime.fbMoveCard(o, id: id, to: column)71                        } isTargeted: { inside in72                            if inside { targeted = column } else if targeted == column { targeted = nil }73                        }74                        .accessibilityElement(children: .contain)75                        .accessibilityLabel("\(column.isEmpty ? "No status" : column), \(cards.count) cards")76                    }77                }78                .fixedSize(horizontal: false, vertical: true)79                .padding(1)80            }81        } else if runtime.schema(table) == nil {82            FBMissingTable(table: table)83        } else {84            Label("Table “\(table)” has no column “\(status)”.", systemImage: "exclamationmark.triangle").foregroundStyle(.orange)85        }86    }8788    private func card(_ row: [String: JSONValue], column: String, columns: [String], table: String, titleColumn: String, subtitle: String?, selected: Int?) -> some View {89        let id = row["id"]?.intValue ?? -190        let title = runtime.fbCell(row, titleColumn, table: table)91        let detail = subtitle.map { runtime.fbCell(row, $0, table: table) } ?? ""92        return VStack(alignment: .leading, spacing: 2) {93            Text(title.isEmpty ? "Untitled" : title).font(.callout).lineLimit(2)94            if !detail.isEmpty { Text(detail).font(.caption).foregroundStyle(.secondary).lineLimit(1) }95        }96        .padding(8)97        .frame(maxWidth: .infinity, alignment: .leading)98        .background(.background, in: RoundedRectangle(cornerRadius: 6))99        .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(selected == id ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.separator), lineWidth: selected == id ? 2 : 1))100        .contentShape(Rectangle())101        .onTapGesture {102            if let path = runtime.bindingPath(o.props["selection"]) { runtime.setState(path, .int(id)) }103            runtime.fire("select", on: o.id, value: .int(id), row: .object(row))104        }105        .draggable(String(id))106        .contextMenu {107            // The keyboard and VoiceOver route to the same move as a drag.108            ForEach(columns.filter { $0 != column }, id: \.self) { target in109                Button("Move to \(target.isEmpty ? "No status" : target)") { runtime.fbMoveCard(o, id: id, to: target) }110            }111        }112        .accessibilityElement(children: .combine)113        .accessibilityAddTraits(.isButton)114        .accessibilityActions {115            ForEach(columns.filter { $0 != column }, id: \.self) { target in116                Button("Move to \(target.isEmpty ? "No status" : target)") { runtime.fbMoveCard(o, id: id, to: target) }117            }118        }119    }120}121122struct FBCalendarComponent: View {123    @Environment(AppRuntime.self) private var runtime124    @Environment(\.prismTheme) private var theme125    let o: PrismObject126    /// The month on screen once the user has navigated; before that it follows the selection.127    @State private var shown: String?128129    var body: some View {130        let table = o.props["table"]?.stringValue ?? ""131        let dateColumn = o.props["dateColumn"]?.stringValue ?? ""132        let today = LocalDate.iso(Date())133        let selection = FBDay.normalized(runtime.string(o.props["selection"]))134        let anchor = FBDay.parts(shown ?? selection ?? today) ?? (2026, 1, 1)135        let firstWeekday = Calendar.current.firstWeekday136        let grid = MonthGrid(year: anchor.year, month: anchor.month, firstWeekday: firstWeekday)137        let byDay = FBRecords.byDay(runtime.fbRows(table), column: dateColumn)138        let titleColumn = runtime.fbTitleColumn(table, preferred: o.props["titleColumn"]?.stringValue, excluding: [dateColumn])139        let monthTitle = LocalDate.date(grid.iso(1)).map { $0.formatted(Date.FormatStyle().month(.wide).year().locale(runtime.locale)) } ?? grid.iso(1)140        VStack(alignment: .leading, spacing: 6) {141            if runtime.schema(table) == nil { FBMissingTable(table: table) }142            HStack(spacing: 6) {143                Text(monthTitle).font(.headline).accessibilityAddTraits(.isHeader)144                Spacer(minLength: 0)145                Button { move(grid, by: -1) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Previous month")146                Button("Today") { shown = String(today.prefix(7)) + "-01" }147                Button { move(grid, by: 1) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Next month")148            }149            Grid(horizontalSpacing: 3, verticalSpacing: 3) {150                GridRow {151                    ForEach(fbWeekdaySymbols(runtime, firstWeekday: firstWeekday), id: \.self) { name in152                        Text(name).font(.caption.weight(.semibold)).foregroundStyle(.secondary).frame(maxWidth: .infinity).accessibilityHidden(true)153                    }154                }155                ForEach(0..<grid.weeks, id: \.self) { week in156                    GridRow {157                        ForEach(0..<7, id: \.self) { weekday in158                            if let day = grid.cells[week * 7 + weekday] {159                                cell(grid.iso(day), day: day, rows: byDay[grid.iso(day)] ?? [], table: table, titleColumn: titleColumn, today: today, selection: selection)160                            } else {161                                Color.clear.frame(maxWidth: .infinity, minHeight: 62, maxHeight: 62).accessibilityHidden(true)162                            }163                        }164                    }165                }166            }167        }168        .frame(minWidth: 320, maxWidth: 760, alignment: .leading)169    }170171    private func move(_ grid: MonthGrid, by delta: Int) {172        let next = FBDay.shiftMonth(year: grid.year, month: grid.month, by: delta)173        shown = FBDay.iso(year: next.year, month: next.month, day: 1)174    }175176    private func cell(_ iso: String, day: Int, rows: [[String: JSONValue]], table: String, titleColumn: String, today: String, selection: String?) -> some View {177        let isSelected = iso == selection178        let titles = rows.map { runtime.fbCell($0, titleColumn, table: table) }179        return Button {180            if let path = runtime.bindingPath(o.props["selection"]) { runtime.setState(path, .string(iso)) }181            runtime.fire("select", on: o.id, value: .string(iso))182        } label: {183            VStack(alignment: .leading, spacing: 1) {184                Text("\(day)").font(.caption.weight(iso == today ? .bold : .regular)).monospacedDigit()185                    .foregroundStyle(iso == today ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.primary))186                ForEach(Array(titles.prefix(2).enumerated()), id: \.offset) { _, title in187                    Text(title).font(.caption2).lineLimit(1).padding(.horizontal, 3)188                        .frame(maxWidth: .infinity, alignment: .leading)189                        .background(theme.accent.opacity(0.18), in: RoundedRectangle(cornerRadius: 3))190                }191                if titles.count > 2 { Text("+\(titles.count - 2) more").font(.caption2).foregroundStyle(.secondary) }192            }193            .padding(4)194            .frame(maxWidth: .infinity, minHeight: 62, maxHeight: 62, alignment: .topLeading)195            .background(isSelected ? AnyShapeStyle(theme.accent.opacity(0.14)) : AnyShapeStyle(.quaternary.opacity(0.3)), in: RoundedRectangle(cornerRadius: 5))196            .overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(theme.accent, lineWidth: isSelected ? 1.5 : 0))197            .contentShape(Rectangle())198        }199        .buttonStyle(.plain)200        .accessibilityLabel(fbDayTitle(iso, runtime: runtime))201        .accessibilityValue(titles.isEmpty ? "No entries" : titles.joined(separator: ", "))202        .accessibilityAddTraits(isSelected ? .isSelected : [])203    }204}205206struct FBAgendaComponent: View {207    @Environment(AppRuntime.self) private var runtime208    @Environment(\.prismTheme) private var theme209    let o: PrismObject210211    var body: some View {212        let table = o.props["table"]?.stringValue ?? ""213        let dateColumn = o.props["dateColumn"]?.stringValue ?? ""214        let today = LocalDate.iso(Date())215        let from = FBDay.normalized(runtime.fbText(o, "from")) ?? today216        let days = FBRecords.agenda(runtime.fbRows(table), column: dateColumn, today: from, includePast: o.props["includePast"]?.boolValue == true, limit: o.props["limit"]?.intValue ?? 50)217        let titleColumn = runtime.fbTitleColumn(table, preferred: o.props["titleColumn"]?.stringValue, excluding: [dateColumn])218        let subtitle = o.props["subtitleColumn"]?.stringValue.flatMap { runtime.schema(table)?.column($0)?.name }219        let title = runtime.fbText(o, "title")220        VStack(alignment: .leading, spacing: 10) {221            if !title.isEmpty { Text(title).font(.headline).accessibilityAddTraits(.isHeader) }222            if runtime.schema(table) == nil {223                FBMissingTable(table: table)224            } else if days.isEmpty {225                Label(runtime.fbText(o, "emptyText", "Nothing coming up."), systemImage: "calendar").foregroundStyle(.secondary)226            }227            ForEach(days, id: \.day) { day in228                VStack(alignment: .leading, spacing: 4) {229                    HStack(spacing: 6) {230                        Text(fbDayTitle(day.day, runtime: runtime)).font(.callout.weight(.semibold))231                            .foregroundStyle(day.day < today ? AnyShapeStyle(.secondary) : AnyShapeStyle(.primary))232                        if day.day == today { BadgeView(text: "Today", tone: "accent") }233                    }234                    .accessibilityAddTraits(.isHeader)235                    ForEach(day.rows, id: \.self) { row in236                        let detail = subtitle.map { runtime.fbCell(row, $0, table: table) } ?? ""237                        Button {238                            runtime.fire("select", on: o.id, value: row["id"] ?? .null, row: .object(row))239                        } label: {240                            HStack(spacing: 8) {241                                RoundedRectangle(cornerRadius: 2).fill(day.day < today ? AnyShapeStyle(.tertiary) : AnyShapeStyle(theme.accent)).frame(width: 3, height: 22)242                                Text(runtime.fbCell(row, titleColumn, table: table)).lineLimit(1)243                                Spacer(minLength: 8)244                                if !detail.isEmpty { Text(detail).font(.callout).foregroundStyle(.secondary).lineLimit(1) }245                            }246                            .contentShape(Rectangle())247                        }248                        .buttonStyle(.plain)249                    }250                }251            }252        }253        .frame(maxWidth: 560, alignment: .leading)254    }255}256257struct FBChecklistComponent: View {258    @Environment(AppRuntime.self) private var runtime259    let o: PrismObject260    @State private var draft = ""261262    var body: some View {263        let table = o.props["table"]?.stringValue ?? ""264        let doneColumn = o.props["doneColumn"]?.stringValue ?? ""265        let titleColumn = runtime.fbTitleColumn(table, preferred: o.props["titleColumn"]?.stringValue, excluding: [doneColumn])266        let all = runtime.fbRows(table)267        let rows = o.props["hideDone"]?.boolValue == true ? all.filter { !($0[doneColumn]?.isTruthy ?? false) } : all268        let done = all.filter { $0[doneColumn]?.isTruthy ?? false }.count269        let title = runtime.fbText(o, "title")270        VStack(alignment: .leading, spacing: 6) {271            FBPanelHeader(title: title) {272                Text("\(done) of \(all.count) done").font(.caption.monospacedDigit()).foregroundStyle(.secondary)273            }274            if runtime.schema(table) == nil {275                FBMissingTable(table: table)276            } else if rows.isEmpty {277                Text(all.isEmpty ? "Nothing to do yet." : "Everything is done.").font(.callout).foregroundStyle(.secondary)278            }279            ForEach(rows, id: \.self) { row in280                let isDone = row[doneColumn]?.isTruthy ?? false281                let text = runtime.fbCell(row, titleColumn, table: table)282                Toggle(isOn: Binding(get: { isDone }, set: { new in283                    if let id = row["id"]?.intValue { runtime.fbToggleItem(o, id: id, to: new) }284                })) {285                    Text(text.isEmpty ? "Untitled" : text).strikethrough(isDone).foregroundStyle(isDone ? .secondary : .primary)286                }287                .toggleStyle(.checkbox)288            }289            if o.props["allowAdd"]?.boolValue != false {290                HStack(spacing: 6) {291                    TextField(runtime.fbText(o, "placeholder", "Add an item"), text: $draft)292                        .textFieldStyle(.roundedBorder)293                        .onSubmit(add)294                        .accessibilityLabel("New item")295                    Button(action: add) { Image(systemName: "plus") }296                        .disabled(draft.trimmingCharacters(in: .whitespaces).isEmpty)297                        .accessibilityLabel("Add item")298                }299            }300        }301        .frame(minWidth: 200, maxWidth: 460, alignment: .leading)302    }303304    private func add() {305        if runtime.fbAddItem(o, title: draft) { draft = "" }306    }307}308309struct FBNotesComponent: View {310    @Environment(AppRuntime.self) private var runtime311    let o: PrismObject312313    var body: some View {314        let value = runtime.stateBinding(o)315        let text = value.wrappedValue.displayString316        let limit = o.props["maxLength"]?.intValue.map { max($0, 1) }317        let label = runtime.fbText(o, "label")318        VStack(alignment: .leading, spacing: 4) {319            if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary).accessibilityHidden(true) }320            TextEditor(text: Binding(get: { text }, set: { new in321                let next = limit.map { String(new.prefix($0)) } ?? new322                if next != text { value.wrappedValue = .string(next) }323            }))324            .font(.body)325            .scrollContentBackground(.hidden)326            .frame(minWidth: 200, maxWidth: .infinity, minHeight: 110, maxHeight: .infinity)327            .overlay(alignment: .topLeading) {328                if text.isEmpty {329                    Text(runtime.fbText(o, "placeholder", "Write a note…")).foregroundStyle(.tertiary).padding(.leading, 5).allowsHitTesting(false).accessibilityHidden(true)330                }331            }332            .modifier(FBFieldFrame())333            .accessibilityLabel(label.isEmpty ? "Notes" : label)334            HStack {335                Spacer(minLength: 0)336                Text(limit.map { "\(text.count) / \($0) characters" } ?? "\(text.count) character\(text.count == 1 ? "" : "s")")337                    .font(.caption.monospacedDigit())338                    .foregroundStyle(limit.map { text.count >= $0 } == true ? AnyShapeStyle(.orange) : AnyShapeStyle(.secondary))339            }340        }341        .frame(maxHeight: 260)342    }343}344345struct FBCounterComponent: View {346    @Environment(AppRuntime.self) private var runtime347    let o: PrismObject348349    var body: some View {350        let bounds = FBBounds(lo: o.props["min"]?.doubleValue ?? -1_000_000_000, hi: o.props["max"]?.doubleValue ?? 1_000_000_000, step: o.props["step"]?.doubleValue ?? 1)351        let value = runtime.stateBinding(o)352        let current = bounds.clamp(value.wrappedValue.numericValue ?? 0)353        let label = runtime.fbText(o, "label")354        func bump(_ delta: Double) {355            let next = bounds.clamp(((current + delta) * 1e9).rounded() / 1e9)356            if next != current { value.wrappedValue = .fbNumber(next) }357        }358        return Labeled(label: label) {359            HStack(spacing: 10) {360                Button { bump(-bounds.step) } label: { Image(systemName: "minus").frame(width: 16, height: 16) }361                    .disabled(current <= bounds.lo).accessibilityLabel("Decrease")362                Text(JSONValue.fbNumber(current).displayString).font(.title2.weight(.semibold)).monospacedDigit().frame(minWidth: 44)363                    .accessibilityLabel(label.isEmpty ? "Count" : label).accessibilityValue(JSONValue.fbNumber(current).displayString)364                Button { bump(bounds.step) } label: { Image(systemName: "plus").frame(width: 16, height: 16) }365                    .disabled(current >= bounds.hi).accessibilityLabel("Increase")366            }367            .fixedSize()368        }369    }370}371372struct FBHabitGridComponent: View {373    @Environment(AppRuntime.self) private var runtime374    @Environment(\.prismTheme) private var theme375    let o: PrismObject376377    var body: some View {378        let table = o.props["table"]?.stringValue ?? ""379        let dateColumn = o.props["dateColumn"]?.stringValue ?? ""380        let end = FBDay.normalized(runtime.fbText(o, "endDate")) ?? LocalDate.iso(Date())381        let weeks = FBRecords.heatWeeks(end: end, weeks: o.props["weeks"]?.intValue ?? 18, firstWeekday: Calendar.current.firstWeekday)382        let counts = FBRecords.counts(runtime.fbRows(table), column: dateColumn)383        let visible = weeks.flatMap { $0 }.compactMap { $0 }384        let top = visible.map { counts[$0] ?? 0 }.max() ?? 0385        let total = visible.reduce(0) { $0 + (counts[$1] ?? 0) }386        let active = visible.filter { (counts[$0] ?? 0) > 0 }.count387        let tone = runtime.fbText(o, "tone")388        let color = tone.isEmpty || tone == "neutral" ? theme.color("success") : theme.color(tone)389        let title = runtime.fbText(o, "title")390        VStack(alignment: .leading, spacing: 6) {391            FBPanelHeader(title: title) {392                Text("\(total) entr\(total == 1 ? "y" : "ies") on \(active) day\(active == 1 ? "" : "s")").font(.caption).foregroundStyle(.secondary)393            }394            if runtime.schema(table) == nil { FBMissingTable(table: table) }395            HStack(alignment: .top, spacing: 3) {396                ForEach(Array(weeks.enumerated()), id: \.offset) { _, week in397                    VStack(spacing: 3) {398                        ForEach(Array(week.enumerated()), id: \.offset) { _, day in399                            if let day {400                                let count = counts[day] ?? 0401                                RoundedRectangle(cornerRadius: 2.5)402                                    .fill(count == 0 ? AnyShapeStyle(.quaternary.opacity(0.7)) : AnyShapeStyle(color.opacity(0.25 + 0.1875 * Double(FBRecords.level(count, max: top)))))403                                    .frame(width: 12, height: 12)404                                    .help("\(day): \(count)")405                            } else {406                                Color.clear.frame(width: 12, height: 12)407                            }408                        }409                    }410                }411            }412            .accessibilityElement(children: .ignore)413            .accessibilityLabel(title.isEmpty ? "Activity grid" : title)414            .accessibilityValue("\(total) entries on \(active) days in the last \(weeks.count) weeks")415            HStack(spacing: 3) {416                Text("Less").font(.caption2).foregroundStyle(.secondary)417                ForEach(0..<5, id: \.self) { level in418                    RoundedRectangle(cornerRadius: 2.5).fill(level == 0 ? AnyShapeStyle(.quaternary.opacity(0.7)) : AnyShapeStyle(color.opacity(0.25 + 0.1875 * Double(level)))).frame(width: 10, height: 10)419                }420                Text("More").font(.caption2).foregroundStyle(.secondary)421            }422            .accessibilityHidden(true)423        }424        .fixedSize()425    }426}427428struct FBWeekPlannerComponent: View {429    @Environment(AppRuntime.self) private var runtime430    @Environment(\.prismTheme) private var theme431    let o: PrismObject432    /// The week on screen when `week` is not bound to state.433    @State private var local: String?434435    var body: some View {436        let table = o.props["table"]?.stringValue ?? ""437        let dateColumn = o.props["dateColumn"]?.stringValue ?? ""438        let today = LocalDate.iso(Date())439        let bound = runtime.bindingPath(o.props["week"])440        let anchor = (bound == nil ? local : nil) ?? FBDay.normalized(runtime.fbText(o, "week")) ?? today441        let firstWeekday = Calendar.current.firstWeekday442        let start = FBDay.weekStart(anchor, firstWeekday: firstWeekday)443        let days = (0..<7).map { FBDay.adding($0, to: start) }444        let byDay = FBRecords.byDay(runtime.fbRows(table), column: dateColumn)445        let titleColumn = runtime.fbTitleColumn(table, preferred: o.props["titleColumn"]?.stringValue, excluding: [dateColumn])446        let names = fbWeekdaySymbols(runtime, firstWeekday: firstWeekday)447        func go(_ day: String) {448            if let bound { runtime.setState(bound, .string(day)) } else { local = day }449            runtime.fire("change", on: o.id, value: .string(day))450        }451        return VStack(alignment: .leading, spacing: 6) {452            if runtime.schema(table) == nil { FBMissingTable(table: table) }453            HStack(spacing: 6) {454                Text("Week of \(fbDayTitle(start, runtime: runtime, weekday: false))").font(.headline).accessibilityAddTraits(.isHeader)455                Spacer(minLength: 0)456                Button { go(FBDay.adding(-7, to: start)) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Previous week")457                Button("Today") { go(today) }458                Button { go(FBDay.adding(7, to: start)) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Next week")459            }460            HStack(alignment: .top, spacing: 4) {461                ForEach(Array(days.enumerated()), id: \.offset) { index, day in462                    let rows = byDay[day] ?? []463                    VStack(alignment: .leading, spacing: 4) {464                        HStack(spacing: 4) {465                            Text(names[index]).font(.caption.weight(.semibold)).foregroundStyle(.secondary)466                            Text(String(Int(day.suffix(2)) ?? 0)).font(.caption.weight(day == today ? .bold : .regular)).monospacedDigit()467                                .foregroundStyle(day == today ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.primary))468                        }469                        .accessibilityElement(children: .ignore)470                        .accessibilityLabel(fbDayTitle(day, runtime: runtime))471                        .accessibilityAddTraits(.isHeader)472                        ForEach(rows, id: \.self) { row in473                            Button {474                                runtime.fire("select", on: o.id, value: row["id"] ?? .null, row: .object(row))475                            } label: {476                                Text(runtime.fbCell(row, titleColumn, table: table)).font(.caption).lineLimit(2).multilineTextAlignment(.leading)477                                    .padding(4).frame(maxWidth: .infinity, alignment: .leading)478                                    .background(theme.accent.opacity(0.18), in: RoundedRectangle(cornerRadius: 4))479                                    .contentShape(Rectangle())480                            }481                            .buttonStyle(.plain)482                        }483                    }484                    .padding(5)485                    .frame(maxWidth: .infinity, minHeight: 120, maxHeight: .infinity, alignment: .topLeading)486                    .background(.quaternary.opacity(day == today ? 0.6 : 0.3), in: RoundedRectangle(cornerRadius: 6))487                    .accessibilityElement(children: .contain)488                }489            }490            .fixedSize(horizontal: false, vertical: true)491        }492        .frame(minWidth: 420, maxWidth: 900, alignment: .leading)493    }494}495496struct FBTreeComponent: View {497    @Environment(AppRuntime.self) private var runtime498    @Environment(\.prismTheme) private var theme499    let o: PrismObject500    /// Nodes opened or closed by the user; nil until the first click, when the default applies.501    @State private var expanded: Set<String>?502    @State private var localSelection: String?503504    var body: some View {505        let items = o.props["items"]?.arrayValue ?? []506        let open = expanded ?? (o.props["expandAll"]?.boolValue != false ? FBTree.parents(items) : [])507        let rows = FBTree.flatten(items, expanded: open)508        let bound = runtime.bindingPath(o.props["selection"])509        let selection = bound != nil ? runtime.string(o.props["selection"]) : (localSelection ?? "")510        VStack(alignment: .leading, spacing: 1) {511            ForEach(rows) { row in512                HStack(spacing: 4) {513                    if row.hasChildren {514                        Button {515                            var next = open516                            if next.contains(row.id) { next.remove(row.id) } else { next.insert(row.id) }517                            expanded = next518                        } label: {519                            Image(systemName: open.contains(row.id) ? "chevron.down" : "chevron.right").font(.caption2.weight(.semibold)).frame(width: 14, height: 18).contentShape(Rectangle())520                        }521                        .buttonStyle(.plain)522                        .foregroundStyle(.secondary)523                        .accessibilityLabel(open.contains(row.id) ? "Collapse \(row.title)" : "Expand \(row.title)")524                    } else {525                        Color.clear.frame(width: 14, height: 18).accessibilityHidden(true)526                    }527                    Button {528                        localSelection = row.id529                        if let bound { runtime.setState(bound, .string(row.id)) }530                        runtime.fire("select", on: o.id, value: .string(row.id))531                    } label: {532                        HStack(spacing: 5) {533                            if let icon = row.icon { Image(systemName: SymbolName.safe(icon)).foregroundStyle(row.id == selection ? AnyShapeStyle(Color.white) : AnyShapeStyle(theme.accent)).frame(width: 16).accessibilityHidden(true) }534                            Text(row.title).lineLimit(1)535                            Spacer(minLength: 0)536                        }537                        .padding(.horizontal, 5).padding(.vertical, 3)538                        .foregroundStyle(row.id == selection ? AnyShapeStyle(Color.white) : AnyShapeStyle(.primary))539                        .background(row.id == selection ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.clear), in: RoundedRectangle(cornerRadius: 5))540                        .contentShape(Rectangle())541                    }542                    .buttonStyle(.plain)543                    .accessibilityAddTraits(row.id == selection ? .isSelected : [])544                    .accessibilityValue("Level \(row.depth + 1)")545                }546                .padding(.leading, CGFloat(row.depth) * 16)547            }548        }549        .frame(minWidth: 180, maxWidth: 360, alignment: .leading)550    }551}552553struct FBPaginationComponent: View {554    @Environment(AppRuntime.self) private var runtime555    @Environment(\.prismTheme) private var theme556    let o: PrismObject557558    var body: some View {559        let count = max(Int(runtime.number(o.props["pageCount"]) ?? 1), 1)560        let page = FBPagination.clamp(Int(runtime.number(o.props["page"]) ?? 1), count: count)561        func go(_ target: Int) {562            let next = FBPagination.clamp(target, count: count)563            guard next != page else { return }564            runtime.fbSet(o, "page", .int(next), event: "page")565        }566        return HStack(spacing: 4) {567            Button { go(page - 1) } label: { Image(systemName: "chevron.left") }.disabled(page <= 1).accessibilityLabel("Previous page")568            ForEach(Array(FBPagination.window(page: page, count: count).enumerated()), id: \.offset) { _, entry in569                if let number = entry {570                    Button { go(number) } label: {571                        Text("\(number)").monospacedDigit().frame(minWidth: 22, minHeight: 22).padding(.horizontal, 3)572                            .foregroundStyle(number == page ? AnyShapeStyle(Color.white) : AnyShapeStyle(.primary))573                            .background(number == page ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.quaternary.opacity(0.5)), in: RoundedRectangle(cornerRadius: 5))574                            .contentShape(Rectangle())575                    }576                    .buttonStyle(.plain)577                    .accessibilityLabel("Page \(number)")578                    .accessibilityAddTraits(number == page ? .isSelected : [])579                } else {580                    Text("…").foregroundStyle(.secondary).frame(minWidth: 16).accessibilityHidden(true)581                }582            }583            Button { go(page + 1) } label: { Image(systemName: "chevron.right") }.disabled(page >= count).accessibilityLabel("Next page")584        }585        .fixedSize()586        .accessibilityElement(children: .contain)587        .accessibilityLabel("Page \(page) of \(count)")588    }589}590591struct FBCommandBarComponent: View {592    @Environment(AppRuntime.self) private var runtime593    let o: PrismObject594    @State private var query = ""595596    var body: some View {597        let items = o.props["items"]?.arrayValue ?? []598        let matches = Array(FBSuggest.commands(items, query: query).prefix(min(max(o.props["maxResults"]?.intValue ?? 8, 1), 50)))599        let placeholder = runtime.fbText(o, "placeholder", "Type a command")600        VStack(alignment: .leading, spacing: 0) {601            HStack(spacing: 6) {602                Image(systemName: "command").foregroundStyle(.secondary).accessibilityHidden(true)603                TextField(placeholder, text: $query)604                    .textFieldStyle(.plain)605                    .onSubmit {606                        // Return runs the first match.607                        if let first = matches.first { run(first) }608                    }609                    .accessibilityLabel(placeholder)610            }611            .padding(.horizontal, 10).padding(.vertical, 8)612            Divider()613            if matches.isEmpty {614                Text("No command matches “\(query)”.").font(.callout).foregroundStyle(.secondary).padding(10)615            }616            ForEach(Array(matches.enumerated()), id: \.offset) { index, item in617                let actions = item["actions"]?.arrayValue ?? []618                Button { run(item) } label: {619                    HStack(spacing: 8) {620                        Image(systemName: SymbolName.safe(item["icon"]?.stringValue, fallback: "chevron.right.circle")).foregroundStyle(.secondary).frame(width: 18).accessibilityHidden(true)621                        Text(item["title"]?.stringValue ?? "").lineLimit(1)622                        Spacer(minLength: 0)623                        if index == 0 && !query.isEmpty { Image(systemName: "return").font(.caption).foregroundStyle(.tertiary).accessibilityHidden(true) }624                    }625                    .padding(.horizontal, 10).padding(.vertical, 5)626                    .contentShape(Rectangle())627                }628                .buttonStyle(.plain)629                .disabled(actions.isEmpty)630            }631        }632        .padding(.bottom, 4)633        .frame(minWidth: 240, maxWidth: 460, alignment: .leading)634        .prismSurface()635    }636637    private func run(_ item: JSONValue) {638        let actions = item["actions"]?.arrayValue ?? []639        guard !actions.isEmpty else { return }640        runtime.run(actions)641        query = ""642    }643}644645struct FBWizardComponent: View {646    @Environment(AppRuntime.self) private var runtime647    @Environment(\.prismTheme) private var theme648    let o: PrismObject649    @State private var local = 0650651    var body: some View {652        let count = o.children.count653        let bound = runtime.bindingPath(o.props["step"])654        let step = FBWizard.clamp(bound != nil ? Int(runtime.number(o.props["step"]) ?? 0) : local, count: count)655        func go(_ target: Int) {656            let next = FBWizard.clamp(target, count: count)657            guard next != step else { return }658            local = next659            if let bound { runtime.setState(bound, .int(next)) }660            runtime.fire("change", on: o.id, value: .int(next))661        }662        return VStack(alignment: .leading, spacing: theme.spacing) {663            HStack(spacing: 6) {664                ForEach(Array(o.children.enumerated()), id: \.offset) { index, child in665                    let name = runtime.blueprint.object(child)?.name ?? ""666                    HStack(spacing: 5) {667                        ZStack {668                            Circle().fill(index <= step ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.quaternary))669                            if index < step { Image(systemName: "checkmark").font(.caption2.weight(.bold)).foregroundStyle(.white) }670                            else { Text("\(index + 1)").font(.caption.weight(.semibold)).foregroundStyle(index == step ? AnyShapeStyle(Color.white) : AnyShapeStyle(.secondary)) }671                        }672                        .frame(width: 20, height: 20)673                        Text(name.isEmpty ? "Step \(index + 1)" : name).font(.callout.weight(index == step ? .semibold : .regular))674                            .foregroundStyle(index == step ? .primary : .secondary).lineLimit(1)675                    }676                    .accessibilityElement(children: .ignore)677                    .accessibilityLabel("Step \(index + 1) of \(count): \(name)")678                    .accessibilityAddTraits(index == step ? .isSelected : [])679                    if index < count - 1 { Rectangle().fill(.separator).frame(width: 18, height: 1).accessibilityHidden(true) }680                }681            }682            if o.children.indices.contains(step) {683                NodeView(id: o.children[step]).frame(maxWidth: .infinity, alignment: .leading)684            } else {685                Text("This wizard has no steps yet.").foregroundStyle(.secondary)686            }687            HStack {688                Button("Back") { go(step - 1) }.disabled(step == 0)689                Spacer(minLength: 0)690                if step >= count - 1 {691                    Button(runtime.fbText(o, "finishTitle", "Finish")) { runtime.fire("complete", on: o.id, value: .int(step)) }692                        .buttonStyle(.borderedProminent).disabled(count == 0)693                } else {694                    Button("Next") { go(step + 1) }.buttonStyle(.borderedProminent)695                }696            }697        }698        .padding(14)699        .frame(maxWidth: 620, alignment: .leading)700        .prismSurface()701    }702}703
Files main
Menu

Theme