import FoldFormat import Notation import SwiftUI /// One step of a model: its diagram, captioned with the step's instruction, beside the folding /// model on a regular-width screen and above it on a compact one. The Steps button lists every /// step, in a popover on a regular-width screen and a sheet on a compact one. Finishing the model /// locks it and celebrates over the paper; the lock button unlocks it to unfold. struct StepView: View { private let title: String @State private var session: FoldSession? @State private var isShowingSteps = false @State private var isCelebrating = false @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Environment(\.verticalSizeClass) private var verticalSizeClass /// `step` counts from 1. init(model: FoldFile, step: Int) { title = model.fileTitle ?? "Untitled" let session = try? FoldSession(model: model, step: step) if let session { ScreenshotScene.requested?.apply(to: session) } _session = State(initialValue: session) } var body: some View { Group { if let session { let sideBySide = horizontalSizeClass == .regular || verticalSizeClass == .compact let layout = sideBySide ? AnyLayout(HStackLayout(spacing: 0)) : AnyLayout(VStackLayout(spacing: 0)) layout { diagram(session) paper(session) } } else { ContentUnavailableView("This Model Can't Be Shown", systemImage: "exclamationmark.triangle") } } .navigationTitle(session.map { "Step \($0.step.index) of \($0.model.frames.count - 1)" } ?? title) .navigationBarTitleDisplayMode(.inline) .toolbar { if let session { if session.isFinished { ToolbarItem(placement: .topBarTrailing) { Button(session.isLocked ? "Unlock to unfold" : "Lock", systemImage: session.isLocked ? "lock.fill" : "lock.open") { session.toggleLock() } .accessibilityIdentifier("paper.lock") } } ToolbarItem(placement: .topBarTrailing) { Button("Steps", systemImage: "list.number") { isShowingSteps = true } .accessibilityIdentifier("steps.button") .popover(isPresented: $isShowingSteps) { StepListView(session: session) .frame(idealWidth: 360, idealHeight: 480) .presentationDetents([.medium, .large]) .presentationDragIndicator(.visible) // the paper seen through a translucent sheet fails the contrast audit .presentationBackground(.background) } } } } } /// The caption takes the height it needs up to `captionShare` of the pane, and scrolls beyond /// that, so the diagram stays in view at large text sizes. private func diagram(_ session: FoldSession) -> some View { GeometryReader { pane in VStack(alignment: .leading, spacing: 0) { DiagramCanvas(diagram: session.diagram, style: .standard) .accessibilityLabel("Diagram of step \(session.step.index)") ScrollView { HStack(alignment: .firstTextBaseline, spacing: 12) { Text("\(session.step.index)") .font(.title.bold()) .monospacedDigit() .accessibilityIdentifier("step.index") Text(session.step.instruction) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("diagram.caption") } .frame(maxWidth: .infinity, alignment: .leading) .padding() } .scrollBounceBehavior(.basedOnSize) .frame(maxHeight: pane.size.height * Self.captionShare) .fixedSize(horizontal: false, vertical: true) } } } private static let captionShare = 0.45 private func paper(_ session: FoldSession) -> some View { PaperView(positions: session.meshPositions, mesh: session.interpolator.mesh, clusters: session.clusters, camera: session.camera) .onGeometryChange(for: CGSize.self) { $0.size } action: { size in if size.width > 0 && size.height > 0 { session.viewportSize = SIMD2(size.width, size.height) } } .foldGesture(session) .reorientGesture(session) .orbitGesture(session) // a representation, so that dropping the adjustable action when locked leaves the // paper's Metal view in place .accessibilityRepresentation { paperElement(session) } .overlay(alignment: .topLeading) { if Self.isUITesting { foldPath(session) cameraValue(session) stepKind(session) } } .overlay { if isCelebrating && session.isFinished { celebration.id(session.finishCount) } } .sensoryFeedback(.success, trigger: session.finishCount) .task(id: session.finishCount) { guard session.finishCount > 0 else { return } // high priority, so that the paper's value changing on an adjust does not cut it off var announcement = AttributedString("\(title) folded") announcement.accessibilitySpeechAnnouncementPriority = .high AccessibilityNotification.Announcement(announcement).post() withAnimation(.easeIn(duration: 0.6)) { isCelebrating = true } do { try await Task.sleep(for: .seconds(Confetti.duration)) } catch { return } withAnimation { isCelebrating = false } } } @ViewBuilder private func paperElement(_ session: FoldSession) -> some View { let element = Color.clear .accessibilityElement() .accessibilityLabel(session.step.instruction) .accessibilityValue(session.isLocked ? "Folded, locked" : session.t.formatted(.percent.precision(.fractionLength(0)))) .accessibilityIdentifier("fold.paper") if session.isLocked { element } else { element.accessibilityAdjustableAction { direction in switch direction { case .increment: session.adjust(1) case .decrement: session.adjust(-1) @unknown default: break } } } } /// Confetti over the paper, or under Reduce Motion a label that fades in and out. private var celebration: some View { Group { if reduceMotion { Text("Folded") .font(.largeTitle.bold()) .padding(.horizontal, 24) .padding(.vertical, 12) .background(.regularMaterial, in: Capsule()) } else { Confetti() .clipped() .accessibilityElement() .accessibilityLabel("Folded") } } .allowsHitTesting(false) .transition(reduceMotion ? .opacity : .identity) .accessibilityIdentifier("confetti") } private static let isUITesting = ProcessInfo.processInfo.arguments.contains("-UITesting") /// For UI tests: the fold path's samples, each as x,y normalised to the paper view's frame. private func foldPath(_ session: FoldSession) -> some View { let mapping = session.mapping, size = session.viewportSize let value = mapping.path.map { p in String(format: "%.5f,%.5f", p.x / size.x, p.y / size.y) }.joined(separator: " ") return Color.clear .frame(width: 1, height: 1) .allowsHitTesting(false) .accessibilityElement() .accessibilityValue(value) .accessibilityIdentifier("fold.path") } /// For UI tests: the step's kind, as in `krz:step`. private func stepKind(_ session: FoldSession) -> some View { Color.clear .frame(width: 1, height: 1) .allowsHitTesting(false) .accessibilityElement() .accessibilityValue(session.step.kind.rawValue) .accessibilityIdentifier("step.kind") } /// For UI tests: the camera's eye, up and field of view, to 3 decimals. private func cameraValue(_ session: FoldSession) -> some View { let camera = session.camera let value = [camera.eye, camera.up].map { v in String(format: "%.3f,%.3f,%.3f", v.x, v.y, v.z) }.joined(separator: " ") + String(format: " %.3f", camera.fieldOfView) return Color.clear .frame(width: 1, height: 1) .allowsHitTesting(false) .accessibilityElement() .accessibilityValue(value) .accessibilityIdentifier("paper.camera") } }