Repository Public License
1import AppKit2import PrismCore3import PrismLogicRuntime4import PrismObjectModel5import SwiftUI67// Family B, part 2: buttons, the form container and the richer input surfaces.89struct FBToggleButtonComponent: View {10 @Environment(AppRuntime.self) private var runtime11 let o: PrismObject1213 var body: some View {14 let value = runtime.stateBinding(o)15 let title = runtime.fbText(o, "title")16 let icon = o.props["icon"].map { SymbolName.safe(runtime.string($0)) }17 Toggle(isOn: Binding(get: { value.wrappedValue.isTruthy }, set: { value.wrappedValue = .bool($0) })) {18 if let icon, !title.isEmpty { Label(title, systemImage: icon) }19 else if let icon { Image(systemName: icon) }20 else { Text(title.isEmpty ? "Toggle" : title) }21 }22 .toggleStyle(.button)23 .fixedSize()24 .accessibilityLabel(title.isEmpty ? "Toggle" : title)25 }26}2728struct FBButtonGroupComponent: View {29 @Environment(AppRuntime.self) private var runtime30 let o: PrismObject3132 var body: some View {33 let items = o.props["items"]?.arrayValue ?? []34 let label = runtime.fbText(o, "label")35 ControlGroup {36 ForEach(Array(items.enumerated()), id: \.offset) { _, item in37 let actions = item["actions"]?.arrayValue ?? []38 let title = item["title"]?.stringValue ?? ""39 Button { runtime.run(actions) } label: {40 if let icon = item["icon"]?.stringValue {41 if title.isEmpty { Image(systemName: SymbolName.safe(icon)) } else { Label(title, systemImage: SymbolName.safe(icon)) }42 } else {43 Text(title)44 }45 }46 .disabled(actions.isEmpty)47 .accessibilityLabel(title.isEmpty ? (item["icon"]?.stringValue ?? "Action") : title)48 }49 }50 .labelStyle(.titleAndIcon)51 .fixedSize()52 .accessibilityElement(children: .contain)53 .accessibilityLabel(label.isEmpty ? "Actions" : label)54 }55}5657struct FBSplitButtonComponent: View {58 @Environment(AppRuntime.self) private var runtime59 let o: PrismObject6061 var body: some View {62 let items = o.props["items"]?.arrayValue ?? []63 let title = runtime.fbText(o, "title", "Action")64 Menu {65 ForEach(Array(items.enumerated()), id: \.offset) { _, item in66 let actions = item["actions"]?.arrayValue ?? []67 Button { runtime.run(actions) } label: {68 if let icon = item["icon"]?.stringValue { Label(item["title"]?.stringValue ?? "", systemImage: SymbolName.safe(icon)) }69 else { Text(item["title"]?.stringValue ?? "") }70 }71 .disabled(actions.isEmpty)72 }73 } label: {74 if let icon = o.props["icon"]?.stringValue { Label(title, systemImage: SymbolName.safe(icon)) } else { Text(title) }75 } primaryAction: {76 runtime.fire("click", on: o.id)77 }78 .fixedSize()79 }80}8182struct FBCopyButtonComponent: View {83 @Environment(AppRuntime.self) private var runtime84 let o: PrismObject85 @State private var copiedAt: Date?8687 var body: some View {88 let title = runtime.fbText(o, "title", "Copy")89 Button {90 let text = runtime.string(o.props["value"])91 NSPasteboard.general.clearContents()92 NSPasteboard.general.setString(text, forType: .string)93 runtime.fire("copy", on: o.id, value: .string(text))94 copiedAt = Date()95 } label: {96 Label(copiedAt == nil ? title : "Copied", systemImage: copiedAt == nil ? "doc.on.doc" : "checkmark")97 }98 .task(id: copiedAt) {99 guard copiedAt != nil else { return }100 try? await Task.sleep(for: .seconds(1.6))101 if !Task.isCancelled { copiedAt = nil }102 }103 .accessibilityLabel(title)104 }105}106107struct FBIconButtonComponent: View {108 @Environment(AppRuntime.self) private var runtime109 @Environment(\.prismTheme) private var theme110 let o: PrismObject111112 var body: some View {113 let label = runtime.fbText(o, "label")114 let tone = runtime.fbText(o, "tone")115 let bordered = o.props["bordered"]?.boolValue != false116 let button = Button { runtime.fire("click", on: o.id) } label: {117 Image(systemName: SymbolName.safe(runtime.string(o.props["icon"])))118 .font(.system(size: CGFloat(o.props["size"]?.doubleValue ?? 15)))119 .foregroundStyle(tone.isEmpty || tone == "neutral" ? AnyShapeStyle(.primary) : AnyShapeStyle(theme.color(tone)))120 .frame(minWidth: 18, minHeight: 18)121 .contentShape(Rectangle())122 }123 .disabled(runtime.bool(o.props["disabled"], default: false))124 .accessibilityLabel(label.isEmpty ? runtime.string(o.props["icon"]) : label)125 .help(label)126 if bordered { button.buttonStyle(.bordered) } else { button.buttonStyle(.plain) }127 }128}129130struct FBLinkButtonComponent: View {131 @Environment(AppRuntime.self) private var runtime132 let o: PrismObject133134 var body: some View {135 let address = runtime.string(o.props["url"])136 let allowed = FBValidate.webURL(address) != nil137 let title = runtime.fbText(o, "title", address)138 Button {139 runtime.fbOpenLink(o) { NSWorkspace.shared.open($0) }140 } label: {141 Label(title.isEmpty ? "Open link" : title, systemImage: SymbolName.safe(o.props["icon"]?.stringValue, fallback: "arrow.up.right.square"))142 }143 .buttonStyle(.link)144 .help(allowed ? address : "Only http and https addresses can be opened.")145 .accessibilityHint(allowed ? "Opens in your browser" : "This address cannot be opened")146 }147}148149struct FBFormComponent: View {150 @Environment(AppRuntime.self) private var runtime151 @Environment(\.prismTheme) private var theme152 let o: PrismObject153 /// Messages are shown once the user has tried to submit, then follow the rules live.154 @State private var attempted = false155156 var body: some View {157 let title = runtime.fbText(o, "title")158 let failing = attempted ? runtime.fbFailing(o.props["rules"]) : []159 VStack(alignment: .leading, spacing: theme.spacing) {160 if !title.isEmpty { Text(title).font(.headline).accessibilityAddTraits(.isHeader) }161 ChildrenView(ids: o.children)162 if !failing.isEmpty {163 VStack(alignment: .leading, spacing: 4) {164 ForEach(failing, id: \.self) { Label($0, systemImage: "exclamationmark.circle").font(.callout) }165 }166 .foregroundStyle(.red)167 .accessibilityElement(children: .combine)168 }169 HStack {170 Spacer(minLength: 0)171 Button(runtime.fbText(o, "submitTitle", "Submit")) {172 attempted = !runtime.fbSubmit(form: o).isEmpty173 }174 .buttonStyle(.borderedProminent)175 }176 }177 .padding(14)178 .frame(maxWidth: 560, alignment: .leading)179 .prismSurface()180 }181}182183struct FBInlineEditComponent: View {184 @Environment(AppRuntime.self) private var runtime185 let o: PrismObject186 @State private var draft: String?187 @FocusState private var focused: Bool188189 private func commit() {190 guard let text = draft else { return }191 draft = nil192 if text != runtime.string(o.props["value"]) { runtime.fbSet(o, "value", .string(text)) }193 }194195 var body: some View {196 let text = runtime.string(o.props["value"])197 let placeholder = runtime.fbText(o, "placeholder", "Click to edit")198 if let editing = draft {199 TextField(placeholder, text: Binding(get: { editing }, set: { draft = $0 }))200 .textFieldStyle(.roundedBorder)201 .frame(minWidth: 140, maxWidth: 360)202 .focused($focused)203 .onSubmit { commit() }204 .onExitCommand { draft = nil }205 .onChange(of: focused) { _, isFocused in if !isFocused { commit() } }206 .onAppear { focused = true }207 .accessibilityLabel(placeholder)208 } else {209 Button { draft = text } label: {210 HStack(spacing: 6) {211 Text(text.isEmpty ? placeholder : text).foregroundStyle(text.isEmpty ? .secondary : .primary).lineLimit(1)212 Image(systemName: "pencil").font(.caption).foregroundStyle(.tertiary).accessibilityHidden(true)213 }214 .contentShape(Rectangle())215 }216 .buttonStyle(.plain)217 .accessibilityLabel(text.isEmpty ? placeholder : text)218 .accessibilityHint("Click to edit")219 }220 }221}222223struct FBDrawingPadComponent: View {224 @Environment(AppRuntime.self) private var runtime225 @Environment(\.prismTheme) private var theme226 let o: PrismObject227 @State private var current: [CGPoint] = []228229 var body: some View {230 let strokes = FBDrawing.decode(runtime.resolve(o.props["value"]))231 let width = CGFloat(min(max(o.props["strokeWidth"]?.doubleValue ?? 3, 1), 24))232 let tone = runtime.fbText(o, "tone")233 let ink = tone.isEmpty || tone == "neutral" ? Color.primary : theme.color(tone)234 let label = runtime.fbText(o, "label")235 VStack(alignment: .leading, spacing: 6) {236 HStack(spacing: 8) {237 if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary) }238 Spacer(minLength: 0)239 Text("\(strokes.count) stroke\(strokes.count == 1 ? "" : "s")").font(.caption).foregroundStyle(.secondary)240 Button { runtime.fbSet(o, "value", FBDrawing.encode(Array(strokes.dropLast()))) } label: { Label("Undo", systemImage: "arrow.uturn.backward") }241 .disabled(strokes.isEmpty)242 Button { runtime.fbSet(o, "value", .array([])); runtime.fire("reset", on: o.id) } label: { Label("Clear", systemImage: "trash") }243 .disabled(strokes.isEmpty)244 }245 Canvas { context, _ in246 for stroke in strokes + (current.isEmpty ? [] : [current]) {247 guard let first = stroke.first else { continue }248 var path = Path()249 path.move(to: first)250 if stroke.count == 1 { path.addLine(to: CGPoint(x: first.x + 0.1, y: first.y)) }251 for p in stroke.dropFirst() { path.addLine(to: p) }252 context.stroke(path, with: .color(ink), style: StrokeStyle(lineWidth: width, lineCap: .round, lineJoin: .round))253 }254 }255 .frame(maxWidth: .infinity)256 .frame(height: CGFloat(min(max(o.props["canvasHeight"]?.doubleValue ?? 180, 60), 1200)))257 .background(Color(nsColor: .textBackgroundColor), in: RoundedRectangle(cornerRadius: 8))258 .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.separator))259 .clipShape(RoundedRectangle(cornerRadius: 8))260 .contentShape(Rectangle())261 .gesture(DragGesture(minimumDistance: 0).onChanged { current.append($0.location) }.onEnded { _ in262 let stroke = FBDrawing.thinned(current)263 current = []264 guard !stroke.isEmpty else { return }265 runtime.fbSet(o, "value", FBDrawing.encode(strokes + [stroke]))266 })267 .accessibilityElement()268 .accessibilityLabel(label.isEmpty ? "Drawing pad" : label)269 .accessibilityValue("\(strokes.count) stroke\(strokes.count == 1 ? "" : "s")")270 }271 }272}273274struct FBEmojiPickerComponent: View {275 @Environment(AppRuntime.self) private var runtime276 @Environment(\.prismTheme) private var theme277 let o: PrismObject278279 static let emoji = [280 "😀", "😄", "😊", "😉", "😍", "🤔", "😴", "😢", "😡", "🥳", "👍", "👎", "👏", "🙏", "💪", "👀",281 "❤️", "⭐️", "🔥", "✨", "✅", "❌", "⚠️", "💡", "📌", "📎", "📅", "⏰", "📈", "💰", "🛒", "🎁",282 "🏠", "🚗", "✈️", "🚲", "🍎", "🍕", "☕️", "🍷", "⚽️", "🎵", "🎮", "📚", "💻", "📱", "🌱", "☀️",283 ]284285 var body: some View {286 let value = runtime.stateBinding(o)287 let current = value.wrappedValue.displayString288 let options = o.props["options"].map { runtime.fbStrings($0) } ?? Self.emoji289 let label = runtime.fbText(o, "label")290 Labeled(label: label) {291 LazyVGrid(columns: [GridItem(.adaptive(minimum: 30, maximum: 34), spacing: 4)], alignment: .leading, spacing: 4) {292 ForEach(options, id: \.self) { e in293 Button { value.wrappedValue = .string(e) } label: {294 Text(e).font(.title3).frame(width: 30, height: 30)295 .background(e == current ? AnyShapeStyle(theme.accent.opacity(0.25)) : AnyShapeStyle(.clear), in: RoundedRectangle(cornerRadius: 6))296 .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(theme.accent, lineWidth: e == current ? 1.5 : 0))297 .contentShape(Rectangle())298 }299 .buttonStyle(.plain)300 .accessibilityLabel("Emoji \(e)")301 .accessibilityAddTraits(e == current ? .isSelected : [])302 }303 }304 .frame(maxWidth: 420, alignment: .leading)305 .padding(6)306 .background(.quaternary.opacity(0.35), in: RoundedRectangle(cornerRadius: 8))307 }308 }309}310311struct FBIconPickerComponent: View {312 @Environment(AppRuntime.self) private var runtime313 @Environment(\.prismTheme) private var theme314 let o: PrismObject315 @State private var filter = ""316317 static let symbols = [318 "house", "star", "heart", "bell", "bookmark", "flag", "tag", "pin", "paperclip", "link", "folder", "doc", "doc.text", "tray", "archivebox", "trash",319 "calendar", "clock", "alarm", "timer", "person", "person.2", "envelope", "phone", "message", "bubble.left", "cart", "creditcard", "banknote", "gift", "bag", "shippingbox",320 "chart.bar", "chart.pie", "chart.line.uptrend.xyaxis", "list.bullet", "checklist", "checkmark.circle", "xmark.circle", "exclamationmark.triangle", "info.circle", "questionmark.circle",321 "gearshape", "slider.horizontal.3", "magnifyingglass", "plus", "minus", "pencil", "square.and.arrow.up", "square.and.arrow.down", "arrow.clockwise", "lock", "key", "eye",322 "map", "location", "car", "airplane", "bicycle", "leaf", "flame", "bolt", "sun.max", "moon", "cloud", "drop", "camera", "photo", "music.note", "play.circle", "gamecontroller", "book",323 "graduationcap", "briefcase", "hammer", "wrench.and.screwdriver", "lightbulb", "sparkles", "globe", "wifi", "desktopcomputer", "iphone",324 ]325326 var body: some View {327 let value = runtime.stateBinding(o)328 let current = value.wrappedValue.displayString329 let all = o.props["options"].map { runtime.fbStrings($0) } ?? Self.symbols330 let query = filter.trimmingCharacters(in: .whitespaces).lowercased()331 let shown = all.filter { query.isEmpty || $0.contains(query) }332 let label = runtime.fbText(o, "label")333 Labeled(label: label) {334 VStack(alignment: .leading, spacing: 6) {335 HStack(spacing: 8) {336 TextField("Filter icons", text: $filter).textFieldStyle(.roundedBorder).frame(maxWidth: 200).accessibilityLabel("Filter icons")337 if !current.isEmpty {338 Label(current, systemImage: SymbolName.safe(current)).font(.callout).foregroundStyle(.secondary).lineLimit(1)339 }340 }341 if shown.isEmpty {342 Text("No icon matches “\(filter)”.").font(.callout).foregroundStyle(.secondary).padding(6)343 } else {344 LazyVGrid(columns: [GridItem(.adaptive(minimum: 30, maximum: 34), spacing: 4)], alignment: .leading, spacing: 4) {345 ForEach(shown, id: \.self) { name in346 Button { value.wrappedValue = .string(name) } label: {347 Image(systemName: SymbolName.safe(name)).frame(width: 30, height: 30)348 .foregroundStyle(name == current ? AnyShapeStyle(Color.white) : AnyShapeStyle(.primary))349 .background(name == current ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.clear), in: RoundedRectangle(cornerRadius: 6))350 .contentShape(Rectangle())351 }352 .buttonStyle(.plain)353 .help(name)354 .accessibilityLabel(name.replacingOccurrences(of: ".", with: " "))355 .accessibilityAddTraits(name == current ? .isSelected : [])356 }357 }358 .padding(6)359 .background(.quaternary.opacity(0.35), in: RoundedRectangle(cornerRadius: 8))360 }361 }362 .frame(maxWidth: 460, alignment: .leading)363 }364 }365}366367struct FBSearchSuggestComponent: View {368 @Environment(AppRuntime.self) private var runtime369 let o: PrismObject370371 private func choose(_ term: String, event: String) {372 runtime.fbSet(o, "value", .string(term))373 remember(term)374 runtime.fire(event, on: o.id, value: .string(term))375 }376377 private func remember(_ term: String) {378 guard let path = runtime.bindingPath(o.props["recent"]) else { return }379 let next = FBSuggest.remember(term, in: runtime.fbStrings(o.props["recent"]), max: o.props["maxRecent"]?.intValue ?? 5)380 runtime.setState(path, .array(next.map(JSONValue.string)))381 }382383 var body: some View {384 let value = runtime.stateBinding(o)385 let text = value.wrappedValue.displayString386 let placeholder = runtime.fbText(o, "placeholder", "Search")387 let recent = runtime.fbStrings(o.props["recent"])388 let all = runtime.fbStrings(o.props["suggestions"])389 // While typing, the suggestions narrow to the matching ones; an empty box shows them all.390 let suggested = (text.trimmingCharacters(in: .whitespaces).isEmpty ? all : FBSuggest.filter(all, text: text, limit: 12)).filter { !recent.contains($0) }391 VStack(alignment: .leading, spacing: 8) {392 HStack(spacing: 6) {393 Image(systemName: "magnifyingglass").foregroundStyle(.secondary).accessibilityHidden(true)394 TextField(placeholder, text: Binding(get: { text }, set: { value.wrappedValue = .string($0) }))395 .textFieldStyle(.plain)396 .onSubmit {397 remember(text)398 runtime.fire("submit", on: o.id, value: .string(text))399 }400 .accessibilityLabel(placeholder)401 if !text.isEmpty {402 Button { value.wrappedValue = .string("") } label: { Image(systemName: "xmark.circle.fill") }403 .buttonStyle(.plain).foregroundStyle(.secondary).accessibilityLabel("Clear search")404 }405 }406 .padding(.horizontal, 8).padding(.vertical, 5)407 .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 7))408 if !recent.isEmpty {409 row("Recent", icon: "clock.arrow.circlepath", terms: recent)410 }411 if !suggested.isEmpty {412 row("Suggested", icon: "sparkle.magnifyingglass", terms: suggested)413 }414 }415 .frame(minWidth: 200, maxWidth: 420, alignment: .leading)416 }417418 private func row(_ title: String, icon: String, terms: [String]) -> some View {419 VStack(alignment: .leading, spacing: 4) {420 Label(title, systemImage: SymbolName.safe(icon, fallback: "magnifyingglass")).font(.caption).foregroundStyle(.secondary)421 FBFlowLayout(spacing: 6) {422 ForEach(terms, id: \.self) { term in423 FBChip(title: term) { choose(term, event: "select") }.accessibilityLabel("Search for \(term)")424 }425 }426 }427 }428}429430struct FBKeypadComponent: View {431 @Environment(AppRuntime.self) private var runtime432 let o: PrismObject433 /// The text being typed while the bound value is a number (keeps a trailing `.` that a number cannot hold).434 @State private var draft: String?435436 var body: some View {437 let numeric = o.props["numeric"]?.boolValue == true438 let decimal = o.props["decimal"]?.boolValue != false439 let maxLength = min(max(o.props["maxLength"]?.intValue ?? 12, 1), 30)440 let stored = runtime.resolve(o.props["value"])441 let storedText = stored.displayString442 let text: String = {443 guard numeric, let draft else { return storedText }444 // The draft stands only while it still means the stored number.445 return Double(draft) == stored.numericValue || (draft.isEmpty && (stored.numericValue ?? 0) == 0) ? draft : storedText446 }()447 let label = runtime.fbText(o, "label")448 VStack(alignment: .leading, spacing: 8) {449 if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary) }450 Text(text.isEmpty ? "0" : text)451 .font(.title2.monospacedDigit())452 .foregroundStyle(text.isEmpty ? .secondary : .primary)453 .lineLimit(1).minimumScaleFactor(0.5)454 .frame(maxWidth: .infinity, alignment: .trailing)455 .modifier(FBFieldFrame())456 .accessibilityLabel(label.isEmpty ? "Entered value" : label)457 .accessibilityValue(text.isEmpty ? "Empty" : text)458 LazyVGrid(columns: Array(repeating: GridItem(.fixed(54), spacing: 6), count: 3), spacing: 6) {459 ForEach(FBKeypad.keys, id: \.self) { key in460 Button {461 let next = FBKeypad.press(text, key: key, decimal: decimal, maxLength: maxLength)462 guard next != text else { return }463 if numeric {464 draft = next465 runtime.fbSet(o, "value", .fbNumber(Double(next) ?? 0))466 } else {467 runtime.fbSet(o, "value", .string(next))468 }469 } label: {470 Group {471 if key == "⌫" { Image(systemName: "delete.left") } else { Text(key) }472 }473 .font(.title3).frame(width: 54, height: 36)474 .background(.quaternary.opacity(0.6), in: RoundedRectangle(cornerRadius: 7))475 .contentShape(Rectangle())476 }477 .buttonStyle(.plain)478 .disabled(key == "." && !decimal)479 .accessibilityLabel(key == "⌫" ? "Delete" : key == "." ? "Decimal point" : key)480 }481 }482 }483 .frame(width: 54 * 3 + 12)484 }485}486487struct FBDialComponent: View {488 @Environment(AppRuntime.self) private var runtime489 @Environment(\.prismTheme) private var theme490 @Environment(\.accessibilityReduceMotion) private var reduceMotion491 let o: PrismObject492493 var body: some View {494 let bounds = FBBounds(o.props)495 let value = runtime.stateBinding(o)496 let current = bounds.clamp(value.wrappedValue.numericValue ?? bounds.lo)497 let fraction = bounds.fraction(current)498 let diameter = CGFloat(min(max(o.props["diameter"]?.doubleValue ?? 120, 60), 400))499 let line = max(diameter / 14, 5)500 let label = runtime.fbText(o, "label")501 let angle = Angle.degrees(FBDial.startAngle + FBDial.sweep * fraction)502 let radius = diameter / 2 - line * 2.2503 VStack(spacing: 6) {504 ZStack {505 Circle().trim(from: 0, to: FBDial.sweep / 360).stroke(.quaternary, style: StrokeStyle(lineWidth: line, lineCap: .round))506 .rotationEffect(.degrees(FBDial.startAngle))507 Circle().trim(from: 0, to: FBDial.sweep / 360 * fraction).stroke(theme.accent, style: StrokeStyle(lineWidth: line, lineCap: .round))508 .rotationEffect(.degrees(FBDial.startAngle))509 .animation(reduceMotion ? nil : .snappy(duration: 0.15), value: fraction)510 Circle().fill(theme.accent).frame(width: line * 1.3, height: line * 1.3)511 .offset(x: CGFloat(cos(angle.radians)) * radius, y: CGFloat(sin(angle.radians)) * radius)512 Text(JSONValue.fbNumber(current).displayString).font(.system(size: diameter / 4.2, weight: .semibold)).monospacedDigit().minimumScaleFactor(0.5).lineLimit(1)513 .frame(maxWidth: diameter * 0.55)514 }515 .padding(line / 2)516 .frame(width: diameter, height: diameter)517 .contentShape(Circle())518 .gesture(DragGesture(minimumDistance: 0).onChanged { g in519 let next = bounds.value(fraction: FBDial.fraction(dx: Double(g.location.x - diameter / 2), dy: Double(g.location.y - diameter / 2)))520 if next != current { value.wrappedValue = .fbNumber(next) }521 })522 .accessibilityElement()523 .accessibilityLabel(label.isEmpty ? "Dial" : label)524 .accessibilityValue(JSONValue.fbNumber(current).displayString)525 .accessibilityAdjustableAction { direction in526 let next = bounds.snap(current + (direction == .increment ? bounds.step : -bounds.step))527 if next != current { value.wrappedValue = .fbNumber(next) }528 }529 if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary).accessibilityHidden(true) }530 }531 }532}533