SPB Git

Repository Public License

Components+FamilyCFeeds.swift 14.1 KB 253 lines swift

1import PrismCore2import PrismDataRuntime3import PrismLogicRuntime4import PrismObjectModel5import SwiftUI67// MARK: Simple list89struct FCDataList: View {10    @Environment(AppRuntime.self) private var runtime11    let o: PrismObject12    @State private var local: Int?1314    var body: some View {15        let title = FC.column(o, "titleColumn"), detail = FC.column(o, "detailColumn")16        let source = FC.source(runtime, o, columns: [title, detail], sort: FC.sort(runtime, o.props["sort"])).orProblem(title == nil, "Set `titleColumn` to a column of the query.")17        let selection = FCSelection(runtime: runtime, o: o, local: $local)18        let items = FCItem.list(source.rows)19        FCPanel(20            title: runtime.string(o.props["title"]), fallbackLabel: "List", problem: source.problem, isEmpty: items.isEmpty,21            emptyTitle: o.props["emptyText"].map { runtime.string($0) } ?? "Nothing to show", emptyMessage: "", emptySymbol: "list.bullet", summary: "\(source.rows.count) rows."22        ) {23            VStack(alignment: .leading, spacing: 0) {24                ForEach(items) { item in25                    let heading = source.text(item.row, title, runtime: runtime), sub = source.text(item.row, detail, runtime: runtime, format: o.props["format"]?.stringValue)26                    if item.index > 0 { Divider().padding(.leading, 10) }27                    FCRowButton(selected: selection.isSelected(item.row), accessibility: sub.isEmpty ? heading : "\(heading), \(sub)", action: { selection.select(item.row) }) {28                        HStack {29                            Text(heading.isEmpty ? "(untitled)" : heading).lineLimit(1)30                            Spacer(minLength: 8)31                            if !sub.isEmpty { Text(sub).foregroundStyle(.secondary).monospacedDigit().lineLimit(1) }32                        }33                    }34                }35                FCMoreFooter(shown: items.count, total: source.rows.count)36            }37        }38    }39}4041// MARK: Time-ordered views4243struct FCRecordTimeline: View {44    @Environment(AppRuntime.self) private var runtime45    @Environment(\.prismTheme) private var theme46    let o: PrismObject4748    var body: some View {49        let date = FC.column(o, "dateColumn"), title = FC.column(o, "titleColumn"), detail = FC.column(o, "detailColumn")50        let source = FC.source(runtime, o, columns: [date, title, detail]).orProblem(date == nil || title == nil, "Set `dateColumn` and `titleColumn` to columns of the query.")51        let newestFirst = o.props["descending"]?.boolValue != false52        let ordered = source.rows.enumerated().sorted { a, b in53            let da = a.element[date ?? ""]?.displayString ?? "", db = b.element[date ?? ""]?.displayString ?? ""54            return da != db ? (newestFirst ? da > db : da < db) : a.offset < b.offset55        }.map(\.element)56        let items = FCItem.list(ordered)57        let color = FC.toneColor(theme, runtime.string(o.props["tone"]))58        let when: (FCRow) -> String = { row in59            let raw = row[date ?? ""]?.displayString ?? ""60            return LocalDate.date(raw) != nil && raw.count <= 10 ? CellFormat.text(.string(raw), format: "date", runtime: runtime) : (raw.isEmpty ? "No date" : raw)61        }62        FCPanel(63            title: runtime.string(o.props["title"]), fallbackLabel: "Timeline", problem: source.problem, isEmpty: items.isEmpty, emptySymbol: "calendar.day.timeline.left",64            summary: items.prefix(24).map { "\(when($0.row)): \(source.text($0.row, title, runtime: runtime))" }.joined(separator: "; ")65        ) {66            VStack(alignment: .leading, spacing: 0) {67                ForEach(items) { item in68                    let sub = source.text(item.row, detail, runtime: runtime)69                    VStack(alignment: .leading, spacing: 1) {70                        Text(when(item.row)).font(.caption).foregroundStyle(.secondary).monospacedDigit()71                        Text(FC.label(.string(source.text(item.row, title, runtime: runtime)))).fontWeight(.medium).fixedSize(horizontal: false, vertical: true)72                        if !sub.isEmpty { Text(sub).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }73                    }74                    .padding(.leading, 24).padding(.bottom, 12)75                    .frame(maxWidth: .infinity, alignment: .leading)76                    .background(alignment: .topLeading) {77                        // The axis is drawn behind the row, so it follows the row's height without influencing it.78                        ZStack(alignment: .top) {79                            if item.index < items.count - 1 { Rectangle().fill(.secondary.opacity(0.3)).frame(width: 2).padding(.top, 6) }80                            Circle().fill(color).frame(width: 10, height: 10).padding(.top, 3)81                        }82                        .frame(width: 12)83                        .accessibilityHidden(true)84                    }85                    .accessibilityElement(children: .combine)86                }87                FCMoreFooter(shown: items.count, total: source.rows.count)88            }89        }90    }91}9293struct FCActivityFeed: View {94    @Environment(AppRuntime.self) private var runtime95    @Environment(\.prismTheme) private var theme96    let o: PrismObject9798    var body: some View {99        let title = FC.column(o, "titleColumn"), detail = FC.column(o, "detailColumn"), date = FC.column(o, "dateColumn")100        let source = FC.source(runtime, o, columns: [title, detail, date]).orProblem(title == nil, "Set `titleColumn` to a column of the query.")101        let ordered = date == nil ? source.rows : source.rows.enumerated().sorted { a, b in102            let da = a.element[date ?? ""]?.displayString ?? "", db = b.element[date ?? ""]?.displayString ?? ""103            return da != db ? da > db : a.offset > b.offset104        }.map(\.element)105        let items = FCItem.list(ordered, cap: o.props["limit"]?.intValue ?? 20)106        let now = Date()107        let color = FC.toneColor(theme, runtime.string(o.props["tone"]))108        let icon = o.props["icon"].map { runtime.string($0) } ?? "bolt.fill"109        let when: (FCRow) -> String = { row in date.map { FamilyCMath.relativeDate(row[$0]?.displayString ?? "", now: now) } ?? "" }110        FCPanel(111            title: runtime.string(o.props["title"]), fallbackLabel: "Activity", problem: source.problem, isEmpty: items.isEmpty, emptyTitle: "No activity yet", emptyMessage: "",112            emptySymbol: "bolt.slash", summary: items.prefix(24).map { "\(source.text($0.row, title, runtime: runtime)) \(when($0.row))" }.joined(separator: "; ")113        ) {114            VStack(alignment: .leading, spacing: 10) {115                ForEach(items) { item in116                    let heading = source.text(item.row, title, runtime: runtime), sub = source.text(item.row, detail, runtime: runtime)117                    HStack(alignment: .top, spacing: 10) {118                        FCAvatar(name: heading, symbol: icon, color: color, size: 28)119                        VStack(alignment: .leading, spacing: 1) {120                            Text(heading.isEmpty ? "(untitled)" : heading).fontWeight(.medium).fixedSize(horizontal: false, vertical: true)121                            if !sub.isEmpty { Text(sub).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }122                        }123                        Spacer(minLength: 8)124                        Text(when(item.row)).font(.caption).foregroundStyle(.secondary).lineLimit(1)125                    }126                    .accessibilityElement(children: .combine)127                }128                FCMoreFooter(shown: items.count, total: source.rows.count)129            }130        }131    }132}133134// MARK: Comments and chat135136/// A thread stored in a table. As comments: author, text and date with an add box. As chat: bubbles, own messages on the right.137struct FCThread: View {138    @Environment(AppRuntime.self) private var runtime139    @Environment(\.prismTheme) private var theme140    let o: PrismObject141    let chat: Bool142    @State private var draft = ""143144    private var authorColumn: String? { FC.column(o, chat ? "senderColumn" : "authorColumn") }145    private var textColumn: String? { FC.column(o, "textColumn") }146    private var dateColumn: String? { FC.column(o, "dateColumn") }147    private var me: String {148        let name = runtime.string(o.props[chat ? "me" : "author"])149        return name.isEmpty ? "Me" : name150    }151152    var body: some View {153        let source = FC.tableSource(runtime, table: FC.column(o, "table"), columns: [authorColumn, textColumn, dateColumn])154            .orProblem(authorColumn == nil || textColumn == nil, "Set `\(chat ? "senderColumn" : "authorColumn")` and `textColumn` to columns of the table.")155        let cap = max(1, o.props["limit"]?.intValue ?? (chat ? 50 : FC.rowCap))156        let shown = Array(source.rows.suffix(cap))157        let items = FCItem.list(shown, cap: cap)158        let title = runtime.string(o.props["title"])159        let now = Date()160        VStack(alignment: .leading, spacing: 10) {161            if !title.isEmpty || !chat {162                HStack {163                    Text(title.isEmpty ? "Comments" : title).font(.headline).accessibilityAddTraits(.isHeader)164                    Text("\(source.rows.count)").font(.caption).foregroundStyle(.secondary).monospacedDigit().accessibilityLabel("\(source.rows.count) messages")165                }166            }167            if let problem = source.problem {168                Label(problem, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout)169            } else {170                if source.rows.count > shown.count { Text("Showing the last \(shown.count) of \(source.rows.count).").font(.caption).foregroundStyle(.secondary) }171                if items.isEmpty {172                    Label(chat ? "No messages yet" : "No comments yet", systemImage: chat ? "bubble.left.and.bubble.right" : "text.bubble").foregroundStyle(.secondary)173                }174                ForEach(items) { item in175                    let author = source.text(item.row, authorColumn, runtime: runtime), text = source.text(item.row, textColumn, runtime: runtime)176                    let when = dateColumn.map { FamilyCMath.relativeDate(item.row[$0]?.displayString ?? "", now: now) } ?? ""177                    if chat { bubble(author: author, text: text, when: when) } else { comment(author: author, text: text, when: when) }178                }179                HStack(spacing: 8) {180                    TextField(o.props["placeholder"].map { runtime.string($0) } ?? (chat ? "Message" : "Add a comment…"), text: $draft)181                        .textFieldStyle(.roundedBorder)182                        .onSubmit(send)183                        .accessibilityLabel(chat ? "Message" : "New comment")184                    Button(action: send) { Image(systemName: chat ? "arrow.up.circle.fill" : "paperplane.fill").font(.title3) }185                        .buttonStyle(.plain)186                        .foregroundStyle(canSend ? theme.accent : Color.secondary)187                        .disabled(!canSend)188                        .accessibilityLabel(chat ? "Send message" : "Add comment")189                }190            }191        }192        .padding(14)193        .frame(maxWidth: .infinity, alignment: .leading)194        .prismSurface()195        .accessibilityElement(children: .contain)196        .accessibilityLabel(title.isEmpty ? (chat ? "Chat" : "Comments") : title)197    }198199    private var canSend: Bool { !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }200201    private func comment(author: String, text: String, when: String) -> some View {202        HStack(alignment: .top, spacing: 10) {203            FCAvatar(name: author, color: theme.accent, size: 30)204            VStack(alignment: .leading, spacing: 2) {205                HStack(alignment: .firstTextBaseline, spacing: 6) {206                    Text(author.isEmpty ? "Unknown" : author).font(.callout.weight(.semibold))207                    if !when.isEmpty { Text(when).font(.caption).foregroundStyle(.secondary) }208                }209                Text(text).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)210            }211            Spacer(minLength: 0)212        }213        .accessibilityElement(children: .combine)214    }215216    private func bubble(author: String, text: String, when: String) -> some View {217        let mine = author == me218        return HStack {219            if mine { Spacer(minLength: 48) }220            VStack(alignment: mine ? .trailing : .leading, spacing: 2) {221                if !mine { Text(author.isEmpty ? "Unknown" : author).font(.caption).foregroundStyle(.secondary) }222                Text(text)223                    .fixedSize(horizontal: false, vertical: true)224                    .padding(.horizontal, 11).padding(.vertical, 7)225                    .foregroundStyle(mine ? Color.white : Color.primary)226                    .background(mine ? AnyShapeStyle(theme.accent) : AnyShapeStyle(Color.secondary.opacity(0.16)), in: RoundedRectangle(cornerRadius: 13, style: .continuous))227                if !when.isEmpty { Text(when).font(.caption2).foregroundStyle(.tertiary) }228            }229            if !mine { Spacer(minLength: 48) }230        }231        .frame(maxWidth: .infinity, alignment: mine ? .trailing : .leading)232        .accessibilityElement(children: .ignore)233        .accessibilityLabel("\(mine ? "You" : author): \(text)")234        .accessibilityValue(when)235    }236237    /// Creates the record; the box is cleared only when the write succeeded.238    private func send() {239        let text = draft.trimmingCharacters(in: .whitespacesAndNewlines)240        guard !text.isEmpty, let table = FC.column(o, "table"), let authorColumn, let textColumn else { return }241        var values: [String: JSONValue] = [authorColumn: .string(me), textColumn: .string(text)]242        if let dateColumn {243            let isDate = runtime.schema(table)?.column(dateColumn)?.type == .date244            values[dateColumn] = .string(isDate ? LocalDate.iso(Date()) : ISO8601DateFormatter().string(from: Date()))245        }246        var id = 0247        guard runtime.write("Saving", { id = try runtime.store.insert(into: table, values: values) }) else { return }248        draft = ""249        values["id"] = .int(id)250        runtime.fire(chat ? "submit" : "add", on: o.id, value: .int(id), row: .object(values))251    }252}253
Files main
Menu

Theme