fix: 盲盒展示

This commit is contained in:
Junhui Chen 2025-09-11 17:45:55 +08:00
parent 0ab33cab47
commit 411bf440d4
4 changed files with 253 additions and 246 deletions

View File

@ -0,0 +1,9 @@
import Foundation
//
enum BlindBoxAnimationPhase {
case loading
case ready
case opening
case none
}

View File

@ -0,0 +1,36 @@
import SwiftUI
import Lottie
/// 4 loading / ready / opening / none
struct BlindBoxAnimationView: View {
@Binding var phase: BlindBoxAnimationPhase
let onTapReady: () -> Void
let onOpeningCompleted: () -> Void
var body: some View {
ZStack {
switch phase {
case .loading:
LottieView(name: "loading", isPlaying: true)
case .ready:
ZStack {
LottieView(name: "ready", isPlaying: true)
Color.clear
.contentShape(Rectangle())
.onTapGesture {
onTapReady()
}
}
case .opening:
BlindBoxLottieOnceView(name: "opening") {
onOpeningCompleted()
}
case .none:
Image("Empty")
.resizable()
.scaledToFit()
}
}
.frame(width: 300, height: 300)
}
}

View File

@ -0,0 +1,31 @@
import SwiftUI
import Lottie
/// Lottie
struct BlindBoxLottieOnceView: UIViewRepresentable {
let name: String
var animationSpeed: CGFloat = 1.0
let onCompleted: () -> Void
func makeUIView(context: Context) -> LottieAnimationView {
let animationView = LottieAnimationView()
if let animation = LottieAnimation.named(name) {
animationView.animation = animation
} else if let path = Bundle.main.path(forResource: name, ofType: "json") {
let animation = LottieAnimation.filepath(path)
animationView.animation = animation
}
animationView.loopMode = .playOnce
animationView.animationSpeed = animationSpeed
animationView.contentMode = .scaleAspectFit
animationView.backgroundBehavior = .pauseAndRestore
animationView.play { _ in
onCompleted()
}
return animationView
}
func updateUIView(_ uiView: LottieAnimationView, context: Context) {
//
}
}

View File

@ -8,13 +8,6 @@ extension Notification.Name {
static let blindBoxStatusChanged = Notification.Name("blindBoxStatusChanged") static let blindBoxStatusChanged = Notification.Name("blindBoxStatusChanged")
} }
internal enum BlindBoxAnimationPhase {
case loading
case ready
case opening
case none
}
extension Notification.Name { extension Notification.Name {
static let navigateToMediaViewer = Notification.Name("navigateToMediaViewer") static let navigateToMediaViewer = Notification.Name("navigateToMediaViewer")
} }
@ -28,13 +21,7 @@ struct BlindBoxView: View {
@State private var showSettings = false // @State private var showSettings = false //
@State private var showLogin = false @State private var showLogin = false
// ViewModel countdownText // ViewModel countdownText
//
@State private var showScalingOverlay = false
@State private var animationPhase: BlindBoxAnimationPhase = .none @State private var animationPhase: BlindBoxAnimationPhase = .none
@State private var scale: CGFloat = 0.1
// showControls BlindBoxMediaOverlay
@State private var isAnimating = true
@State private var showMedia = false
// - // -
@Query private var login: [Login] @Query private var login: [Login]
@ -45,16 +32,7 @@ struct BlindBoxView: View {
_viewModel = StateObject(wrappedValue: BlindBoxViewModel(mediaType: mediaType, currentBoxId: blindBoxId)) _viewModel = StateObject(wrappedValue: BlindBoxViewModel(mediaType: mediaType, currentBoxId: blindBoxId))
} }
private func startScalingAnimation() { // BlindBoxMediaOverlay 使
self.scale = 0.1
self.showScalingOverlay = true
withAnimation(.spring(response: 2.0, dampingFraction: 0.5, blendDuration: 0.8)) {
self.scale = 1.0
}
}
// BlindBoxMediaOverlay
var body: some View { var body: some View {
ZStack { ZStack {
@ -100,12 +78,12 @@ struct BlindBoxView: View {
} }
} }
.onChange(of: viewModel.videoURL) { _, url in .onChange(of: viewModel.videoURL) { _, url in
if !url.isEmpty { if !url.isEmpty && self.animationPhase != .opening {
withAnimation { self.animationPhase = .ready } withAnimation { self.animationPhase = .ready }
} }
} }
.onChange(of: viewModel.imageURL) { _, url in .onChange(of: viewModel.imageURL) { _, url in
if !url.isEmpty { if !url.isEmpty && self.animationPhase != .opening {
withAnimation { self.animationPhase = .ready } withAnimation { self.animationPhase = .ready }
} }
} }
@ -123,23 +101,7 @@ struct BlindBoxView: View {
} }
} }
if showScalingOverlay { // overlay
BlindBoxMediaOverlay(
mediaType: mediaType,
player: .init(get: { viewModel.player }, set: { viewModel.player = $0 }),
displayImage: viewModel.displayImage,
isPortrait: viewModel.isPortrait,
aspectRatio: viewModel.aspectRatio,
scale: $scale,
onBack: {
if mediaType == .all, !viewModel.videoURL.isEmpty, let url = URL(string: viewModel.videoURL) {
Router.shared.navigate(to: .blindOutcome(media: .video(url, nil), time: viewModel.blindGenerate?.name ?? "Your box", description: viewModel.blindGenerate?.description ?? "", isMember: viewModel.isMember))
} else if mediaType == .image, let image = viewModel.displayImage {
Router.shared.navigate(to: .blindOutcome(media: .image(image), time: viewModel.blindGenerate?.name ?? "Your box", description: viewModel.blindGenerate?.description ?? "", isMember: viewModel.isMember))
}
}
)
} else {
// Original content // Original content
VStack { VStack {
VStack(spacing: 20) { VStack(spacing: 20) {
@ -153,129 +115,49 @@ struct BlindBoxView: View {
// //
BlindBoxTitleView() BlindBoxTitleView()
.opacity(showScalingOverlay ? 0 : 1) .opacity(animationPhase == .opening ? 0 : 1)
.offset(y: showScalingOverlay ? -UIScreen.main.bounds.height * 0.2 : 0)
.animation(.easeInOut(duration: 0.5), value: showScalingOverlay)
// //
ZStack { ZStack {
// 1. Card // 1. Card
if !showScalingOverlay {
CardBlindBackground() CardBlindBackground()
} if mediaType == .all {
if mediaType == .all && !showScalingOverlay {
BlindCountBadge(text: "\(viewModel.blindCount?.availableQuantity ?? 0) Boxes") BlindCountBadge(text: "\(viewModel.blindCount?.availableQuantity ?? 0) Boxes")
.position(x: UIScreen.main.bounds.width * 0.7, .position(x: UIScreen.main.bounds.width * 0.7,
y: UIScreen.main.bounds.height * 0.18) y: UIScreen.main.bounds.height * 0.18)
.opacity(showScalingOverlay ? 0 : 1)
.animation(.easeOut(duration: 1.5), value: showScalingOverlay)
} }
if !showScalingOverlay {
VStack(spacing: 20) { VStack(spacing: 20) {
switch animationPhase { BlindBoxAnimationView(
case .loading: phase: $animationPhase,
LottieView(name: "ready", isPlaying: animationPhase == .loading && !showScalingOverlay) onTapReady: {
.frame(width: 300, height: 300)
// .onAppear {
// DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
// withAnimation {
// animationPhase = .ready
// }
// }
// }
case .ready:
ZStack {
LottieView(name: "ready", isPlaying: animationPhase == .ready && !showScalingOverlay)
.frame(width: 300, height: 300)
// Add a transparent overlay to capture taps
Color.clear
.contentShape(Rectangle()) // Make the entire area tappable
.frame(width: 300, height: 300)
.onTapGesture {
Perf.event("BlindBox_Open_Tapped") Perf.event("BlindBox_Open_Tapped")
print("点击了盲盒") print("点击了盲盒")
let boxIdToOpen = self.currentBoxId ?? self.viewModel.blindGenerate?.id let boxIdToOpen = self.currentBoxId ?? self.viewModel.blindGenerate?.id
if let boxId = boxIdToOpen { if let boxId = boxIdToOpen {
Task { Task {
do { do {
try await viewModel.openBlindBox(for: boxId) try await viewModel.openBlindBox(for: boxId)
print("✅ 盲盒开启成功") print("✅ 盲盒开启成功")
await viewModel.startPolling()
withAnimation {
animationPhase = .opening
}
} catch { } catch {
print("❌ 开启盲盒失败: \(error)") print("❌ 开启盲盒失败: \(error)")
} }
} }
} }
withAnimation { },
animationPhase = .opening onOpeningCompleted: {
} navigateToOutcome()
}
}
.frame(width: 300, height: 300)
case .opening:
ZStack {
if !showMedia {
LottieView(name: "ready", loopMode: .playOnce, isPlaying: !showMedia)
.frame(width: 300, height: 300)
.scaleEffect(scale)
}
// GIFView
Color.clear
.onAppear {
Perf.event("BlindBox_Opening_Begin")
print("开始播放开启动画")
// 1
self.scale = 1.0
// 1
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
withAnimation(.spring(response: 1.0, dampingFraction: 0.7)) {
//
self.scale = max(
UIScreen.main.bounds.width / 300,
UIScreen.main.bounds.height / 300
) * 1.2
//
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
withAnimation(.spring(response: 0.8, dampingFraction: 0.7)) {
self.scale = 1.0
//
Perf.event("BlindBox_Opening_ShowMedia")
self.showScalingOverlay = true
Task { await viewModel.prepareMedia() }
// GIF
self.showMedia = true
}
}
}
}
}
}
.frame(width: 300, height: 300)
case .none:
//
LottieView(name: "ready", loopMode: .loop, isPlaying: true)
.frame(width: 300, height: 300)
.scaleEffect(scale)
// Color.clear
// .frame(width: 300, height: 300)
// SVGImage(svgName: "BlindNone")
// .frame(width: 300, height: 300)
} }
)
} }
.offset(y: -50) .offset(y: -50)
.compositingGroup() .compositingGroup()
.padding() .padding()
} // opening
// if animationPhase != .opening {
if !showScalingOverlay && !showMedia {
BlindBoxDescriptionView( BlindBoxDescriptionView(
name: viewModel.blindGenerate?.name ?? "Some box", name: viewModel.blindGenerate?.name ?? "Some box",
description: viewModel.blindGenerate?.description ?? "" description: viewModel.blindGenerate?.description ?? ""
@ -288,10 +170,7 @@ struct BlindBoxView: View {
maxWidth: .infinity, maxWidth: .infinity,
maxHeight: UIScreen.main.bounds.height * 0.65 maxHeight: UIScreen.main.bounds.height * 0.65
) )
.opacity(showScalingOverlay ? 0 : 1)
.animation(.easeOut(duration: 1.5), value: showScalingOverlay)
.offset(y: showScalingOverlay ? -100 : 0)
.animation(.easeInOut(duration: 1.5), value: showScalingOverlay)
// TODO // TODO
if mediaType == .all, viewModel.didBootstrap { if mediaType == .all, viewModel.didBootstrap {
@ -305,14 +184,15 @@ struct BlindBoxView: View {
do { do {
try await viewModel.openBlindBox(for: boxId) try await viewModel.openBlindBox(for: boxId)
print("✅ 盲盒开启成功") print("✅ 盲盒开启成功")
await viewModel.startPolling()
withAnimation {
animationPhase = .opening
}
} catch { } catch {
print("❌ 开启盲盒失败: \(error)") print("❌ 开启盲盒失败: \(error)")
} }
} }
} }
withAnimation {
animationPhase = .opening
}
}, },
onGoToBuy: { onGoToBuy: {
Router.shared.navigate(to: .mediaUpload) Router.shared.navigate(to: .mediaUpload)
@ -360,7 +240,6 @@ struct BlindBoxView: View {
} }
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showSettings) .animation(.spring(response: 0.6, dampingFraction: 0.8), value: showSettings)
} }
}
.navigationBarBackButtonHidden(true) .navigationBarBackButtonHidden(true)
} }
/// ///
@ -391,6 +270,58 @@ struct BlindBoxView: View {
showSettings = false showSettings = false
} }
} }
///
private func navigateToOutcome() {
Perf.event("BlindBox_Opening_Completed")
Task { @MainActor in
let interval: UInt64 = 300_000_000 // 300ms
let timeout: UInt64 = 6_000_000_000 // 6s
var waited: UInt64 = 0
if mediaType == .all {
// URL
while viewModel.videoURL.isEmpty && waited < timeout {
try? await Task.sleep(nanoseconds: interval)
waited += interval
}
// URL player
if !viewModel.videoURL.isEmpty, let url = URL(string: viewModel.videoURL) {
Router.shared.navigate(
to: .blindOutcome(
media: .video(url, nil),
time: viewModel.blindGenerate?.name ?? "Your box",
description: viewModel.blindGenerate?.description ?? "",
isMember: viewModel.isMember
)
)
return
}
} else if mediaType == .image {
// imageURL UIImage
while viewModel.imageURL.isEmpty && waited < timeout {
try? await Task.sleep(nanoseconds: interval)
waited += interval
}
if viewModel.displayImage == nil && !viewModel.imageURL.isEmpty {
await viewModel.prepareMedia()
}
if let image = viewModel.displayImage {
Router.shared.navigate(
to: .blindOutcome(
media: .image(image),
time: viewModel.blindGenerate?.name ?? "Your box",
description: viewModel.blindGenerate?.description ?? "",
isMember: viewModel.isMember
)
)
return
}
}
// 便
print("⚠️ navigateToOutcome: 媒体尚未准备好videoURL=\(viewModel.videoURL), image=\(String(describing: viewModel.displayImage))")
}
}
} }
// MARK: - // MARK: -