Compare commits

...

18 Commits

21 changed files with 986 additions and 1796 deletions

View File

@ -1,4 +1,5 @@
{ {
"lldb.library": "/Library/Developer/CommandLineTools/Library/PrivateFrameworks/LLDB.framework/Versions/A/LLDB", "lldb.library": "/Library/Developer/CommandLineTools/Library/PrivateFrameworks/LLDB.framework/Versions/A/LLDB",
"lldb.launch.expressions": "native" "lldb.launch.expressions": "native",
"sweetpad.build.xcodeWorkspacePath": "wake.xcodeproj/project.xcworkspace"
} }

View File

@ -0,0 +1,174 @@
import Foundation
// MARK: - Blind Box Media Type
enum BlindBoxMediaType {
case video
case image
case all
}
// MARK: - Blind Box List
struct BlindList: Codable, Identifiable {
// API
let id: String
let boxCode: String
let userId: String
let name: String
let boxType: String
let features: String?
let resultFile: FileInfo?
let status: String
let workflowInstanceId: String?
let videoGenerateTime: String?
let createTime: String
let coverFile: FileInfo?
let description: String?
struct FileInfo: Codable {
let id: String
let fileName: String?
let url: String?
// 使
// AnyCodable/JSONValue
let metadata: [String: String]?
enum CodingKeys: String, CodingKey {
case id
case fileName = "file_name"
case url
case metadata
}
}
enum CodingKeys: String, CodingKey {
case id
case boxCode = "box_code"
case userId = "user_id"
case name
case boxType = "box_type"
case features
case resultFile = "result_file"
case status
case workflowInstanceId = "workflow_instance_id"
case videoGenerateTime = "video_generate_time"
case createTime = "create_time"
case coverFile = "cover_file"
case description
}
}
// MARK: - Blind Box Count
struct BlindCount: Codable {
let availableQuantity: Int
enum CodingKeys: String, CodingKey {
case availableQuantity = "available_quantity"
}
}
// MARK: - Blind Box Data
struct BlindBoxData: Codable {
let id: String
let boxCode: String
let userId: String
let name: String
let boxType: String
let features: String?
let resultFile: FileInfo?
let status: String
let workflowInstanceId: String?
let videoGenerateTime: String?
let createTime: String
let coverFile: FileInfo?
let description: String
// Int64
var idValue: Int64 { Int64(id) ?? 0 }
var userIdValue: Int64 { Int64(userId) ?? 0 }
struct FileInfo: Codable {
let id: String
let fileName: String?
let url: String?
let metadata: [String: String]?
enum CodingKeys: String, CodingKey {
case id
case fileName = "file_name"
case url
case metadata
}
}
enum CodingKeys: String, CodingKey {
case id
case boxCode = "box_code"
case userId = "user_id"
case name
case boxType = "box_type"
case features
case resultFile = "result_file"
case status
case workflowInstanceId = "workflow_instance_id"
case videoGenerateTime = "video_generate_time"
case createTime = "create_time"
case coverFile = "cover_file"
case description
}
init(id: String, boxCode: String, userId: String, name: String, boxType: String, features: String?, resultFile: FileInfo?, status: String, workflowInstanceId: String?, videoGenerateTime: String?, createTime: String, coverFile: FileInfo?, description: String) {
self.id = id
self.boxCode = boxCode
self.userId = userId
self.name = name
self.boxType = boxType
self.features = features
self.resultFile = resultFile
self.status = status
self.workflowInstanceId = workflowInstanceId
self.videoGenerateTime = videoGenerateTime
self.createTime = createTime
self.coverFile = coverFile
self.description = description
}
init(from listItem: BlindList) {
self.id = listItem.id
self.boxCode = listItem.boxCode
self.userId = listItem.userId
self.name = listItem.name
self.boxType = listItem.boxType
self.features = listItem.features
// FileInfo
if let resultFileInfo = listItem.resultFile {
self.resultFile = FileInfo(
id: resultFileInfo.id,
fileName: resultFileInfo.fileName,
url: resultFileInfo.url,
metadata: resultFileInfo.metadata
)
} else {
self.resultFile = nil
}
self.status = listItem.status
self.workflowInstanceId = listItem.workflowInstanceId
self.videoGenerateTime = listItem.videoGenerateTime
self.createTime = listItem.createTime
// coverFileFileInfo
if let coverFileInfo = listItem.coverFile {
self.coverFile = FileInfo(
id: coverFileInfo.id,
fileName: coverFileInfo.fileName,
url: coverFileInfo.url,
metadata: coverFileInfo.metadata
)
} else {
self.coverFile = nil
}
self.description = listItem.description ?? ""
}
}

View File

@ -16,6 +16,41 @@ struct MemberProfileResponse: Codable {
} }
} }
// MARK: - TitleRanking
struct TitleRanking: Codable {
let displayName: String
let ranking: Int
let value: Int
let materialType: String
let userId: String
let region: String
let userAvatarUrl: String?
let userNickName: String?
enum CodingKeys: String, CodingKey {
case displayName = "display_name"
case ranking
case value
case materialType = "material_type"
case userId = "user_id"
case region
case userAvatarUrl = "user_avatar_url"
case userNickName = "user_nick_name"
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(displayName, forKey: .displayName)
try container.encode(ranking, forKey: .ranking)
try container.encode(value, forKey: .value)
try container.encode(materialType, forKey: .materialType)
try container.encode(userId, forKey: .userId)
try container.encode(region, forKey: .region)
try container.encodeIfPresent(userAvatarUrl, forKey: .userAvatarUrl)
try container.encodeIfPresent(userNickName, forKey: .userNickName)
}
}
// MARK: - MemberProfile // MARK: - MemberProfile
struct MemberProfile: Codable { struct MemberProfile: Codable {
let materialCounter: MaterialCounter let materialCounter: MaterialCounter
@ -26,7 +61,7 @@ struct MemberProfile: Codable {
let totalPoints: Int let totalPoints: Int
let usedBytes: Int let usedBytes: Int
let totalBytes: Int let totalBytes: Int
let titleRankings: [String] let titleRankings: [TitleRanking]
let medalInfos: [MedalInfo] let medalInfos: [MedalInfo]
let membershipLevel: String let membershipLevel: String
let membershipEndAt: String let membershipEndAt: String
@ -57,7 +92,7 @@ struct MemberProfile: Codable {
totalPoints = try container.decode(Int.self, forKey: .totalPoints) totalPoints = try container.decode(Int.self, forKey: .totalPoints)
usedBytes = try container.decode(Int.self, forKey: .usedBytes) usedBytes = try container.decode(Int.self, forKey: .usedBytes)
totalBytes = try container.decode(Int.self, forKey: .totalBytes) totalBytes = try container.decode(Int.self, forKey: .totalBytes)
titleRankings = try container.decode([String].self, forKey: .titleRankings) titleRankings = try container.decode([TitleRanking].self, forKey: .titleRankings)
if let medalInfos = try? container.decode([MedalInfo].self, forKey: .medalInfos) { if let medalInfos = try? container.decode([MedalInfo].self, forKey: .medalInfos) {
self.medalInfos = medalInfos self.medalInfos = medalInfos

View File

@ -0,0 +1,168 @@
import Foundation
// MARK: - Generate Blind Box Request Model
// struct GenerateBlindBoxRequest: Codable {
// let boxType: String
// let materialIds: [String]
// enum CodingKeys: String, CodingKey {
// case boxType = "box_type"
// case materialIds = "material_ids"
// }
// }
// MARK: - Generate Blind Box Response Model
struct GenerateBlindBoxResponse: Codable {
let code: Int
let data: BlindBoxData?
}
// MARK: - Get Blind Box List Response Model
struct BlindBoxListResponse: Codable {
let code: Int
let data: [BlindBoxData]
}
// MARK: - Open Blind Box Response Model
struct OpenBlindBoxResponse: Codable {
let code: Int
let data: BlindBoxData?
}
// MARK: - Blind Box API Client
class BlindBoxApi {
static let shared = BlindBoxApi()
private init() {}
///
/// - Parameters:
/// - boxType: ( "First")
/// - materialIds: ID
/// - completion:
func generateBlindBox(
boxType: String,
materialIds: [String],
completion: @escaping (Result<BlindBoxData?, Error>) -> Void
) {
// Codable
let parameters: [String: Any] = [
"box_type": boxType,
"material_ids": materialIds
]
NetworkService.shared.postWithToken(
path: "/blind_box/generate",
parameters: parameters,
completion: { (result: Result<GenerateBlindBoxResponse, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
if response.code == 0 {
completion(.success(response.data))
} else {
completion(.failure(NetworkError.serverError("服务器返回错误码: \(response.code)")))
}
case .failure(let error):
completion(.failure(error))
}
}
}
)
}
/// 使 async/await
/// - Parameters:
/// - boxType: ( "First")
/// - materialIds: ID
/// - Returns:
@available(iOS 13.0, *)
func generateBlindBox(boxType: String, materialIds: [String]) async throws -> BlindBoxData? {
let parameters: [String: Any] = [
"box_type": boxType,
"material_ids": materialIds
]
let response: GenerateBlindBoxResponse = try await NetworkService.shared.postWithToken(
path: "/blind_box/generate",
parameters: parameters
)
if response.code == 0 {
return response.data
} else {
throw NetworkError.serverError("服务器返回错误码: \(response.code)")
}
}
///
/// - Parameters:
/// - boxId: ID
/// - completion:
func getBlindBox(
boxId: String,
completion: @escaping (Result<BlindBoxData?, Error>) -> Void
) {
let path = "/blind_box/query/\(boxId)"
NetworkService.shared.getWithToken(
path: path,
completion: { (result: Result<GenerateBlindBoxResponse, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
if response.code == 0 {
completion(.success(response.data))
} else {
completion(.failure(NetworkError.serverError("服务器返回错误码: \(response.code)")))
}
case .failure(let error):
completion(.failure(error))
}
}
}
)
}
/// 使 async/await
/// - Parameter boxId: ID
/// - Returns:
@available(iOS 13.0, *)
func getBlindBox(boxId: String) async throws -> BlindBoxData? {
let path = "/blind_box/query/\(boxId)"
let response: GenerateBlindBoxResponse = try await NetworkService.shared.getWithToken(path: path)
if response.code == 0 {
return response.data
} else {
throw NetworkError.serverError("服务器返回错误码: \(response.code)")
}
}
///
@available(iOS 13.0, *)
func getBlindBoxList() async throws -> [BlindBoxData]? {
let response: BlindBoxListResponse = try await NetworkService.shared.getWithToken(path: "/blind_boxs/query")
if response.code == 0 {
return response.data
} else {
throw NetworkError.serverError("服务器返回错误码: \(response.code)")
}
}
///
/// - Parameter boxId: ID
/// - Returns: null
@available(iOS 13.0, *)
func openBlindBox(boxId: String) async throws {
let response: OpenBlindBoxResponse = try await NetworkService.shared.postWithToken(
path: "/blind_box/open",
parameters: ["box_id": boxId]
)
if response.code == 0 {
// APIdatanull
print("✅ 盲盒开启成功")
} else {
throw NetworkError.serverError("服务器返回错误码: \(response.code)")
}
}
}

View File

@ -0,0 +1,112 @@
import Foundation
// MARK: -
struct MaterialRequest: Codable {
let fileId: String
let previewFileId: String
enum CodingKeys: String, CodingKey {
case fileId = "file_id"
case previewFileId = "preview_file_id"
}
}
struct AddMaterialResponse: Codable {
let code: Int
let data: [String]?
}
// MARK: -
class MaterialUpload {
static let shared = MaterialUpload()
private init() {}
///
/// - Parameters:
/// - fileId: ID
/// - previewFileId: ID
/// - completion: ID
func addMaterial(
fileId: String,
previewFileId: String,
completion: @escaping (Result<[String]?, Error>) -> Void
) {
//
let materials: [[String: String]] = [[
"file_id": fileId,
"preview_file_id": previewFileId
]]
// JSON
print("🔍 准备发送的参数: \(materials)")
// 使NetworkService
NetworkService.shared.post(
path: "/material",
parameters: materials,
completion: { (result: Result<AddMaterialResponse, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
if response.code == 0 {
completion(.success(response.data))
} else {
completion(.failure(NetworkError.serverError("服务器返回错误码: \(response.code)")))
}
case .failure(let error):
print("❌ 素材上传失败: \(error.localizedDescription)")
completion(.failure(error))
}
}
}
)
}
/// 使 async/await
/// - Parameters:
/// - fileId: ID
/// - previewFileId: ID
/// - Returns: ID
/// - Throws: NetworkError
func addMaterial(
fileId: String,
previewFileId: String
) async throws -> [String]? {
//
let materials: [[String: String]] = [[
"file_id": fileId,
"preview_file_id": previewFileId
]]
//
print("🔍(async) 准备发送的参数: \(materials)")
// 使 async/await post
let response: AddMaterialResponse = try await NetworkService.shared.post(
path: "/material",
parameters: materials
)
// code
if response.code == 0 {
return response.data
} else {
throw NetworkError.serverError("服务器返回错误码: \(response.code)")
}
}
func addMaterials(files: [[String: String]]) async throws -> [String]? {
let response: AddMaterialResponse = try await NetworkService.shared.post(
path: "/material",
parameters: files
)
if response.code == 0 {
return response.data
} else {
throw NetworkError.serverError("服务器返回错误码: \(response.code)")
}
}
}

View File

@ -108,6 +108,79 @@ extension NetworkService: NetworkServiceProtocol {
} }
} }
// MARK: - Async/Await Extensions
extension NetworkService {
/// 使 async/await GET Token
public func getWithToken<T: Decodable>(
path: String,
parameters: [String: Any]? = nil
) async throws -> T {
return try await withCheckedThrowingContinuation { continuation in
getWithToken(path: path, parameters: parameters) { (result: Result<T, NetworkError>) in
switch result {
case .success(let value):
continuation.resume(returning: value)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
/// 使 async/await POST Token
public func postWithToken<T: Decodable>(
path: String,
parameters: [String: Any]
) async throws -> T {
return try await withCheckedThrowingContinuation { continuation in
postWithToken(path: path, parameters: parameters) { (result: Result<T, NetworkError>) in
switch result {
case .success(let value):
continuation.resume(returning: value)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
/// 使 async/await POST
public func post<T: Decodable>(
path: String,
parameters: Any? = nil,
headers: [String: String]? = nil
) async throws -> T {
return try await withCheckedThrowingContinuation { continuation in
post(path: path, parameters: parameters, headers: headers) { (result: Result<T, NetworkError>) in
switch result {
case .success(let value):
continuation.resume(returning: value)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
/// 使 async/await POST Token
public func postWithToken<T: Decodable>(
path: String,
parameters: Any? = nil,
headers: [String: String]? = nil
) async throws -> T {
return try await withCheckedThrowingContinuation { continuation in
postWithToken(path: path, parameters: parameters, headers: headers) { (result: Result<T, NetworkError>) in
switch result {
case .success(let value):
continuation.resume(returning: value)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
}
public enum NetworkError: Error { public enum NetworkError: Error {
case invalidURL case invalidURL
case noData case noData

View File

@ -7,8 +7,8 @@ enum AppRoute: Hashable {
case feedbackView case feedbackView
case feedbackDetail(type: FeedbackView.FeedbackType) case feedbackDetail(type: FeedbackView.FeedbackType)
case mediaUpload case mediaUpload
case blindBox(mediaType: BlindBoxView.BlindBoxMediaType) case blindBox(mediaType: BlindBoxMediaType, blindBoxId: String? = nil)
case blindOutcome(media: MediaType, time: String? = nil, description: String? = nil) case blindOutcome(media: MediaType, time: String? = nil, description: String? = nil, isMember: Bool)
case memories case memories
case subscribe case subscribe
case userInfo case userInfo
@ -23,17 +23,18 @@ enum AppRoute: Hashable {
case .login: case .login:
LoginView() LoginView()
case .avatarBox: case .avatarBox:
AvatarBoxView() // AvatarBoxView has been removed; route to BlindBoxView as replacement
BlindBoxView(mediaType: .all)
case .feedbackView: case .feedbackView:
FeedbackView() FeedbackView()
case .feedbackDetail(let type): case .feedbackDetail(let type):
FeedbackDetailView(feedbackType: type) FeedbackDetailView(feedbackType: type)
case .mediaUpload: case .mediaUpload:
MediaUploadView() MediaUploadView()
case .blindBox(let mediaType): case .blindBox(let mediaType, let blindBoxId):
BlindBoxView(mediaType: mediaType) BlindBoxView(mediaType: mediaType, blindBoxId: blindBoxId)
case .blindOutcome(let media, let time, let description): case .blindOutcome(let media, let time, let description, let isMember):
BlindOutcomeView(media: media, time: time, description: description) BlindOutcomeView(media: media, time: time, description: description, isMember: isMember)
case .memories: case .memories:
MemoriesView() MemoriesView()
case .subscribe: case .subscribe:

View File

@ -1,105 +0,0 @@
import SwiftUI
struct AvatarBoxView: View {
@Environment(\.dismiss) private var dismiss
@EnvironmentObject private var router: Router
@State private var isAnimating = false
var body: some View {
ZStack {
// Background color
Color.white
.ignoresSafeArea()
VStack(spacing: 0) {
// Navigation Bar
HStack {
Button(action: {
dismiss()
}) {
Image(systemName: "chevron.left")
.font(.system(size: 17, weight: .medium))
.foregroundColor(.black)
.padding()
}
Spacer()
Text("动画页面")
.font(.headline)
.foregroundColor(.black)
Spacer()
// Invisible spacer to center the title
Color.clear
.frame(width: 44, height: 44)
}
.frame(height: 44)
.background(Color.white)
Spacer()
// Animated Content
ZStack {
// Pulsing circle animation
Circle()
.fill(Color.blue.opacity(0.2))
.frame(width: 200, height: 200)
.scaleEffect(isAnimating ? 1.5 : 1.0)
.opacity(isAnimating ? 0.5 : 1.0)
.animation(
Animation.easeInOut(duration: 1.5)
.repeatForever(autoreverses: true),
value: isAnimating
)
// Center icon
Image(systemName: "sparkles")
.font(.system(size: 60))
.foregroundColor(.blue)
.rotationEffect(.degrees(isAnimating ? 360 : 0))
.animation(
Animation.linear(duration: 8)
.repeatForever(autoreverses: false),
value: isAnimating
)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
Spacer()
// Bottom Button
Button(action: {
router.navigate(to: .feedbackView)
}) {
Text("Continue")
.font(.headline)
.foregroundColor(.themeTextMessageMain)
.frame(maxWidth: .infinity)
.frame(height: 56)
.background(Color.themePrimary)
.cornerRadius(25)
.padding(.horizontal, 24)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
.onAppear {
isAnimating = true
}
}
}
// MARK: - Preview
struct AvatarBoxView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
AvatarBoxView()
.environmentObject(Router.shared)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}

View File

@ -6,6 +6,7 @@ struct BlindOutcomeView: View {
let media: MediaType let media: MediaType
let time: String? let time: String?
let description: String? let description: String?
let isMember: Bool
@Environment(\.presentationMode) var presentationMode @Environment(\.presentationMode) var presentationMode
@State private var isFullscreen = false @State private var isFullscreen = false
@State private var isPlaying = false @State private var isPlaying = false
@ -13,10 +14,11 @@ struct BlindOutcomeView: View {
@State private var showIPListModal = false @State private var showIPListModal = false
@State private var player: AVPlayer? @State private var player: AVPlayer?
init(media: MediaType, time: String? = nil, description: String? = nil) { init(media: MediaType, time: String? = nil, description: String? = nil, isMember: Bool = false) {
self.media = media self.media = media
self.time = time self.time = time
self.description = description self.description = description
self.isMember = isMember
} }
var body: some View { var body: some View {

View File

@ -1,301 +0,0 @@
import SwiftUI
struct FilmStripView: View {
@State private var animate = false
// 使SF Symbols
private let symbolNames = [
"photo.fill", "heart.fill", "star.fill", "bookmark.fill",
"flag.fill", "bell.fill", "tag.fill", "paperplane.fill"
]
private let targetIndices = [2, 5, 3] //
var body: some View {
ZStack {
Color.black.edgesIgnoringSafeArea(.all)
//
FilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[0],
offset: 0,
stripColor: .red
)
.rotationEffect(.degrees(5))
.zIndex(1)
FilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[1],
offset: 0.3,
stripColor: .blue
)
.rotationEffect(.degrees(-3))
.zIndex(2)
FilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[2],
offset: 0.6,
stripColor: .green
)
.rotationEffect(.degrees(2))
.zIndex(3)
}
.onAppear {
withAnimation(
.timingCurve(0.2, 0.1, 0.8, 0.9, duration: 4.0)
) {
animate = true
}
}
}
}
//
struct FilmStrip: View {
let symbols: [String]
let targetIndex: Int
let offset: Double
let stripColor: Color
@State private var animate = false
var body: some View {
GeometryReader { geometry in
let itemWidth: CGFloat = 100
let spacing: CGFloat = 8
let totalWidth = itemWidth * CGFloat(symbols.count) + spacing * CGFloat(symbols.count - 1)
//
RoundedRectangle(cornerRadius: 10)
.fill(stripColor.opacity(0.8))
.frame(height: 160)
.overlay(
// 齿
HStack(spacing: spacing) {
ForEach(0..<symbols.count * 3, id: \.self) { index in
Circle()
.fill(Color.black)
.frame(width: 12, height: 12)
.offset(y: -75)
}
}
.frame(width: totalWidth * 3),
alignment: .leading
)
.overlay(
//
HStack(spacing: spacing) {
ForEach(0..<symbols.count * 3, id: \.self) { index in
let actualIndex = index % symbols.count
ZStack {
RoundedRectangle(cornerRadius: 6)
.fill(Color.white)
.frame(width: itemWidth - 10, height: 100)
Image(systemName: symbols[actualIndex])
.font(.system(size: 30))
.foregroundColor(stripColor)
.shadow(radius: 2)
}
}
}
.offset(x: animate ? -CGFloat(targetIndex) * (itemWidth + spacing) - totalWidth : 0)
.frame(width: totalWidth * 3),
alignment: .leading
)
}
.frame(height: 180)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + offset) {
withAnimation(
.timingCurve(0.2, 0.1, 0.8, 0.9, duration: 3.5)
) {
animate = true
}
}
}
}
}
//
struct EnhancedFilmStrip: View {
let symbols: [String]
let targetIndex: Int
let offset: Double
let stripColor: Color
@State private var animate = false
var body: some View {
GeometryReader { geometry in
let itemWidth: CGFloat = 110
let spacing: CGFloat = 10
let totalWidth = itemWidth * CGFloat(symbols.count) + spacing * CGFloat(symbols.count - 1)
ZStack {
//
RoundedRectangle(cornerRadius: 12)
.fill(Color.black.opacity(0.3))
.frame(height: 170)
.offset(y: 5)
.blur(radius: 3)
//
RoundedRectangle(cornerRadius: 12)
.fill(stripColor)
.frame(height: 170)
.overlay(
// 齿
HStack(spacing: spacing) {
ForEach(0..<symbols.count * 3, id: \.self) { index in
VStack {
Circle()
.fill(Color.black)
.frame(width: 14, height: 14)
.padding(.top, 8)
Spacer()
Circle()
.fill(Color.black)
.frame(width: 14, height: 14)
.padding(.bottom, 8)
}
.frame(height: 170)
}
}
.frame(width: totalWidth * 3),
alignment: .leading
)
//
HStack(spacing: spacing) {
ForEach(0..<symbols.count * 3, id: \.self) { index in
let actualIndex = index % symbols.count
ZStack {
RoundedRectangle(cornerRadius: 8)
.fill(Color.white)
.frame(width: itemWidth - 15, height: 110)
.shadow(color: .black.opacity(0.2), radius: 3, x: 0, y: 2)
VStack {
Image(systemName: symbols[actualIndex])
.font(.system(size: 32, weight: .bold))
.foregroundColor(stripColor)
Text("\(actualIndex + 1)")
.font(.caption)
.foregroundColor(.gray)
}
}
}
}
.offset(x: animate ? -CGFloat(targetIndex) * (itemWidth + spacing) - totalWidth : 0)
.frame(width: totalWidth * 3)
}
}
.frame(height: 180)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + offset) {
withAnimation(
.timingCurve(0.2, 0.1, 0.8, 0.9, duration: 3.5)
) {
animate = true
}
}
}
}
}
//
struct FilmStripView_Previews: PreviewProvider {
static var previews: some View {
FilmStripView()
}
}
// 使
struct EnhancedFilmStripView: View {
@State private var animate = false
private let symbolNames = [
"camera.fill", "film.fill", "photo.fill", "heart.fill",
"star.fill", "bookmark.fill", "flag.fill", "bell.fill"
]
private let targetIndices = [2, 5, 3]
var body: some View {
ZStack {
LinearGradient(
gradient: Gradient(colors: [Color.blue.opacity(0.8), Color.purple.opacity(0.8)]),
startPoint: .topLeading,
endPoint: .bottomTrailing
)
.edgesIgnoringSafeArea(.all)
VStack(spacing: 30) {
Text("胶片动效展示")
.font(.title)
.fontWeight(.bold)
.foregroundColor(.white)
.padding(.top)
EnhancedFilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[0],
offset: 0,
stripColor: .red
)
.rotationEffect(.degrees(4))
EnhancedFilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[1],
offset: 0.4,
stripColor: .blue
)
.rotationEffect(.degrees(-2))
EnhancedFilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[2],
offset: 0.8,
stripColor: .green
)
.rotationEffect(.degrees(3))
Button("重新播放") {
restartAnimation()
}
.padding()
.background(Color.white)
.foregroundColor(.blue)
.cornerRadius(10)
.padding()
}
}
.onAppear {
startAnimation()
}
}
private func startAnimation() {
withAnimation(
.timingCurve(0.2, 0.1, 0.8, 0.9, duration: 4.0)
) {
animate = true
}
}
private func restartAnimation() {
animate = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
startAnimation()
}
}
}
//
struct EnhancedFilmStripView_Previews: PreviewProvider {
static var previews: some View {
EnhancedFilmStripView()
}
}

View File

@ -1,253 +0,0 @@
import SwiftUI
struct ReplayableFilmReelAnimation: View {
//
@State private var animationProgress: CGFloat = 0
@State private var isCatching: Bool = false
@State private var isDisappearing: Bool = false
@State private var showReplayButton: Bool = false
// 16
private let reelImages: [[String]] = [
(0..<16).map { "film1-\($0+1)" }, //
(0..<16).map { "film2-\($0+1)" }, //
(0..<16).map { "film3-\($0+1)" } //
]
//
private let topTiltAngle: Double = -7 //
private let bottomTiltAngle: Double = 7 //
//
private let targetImageIndex: Int = 8
var body: some View {
ZStack {
//
Color(red: 0.08, green: 0.08, blue: 0.08).edgesIgnoringSafeArea(.all)
// -
ZStack {
//
FilmReelView1(images: reelImages[0])
.rotationEffect(Angle(degrees: topTiltAngle))
.offset(x: calculateTopOffset(), y: -200)
.opacity(isDisappearing ? 0 : 1)
.zIndex(1)
//
FilmReelView1(images: reelImages[1])
.offset(x: calculateMiddleOffset(), y: 0)
.scaleEffect(isCatching ? 1.03 : 1.0)
.opacity(isDisappearing ? 0 : 1)
.zIndex(2)
//
FilmReelView1(images: reelImages[2])
.rotationEffect(Angle(degrees: bottomTiltAngle))
.offset(x: calculateBottomOffset(), y: 200)
.opacity(isDisappearing ? 0 : 1)
.zIndex(1)
//
if isDisappearing {
Image(reelImages[1][targetImageIndex])
.resizable()
.scaledToFit()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding()
.transition(.opacity.combined(with: .scale))
.zIndex(3)
}
}
//
if showReplayButton {
Button(action: resetAndReplay) {
ZStack {
Circle()
.fill(Color.black.opacity(0.7))
.frame(width: 60, height: 60)
.shadow(radius: 10)
Image(systemName: "arrow.counterclockwise")
.foregroundColor(.white)
.font(.system(size: 24))
}
}
.position(x: UIScreen.main.bounds.width - 40, y: 40)
.transition(.opacity.combined(with: .scale))
.zIndex(4)
}
}
.onAppear {
startAnimation()
}
}
//
private func resetAndReplay() {
withAnimation(.easeInOut(duration: 0.5)) {
showReplayButton = false
isDisappearing = false
isCatching = false
animationProgress = 0
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
startAnimation()
}
}
//
private func calculateTopOffset() -> CGFloat {
let baseDistance: CGFloat = 1000
let speedFactor: CGFloat = 1.0
return baseDistance * speedFactor * progressCurve()
}
//
private func calculateMiddleOffset() -> CGFloat {
let baseDistance: CGFloat = -1100
let speedFactor: CGFloat = 1.05
return baseDistance * speedFactor * progressCurve()
}
//
private func calculateBottomOffset() -> CGFloat {
let baseDistance: CGFloat = 1000
let speedFactor: CGFloat = 0.95
return baseDistance * speedFactor * progressCurve()
}
// 线
private func progressCurve() -> CGFloat {
if animationProgress < 0.6 {
//
return easeInQuad(animationProgress / 0.6) * 0.7
} else if animationProgress < 0.85 {
//
return 0.7 + easeOutQuad((animationProgress - 0.6) / 0.25) * 0.25
} else {
//
let t = (animationProgress - 0.85) / 0.15
return 0.95 + t * 0.05
}
}
// 线
private func easeInQuad(_ t: CGFloat) -> CGFloat {
return t * t
}
// 线
private func easeOutQuad(_ t: CGFloat) -> CGFloat {
return t * (2 - t)
}
//
private func startAnimation() {
//
withAnimation(.easeIn(duration: 3.5)) {
animationProgress = 0.6
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) {
withAnimation(.linear(duration: 2.5)) {
animationProgress = 0.85
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
withAnimation(.easeOut(duration: 1.8)) {
animationProgress = 1.0
isCatching = true
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 1.8) {
withAnimation(.easeInOut(duration: 0.7)) {
isDisappearing = true
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
withAnimation(.easeInOut(duration: 0.3)) {
showReplayButton = true
}
}
}
}
}
}
}
//
struct FilmReelView1: View {
let images: [String]
var body: some View {
HStack(spacing: 10) {
ForEach(images.indices, id: \.self) { index in
ZStack {
//
RoundedRectangle(cornerRadius: 4)
.stroke(Color.gray, lineWidth: 2)
.background(Color(red: 0.15, green: 0.15, blue: 0.15))
//
Rectangle()
.fill(
LinearGradient(
gradient: Gradient(colors: [.blue, .indigo]),
startPoint: .topLeading,
endPoint: .bottomTrailing
)
)
.opacity(0.9)
.cornerRadius(2)
.padding(2)
//
Text("\(images[index])")
.foregroundColor(.white)
.font(.caption2)
}
.frame(width: 90, height: 130)
//
.overlay(
HStack {
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
Spacer()
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
}
)
}
}
}
}
//
struct ReplayableFilmReelAnimation_Previews: PreviewProvider {
static var previews: some View {
ReplayableFilmReelAnimation()
}
}

View File

@ -1,226 +0,0 @@
import SwiftUI
struct FilmAnimation1: View {
//
private let deviceWidth = UIScreen.main.bounds.width
private let deviceHeight = UIScreen.main.bounds.height
//
@State private var animationProgress: CGFloat = 0.0 // 0-1
@State private var isAnimating: Bool = false
@State private var animationComplete: Bool = false
//
private let reelImages: [[String]] = [
(0..<150).map { "film1-\($0+1)" }, //
(0..<180).map { "film2-\($0+1)" }, //
(0..<150).map { "film3-\($0+1)" } //
]
//
private let frameWidth: CGFloat = 90
private let frameHeight: CGFloat = 130
private let frameSpacing: CGFloat = 10
private let totalDistance: CGFloat = 2000 //
//
private let accelerationDuration: Double = 5.0 // 0-5s
private let constantSpeedDuration: Double = 6.0 // +5-11s
private var totalDuration: Double { accelerationDuration + constantSpeedDuration }
private var scaleStartProgress: CGFloat { accelerationDuration / totalDuration }
private let finalScale: CGFloat = 3.0 //
//
private let symmetricTiltAngle: Double = 8 //
private let verticalOffset: CGFloat = 140 //
private let initialMiddleY: CGFloat = 50 //
//
private let horizontalOffset: CGFloat = 30
var body: some View {
ZStack {
//
Color(red: 0.08, green: 0.08, blue: 0.08)
.edgesIgnoringSafeArea(.all)
//
FilmReelView3(images: reelImages[0])
.rotationEffect(Angle(degrees: -symmetricTiltAngle))
.offset(x: topReelPosition - horizontalOffset, y: -verticalOffset) //
.opacity(upperLowerOpacity)
.zIndex(1)
//
FilmReelView3(images: reelImages[2])
.rotationEffect(Angle(degrees: symmetricTiltAngle))
.offset(x: bottomReelPosition + horizontalOffset, y: verticalOffset) //
.opacity(upperLowerOpacity)
.zIndex(1)
//
FilmReelView3(images: reelImages[1])
.offset(x: middleReelPosition, y: middleYPosition)
.scaleEffect(currentScale)
.position(centerPosition)
.zIndex(2)
.edgesIgnoringSafeArea(.all)
}
.onAppear {
startAnimation()
}
}
// MARK: -
private func startAnimation() {
guard !isAnimating && !animationComplete else { return }
isAnimating = true
withAnimation(Animation.timingCurve(0.2, 0.0, 0.8, 1.0, duration: totalDuration)) {
animationProgress = 1.0
}
DispatchQueue.main.asyncAfter(deadline: .now() + totalDuration) {
isAnimating = false
animationComplete = true
}
}
// MARK: -
private var currentScale: CGFloat {
guard animationProgress >= scaleStartProgress else {
return 1.0
}
let scalePhaseProgress = (animationProgress - scaleStartProgress) / (1.0 - scaleStartProgress)
return 1.0 + (finalScale - 1.0) * scalePhaseProgress
}
// Y
private var middleYPosition: CGFloat {
if animationProgress < scaleStartProgress {
return initialMiddleY - (initialMiddleY * (animationProgress / scaleStartProgress))
} else {
return 0 // 5s
}
}
private var upperLowerOpacity: Double {
if animationProgress < scaleStartProgress {
return 0.8
} else {
let fadeProgress = (animationProgress - scaleStartProgress) / (1.0 - scaleStartProgress)
return 0.8 * (1.0 - fadeProgress)
}
}
private var centerPosition: CGPoint {
CGPoint(x: deviceWidth / 2, y: deviceHeight / 2)
}
// MARK: -
private var motionProgress: CGFloat {
if animationProgress < scaleStartProgress {
let t = animationProgress / scaleStartProgress
return t * t //
} else {
return 1.0 + (animationProgress - scaleStartProgress) *
(scaleStartProgress / (1.0 - scaleStartProgress))
}
}
//
private var topReelPosition: CGFloat {
totalDistance * 0.9 * motionProgress
}
//
private var middleReelPosition: CGFloat {
-totalDistance * 1.2 * motionProgress
}
//
private var bottomReelPosition: CGFloat {
totalDistance * 0.9 * motionProgress //
}
}
// MARK: -
struct FilmReelView3: View {
let images: [String]
var body: some View {
HStack(spacing: 10) {
ForEach(images.indices, id: \.self) { index in
FilmFrameView3(imageName: images[index])
}
}
}
}
struct FilmFrameView3: View {
let imageName: String
var body: some View {
ZStack {
//
RoundedRectangle(cornerRadius: 4)
.stroke(Color.gray, lineWidth: 2)
.background(Color(red: 0.15, green: 0.15, blue: 0.15))
//
Rectangle()
.fill(gradientColor)
.cornerRadius(2)
.padding(2)
//
Text(imageName)
.foregroundColor(.white)
.font(.caption2)
}
.frame(width: 90, height: 130)
//
.overlay(
HStack {
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
Spacer()
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
}
)
}
private var gradientColor: LinearGradient {
if imageName.hasPrefix("film1") {
return LinearGradient(gradient: Gradient(colors: [.blue, .indigo]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else if imageName.hasPrefix("film2") {
return LinearGradient(gradient: Gradient(colors: [.yellow, .orange]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else {
return LinearGradient(gradient: Gradient(colors: [.teal, .cyan]), startPoint: .topLeading, endPoint: .bottomTrailing)
}
}
}
//
struct FilmAnimation_Previews3: PreviewProvider {
static var previews: some View {
FilmAnimation1()
}
}

View File

@ -1,140 +0,0 @@
import SwiftUI
// MARK: -
struct FilmStripBlindBoxView: View {
@State private var isAnimating = false
@State private var revealCenter = false
// 使 SF Symbols
let boxContents = ["popcorn", "star", "music.note"]
var body: some View {
GeometryReader { geometry in
let width = geometry.size.width
ZStack {
//
BlindBoxFrame(symbol: boxContents[0])
.offset(x: isAnimating ? -width / 4 : -width)
.opacity(isAnimating ? 1 : 0)
//
BlindBoxFrame(symbol: boxContents[1])
.scaleEffect(revealCenter ? 1.6 : 1)
.offset(x: isAnimating ? 0 : width)
.opacity(isAnimating ? 1 : 0)
//
BlindBoxFrame(symbol: boxContents[2])
.offset(x: isAnimating ? width / 4 : width * 1.5)
.opacity(isAnimating ? 1 : 0)
}
.onAppear {
//
withAnimation(.easeOut(duration: 1.0)) {
isAnimating = true
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
withAnimation(
.interpolatingSpring(stiffness: 80, damping: 12).delay(0.3)
) {
revealCenter = true
}
}
}
}
.frame(height: 140)
.padding()
.background(Color.black.opacity(0.05))
}
}
// MARK: - + + SF Symbol
struct BlindBoxFrame: View {
let symbol: String
var body: some View {
ZStack {
// +
FilmBorder()
// SF Symbol
Image(systemName: symbol)
.resizable()
.scaledToFit()
.foregroundColor(.white.opacity(0.85))
.frame(width: 60, height: 60)
}
.frame(width: 120, height: 120)
}
}
// MARK: - #FFB645 +
struct FilmBorder: View {
var body: some View {
Canvas { context, size in
let w = size.width
let h = size.height
// FFB645
let bgColor = Color(hex: 0xFFB645)
context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(bgColor))
//
let holeRadius: CGFloat = 3.5
let margin: CGFloat = 12
let holeYOffset: CGFloat = h * 0.25
// 3
for i in 0..<3 {
let y = CGFloat(i + 1) * (h / 4)
context.fill(
Path(ellipseIn: CGRect(
x: margin - holeRadius * 2,
y: y - holeRadius,
width: holeRadius * 2,
height: holeRadius * 2
)),
with: .color(.black)
)
}
// 3
for i in 0..<3 {
let y = CGFloat(i + 1) * (h / 4)
context.fill(
Path(ellipseIn: CGRect(
x: w - margin,
y: y - holeRadius,
width: holeRadius * 2,
height: holeRadius * 2
)),
with: .color(.black)
)
}
}
}
}
// MARK: - Color HEX
extension Color {
init(hex: UInt) {
self.init(
.sRGB,
red: Double((hex >> 16) & 0xff) / 255,
green: Double((hex >> 8) & 0xff) / 255,
blue: Double(hex & 0xff) / 255,
opacity: 1.0
)
}
}
// MARK: -
struct FilmStripBlindBoxView_Previews: PreviewProvider {
static var previews: some View {
FilmStripBlindBoxView()
.preferredColorScheme(.dark)
}
}

View File

@ -1,222 +0,0 @@
import SwiftUI
struct FilmAnimation5: View {
//
private let deviceWidth = UIScreen.main.bounds.width
private let deviceHeight = UIScreen.main.bounds.height
//
@State private var animationProgress: CGFloat = 0.0 // 0-1
@State private var isAnimating: Bool = false
@State private var animationComplete: Bool = false
//
private let reelImages: [[String]] = [
(0..<150).map { "film1-\($0+1)" }, //
(0..<180).map { "film2-\($0+1)" }, //
(0..<150).map { "film3-\($0+1)" } //
]
//
private let frameWidth: CGFloat = 90
private let frameHeight: CGFloat = 130
private let totalDistance: CGFloat = 1800 //
//
private let accelerationDuration: Double = 5.0 // 0-5s
private let constantSpeedDuration: Double = 1.0 // 5-6s
private let scaleDuration: Double = 2.0 // 6-8s
private var totalDuration: Double { accelerationDuration + constantSpeedDuration + scaleDuration }
//
private var accelerationEnd: CGFloat { accelerationDuration / totalDuration }
private var constantSpeedEnd: CGFloat { (accelerationDuration + constantSpeedDuration) / totalDuration }
//
private let symmetricTiltAngle: Double = 10 //
private let verticalOffset: CGFloat = 120 //
private let finalScale: CGFloat = 4.0 //
var body: some View {
ZStack {
//
Color(red: 0.08, green: 0.08, blue: 0.08)
.edgesIgnoringSafeArea(.all)
//
FilmReelView5(images: reelImages[0])
.rotationEffect(Angle(degrees: -symmetricTiltAngle))
.offset(x: topReelPosition, y: -verticalOffset)
.scaleEffect(currentScale)
.opacity(upperLowerOpacity)
.zIndex(2)
//
FilmReelView5(images: reelImages[2])
.rotationEffect(Angle(degrees: symmetricTiltAngle))
.offset(x: bottomReelPosition, y: verticalOffset)
.scaleEffect(currentScale)
.opacity(upperLowerOpacity)
.zIndex(2)
//
FilmReelView5(images: reelImages[1])
.offset(x: middleReelPosition, y: 0)
.scaleEffect(currentScale)
.opacity(1.0) //
.zIndex(1)
.edgesIgnoringSafeArea(.all)
}
.onAppear {
startAnimation()
}
}
// MARK: -
private func startAnimation() {
guard !isAnimating && !animationComplete else { return }
isAnimating = true
// 线
withAnimation(Animation.timingCurve(0.3, 0.0, 0.7, 1.0, duration: totalDuration)) {
animationProgress = 1.0
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + totalDuration) {
isAnimating = false
animationComplete = true
}
}
// MARK: -
// 6s
private var currentScale: CGFloat {
guard animationProgress >= constantSpeedEnd else {
return 1.0 // 6s
}
// 0-1
let scalePhaseProgress = (animationProgress - constantSpeedEnd) / (1.0 - constantSpeedEnd)
return 1.0 + (finalScale - 1.0) * scalePhaseProgress
}
//
private var upperLowerOpacity: Double {
guard animationProgress >= constantSpeedEnd else {
return 0.8 // 6s
}
//
let fadeProgress = (animationProgress - constantSpeedEnd) / (1.0 - constantSpeedEnd)
return 0.8 * (1.0 - fadeProgress)
}
// MARK: -
private var motionProgress: CGFloat {
if animationProgress < accelerationEnd {
// 0-5s线
let t = animationProgress / accelerationEnd
return t * t
} else {
// 5s
return 1.0 + (animationProgress - accelerationEnd) *
(accelerationEnd / (1.0 - accelerationEnd))
}
}
//
private var topReelPosition: CGFloat {
totalDistance * 0.8 * motionProgress
}
//
private var middleReelPosition: CGFloat {
-totalDistance * 0.8 * motionProgress //
}
//
private var bottomReelPosition: CGFloat {
totalDistance * 0.8 * motionProgress //
}
}
// MARK: -
struct FilmReelView5: View {
let images: [String]
var body: some View {
HStack(spacing: 10) {
ForEach(images.indices, id: \.self) { index in
FilmFrameView5(imageName: images[index])
}
}
}
}
struct FilmFrameView5: View {
let imageName: String
var body: some View {
ZStack {
//
RoundedRectangle(cornerRadius: 4)
.stroke(Color.gray, lineWidth: 2)
.background(Color(red: 0.15, green: 0.15, blue: 0.15))
//
Rectangle()
.fill(gradientColor)
.cornerRadius(2)
.padding(2)
//
Text(imageName)
.foregroundColor(.white)
.font(.caption2)
}
.frame(width: 90, height: 130)
//
.overlay(
HStack {
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
Spacer()
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
}
)
}
private var gradientColor: LinearGradient {
if imageName.hasPrefix("film1") {
return LinearGradient(gradient: Gradient(colors: [.blue, .indigo]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else if imageName.hasPrefix("film2") {
return LinearGradient(gradient: Gradient(colors: [.yellow, .orange]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else {
return LinearGradient(gradient: Gradient(colors: [.teal, .cyan]), startPoint: .topLeading, endPoint: .bottomTrailing)
}
}
}
//
struct FilmAnimation_Previews5: PreviewProvider {
static var previews: some View {
FilmAnimation5()
}
}

View File

@ -1,250 +0,0 @@
import SwiftUI
struct FilmAnimation: View {
//
private let deviceWidth = UIScreen.main.bounds.width
private let deviceHeight = UIScreen.main.bounds.height
//
@State private var animationProgress: CGFloat = 0.0 // 0-1
@State private var isAnimating: Bool = false
@State private var animationComplete: Bool = false
//
private let reelImages: [[String]] = [
(0..<300).map { "film1-\($0+1)" }, //
(0..<350).map { "film2-\($0+1)" }, //
(0..<300).map { "film3-\($0+1)" } //
]
//
private let frameWidth: CGFloat = 90
private let frameHeight: CGFloat = 130
private let frameSpacing: CGFloat = 12
//
private let accelerationDuration: Double = 5.0 // 0-5s
private let constantSpeedDuration: Double = 1.0 // 5-6s
private let scaleStartDuration: Double = 1.0 // 6-7s
private let scaleFinishDuration: Double = 1.0 // 7-8s
private var totalDuration: Double {
accelerationDuration + constantSpeedDuration + scaleStartDuration + scaleFinishDuration
}
//
private var accelerationEnd: CGFloat { accelerationDuration / totalDuration }
private var constantSpeedEnd: CGFloat { (accelerationDuration + constantSpeedDuration) / totalDuration }
private var scaleStartEnd: CGFloat {
(accelerationDuration + constantSpeedDuration + scaleStartDuration) / totalDuration
}
//
private let tiltAngle: Double = 10 //
private let upperTilt: Double = -10 //
private let lowerTilt: Double = 10 //
private let verticalSpacing: CGFloat = 200 //
private let finalScale: CGFloat = 4.5
//
private let maxTiltedReelMovement: CGFloat = 3500 //
private let maxMiddleReelMovement: CGFloat = -3000 //
var body: some View {
//
Color(red: 0.08, green: 0.08, blue: 0.08)
.edgesIgnoringSafeArea(.all)
.overlay(
ZStack {
//
if showTiltedReels {
FilmReelView(images: reelImages[0])
.rotationEffect(Angle(degrees: upperTilt)) //
.offset(x: upperReelXPosition, y: -verticalSpacing/2)
.scaleEffect(tiltedScale)
.opacity(tiltedOpacity)
.zIndex(1)
}
//
if showTiltedReels {
FilmReelView(images: reelImages[2])
.rotationEffect(Angle(degrees: lowerTilt)) //
.offset(x: lowerReelXPosition, y: verticalSpacing/2)
.scaleEffect(tiltedScale)
.opacity(tiltedOpacity)
.zIndex(1)
}
//
FilmReelView(images: reelImages[1])
.offset(x: middleReelXPosition, y: 0)
.scaleEffect(middleScale)
.opacity(1.0)
.zIndex(2)
.edgesIgnoringSafeArea(.all)
}
)
.onAppear {
startAnimation()
}
}
// MARK: -
private func startAnimation() {
guard !isAnimating && !animationComplete else { return }
isAnimating = true
withAnimation(Animation.easeInOut(duration: totalDuration)) {
animationProgress = 1.0
}
DispatchQueue.main.asyncAfter(deadline: .now() + totalDuration) {
isAnimating = false
animationComplete = true
}
}
// MARK: -
// X
private var upperReelXPosition: CGFloat {
let startPosition: CGFloat = -deviceWidth * 1.2 //
return startPosition + (maxTiltedReelMovement * movementProgress)
}
// X
private var lowerReelXPosition: CGFloat {
let startPosition: CGFloat = -deviceWidth * 0.8 //
return startPosition + (maxTiltedReelMovement * movementProgress)
}
// X
private var middleReelXPosition: CGFloat {
let startPosition: CGFloat = deviceWidth * 0.3
return startPosition + (maxMiddleReelMovement * movementProgress)
}
// 0-1
private var movementProgress: CGFloat {
if animationProgress < constantSpeedEnd {
return animationProgress / constantSpeedEnd
} else {
return 1.0 // 6
}
}
// MARK: -
//
private var middleScale: CGFloat {
guard animationProgress >= constantSpeedEnd else {
return 1.0
}
let scalePhaseProgress = (animationProgress - constantSpeedEnd) / (1.0 - constantSpeedEnd)
return 1.0 + (finalScale - 1.0) * scalePhaseProgress
}
//
private var tiltedScale: CGFloat {
guard animationProgress >= constantSpeedEnd, animationProgress < scaleStartEnd else {
return 1.0
}
let scalePhaseProgress = (animationProgress - constantSpeedEnd) / (scaleStartEnd - constantSpeedEnd)
return 1.0 + (finalScale * 0.6 - 1.0) * scalePhaseProgress
}
//
private var tiltedOpacity: Double {
guard animationProgress >= constantSpeedEnd, animationProgress < scaleStartEnd else {
return 0.8
}
let fadeProgress = (animationProgress - constantSpeedEnd) / (scaleStartEnd - constantSpeedEnd)
return 0.8 * (1.0 - fadeProgress)
}
//
private var showTiltedReels: Bool {
animationProgress < scaleStartEnd
}
}
// MARK: -
struct FilmReelView: View {
let images: [String]
var body: some View {
HStack(spacing: 12) {
ForEach(images.indices, id: \.self) { index in
FilmFrameView(imageName: images[index])
}
}
}
}
struct FilmFrameView: View {
let imageName: String
var body: some View {
ZStack {
//
RoundedRectangle(cornerRadius: 4)
.stroke(Color.gray, lineWidth: 2)
.background(Color(red: 0.15, green: 0.15, blue: 0.15))
//
Rectangle()
.fill(gradientColor)
.cornerRadius(2)
.padding(2)
//
Text(imageName)
.foregroundColor(.white)
.font(.caption2)
}
.frame(width: 90, height: 130)
//
.overlay(
HStack {
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
Spacer()
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
}
)
}
private var gradientColor: LinearGradient {
if imageName.hasPrefix("film1") {
return LinearGradient(gradient: Gradient(colors: [.blue, .indigo]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else if imageName.hasPrefix("film2") {
return LinearGradient(gradient: Gradient(colors: [.yellow, .orange]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else {
return LinearGradient(gradient: Gradient(colors: [.purple, .pink]), startPoint: .topLeading, endPoint: .bottomTrailing)
}
}
}
//
struct FilmAnimation_Previews: PreviewProvider {
static var previews: some View {
FilmAnimation()
}
}

View File

@ -1,6 +1,7 @@
import SwiftUI import SwiftUI
import SwiftData import SwiftData
import AVKit import AVKit
import Foundation
// //
extension Notification.Name { extension Notification.Name {
@ -68,118 +69,9 @@ struct AVPlayerController: UIViewControllerRepresentable {
} }
struct BlindBoxView: View { struct BlindBoxView: View {
enum BlindBoxMediaType {
case video
case image
case all
}
//
struct BlindList: Codable, Identifiable {
let id: Int64
let boxCode: String
let userId: Int64
let name: String
let boxType: String
let features: String?
let resultFileId: Int64?
let status: String
let workflowInstanceId: String?
let videoGenerateTime: String?
let createTime: String
let coverFileId: Int64?
let description: String
enum CodingKeys: String, CodingKey {
case id
case boxCode = "box_code"
case userId = "user_id"
case name
case boxType = "box_type"
case features
case resultFileId = "result_file_id"
case status
case workflowInstanceId = "workflow_instance_id"
case videoGenerateTime = "video_generate_time"
case createTime = "create_time"
case coverFileId = "cover_file_id"
case description
}
}
//
struct BlindCount: Codable {
let availableQuantity: Int
enum CodingKeys: String, CodingKey {
case availableQuantity = "available_quantity"
}
}
// MARK: - BlindBox Response Model
struct BlindBoxData: Codable {
let id: Int64
let boxCode: String
let userId: Int64
let name: String
let boxType: String
let features: String?
let url: String?
let status: String
let workflowInstanceId: String?
//
let videoGenerateTime: String?
let createTime: String
let description: String?
enum CodingKeys: String, CodingKey {
case id
case boxCode = "box_code"
case userId = "user_id"
case name
case boxType = "box_type"
case features
case url
case status
case workflowInstanceId = "workflow_instance_id"
case videoGenerateTime = "video_generate_time"
case createTime = "create_time"
case description
}
init(id: Int64, boxCode: String, userId: Int64, name: String, boxType: String, features: String?, url: String?, status: String, workflowInstanceId: String?, videoGenerateTime: String?, createTime: String, description: String?) {
self.id = id
self.boxCode = boxCode
self.userId = userId
self.name = name
self.boxType = boxType
self.features = features
self.url = url
self.status = status
self.workflowInstanceId = workflowInstanceId
self.videoGenerateTime = videoGenerateTime
self.createTime = createTime
self.description = description
}
init(from listItem: BlindList) {
self.init(
id: listItem.id,
boxCode: listItem.boxCode,
userId: listItem.userId,
name: listItem.name,
boxType: listItem.boxType,
features: listItem.features,
url: nil,
status: listItem.status,
workflowInstanceId: listItem.workflowInstanceId,
videoGenerateTime: listItem.videoGenerateTime,
createTime: listItem.createTime,
description: listItem.description
)
}
}
let mediaType: BlindBoxMediaType let mediaType: BlindBoxMediaType
let currentBoxId: String?
@State private var showModal = false // @State private var showModal = false //
@State private var showSettings = false // @State private var showSettings = false //
@State private var isMember = false // @State private var isMember = false //
@ -189,7 +81,7 @@ struct BlindBoxView: View {
@State private var blindCount: BlindCount? = nil @State private var blindCount: BlindCount? = nil
@State private var blindList: [BlindList] = [] // Changed to array @State private var blindList: [BlindList] = [] // Changed to array
// //
@State private var blindGenerate : BlindBoxData? @State private var blindGenerate: BlindBoxData?
@State private var showLottieAnimation = true @State private var showLottieAnimation = true
// //
@State private var isPolling = false @State private var isPolling = false
@ -217,8 +109,9 @@ struct BlindBoxView: View {
// - // -
@Query private var login: [Login] @Query private var login: [Login]
init(mediaType: BlindBoxMediaType) { init(mediaType: BlindBoxMediaType, blindBoxId: String? = nil) {
self.mediaType = mediaType self.mediaType = mediaType
self.currentBoxId = blindBoxId
} }
// //
@ -254,20 +147,63 @@ struct BlindBoxView: View {
} }
} }
private func loadMedia() { private func loadBlindBox() async {
print("loadMedia called with mediaType: \(mediaType)") print("loadMedia called with mediaType: \(mediaType)")
switch mediaType { if self.currentBoxId != nil {
case .video: print("指定监听某盲盒结果: ", self.currentBoxId! as Any)
loadVideo() //
currentBoxType = "Video" await pollingToQuerySingleBox()
startPolling() } else {
case .image: //
loadImage() await pollingToQueryBlindBox()
currentBoxType = "Image" }
startPolling()
case .all: // switch mediaType {
print("Loading all content...") // case .video:
// loadVideo()
// currentBoxType = "Video"
// startPolling()
// case .image:
// loadImage()
// currentBoxType = "Image"
// startPolling()
// case .all:
// print("Loading all content...")
// // First/Second
// // 使NetworkService.shared.getasync/await
// NetworkService.shared.get(
// path: "/blind_boxs/query",
// parameters: nil
// ) { (result: Result<APIResponse<[BlindList]>, NetworkError>) in
// DispatchQueue.main.async {
// switch result {
// case .success(let response):
// if response.data.count == 0 {
// // -First
// print(" -First")
// // return
// }
// if response.data.count == 1 && response.data[0].boxType == "First" {
// // -Second
// print(" First-Second")
// // return
// }
// self.blindList = response.data ?? []
// // none
// if self.blindList.isEmpty {
// self.animationPhase = .none
// }
// print(" \(self.blindList.count) ")
// case .failure(let error):
// self.blindList = []
// self.animationPhase = .none
// print(" :", error.localizedDescription)
// }
// }
// }
// //
NetworkService.shared.get( NetworkService.shared.get(
path: "/membership/personal-center-info", path: "/membership/personal-center-info",
@ -287,43 +223,111 @@ struct BlindBoxView: View {
} }
} }
// //
NetworkService.shared.get( // NetworkService.shared.get(
path: "/blind_box/available/quantity", // path: "/blind_box/available/quantity",
parameters: nil // parameters: nil
) { (result: Result<APIResponse<BlindCount>, NetworkError>) in // ) { (result: Result<APIResponse<BlindCount>, NetworkError>) in
DispatchQueue.main.async { // DispatchQueue.main.async {
switch result { // switch result {
case .success(let response): // case .success(let response):
self.blindCount = response.data // self.blindCount = response.data
print("✅ 成功获取盲盒数量:", response.data) // print(" :", response.data)
case .failure(let error): // case .failure(let error):
print("❌ 获取数量失败:", error) // print(" :", error)
} // }
} // }
} // }
// // }
NetworkService.shared.get(
path: "/blind_boxs/query",
parameters: nil
) { (result: Result<APIResponse<[BlindList]>, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
self.blindList = response.data ?? []
// none
if self.blindList.isEmpty {
self.animationPhase = .none
}
print("✅ 成功获取 \(self.blindList.count) 个盲盒")
case .failure(let error):
self.blindList = []
self.animationPhase = .none
print("❌ 获取盲盒列表失败:", error.localizedDescription)
}
}
}
}
} }
private func pollingToQuerySingleBox() async {
stopPolling()
isPolling = true
// Unopened
while isPolling {
do {
let blindBoxData = try await BlindBoxApi.shared.getBlindBox(boxId: self.currentBoxId!)
// UI
if let data = blindBoxData {
self.blindGenerate = data
// URL
if mediaType == .image {
self.imageURL = data.resultFile?.url ?? ""
}
else {
self.videoURL = data.resultFile?.url ?? ""
}
print("✅ 成功获取盲盒数据: \(data.name), 状态: \(data.status)")
// Unopened
if data.status == "Unopened" {
print("✅ 盲盒已准备就绪,停止轮询")
self.animationPhase = .ready
stopPolling()
break
}
}
// 2
try await Task.sleep(nanoseconds: 2_000_000_000)
} catch {
print("❌ 获取盲盒数据失败: \(error)")
//
self.animationPhase = .none
stopPolling()
break
}
}
}
private func pollingToQueryBlindBox() async {
stopPolling()
isPolling = true
while isPolling {
do {
let blindBoxList = try await BlindBoxApi.shared.getBlindBoxList()
print("✅ 获取盲盒列表: \(blindBoxList?.count ?? 0)")
//
self.blindCount = BlindCount(availableQuantity: blindBoxList?.filter({ $0.status == "Unopened" }).count ?? 0)
//
if let blindBox = blindBoxList?.first(where: { $0.status == "Unopened" }) {
self.blindGenerate = blindBox
self.animationPhase = .ready
// UI
// URL
if mediaType == .image {
self.imageURL = blindBox.resultFile?.url ?? ""
}
else {
self.videoURL = blindBox.resultFile?.url ?? ""
}
print("✅ 成功获取盲盒数据: \(blindBox.name), 状态: \(blindBox.status)")
stopPolling()
break
} else {
if self.animationPhase != .none {
self.animationPhase = .none
}
}
// 2
try await Task.sleep(nanoseconds: 2_000_000_000)
} catch {
print("❌ 获取盲盒列表失败: \(error)")
stopPolling()
break
}
}
}
// //
private func startPolling() { private func startPolling() {
stopPolling() stopPolling()
@ -343,52 +347,54 @@ struct BlindBoxView: View {
return return
} }
NetworkService.shared.postWithToken( // NetworkService.shared.postWithToken(
path: "/blind_box/generate/mock", // path: "/blind_box/generate/mock",
parameters: ["box_type": currentBoxType] // parameters: ["box_type": currentBoxType]
) { (result: Result<APIResponse<BlindBoxData>, NetworkError>) in // ) { (result: Result<GenerateBlindBoxResponse, NetworkError>) in
DispatchQueue.main.async { // DispatchQueue.main.async {
switch result { // switch result {
case .success(let response): // case .success(let response):
let data = response.data // let data = response.data
self.blindGenerate = data // self.blindGenerate = data
print("当前盲盒状态: \(data.status)") // print(": \(data?.status ?? "Unknown")")
// // //
if self.mediaType == .all, let firstItem = self.blindList.first { // if self.mediaType == .all, let firstItem = self.blindList.first {
self.displayData = BlindBoxData(from: firstItem) // self.displayData = BlindBoxData(from: firstItem)
} else { // } else {
self.displayData = data // self.displayData = data
} // }
//
// // //
NotificationCenter.default.post( // if let status = data?.status {
name: .blindBoxStatusChanged, // NotificationCenter.default.post(
object: nil, // name: .blindBoxStatusChanged,
userInfo: ["status": data.status] // object: nil,
) // userInfo: ["status": status]
// )
if data.status != "Preparing" { // }
self.stopPolling() //
print("✅ 盲盒准备就绪,状态: \(data.status)") // if data?.status != "Preparing" {
if self.mediaType == .video { // self.stopPolling()
self.videoURL = data.url ?? "" // print(" : \(data?.status ?? "Unknown")")
} else if self.mediaType == .image { // if self.mediaType == .video {
self.imageURL = data.url ?? "" // self.videoURL = data?.resultFile?.url ?? ""
} // } else if self.mediaType == .image {
} else { // self.imageURL = data?.resultFile?.url ?? ""
self.pollingTimer = Timer.scheduledTimer( // }
withTimeInterval: 2.0, // } else {
repeats: false // self.pollingTimer = Timer.scheduledTimer(
) { _ in // withTimeInterval: 2.0,
self.checkBlindBoxStatus() // repeats: false
} // ) { _ in
} // self.checkBlindBoxStatus()
case .failure(let error): // }
print("❌ 获取盲盒状态失败: \(error.localizedDescription)") // }
self.stopPolling() // case .failure(let error):
} // print(" : \(error.localizedDescription)")
} // self.stopPolling()
} // }
// }
// }
} }
private func loadImage() { private func loadImage() {
@ -508,40 +514,45 @@ struct BlindBoxView: View {
.onAppear { .onAppear {
print("🎯 BlindBoxView appeared with mediaType: \(mediaType)") print("🎯 BlindBoxView appeared with mediaType: \(mediaType)")
print("🎯 Current thread: \(Thread.current)") print("🎯 Current thread: \(Thread.current)")
// //
if mediaType == .all, let firstItem = blindList.first { // if mediaType == .all, let firstItem = blindList.first {
displayData = BlindBoxData(from: firstItem) // displayData = BlindBoxData(from: firstItem)
} else { // } else {
displayData = blindGenerate // displayData = blindGenerate
} // }
// //
NotificationCenter.default.addObserver( // NotificationCenter.default.addObserver(
forName: .blindBoxStatusChanged, // forName: .blindBoxStatusChanged,
object: nil, // object: nil,
queue: .main // queue: .main
) { notification in // ) { notification in
if let status = notification.userInfo?["status"] as? String { // if let status = notification.userInfo?["status"] as? String {
switch status { // switch status {
case "Preparing": // case "Preparing":
withAnimation { // withAnimation {
self.animationPhase = .loading // self.animationPhase = .loading
} // }
case "Unopened": // case "Unopened":
withAnimation { // withAnimation {
self.animationPhase = .ready // self.animationPhase = .ready
} // }
default: // default:
// // //
withAnimation { // withAnimation {
self.animationPhase = .ready // self.animationPhase = .ready
} // }
break // break
} // }
} // }
} // }
// //
loadMedia() Task {
await loadBlindBox()
}
} }
.onDisappear { .onDisappear {
stopPolling() stopPolling()
@ -567,7 +578,7 @@ struct BlindBoxView: View {
.edgesIgnoringSafeArea(.all) .edgesIgnoringSafeArea(.all)
Group { Group {
if mediaType == .video, let player = videoPlayer { if mediaType == .all, let player = videoPlayer {
// Video Player // Video Player
AVPlayerController(player: $videoPlayer) AVPlayerController(player: $videoPlayer)
.frame(width: scaledWidth, height: scaledHeight) .frame(width: scaledWidth, height: scaledHeight)
@ -595,10 +606,10 @@ struct BlindBoxView: View {
HStack { HStack {
Button(action: { Button(action: {
// BlindOutcomeView // BlindOutcomeView
if mediaType == .video, !videoURL.isEmpty, let url = URL(string: videoURL) { if mediaType == .all, !videoURL.isEmpty, let url = URL(string: videoURL) {
Router.shared.navigate(to: .blindOutcome(media: .video(url, nil), time: blindGenerate?.videoGenerateTime ?? "hhsdshjsjdhn", description:blindGenerate?.description ?? "informationinformationinformationinformationinformationinformation")) Router.shared.navigate(to: .blindOutcome(media: .video(url, nil), time: blindGenerate?.name ?? "Your box", description:blindGenerate?.description ?? "", isMember: self.isMember))
} else if mediaType == .image, let image = displayImage { } else if mediaType == .image, let image = displayImage {
Router.shared.navigate(to: .blindOutcome(media: .image(image), time: blindGenerate?.videoGenerateTime ?? "hhsdshjsjdhn", description:blindGenerate?.description ?? "informationinformationinformationinformationinformationinformation")) Router.shared.navigate(to: .blindOutcome(media: .image(image), time: blindGenerate?.name ?? "Your box", description:blindGenerate?.description ?? "", isMember: self.isMember))
} }
}) { }) {
Image(systemName: "chevron.left") Image(systemName: "chevron.left")
@ -694,10 +705,11 @@ struct BlindBoxView: View {
.padding(.horizontal) .padding(.horizontal)
.padding(.top, 20) .padding(.top, 20)
} }
// //
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
Text("Hi! Click And") Text("Hi! Click And")
Text("Open Your First Box~") Text("Open Your Box~")
} }
.font(Typography.font(for: .smallLargeTitle)) .font(Typography.font(for: .smallLargeTitle))
.fontWeight(.bold) .fontWeight(.bold)
@ -758,6 +770,28 @@ struct BlindBoxView: View {
.frame(width: 300, height: 300) .frame(width: 300, height: 300)
.onTapGesture { .onTapGesture {
print("点击了盲盒") print("点击了盲盒")
//
if let boxId = self.currentBoxId {
Task {
do {
try await BlindBoxApi.shared.openBlindBox(boxId: boxId)
print("✅ 盲盒开启成功")
} catch {
print("❌ 开启盲盒失败: \(error)")
}
}
}
if let boxId = self.blindGenerate?.id {
Task {
do {
try await BlindBoxApi.shared.openBlindBox(boxId: boxId)
print("✅ 盲盒开启成功")
} catch {
print("❌ 开启盲盒失败: \(error)")
}
}
}
withAnimation { withAnimation {
animationPhase = .opening animationPhase = .opening
} }
@ -792,7 +826,7 @@ struct BlindBoxView: View {
// //
self.showScalingOverlay = true self.showScalingOverlay = true
if mediaType == .video { if mediaType == .all {
loadVideo() loadVideo()
} else if mediaType == .image { } else if mediaType == .image {
loadImage() loadImage()
@ -809,8 +843,11 @@ struct BlindBoxView: View {
.frame(width: 300, height: 300) .frame(width: 300, height: 300)
case .none: case .none:
SVGImage(svgName: "BlindNone") // FIXME: 使 BlindLoading GIF
GIFView(name: "BlindLoading")
.frame(width: 300, height: 300) .frame(width: 300, height: 300)
// SVGImage(svgName: "BlindNone")
// .frame(width: 300, height: 300)
} }
} }
.offset(y: -50) .offset(y: -50)
@ -821,10 +858,10 @@ struct BlindBoxView: View {
if !showScalingOverlay && !showMedia { if !showScalingOverlay && !showMedia {
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
// blindGeneratedescription // blindGeneratedescription
Text(blindGenerate?.videoGenerateTime ?? "hhsdshjsjdhn") Text(blindGenerate?.name ?? "Some box")
.font(Typography.font(for: .body, family: .quicksandBold)) .font(Typography.font(for: .body, family: .quicksandBold))
.foregroundColor(Color.themeTextMessageMain) .foregroundColor(Color.themeTextMessageMain)
Text(blindGenerate?.description ?? "informationinformationinformationinformationinformationinformation") Text(blindGenerate?.description ?? "")
.font(.system(size: 14)) .font(.system(size: 14))
.foregroundColor(Color.themeTextMessageMain) .foregroundColor(Color.themeTextMessageMain)
} }
@ -842,15 +879,38 @@ struct BlindBoxView: View {
.animation(.easeOut(duration: 1.5), value: showScalingOverlay) .animation(.easeOut(duration: 1.5), value: showScalingOverlay)
.offset(y: showScalingOverlay ? -100 : 0) .offset(y: showScalingOverlay ? -100 : 0)
.animation(.easeInOut(duration: 1.5), value: showScalingOverlay) .animation(.easeInOut(duration: 1.5), value: showScalingOverlay)
//
// TODO
if mediaType == .all { if mediaType == .all {
Button(action: { Button(action: {
if animationPhase == .ready { if animationPhase == .ready {
// //
// //
Router.shared.navigate(to: .subscribe) if let boxId = self.currentBoxId {
} else { Task {
showUserProfile() do {
try await BlindBoxApi.shared.openBlindBox(boxId: boxId)
print("✅ 盲盒开启成功")
} catch {
print("❌ 开启盲盒失败: \(error)")
}
}
}
if let boxId = self.blindGenerate?.id {
Task {
do {
try await BlindBoxApi.shared.openBlindBox(boxId: boxId)
print("✅ 盲盒开启成功")
} catch {
print("❌ 开启盲盒失败: \(error)")
}
}
}
withAnimation {
animationPhase = .opening
}
} else if animationPhase == .none {
Router.shared.navigate(to: .mediaUpload)
} }
}) { }) {
if animationPhase == .loading { if animationPhase == .loading {
@ -894,6 +954,7 @@ struct BlindBoxView: View {
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showModal) .animation(.spring(response: 0.6, dampingFraction: 0.8), value: showModal)
.edgesIgnoringSafeArea(.all) .edgesIgnoringSafeArea(.all)
} }
// //
SlideInModal( SlideInModal(
isPresented: $showModal, isPresented: $showModal,
@ -961,16 +1022,42 @@ struct BlindBoxView: View {
// MARK: - // MARK: -
#Preview { #Preview {
BlindBoxView(mediaType: .video) BlindBoxView(mediaType: .all)
.onAppear {
// Preview使
#if DEBUG
if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
// Preview
let previewToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9.eyJqdGkiOjczNzAwMTY5NzMzODE1NzA1NjAsImlkZW50aXR5IjoiNzM1MDQzOTY2MzExNjYxOTc3NyIsImV4cCI6MTc1Nzc1Mzc3NH0.tZ8p5sW4KX6HFoJpJN0e4VmJOAGhTrYD2yTwQwilKpufzqOAfXX4vpGYBurgBIcHj2KmXKX2PQMOeeAtvAypDA"
let _ = KeychainHelper.saveAccessToken(previewToken)
print("🔑 Preview token set for testing")
}
#endif
}
} }
struct TransparentVideoPlayer: UIViewRepresentable { //
func makeUIView(context: Context) -> UIView { #Preview("First Blind Box") {
let view = UIView() BlindBoxView(mediaType: .image, blindBoxId: "7370140297747107840")
view.backgroundColor = .clear .onAppear {
view.isOpaque = false // Preview使
return view #if DEBUG
} if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
// Preview
func updateUIView(_ uiView: UIView, context: Context) {} let previewToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9.eyJqdGkiOjczNzAwMTY5NzMzODE1NzA1NjAsImlkZW50aXR5IjoiNzM1MDQzOTY2MzExNjYxOTc3NyIsImV4cCI6MTc1Nzc1Mzc3NH0.tZ8p5sW4KX6HFoJpJN0e4VmJOAGhTrYD2yTwQwilKpufzqOAfXX4vpGYBurgBIcHj2KmXKX2PQMOeeAtvAypDA"
let _ = KeychainHelper.saveAccessToken(previewToken)
print("🔑 Preview token set for testing")
}
#endif
}
} }
// struct TransparentVideoPlayer: UIViewRepresentable {
// func makeUIView(context: Context) -> UIView {
// let view = UIView()
// view.backgroundColor = .clear
// view.isOpaque = false
// return view
// }
// func updateUIView(_ uiView: UIView, context: Context) {}
// }

View File

@ -329,21 +329,24 @@ struct MediaUploadView: View {
] ]
} }
// POST/material // id
NetworkService.shared.postWithToken( Task {
path: "/material", do {
parameters: files let materialIds = try await MaterialUpload.shared.addMaterials(files: files)
) { (result: Result<EmptyResponse, NetworkError>) in print("🚀 素材ID: \(materialIds ?? [])")
switch result { //
case .success: if let materialIds = materialIds {
print("✅ 素材提交成功") let result = try await BlindBoxApi.shared.generateBlindBox(boxType: "Second", materialIds: materialIds)
// print("🎉 盲盒结果: \(result ?? nil)")
DispatchQueue.main.async { if let result = result {
Router.shared.navigate(to: .blindBox(mediaType: .video)) let blindBoxId = result.id ?? ""
print("🎉 盲盒ID: \(blindBoxId)")
//
Router.shared.navigate(to: .blindBox(mediaType: .all, blindBoxId: blindBoxId))
}
} }
case .failure(let error): } catch {
print("❌ 素材提交失败: \(error.localizedDescription)") print("❌ 添加素材失败: \(error)")
//
} }
} }
} }
@ -370,7 +373,7 @@ struct MainUploadArea: View {
Spacer() Spacer()
.frame(height: 30) .frame(height: 30)
// //
Text("Click to upload 20 images and 5 videos to generate your next blind box.") Text("Click to upload 5+ videos to generate your next blind box.")
.font(Typography.font(for: .title2, family: .quicksandBold)) .font(Typography.font(for: .title2, family: .quicksandBold))
.fontWeight(.bold) .fontWeight(.bold)
.foregroundColor(.black) .foregroundColor(.black)

View File

@ -116,7 +116,7 @@ struct UserInfo: View {
// Content VStack // Content VStack
VStack(spacing: 20) { VStack(spacing: 20) {
// Title // Title
Text(showUsername ? "Add Your Avatar" : "What's Your Name?") Text(showUsername ? "What's Your Name?" : "Add Your Avatar")
.font(Typography.font(for: .body, family: .quicksandBold)) .font(Typography.font(for: .body, family: .quicksandBold))
.frame(maxWidth: .infinity, alignment: .center) .frame(maxWidth: .infinity, alignment: .center)
@ -180,8 +180,33 @@ struct UserInfo: View {
if let userData = response.data { if let userData = response.data {
self.userName = userData.username self.userName = userData.username
} }
Router.shared.navigate(to: .blindBox(mediaType: .image))
//
MaterialUpload.shared.addMaterial(
fileId: uploadedFileId ?? "",
previewFileId: uploadedFileId ?? ""
) { result in
switch result {
case .success(let data):
print("素材添加成功返回ID: \(data ?? [])")
//
BlindBoxApi.shared.generateBlindBox(
boxType: "First",
materialIds: data ?? []
) { result in
switch result {
case .success(let blindBoxData):
print("✅ 盲盒生成成功: \(blindBoxData?.id ?? "0")")
//
Router.shared.navigate(to: .blindBox(mediaType: .image, blindBoxId: blindBoxData?.id ?? "0"))
case .failure(let error):
print("❌ 盲盒生成失败: \(error.localizedDescription)")
}
}
case .failure(let error):
print("素材添加失败: \(error.localizedDescription)")
}
}
case .failure(let error): case .failure(let error):
print("❌ 用户信息更新失败: \(error.localizedDescription)") print("❌ 用户信息更新失败: \(error.localizedDescription)")
self.errorMessage = "更新失败: \(error.localizedDescription)" self.errorMessage = "更新失败: \(error.localizedDescription)"
@ -195,7 +220,8 @@ struct UserInfo: View {
} }
} }
}) { }) {
Text(showUsername ? "Open" : "Continue") // Text(showUsername ? "Open" : "Continue")
Text("Continue")
.font(Typography.font(for: .body)) .font(Typography.font(for: .body))
.fontWeight(.bold) .fontWeight(.bold)
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)

View File

@ -46,10 +46,15 @@ struct WakeApp: App {
if authState.isAuthenticated { if authState.isAuthenticated {
// //
NavigationStack(path: $router.path) { NavigationStack(path: $router.path) {
BlindBoxView(mediaType: .all) // FIXME
.navigationDestination(for: AppRoute.self) { route in BlindBoxView(mediaType: .all)
route.view .navigationDestination(for: AppRoute.self) { route in
} route.view
}
// UserInfo()
// .navigationDestination(for: AppRoute.self) { route in
// route.view
// }
} }
} else { } else {
// //