Repository Public License
1import PrismCore2import PrismLogicRuntime3import PrismObjectModel4import SwiftUI56// Family B, part 4: clocks and the calculator. The clocks run in `.task` loops and stand still in Design mode.78/// A ring that empties as time runs out.9private struct FBTimeRing<Center: View>: View {10 @Environment(\.accessibilityReduceMotion) private var reduceMotion11 let fraction: Double12 let color: Color13 var diameter: CGFloat = 13214 @ViewBuilder var center: Center1516 var body: some View {17 ZStack {18 Circle().stroke(.quaternary, lineWidth: 8)19 Circle().trim(from: 0, to: min(max(fraction, 0), 1)).stroke(color, style: StrokeStyle(lineWidth: 8, lineCap: .round))20 .rotationEffect(.degrees(-90))21 .animation(reduceMotion ? nil : .linear(duration: 0.25), value: fraction)22 center23 }24 .padding(4)25 .frame(width: diameter, height: diameter)26 }27}2829struct FBStopwatchComponent: View {30 @Environment(AppRuntime.self) private var runtime31 @Environment(\.prismDesign) private var design32 let o: PrismObject33 @State private var watch = StopwatchState()34 @State private var now = Date()3536 private func mirror(_ elapsed: Double) {37 if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, .int(Int(elapsed))) }38 }3940 var body: some View {41 let elapsed = watch.elapsed(at: now)42 let label = runtime.fbText(o, "label")43 VStack(alignment: .leading, spacing: 8) {44 if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary) }45 Text(FBTime.stopwatch(elapsed)).font(.system(size: 34, weight: .semibold)).monospacedDigit()46 .accessibilityLabel(label.isEmpty ? "Stopwatch" : label)47 .accessibilityValue("\(Int(elapsed)) seconds")48 HStack(spacing: 8) {49 Button {50 now = Date()51 if watch.isRunning {52 watch.stop(at: now)53 mirror(watch.elapsed(at: now))54 runtime.fire("stop", on: o.id, value: .fbNumber((watch.elapsed(at: now) * 10).rounded() / 10))55 } else {56 watch.start(at: now)57 runtime.fire("start", on: o.id)58 }59 } label: { Label(watch.isRunning ? "Stop" : "Start", systemImage: watch.isRunning ? "pause.fill" : "play.fill") }60 .buttonStyle(.borderedProminent)61 Button {62 watch.reset()63 now = Date()64 mirror(0)65 runtime.fire("reset", on: o.id)66 } label: { Label("Reset", systemImage: "arrow.counterclockwise") }67 .disabled(elapsed == 0)68 }69 }70 .task(id: "\(watch.isRunning)-\(design != nil)") {71 guard watch.isRunning, design == nil else { return }72 while !Task.isCancelled {73 try? await Task.sleep(for: .milliseconds(100))74 if Task.isCancelled { break }75 now = Date()76 mirror(watch.elapsed(at: now))77 }78 }79 }80}8182struct FBCountdownComponent: View {83 @Environment(AppRuntime.self) private var runtime84 @Environment(\.prismDesign) private var design85 @Environment(\.prismTheme) private var theme86 let o: PrismObject87 @State private var timer: CountdownState88 @State private var running = false89 /// Wall-clock time of the last whole second counted, so a late wake-up still counts every second.90 @State private var anchor = Date()9192 init(o: PrismObject) {93 self.o = o94 _timer = State(initialValue: CountdownState(duration: Int(o.props["duration"]?.doubleValue ?? 60)))95 }9697 private func mirror() {98 if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, .int(timer.remaining)) }99 }100101 private func setDuration(_ seconds: Int) {102 running = false103 timer.setDuration(seconds)104 mirror()105 }106107 var body: some View {108 let label = runtime.fbText(o, "label")109 let editable = o.props["editable"]?.boolValue != false110 VStack(spacing: 8) {111 if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary) }112 FBTimeRing(fraction: timer.fraction, color: timer.remaining <= 10 && timer.duration > 10 ? theme.color("warning") : theme.accent) {113 Text(FBTime.clock(timer.remaining)).font(.system(size: 28, weight: .semibold)).monospacedDigit().minimumScaleFactor(0.6).lineLimit(1).padding(.horizontal, 14)114 }115 .accessibilityElement(children: .ignore)116 .accessibilityLabel(label.isEmpty ? "Countdown" : label)117 .accessibilityValue("\(timer.remaining) seconds left")118 if editable {119 HStack(spacing: 6) {120 Button { setDuration(timer.duration - 60) } label: { Image(systemName: "minus").frame(width: 12, height: 12) }.disabled(running || timer.duration <= 60).accessibilityLabel("One minute less")121 Text("Set: \(FBTime.clock(timer.duration))").font(.caption.monospacedDigit()).foregroundStyle(.secondary)122 Button { setDuration(timer.duration + 60) } label: { Image(systemName: "plus").frame(width: 12, height: 12) }.disabled(running).accessibilityLabel("One minute more")123 }124 .controlSize(.small)125 }126 HStack(spacing: 8) {127 Button {128 if running {129 running = false130 runtime.fire("stop", on: o.id, value: .int(timer.remaining))131 } else {132 if timer.isFinished { timer.reset() }133 anchor = Date()134 running = true135 runtime.fire("start", on: o.id, value: .int(timer.remaining))136 }137 } label: { Label(running ? "Pause" : "Start", systemImage: running ? "pause.fill" : "play.fill") }138 .buttonStyle(.borderedProminent)139 Button {140 running = false141 timer.reset()142 mirror()143 runtime.fire("reset", on: o.id)144 } label: { Label("Reset", systemImage: "arrow.counterclockwise") }145 .disabled(!running && timer.remaining == timer.duration)146 }147 }148 .onChange(of: o.props["duration"]?.doubleValue) { _, new in setDuration(Int(new ?? 60)) }149 .task(id: "\(running)-\(design != nil)") {150 guard running, design == nil else { return }151 while !Task.isCancelled && running {152 try? await Task.sleep(for: .milliseconds(200))153 if Task.isCancelled { break }154 let whole = Int(Date().timeIntervalSince(anchor))155 guard whole > 0 else { continue }156 anchor = anchor.addingTimeInterval(Double(whole))157 let finished = timer.tick(whole)158 mirror()159 if finished {160 running = false161 runtime.fire("complete", on: o.id)162 }163 }164 }165 }166}167168struct FBPomodoroComponent: View {169 @Environment(AppRuntime.self) private var runtime170 @Environment(\.prismDesign) private var design171 @Environment(\.prismTheme) private var theme172 let o: PrismObject173 @State private var machine: PomodoroMachine174 @State private var running = false175 @State private var anchor = Date()176177 private static func machine(_ props: [String: JSONValue]) -> PomodoroMachine {178 func seconds(_ key: String, _ fallback: Double) -> Int { Int(((props[key]?.doubleValue ?? fallback) * 60).rounded()) }179 return PomodoroMachine(work: seconds("workMinutes", 25), shortBreak: seconds("breakMinutes", 5), longBreak: seconds("longBreakMinutes", 15),180 cyclesBeforeLongBreak: props["cyclesBeforeLongBreak"]?.intValue ?? 4)181 }182183 init(o: PrismObject) {184 self.o = o185 _machine = State(initialValue: Self.machine(o.props))186 }187188 private func completed(_ count: Int) {189 guard count > 0 else { return }190 if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, .int(machine.completedCycles)) }191 for _ in 0..<count { runtime.fire("complete", on: o.id, value: .int(machine.completedCycles)) }192 }193194 private var phaseTitle: String {195 switch machine.phase { case .work: "Focus"; case .shortBreak: "Short break"; case .longBreak: "Long break" }196 }197198 var body: some View {199 let label = runtime.fbText(o, "label")200 let color = machine.phase == .work ? theme.accent : theme.color("success")201 let durations = [o.props["workMinutes"]?.doubleValue, o.props["breakMinutes"]?.doubleValue, o.props["longBreakMinutes"]?.doubleValue, o.props["cyclesBeforeLongBreak"]?.doubleValue]202 VStack(spacing: 8) {203 if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary) }204 FBTimeRing(fraction: machine.fraction, color: color, diameter: 148) {205 VStack(spacing: 2) {206 Text(phaseTitle).font(.caption.weight(.semibold)).foregroundStyle(color)207 Text(FBTime.clock(machine.remaining)).font(.system(size: 28, weight: .semibold)).monospacedDigit().minimumScaleFactor(0.6).lineLimit(1)208 }209 .padding(.horizontal, 14)210 }211 .accessibilityElement(children: .ignore)212 .accessibilityLabel(label.isEmpty ? "Pomodoro timer" : label)213 .accessibilityValue("\(phaseTitle), \(machine.remaining) seconds left, \(machine.completedCycles) sessions done")214 HStack(spacing: 4) {215 ForEach(0..<machine.cyclesBeforeLongBreak, id: \.self) { i in216 Circle().fill(i < machine.completedCycles % machine.cyclesBeforeLongBreak || (machine.phase == .longBreak) ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.quaternary))217 .frame(width: 7, height: 7)218 }219 Text("\(machine.completedCycles) done").font(.caption.monospacedDigit()).foregroundStyle(.secondary).padding(.leading, 4)220 }221 .accessibilityHidden(true)222 HStack(spacing: 8) {223 Button {224 if running {225 running = false226 runtime.fire("stop", on: o.id)227 } else {228 anchor = Date()229 running = true230 runtime.fire("start", on: o.id)231 }232 } label: { Label(running ? "Pause" : "Start", systemImage: running ? "pause.fill" : "play.fill") }233 .buttonStyle(.borderedProminent)234 Button {235 anchor = Date()236 completed(machine.skip() ? 1 : 0)237 } label: { Label("Skip", systemImage: "forward.end.fill") }238 .help("End this phase now")239 Button {240 running = false241 machine.reset()242 if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, .int(0)) }243 runtime.fire("reset", on: o.id)244 } label: { Label("Reset", systemImage: "arrow.counterclockwise") }245 }246 }247 .onChange(of: durations) { _, _ in248 running = false249 machine = Self.machine(o.props)250 }251 .task(id: "\(running)-\(design != nil)") {252 guard running, design == nil else { return }253 while !Task.isCancelled && running {254 try? await Task.sleep(for: .milliseconds(200))255 if Task.isCancelled { break }256 let whole = Int(Date().timeIntervalSince(anchor))257 guard whole > 0 else { continue }258 anchor = anchor.addingTimeInterval(Double(whole))259 completed(machine.tick(whole))260 }261 }262 }263}264265struct FBCalculatorComponent: View {266 @Environment(AppRuntime.self) private var runtime267 @Environment(\.prismTheme) private var theme268 let o: PrismObject269 @State private var engine = CalculatorEngine()270271 private func name(_ key: String) -> String {272 switch key {273 case "C": "Clear"274 case "±": "Change sign"275 case "%": "Percent"276 case "÷": "Divide"277 case "×": "Multiply"278 case "−": "Subtract"279 case "+": "Add"280 case "=": "Equals"281 case ".": "Decimal point"282 case "⌫": "Delete"283 default: key284 }285 }286287 var body: some View {288 let label = runtime.fbText(o, "label")289 VStack(alignment: .leading, spacing: 8) {290 if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary) }291 HStack(spacing: 6) {292 if let pending = engine.pendingOperator { Text(pending).font(.callout).foregroundStyle(.secondary).accessibilityHidden(true) }293 Spacer(minLength: 0)294 Text(engine.display).font(.system(size: 26, weight: .medium)).monospacedDigit().lineLimit(1).minimumScaleFactor(0.4)295 .foregroundStyle(engine.isError ? AnyShapeStyle(.red) : AnyShapeStyle(.primary))296 }297 .frame(height: 34)298 .modifier(FBFieldFrame())299 .accessibilityElement(children: .ignore)300 .accessibilityLabel(label.isEmpty ? "Calculator display" : label)301 .accessibilityValue(engine.display)302 LazyVGrid(columns: Array(repeating: GridItem(.fixed(48), spacing: 6), count: 4), spacing: 6) {303 ForEach(CalculatorEngine.keys, id: \.self) { key in304 let isOperator = ["÷", "×", "−", "+", "="].contains(key)305 Button {306 engine.press(key)307 guard !engine.isError, key == "=" || key == "C" || key == "%" || key == "±" else { return }308 // The result reaches state when a calculation ends, not on every digit.309 runtime.fbSet(o, "value", .fbNumber(engine.value))310 } label: {311 Group {312 if key == "⌫" { Image(systemName: "delete.left") } else { Text(key) }313 }314 .font(.title3.weight(isOperator ? .semibold : .regular))315 .frame(width: 48, height: 34)316 .foregroundStyle(key == "=" ? AnyShapeStyle(Color.white) : isOperator ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.primary))317 .background(key == "=" ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.quaternary.opacity(isOperator ? 0.9 : 0.5)), in: RoundedRectangle(cornerRadius: 7))318 .contentShape(Rectangle())319 }320 .buttonStyle(.plain)321 .accessibilityLabel(name(key))322 }323 }324 }325 .frame(width: 48 * 4 + 18)326 }327}328