🚚 Rename watchOS project to proper one

This commit is contained in:
2025-11-01 12:21:37 +08:00
parent b60bd63d0c
commit 9a628779d9
80 changed files with 36 additions and 30 deletions

View File

@@ -0,0 +1,284 @@
//
// AccountView.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/30.
//
import SwiftUI
struct AccountView: View {
@EnvironmentObject var appState: AppState
@State private var user: SnAccount?
@State private var status: SnAccountStatus?
@State private var isLoading = false
@State private var error: Error?
@State private var showingClearConfirmation = false
@StateObject private var profileImageLoader = ImageLoader()
@StateObject private var bannerImageLoader = ImageLoader()
private let networkService = NetworkService()
var body: some View {
ScrollView {
if isLoading {
ProgressView()
.padding()
} else if let error = error {
VStack {
Text("Failed to load account")
.foregroundColor(.red)
Text(error.localizedDescription)
.font(.caption)
.foregroundColor(.secondary)
}
.padding()
} else if let user = user {
VStack(spacing: 16) {
// Banner
if user.profile.background != nil {
if bannerImageLoader.isLoading {
ProgressView()
.frame(height: 80)
} else if let bannerImage = bannerImageLoader.image {
bannerImage
.resizable()
.aspectRatio(contentMode: .fill)
.frame(height: 80)
.clipped()
.cornerRadius(8)
} else if bannerImageLoader.errorMessage != nil {
Rectangle()
.fill(Color.gray.opacity(0.3))
.frame(height: 80)
.cornerRadius(8)
} else {
Rectangle()
.fill(Color.gray.opacity(0.3))
.frame(height: 80)
.cornerRadius(8)
}
}
// Profile Picture
HStack(spacing: 16)
{
if profileImageLoader.isLoading {
ProgressView()
.frame(width: 60, height: 60)
} else if let profileImage = profileImageLoader.image {
profileImage
.resizable()
.frame(width: 60, height: 60)
.clipShape(Circle())
} else if profileImageLoader.errorMessage != nil {
Circle()
.fill(Color.red.opacity(0.3))
.frame(width: 60, height: 60)
.overlay(
Image(systemName: "exclamationmark.triangle")
.resizable()
.scaledToFit()
.foregroundColor(.red)
)
} else {
Circle()
.fill(Color.gray.opacity(0.3))
.frame(width: 60, height: 60)
.overlay(
Image(systemName: "person.circle.fill")
.resizable()
.scaledToFit()
.foregroundColor(.gray)
)
}
// Username and Handle
VStack(alignment: .leading) {
Text(user.nick)
.font(.headline)
Text("@\(user.name)")
.font(.caption)
.foregroundColor(.secondary)
}
}
// Status
VStack(alignment: .leading, spacing: 8) {
HStack {
Text("Status")
.font(.subheadline)
.foregroundColor(.secondary)
Spacer()
if status?.isCustomized == true {
Button(action: {
showingClearConfirmation = true
}) {
ZStack {
Circle()
.fill(Color.red.opacity(0.1))
.frame(width: 28, height: 28)
Image(systemName: "trash")
.foregroundColor(.red)
}
}
.buttonStyle(.plain)
.frame(width: 28, height: 28)
}
NavigationLink(
destination: StatusCreationView(initialStatus: status?.isCustomized == true ? status : nil)
.environmentObject(appState)
) {
ZStack {
Circle()
.fill(Color.blue.opacity(0.1))
.frame(width: 28, height: 28)
Image(systemName: "pencil")
.foregroundColor(.blue)
}
}
.buttonStyle(.plain)
.frame(width: 28, height: 28)
}
if let status = status {
VStack(alignment: .leading, spacing: 4) {
HStack {
Circle()
.fill(status.isOnline ? Color.green : Color.gray)
.frame(width: 8, height: 8)
Text(status.label.isEmpty ? "No status" : status.label)
.font(.body)
}
if status.isInvisible {
Text("Invisible")
.font(.caption)
.foregroundColor(.secondary)
}
if status.isNotDisturb {
Text("Do Not Disturb")
.font(.caption)
.foregroundColor(.secondary)
}
if let clearedAt = status.clearedAt {
Text("Clears: \(clearedAt.formatted(date: .abbreviated, time: .shortened))")
.font(.caption)
.foregroundColor(.secondary)
}
}
} else {
Text("No status set")
.font(.body)
.foregroundColor(.secondary)
}
}
// Level and Progress
VStack(alignment: .leading, spacing: 8) {
Text("Level \(user.profile.level)")
.font(.title3)
.bold()
ProgressView(value: user.profile.levelingProgress)
.progressViewStyle(LinearProgressViewStyle())
.frame(height: 8)
Text("Experience: \(user.profile.experience)")
.font(.caption)
.foregroundColor(.secondary)
}
// Bio
if let bio = user.profile.bio, !bio.isEmpty {
Text(bio)
.font(.body)
.multilineTextAlignment(.center)
.foregroundColor(.secondary)
.frame(alignment: .leading)
} else {
Text("No bio available")
.font(.body)
.foregroundColor(.secondary)
.frame(alignment: .leading)
}
// Member since
Text("Joined at \(user.createdAt.formatted(.dateTime.month(.abbreviated).year()))")
.font(.caption)
.foregroundColor(.secondary)
.frame(alignment: .leading)
}
.padding()
// Load images when user data is available
.task(id: user.profile.picture?.id) {
if let serverUrl = appState.serverUrl, let pictureId = user.profile.picture?.id, let imageUrl = getAttachmentUrl(for: pictureId, serverUrl: serverUrl), let token = appState.token {
await profileImageLoader.loadImage(from: imageUrl, token: token)
}
}
.task(id: user.profile.background?.id) {
if let serverUrl = appState.serverUrl, let backgroundId = user.profile.background?.id, let imageUrl = getAttachmentUrl(for: backgroundId, serverUrl: serverUrl), let token = appState.token {
await bannerImageLoader.loadImage(from: imageUrl, token: token)
}
}
} else {
Text("No account data")
.padding()
}
}
.navigationTitle("Account")
.confirmationDialog("Clear Status", isPresented: $showingClearConfirmation) {
Button("Clear Status", role: .destructive) {
Task {
await clearStatus()
}
}
Button("Cancel", role: .cancel) {}
} message: {
Text("Are you sure you want to clear your status? This action cannot be undone.")
}
.onAppear {
Task.detached {
await loadUserProfile()
}
}
}
private func loadUserProfile() async {
guard let token = appState.token, let serverUrl = appState.serverUrl else {
error = NSError(domain: "AccountView", code: 1, userInfo: [NSLocalizedDescriptionKey: "Authentication not available"])
return
}
isLoading = true
error = nil
do {
user = try await networkService.fetchUserProfile(token: token, serverUrl: serverUrl)
status = try await networkService.fetchAccountStatus(token: token, serverUrl: serverUrl)
} catch {
self.error = error
}
isLoading = false
}
private func clearStatus() async {
guard let token = appState.token, let serverUrl = appState.serverUrl else {
error = NSError(domain: "AccountView", code: 1, userInfo: [NSLocalizedDescriptionKey: "Authentication not available"])
return
}
do {
try await networkService.clearStatus(token: token, serverUrl: serverUrl)
// Refresh status after clearing
status = try await networkService.fetchAccountStatus(token: token, serverUrl: serverUrl)
} catch {
self.error = error
}
}
}
#Preview {
AccountView()
.environmentObject(AppState())
}

View File

@@ -0,0 +1,86 @@
//
// ActivityListView.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/29.
//
import SwiftUI
// MARK: - Views
struct ActivityListView: View {
@StateObject private var viewModel: ActivityViewModel
@EnvironmentObject var appState: AppState
init(filter: String, mockActivities: [SnActivity]? = nil) {
_viewModel = StateObject(wrappedValue: ActivityViewModel(filter: filter, mockActivities: mockActivities))
}
var body: some View {
Group {
if viewModel.isLoading {
ProgressView()
} else if let errorMessage = viewModel.errorMessage {
VStack {
Text("Error fetching data")
.font(.headline)
Text(errorMessage)
.font(.caption)
.lineLimit(nil)
}
.padding()
} else if viewModel.activities.isEmpty {
Text("No activities found.")
} else {
List {
ForEach(viewModel.activities) { activity in
switch activity.type {
case "posts.new", "posts.new.replies":
if case .post(let post) = activity.data {
NavigationLink(
destination: PostDetailView(post: post).environmentObject(appState)
) {
PostRowView(post: post)
}
}
case "discovery":
if case .discovery(let discoveryData) = activity.data {
DiscoveryView(discoveryData: discoveryData)
}
default:
Text("Unknown activity type: \(activity.type)")
}
}
if viewModel.hasMore {
if viewModel.isLoadingMore {
HStack {
Spacer()
ProgressView()
Spacer()
}
} else {
Button("Load More") {
Task {
if let token = appState.token, let serverUrl = appState.serverUrl {
await viewModel.loadMoreActivities(token: token, serverUrl: serverUrl)
}
}
}
.frame(maxWidth: .infinity)
}
}
}
}
}
.onAppear {
if appState.isReady, let token = appState.token, let serverUrl = appState.serverUrl {
Task.detached {
await viewModel.fetchActivities(token: token, serverUrl: serverUrl)
}
}
}
.navigationTitle(viewModel.filter)
.navigationBarTitleDisplayMode(.inline)
}
}

View File

@@ -0,0 +1,62 @@
//
// AppInfoHeader.swift
// Runner
//
// Created by LittleSheep on 2025/10/30.
//
import Combine
import SwiftUI
struct AppInfoHeaderView : View {
@EnvironmentObject var appState: AppState // Access AppState
@State private var webSocketConnectionState: WebSocketState = .disconnected // New state for WebSocket status
@State private var cancellables = Set<AnyCancellable>() // For managing subscriptions
var body: some View {
VStack(alignment: .leading) {
HStack(spacing: 12) {
Image("Logo")
.resizable()
.frame(width: 40, height: 40)
VStack(alignment: .leading) {
Text("Solian").font(.headline)
Text("for Apple Watch").font(.system(size: 11))
// Display WebSocket connection status
Text(webSocketStatusMessage)
.font(.system(size: 10))
.foregroundColor(.secondary)
}
}
}
.onAppear {
setupWebSocketListeners()
}
.onDisappear {
cancellables.forEach { $0.cancel() }
cancellables.removeAll()
}
}
private var webSocketStatusMessage: String {
switch webSocketConnectionState {
case .connected: return "Connected"
case .connecting: return "Connecting..."
case .disconnected: return "Disconnected"
case .serverDown: return "Server Down"
case .duplicateDevice: return "Duplicate Device"
case .error(let msg): return "Error: \(msg)"
}
}
private func setupWebSocketListeners() {
appState.networkService.stateStream
.receive(on: DispatchQueue.main)
.sink { state in
webSocketConnectionState = state
}
.store(in: &cancellables)
}
}

View File

@@ -0,0 +1,109 @@
//
// AttachmentImageView.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/29.
//
import SwiftUI
import AVKit
import AVFoundation
struct AttachmentView: View {
let attachment: SnCloudFile
@EnvironmentObject var appState: AppState
@StateObject private var imageLoader = ImageLoader()
var body: some View {
Group {
if let mimeType = attachment.mimeType {
if mimeType.starts(with: "image") {
if let serverUrl = appState.serverUrl, let imageUrl = getAttachmentUrl(for: attachment.id, serverUrl: serverUrl) {
NavigationLink(
destination: ImageViewer(imageUrl: imageUrl).environmentObject(appState)
) {
if imageLoader.isLoading {
ProgressView()
} else if let image = imageLoader.image {
image
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity)
.cornerRadius(8)
} else if let errorMessage = imageLoader.errorMessage {
Text("Failed to load attachment: \(errorMessage)")
.font(.caption)
.foregroundColor(.red)
.cornerRadius(8)
} else {
Text("File: \(attachment.id)")
.cornerRadius(8)
}
}
.buttonStyle(PlainButtonStyle())
} else {
Text("Image URL not available.")
}
} else if mimeType.starts(with: "video") {
if let serverUrl = appState.serverUrl, let videoUrl = getAttachmentUrl(for: attachment.id, serverUrl: serverUrl) {
NavigationLink(destination: VideoPlayerView(videoUrl: videoUrl)) {
if imageLoader.isLoading {
ProgressView()
} else if let image = imageLoader.image {
ZStack {
image
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity)
.cornerRadius(8)
Image(systemName: "play.circle.fill")
.resizable()
.scaledToFit()
.frame(width: 36, height: 36)
.foregroundColor(.white)
.shadow(color: .black.opacity(0.6), radius: 4, x: 0, y: 2)
}
} else if imageLoader.errorMessage != nil {
Image(systemName: "play.rectangle.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity)
.foregroundColor(.gray)
.cornerRadius(8)
} else {
ProgressView()
.cornerRadius(8)
}
}
.buttonStyle(PlainButtonStyle())
} else {
Text("Video URL not available.")
}
} else if mimeType.starts(with: "audio") {
if let serverUrl = appState.serverUrl, let audioUrl = getAttachmentUrl(for: attachment.id, serverUrl: serverUrl) {
AudioPlayerView(audioUrl: audioUrl)
} else {
Text("Cannot play audio: URL not available.")
}
} else {
Text("Unsupported media type: \(mimeType)")
}
} else {
Text("File: \(attachment.id) (No MIME type)")
}
}
.task(id: attachment.id) {
if let serverUrl = appState.serverUrl, let attachmentUrl = getAttachmentUrl(for: attachment.id, serverUrl: serverUrl), let token = appState.token {
if attachment.mimeType?.starts(with: "image") == true {
await imageLoader.loadImage(from: attachmentUrl, token: token)
}
if attachment.mimeType?.starts(with: "video") == true {
let thumbnailUrl = attachmentUrl
.appending(queryItems: [URLQueryItem(name: "thumbnail", value: "true")]) // Construct thumbnail URL
await imageLoader.loadImage(from: thumbnailUrl, token: token)
}
}
}
}
}

View File

@@ -0,0 +1,47 @@
//
// AudioPlayerView.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/29.
//
import SwiftUI
import AVFoundation
struct AudioPlayerView: View {
let audioUrl: URL
@State private var player: AVPlayer?
@State private var isPlaying: Bool = false
var body: some View {
VStack {
if player != nil {
Button(action: togglePlayPause) {
Image(systemName: isPlaying ? "pause.circle.fill" : "play.circle.fill")
.font(.largeTitle)
}
.buttonStyle(.plain)
} else {
Text("Loading audio...")
}
}
.onAppear {
player = AVPlayer(url: audioUrl)
}
.onDisappear {
player?.pause()
player = nil
}
}
private func togglePlayPause() {
guard let player = player else { return }
if isPlaying {
player.pause()
} else {
player.play()
}
isPlaying.toggle()
}
}

View File

@@ -0,0 +1,785 @@
//
// ChatView.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/30.
//
import SwiftUI
struct ChatView: View {
@EnvironmentObject var appState: AppState
@State private var selectedTab = 0
@State private var chatRooms: [SnChatRoom] = []
@State private var chatInvites: [SnChatMember] = []
@State private var isLoading = false
@State private var error: Error?
@State private var showingInvites = false
private let tabs = ["All", "Direct", "Group"]
var body: some View {
TabView(selection: $selectedTab) {
ForEach(0..<tabs.count, id: \.self) { index in
VStack {
if isLoading {
ProgressView()
} else if error != nil {
VStack {
Text("Error loading chats")
.font(.caption)
Button("Retry") {
Task {
await loadChatRooms()
}
}
.font(.caption2)
}
} else {
ChatRoomListView(
chatRooms: filteredChatRooms(for: index),
selectedTab: index
)
}
}
.tabItem {
Text(tabs[index])
}
.tag(index)
}
}
.tabViewStyle(.page)
.navigationTitle("Chat")
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button {
showingInvites = true
} label: {
ZStack {
Image(systemName: "envelope")
if !chatInvites.isEmpty {
Circle()
.fill(Color.red)
.frame(width: 8, height: 8)
.offset(x: 8, y: -8)
}
}
}
}
}
.sheet(isPresented: $showingInvites) {
ChatInvitesView(invites: $chatInvites, appState: appState)
}
.onAppear {
Task.detached {
await loadChatRooms()
await loadChatInvites()
}
}
}
private func filteredChatRooms(for tabIndex: Int) -> [SnChatRoom] {
switch tabIndex {
case 0: // All
return chatRooms
case 1: // Direct
return chatRooms.filter { $0.type == 1 }
case 2: // Group
return chatRooms.filter { $0.type != 1 }
default:
return chatRooms
}
}
private func loadChatRooms() async {
guard let token = appState.token, let serverUrl = appState.serverUrl else { return }
isLoading = true
error = nil
do {
let response = try await appState.networkService.fetchChatRooms(token: token, serverUrl: serverUrl)
chatRooms = response.rooms
} catch {
self.error = error
}
isLoading = false
}
private func loadChatInvites() async {
guard let token = appState.token, let serverUrl = appState.serverUrl else { return }
do {
let response = try await appState.networkService.fetchChatInvites(token: token, serverUrl: serverUrl)
chatInvites = response.invites
} catch {
// Handle error silently for invites
}
}
}
struct ChatRoomListView: View {
let chatRooms: [SnChatRoom]
let selectedTab: Int
var body: some View {
if chatRooms.isEmpty {
VStack {
Image(systemName: "message")
.font(.largeTitle)
.foregroundColor(.secondary)
Text("No chats yet")
.font(.caption)
.foregroundColor(.secondary)
}
} else {
List(chatRooms) { room in
ChatRoomListItem(room: room)
}
.listStyle(.plain)
}
}
}
struct ChatRoomListItem: View {
let room: SnChatRoom
@EnvironmentObject var appState: AppState
@StateObject private var avatarLoader = ImageLoader()
private var displayName: String {
if room.type == 1, let members = room.members, !members.isEmpty {
// For direct messages, show the other member's name
return members[0].account.nick
} else {
// For group chats, show room name or fallback
return room.name ?? "Group Chat"
}
}
private var subtitle: String {
if room.type == 1, let members = room.members, members.count > 1 {
// For direct messages, show member usernames
return members.map { "@\($0.account.name)" }.joined(separator: ", ")
} else if let description = room.description {
// For group chats with description
return description
} else {
// Fallback
return ""
}
}
private var avatarPictureId: String? {
if room.type == 1, let members = room.members, !members.isEmpty {
// For direct messages, use the other member's avatar
return members[0].account.profile.picture?.id
} else {
// For group chats, use room picture
return room.picture?.id
}
}
var body: some View {
NavigationLink(
destination: ChatRoomView(room: room)
.environmentObject(appState)
) {
HStack {
// Avatar using ImageLoader pattern
Group {
if avatarLoader.isLoading {
ProgressView()
.frame(width: 32, height: 32)
} else if let image = avatarLoader.image {
image
.resizable()
.frame(width: 32, height: 32)
.clipShape(Circle())
} else if avatarLoader.errorMessage != nil {
// Error state - show fallback
Circle()
.fill(Color.gray.opacity(0.3))
.frame(width: 32, height: 32)
.overlay(
Text(displayName.prefix(1).uppercased())
.font(.system(size: 12, weight: .medium))
.foregroundColor(.primary)
)
} else {
// No image available - show initial
Circle()
.fill(Color.gray.opacity(0.3))
.frame(width: 32, height: 32)
.overlay(
Text(displayName.prefix(1).uppercased())
.font(.system(size: 12, weight: .medium))
.foregroundColor(.primary)
)
}
}
.task(id: avatarPictureId) {
if let serverUrl = appState.serverUrl,
let pictureId = avatarPictureId,
let imageUrl = getAttachmentUrl(for: pictureId, serverUrl: serverUrl),
let token = appState.token {
await avatarLoader.loadImage(from: imageUrl, token: token)
}
}
VStack(alignment: .leading, spacing: 2) {
Text(displayName)
.font(.system(size: 14, weight: .medium))
.lineLimit(1)
if !subtitle.isEmpty {
Text(subtitle)
.font(.system(size: 12))
.foregroundColor(.secondary)
.lineLimit(1)
}
}
Spacer()
// Unread count badge placeholder
// In a full implementation, this would show unread count
}
.padding(.vertical, 4)
}
}
}
import Combine
import SwiftUI
struct ChatRoomView: View {
let room: SnChatRoom
@EnvironmentObject var appState: AppState
@State private var messages: [SnChatMessage] = []
@State private var isLoading = false
@State private var error: Error?
@State private var wsState: WebSocketState = .disconnected // New state for WebSocket status
@State private var hasLoadedMessages = false // Track if messages have been loaded
@State private var messageText = "" // Text input for sending messages
@State private var isSending = false // Track sending state
@State private var isInputHidden = false // Track if input should be hidden during scrolling
@State private var scrollTimer: Timer? // Timer to show input after scrolling stops
@State private var cancellables = Set<AnyCancellable>() // For managing subscriptions
var body: some View {
VStack {
// Display WebSocket connection status
if (wsState != .connected)
{
Text(webSocketStatusMessage)
.font(.caption2)
.foregroundColor(.secondary)
.padding(.vertical, 2)
.animation(.easeInOut, value: wsState) // Animate status changes
.transition(.opacity)
}
if isLoading {
ProgressView()
} else if error != nil {
VStack {
Text("Error loading messages")
.font(.caption)
Button("Retry") {
Task {
await loadMessages()
}
}
.font(.caption2)
}
} else if messages.isEmpty {
VStack {
Image(systemName: "bubble.left")
.font(.largeTitle)
.foregroundColor(.secondary)
Text("No messages yet")
.font(.caption)
.foregroundColor(.secondary)
}
} else {
ScrollViewReader { scrollView in
ScrollView {
LazyVStack(alignment: .leading, spacing: 8) {
ForEach(messages) { message in
ChatMessageItem(message: message)
}
}
.padding(.horizontal)
.padding(.vertical, 8)
.padding(.bottom, 8)
}
.onAppear {
// Scroll to bottom when messages load
if let lastMessage = messages.last {
scrollView.scrollTo(lastMessage.id, anchor: .bottom)
}
}
.onChange(of: messages.count) { _, _ in
// Scroll to bottom when new messages arrive
if let lastMessage = messages.last {
withAnimation {
scrollView.scrollTo(lastMessage.id, anchor: .bottom)
}
}
}
.onScrollPhaseChange { _, phase in
switch phase {
case .interacting:
if !isInputHidden {
withAnimation(.easeOut(duration: 0.2)) {
isInputHidden = true
}
}
case .idle:
withAnimation(.easeIn(duration: 0.3)) {
isInputHidden = false
}
default: break
}
}
}
}
// Message input area
if !isInputHidden {
HStack(spacing: 8) {
TextField("Send message...", text: $messageText)
.font(.system(size: 14))
.disabled(isSending)
.frame(height: 40)
Button {
Task {
await sendMessage()
}
} label: {
if isSending {
ProgressView()
.frame(width: 20, height: 20)
} else {
Image(systemName: "arrow.up.circle.fill")
.resizable()
.frame(width: 20, height: 20)
}
}
.labelStyle(.iconOnly)
.buttonStyle(.automatic)
.disabled(messageText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isSending)
.frame(width: 40, height: 40)
}
.padding(.horizontal)
.padding(.top, 8)
.transition(.move(edge: .bottom).combined(with: .opacity))
}
}
.navigationTitle(room.name ?? "Chat")
.task {
await loadMessages()
}
.onAppear {
setupWebSocketListeners()
}
.onDisappear {
cancellables.forEach { $0.cancel() }
cancellables.removeAll()
scrollTimer?.invalidate()
scrollTimer = nil
}
}
private var webSocketStatusMessage: String {
switch wsState {
case .connected: return "Connected"
case .connecting: return "Connecting..."
case .disconnected: return "Disconnected"
case .serverDown: return "Server Down"
case .duplicateDevice: return "Duplicate Device"
case .error(let msg): return "Error: \(msg)"
}
}
private func loadMessages() async {
// Prevent reloading if already loaded
guard !hasLoadedMessages else { return }
guard let token = appState.token, let serverUrl = appState.serverUrl else {
isLoading = false
return
}
isLoading = true
error = nil
do {
let messages = try await appState.networkService.fetchChatMessages(
chatRoomId: room.id,
token: token,
serverUrl: serverUrl
)
// Sort with newest messages first (for flipped list, newest will appear at bottom)
self.messages = messages.sorted { $0.createdAt < $1.createdAt }
hasLoadedMessages = true
} catch {
print("[watchOS] Error loading messages: \(error.localizedDescription)")
self.error = error
}
isLoading = false
}
private func sendMessage() async {
let content = messageText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !content.isEmpty,
let token = appState.token,
let serverUrl = appState.serverUrl else { return }
isSending = true
do {
// Generate a nonce for the message
let nonce = UUID().uuidString
// Prepare the request data
let messageData: [String: Any] = [
"content": content,
"attachments_id": [], // Empty for now, can be extended for attachments
"meta": [:],
"nonce": nonce
]
// Create the URL
guard let url = URL(string: "\(serverUrl)/sphere/chat/\(room.id)/messages") else {
throw URLError(.badURL)
}
// Create the request
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONSerialization.data(withJSONObject: messageData, options: [])
// Send the request
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
throw URLError(.badServerResponse)
}
// Parse the response to get the sent message
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
decoder.keyDecodingStrategy = .convertFromSnakeCase
let sentMessage = try decoder.decode(SnChatMessage.self, from: data)
// Add the message to the local list
messages.append(sentMessage)
// Clear the input
messageText = ""
} catch {
print("[watchOS] Error sending message: \(error.localizedDescription)")
// Could show an error alert here
}
isSending = false
}
private func sendReadReceipt() {
let data: [String: Any] = ["chat_room_id": room.id]
let packet: [String: Any] = ["type": "messages.read", "data": data, "endpoint": "sphere"]
if let jsonData = try? JSONSerialization.data(withJSONObject: packet, options: []),
let jsonString = String(data: jsonData, encoding: .utf8) {
appState.networkService.sendWebSocketMessage(message: jsonString)
}
}
private func setupWebSocketListeners() {
// Listen for WebSocket packets (new messages)
appState.networkService.packetStream
.receive(on: DispatchQueue.main) // Ensure UI updates on main thread
.sink(receiveCompletion: { completion in
if case .failure(let err) = completion {
print("[ChatRoomView] WebSocket packet stream error: \(err.localizedDescription)")
}
}, receiveValue: { packet in
if ["messages.new", "messages.update", "messages.delete"].contains(packet.type),
let messageData = packet.data {
do {
let jsonData = try JSONSerialization.data(withJSONObject: messageData, options: [])
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
decoder.keyDecodingStrategy = .convertFromSnakeCase
let message = try decoder.decode(SnChatMessage.self, from: jsonData)
if message.chatRoomId == room.id {
switch packet.type {
case "messages.new":
if message.type.hasPrefix("call") {
// TODO: Handle ongoing call
}
if !messages.contains(where: { $0.id == message.id }) {
messages.append(message)
}
sendReadReceipt()
case "messages.update":
if let index = messages.firstIndex(where: { $0.id == message.id }) {
messages[index] = message
}
case "messages.delete":
messages.removeAll(where: { $0.id == message.id })
default:
break
}
}
} catch {
print("[ChatRoomView] Error decoding message from websocket: \(error.localizedDescription)")
}
}
})
.store(in: &cancellables)
// Listen for WebSocket connection state changes
appState.networkService.stateStream
.receive(on: DispatchQueue.main) // Ensure UI updates on main thread
.sink { state in
wsState = state
}
.store(in: &cancellables)
}
}
struct ChatMessageItem: View {
let message: SnChatMessage
@EnvironmentObject var appState: AppState
@StateObject private var avatarLoader = ImageLoader()
private var avatarPictureId: String? {
message.sender.account.profile.picture?.id
}
var body: some View {
HStack(alignment: .top, spacing: 8) {
// Avatar
Group {
if avatarLoader.isLoading {
ProgressView()
.frame(width: 24, height: 24)
} else if let image = avatarLoader.image {
image
.resizable()
.frame(width: 24, height: 24)
.clipShape(Circle())
} else {
Circle()
.fill(Color.gray.opacity(0.3))
.frame(width: 24, height: 24)
.overlay(
Text(message.sender.account.nick.prefix(1).uppercased())
.font(.system(size: 10, weight: .medium))
.foregroundColor(.primary)
)
}
}
.task(id: avatarPictureId) {
if let serverUrl = appState.serverUrl,
let pictureId = avatarPictureId,
let imageUrl = getAttachmentUrl(for: pictureId, serverUrl: serverUrl),
let token = appState.token {
await avatarLoader.loadImage(from: imageUrl, token: token)
}
}
VStack(alignment: .leading, spacing: 4) {
HStack {
Text(message.sender.account.nick)
.font(.system(size: 12, weight: .medium))
Spacer()
Text(message.createdAt, style: .time)
.font(.system(size: 10))
.foregroundColor(.secondary)
}
if let content = message.content, !content.isEmpty {
Text(content)
.font(.system(size: 14))
.lineLimit(nil)
.fixedSize(horizontal: false, vertical: true)
}
if !message.attachments.isEmpty {
AttachmentView(attachment: message.attachments[0])
if message.attachments.count > 1 {
HStack(spacing: 8) {
Image(systemName: "paperclip.circle.fill")
.frame(width: 12, height: 12)
.foregroundStyle(.gray)
Text("\(message.attachments.count - 1)+ attachments")
.font(.footnote)
.foregroundStyle(.gray)
}
}
}
}
}
.padding(.vertical, 4)
}
}
struct ChatInvitesView: View {
@Binding var invites: [SnChatMember]
let appState: AppState
@Environment(\.dismiss) private var dismiss
@State private var isLoading = false
var body: some View {
NavigationView {
VStack {
if invites.isEmpty {
VStack {
Image(systemName: "envelope.open")
.font(.largeTitle)
.foregroundColor(.secondary)
Text("No invites")
.font(.caption)
.foregroundColor(.secondary)
}
} else {
List(invites) { invite in
ChatInviteItem(invite: invite, appState: appState, invites: $invites)
}
.listStyle(.plain)
}
}
.navigationTitle("Invites")
.navigationBarTitleDisplayMode(.inline)
}
}
}
struct ChatInviteItem: View {
let invite: SnChatMember
let appState: AppState
@Binding var invites: [SnChatMember]
@State private var isAccepting = false
@State private var isDeclining = false
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Circle()
.fill(Color.gray.opacity(0.3))
.frame(width: 24, height: 24)
.overlay(
Text((invite.chatRoom?.name ?? "C").prefix(1).uppercased())
.font(.system(size: 10, weight: .medium))
.foregroundColor(.primary)
)
VStack(alignment: .leading, spacing: 2) {
Text(invite.chatRoom?.name ?? "Unknown Chat")
.font(.system(size: 14, weight: .medium))
.lineLimit(1)
HStack(spacing: 4) {
Text(invite.role == 100 ? "Owner" : invite.role >= 50 ? "Moderator" : "Member")
.font(.system(size: 12))
.foregroundColor(.secondary)
if invite.chatRoom?.type == 1 {
Text("Direct")
.font(.system(size: 12))
.foregroundColor(.blue)
.padding(.horizontal, 4)
.padding(.vertical, 2)
.background(Color.blue.opacity(0.1))
.cornerRadius(4)
}
}
}
Spacer()
}
HStack(spacing: 8) {
Button {
Task {
await acceptInvite()
}
} label: {
if isAccepting {
ProgressView()
.frame(width: 20, height: 20)
} else {
Image(systemName: "checkmark")
.frame(width: 20, height: 20)
}
}
.disabled(isAccepting || isDeclining)
Button {
Task {
await declineInvite()
}
} label: {
if isDeclining {
ProgressView()
.frame(width: 20, height: 20)
} else {
Image(systemName: "xmark")
.frame(width: 20, height: 20)
}
}
.disabled(isAccepting || isDeclining)
}
}
.padding(.vertical, 8)
}
private func acceptInvite() async {
guard let token = appState.token,
let serverUrl = appState.serverUrl,
let chatRoomId = invite.chatRoom?.id else { return }
isAccepting = true
do {
try await appState.networkService.acceptChatInvite(chatRoomId: chatRoomId, token: token, serverUrl: serverUrl)
// Remove from invites list
invites.removeAll { $0.id == invite.id }
} catch {
// Handle error - could show alert
print("Failed to accept invite: \(error)")
}
isAccepting = false
}
private func declineInvite() async {
guard let token = appState.token,
let serverUrl = appState.serverUrl,
let chatRoomId = invite.chatRoom?.id else { return }
isDeclining = true
do {
try await appState.networkService.declineChatInvite(chatRoomId: chatRoomId, token: token, serverUrl: serverUrl)
// Remove from invites list
invites.removeAll { $0.id == invite.id }
} catch {
// Handle error - could show alert
print("Failed to decline invite: \(error)")
}
isDeclining = false
}
}

View File

@@ -0,0 +1,53 @@
//
// ComposePostView.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/29.
//
import SwiftUI
struct ComposePostView: View {
@StateObject private var viewModel = ComposePostViewModel()
@EnvironmentObject var appState: AppState
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationStack {
Form {
TextField("Title", text: $viewModel.title)
TextField("Content", text: $viewModel.content)
}
.navigationTitle("New Post")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel", systemImage: "xmark") {
dismiss()
}
.labelStyle(.iconOnly)
}
ToolbarItem(placement: .confirmationAction) {
Button("Post", systemImage: "square.and.arrow.up") {
Task {
if let token = appState.token, let serverUrl = appState.serverUrl {
await viewModel.createPost(token: token, serverUrl: serverUrl)
}
}
}
.labelStyle(.iconOnly)
.disabled(viewModel.isPosting)
}
}
.onChange(of: viewModel.didPost) {
if viewModel.didPost {
dismiss()
}
}
.alert("Error", isPresented: .constant(viewModel.errorMessage != nil), actions: {
Button("OK") { viewModel.errorMessage = nil }
}, message: {
Text(viewModel.errorMessage ?? "")
})
}
}
}

View File

@@ -0,0 +1,110 @@
//
// DiscoveryViews.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/29.
//
import SwiftUI
struct DiscoveryView: View {
let discoveryData: DiscoveryData
var body: some View {
NavigationLink(destination: DiscoveryDetailView(discoveryData: discoveryData)) {
VStack(alignment: .leading) {
Text("Discovery")
.font(.headline)
Text("\(discoveryData.items.count) new items to discover")
.font(.subheadline)
.foregroundColor(.secondary)
}
}
}
}
struct DiscoveryDetailView: View {
let discoveryData: DiscoveryData
var body: some View {
List(discoveryData.items) { item in
NavigationLink(destination: destinationView(for: item)) {
itemView(for: item)
}
}
.navigationTitle("Discovery")
}
@ViewBuilder
private func itemView(for item: DiscoveryItem) -> some View {
VStack(alignment: .leading) {
switch item.data {
case .realm(let realm):
Text("Realm").font(.headline)
Text(realm.name).foregroundColor(.secondary)
case .publisher(let publisher):
Text("Publisher").font(.headline)
Text(publisher.name).foregroundColor(.secondary)
case .article(let article):
Text("Article").font(.headline)
Text(article.title).foregroundColor(.secondary)
case .unknown:
Text("Unknown item")
}
}
}
@ViewBuilder
private func destinationView(for item: DiscoveryItem) -> some View {
switch item.data {
case .realm(let realm):
RealmDetailView(realm: realm)
case .publisher(let publisher):
PublisherDetailView(publisher: publisher)
case .article(let article):
ArticleDetailView(article: article)
case .unknown:
Text("Detail view not available")
}
}
}
struct RealmDetailView: View {
let realm: SnRealm
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(realm.name).font(.headline)
if let description = realm.description {
Text(description).font(.body)
}
}
.navigationTitle("Realm")
}
}
struct PublisherDetailView: View {
let publisher: SnPublisher
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(publisher.name).font(.headline)
if let description = publisher.description {
Text(description).font(.body)
}
}
.navigationTitle("Publisher")
}
}
struct ArticleDetailView: View {
let article: SnWebArticle
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(article.title).font(.headline)
Text(article.url).font(.caption).foregroundColor(.secondary)
}
.navigationTitle("Article")
}
}

View File

@@ -0,0 +1,67 @@
//
// ExploreView.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/29.
//
import SwiftUI
// The main view with the TabView for filtering.
struct ExploreView: View {
@EnvironmentObject private var appState: AppState
@State private var isComposing = false
@State private var selectedTab: String = "Explore"
var body: some View {
NavigationStack {
if appState.isReady {
TabView(selection: $selectedTab) {
ActivityListView(filter: "Explore")
.tag("Explore")
.tabItem {
Label("Explore", systemImage: "safari")
}
.labelStyle(.titleOnly)
ActivityListView(filter: "Subscriptions")
.tag("Subscriptions")
.tabItem {
Label("Subscriptions", systemImage: "star")
}
.labelStyle(.titleOnly)
ActivityListView(filter: "Friends")
.tag("Friends")
.tabItem {
Label("Friends", systemImage: "person.2")
}
.labelStyle(.titleOnly)
}
.navigationTitle(selectedTab)
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button(action: { isComposing = true }) {
Label("Compose", systemImage: "plus")
}
}
}
} else {
VStack {
ProgressView { Text("Syncing...") }
Button("Retry") {
appState.requestData()
}
}
}
}
.sheet(isPresented: $isComposing) {
ComposePostView()
}
.alert("Error", isPresented: .constant(appState.errorMessage != nil), actions: {
Button("OK") { appState.errorMessage = nil }
}, message: {
Text(appState.errorMessage ?? "")
})
}
}

View File

@@ -0,0 +1,34 @@
import SwiftUI
struct ImageViewer: View {
let imageUrl: URL
@EnvironmentObject var appState: AppState
@StateObject private var imageLoader = ImageLoader()
var body: some View {
Group {
if imageLoader.isLoading {
ProgressView()
} else if let image = imageLoader.image {
image
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.scaledToFit()
} else if let errorMessage = imageLoader.errorMessage {
Text("Failed to load image: \(errorMessage)")
.font(.caption)
.foregroundColor(.red)
} else {
Text("Failed to load image.")
}
}
.task(id: imageUrl) {
if let token = appState.token {
await imageLoader.loadImage(from: imageUrl, token: token)
}
}
.navigationTitle("Image")
.navigationBarTitleDisplayMode(.inline)
}
}

View File

@@ -0,0 +1,198 @@
//
// NotificationView.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/29.
//
import SwiftUI
import Combine
@MainActor
class NotificationViewModel: ObservableObject {
@Published var notifications = [SnNotification]()
@Published var isLoading = false
@Published var isLoadingMore = false
@Published var errorMessage: String?
@Published var hasMore = false
private let networkService = NetworkService()
private var hasFetched = false
private var offset = 0
private let pageSize = 20
func fetchNotifications(token: String, serverUrl: String) async {
if hasFetched { return }
guard !isLoading else { return }
isLoading = true
errorMessage = nil
hasFetched = true
offset = 0
do {
let response = try await networkService.fetchNotifications(offset: offset, take: pageSize, token: token, serverUrl: serverUrl)
self.notifications = response.notifications
self.hasMore = response.hasMore
offset += response.notifications.count
} catch {
self.errorMessage = error.localizedDescription
print("[watchOS] fetchNotifications failed with error: \(error)")
hasFetched = false
}
isLoading = false
}
func loadMoreNotifications(token: String, serverUrl: String) async {
guard !isLoadingMore && hasMore else { return }
isLoadingMore = true
do {
let response = try await networkService.fetchNotifications(offset: offset, take: pageSize, token: token, serverUrl: serverUrl)
self.notifications.append(contentsOf: response.notifications)
self.hasMore = response.hasMore
offset += response.notifications.count
} catch {
self.errorMessage = error.localizedDescription
print("[watchOS] loadMoreNotifications failed with error: \(error)")
}
isLoadingMore = false
}
}
struct NotificationView: View {
@EnvironmentObject var appState: AppState
@StateObject private var viewModel = NotificationViewModel()
var body: some View {
Group {
if viewModel.isLoading {
ProgressView()
} else if let errorMessage = viewModel.errorMessage {
VStack {
Text("Error")
.font(.headline)
Text(errorMessage)
.font(.caption)
Button("Retry") {
Task {
if let token = appState.token, let serverUrl = appState.serverUrl {
await viewModel.fetchNotifications(token: token, serverUrl: serverUrl)
}
}
}
}
.padding()
} else if viewModel.notifications.isEmpty {
Text("No notifications")
} else {
List {
ForEach(viewModel.notifications) { notification in
NavigationLink(destination: NotificationDetailView(notification: notification)) {
VStack(alignment: .leading, spacing: 4) {
HStack {
Text(notification.title)
.font(.headline)
Spacer()
if notification.viewedAt == nil {
Circle()
.fill(Color.blue)
.frame(width: 8, height: 8)
}
}
if !notification.subtitle.isEmpty {
Text(notification.subtitle)
.font(.subheadline)
.foregroundColor(.secondary)
}
if notification.content.count > 100 {
Text(notification.content.prefix(100) + "...")
.font(.caption)
.foregroundColor(.gray)
.lineLimit(2)
} else {
Text(notification.content)
.font(.caption)
.foregroundColor(.gray)
.lineLimit(2)
}
Text(notification.createdAt, style: .relative)
.font(.caption2)
.foregroundColor(.gray)
}
.padding(.vertical, 8)
}
}
if viewModel.hasMore {
if viewModel.isLoadingMore {
HStack {
Spacer()
ProgressView()
Spacer()
}
} else {
Button("Load More") {
Task {
if let token = appState.token, let serverUrl = appState.serverUrl {
await viewModel.loadMoreNotifications(token: token, serverUrl: serverUrl)
}
}
}
.frame(maxWidth: .infinity)
}
}
}
}
}
.onAppear {
if appState.isReady, let token = appState.token, let serverUrl = appState.serverUrl {
Task.detached {
await viewModel.fetchNotifications(token: token, serverUrl: serverUrl)
}
}
}
.navigationTitle("Notifications")
.navigationBarTitleDisplayMode(.inline)
}
}
struct NotificationDetailView: View {
let notification: SnNotification
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
Text(notification.title)
.font(.headline)
if !notification.subtitle.isEmpty {
Text(notification.subtitle)
.font(.subheadline)
.foregroundColor(.secondary)
}
Text(notification.content)
.font(.body)
HStack {
Text(notification.createdAt, style: .date)
Text("·")
Text(notification.createdAt, style: .time)
}
.font(.caption)
.foregroundColor(.gray)
if notification.viewedAt == nil {
Text("Unread")
.font(.caption)
.foregroundColor(.blue)
}
}
.padding()
}
.navigationTitle("Notification")
.navigationBarTitleDisplayMode(.inline)
}
}

View File

@@ -0,0 +1,151 @@
//
// PostViews.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/29.
//
import SwiftUI
struct PostRowView: View {
let post: SnPost
@EnvironmentObject var appState: AppState
@StateObject private var imageLoader = ImageLoader() // Instantiate ImageLoader
var body: some View {
VStack(alignment: .leading, spacing: 4) {
HStack {
if imageLoader.isLoading {
ProgressView()
.frame(width: 24, height: 24)
} else if let image = imageLoader.image {
image
.resizable()
.frame(width: 24, height: 24)
.clipShape(Circle())
} else if let errorMessage = imageLoader.errorMessage {
Text("Failed: \(errorMessage)")
.font(.caption)
.foregroundColor(.red)
.frame(width: 24, height: 24)
} else {
// Placeholder if no image and not loading
Image(systemName: "person.circle.fill")
.resizable()
.frame(width: 24, height: 24)
.clipShape(Circle())
.foregroundColor(.gray)
}
Text(post.publisher.nick ?? post.publisher.name)
.font(.subheadline)
.bold()
}
.task(id: post.publisher.picture?.id) { // Use task(id:) to reload image when pictureId changes
if let serverUrl = appState.serverUrl, let pictureId = post.publisher.picture?.id, let imageUrl = getAttachmentUrl(for: pictureId, serverUrl: serverUrl), let token = appState.token {
await imageLoader.loadImage(from: imageUrl, token: token)
}
}
if let title = post.title, !title.isEmpty {
Text(title)
.font(.headline)
}
if let content = post.content, !content.isEmpty {
Text(content)
.font(.body)
}
if !post.attachments.isEmpty {
AttachmentView(attachment: post.attachments[0])
if post.attachments.count > 1 {
HStack(spacing: 8) {
Image(systemName: "paperclip.circle.fill")
.frame(width: 12, height: 12)
.foregroundStyle(.gray)
Text("\(post.attachments.count - 1)+ attachments")
.font(.footnote)
.foregroundStyle(.gray)
}
}
}
}.padding(.vertical)
}
}
struct PostDetailView: View {
let post: SnPost
@EnvironmentObject var appState: AppState
@StateObject private var publisherImageLoader = ImageLoader() // Instantiate ImageLoader for publisher avatar
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 8) {
HStack {
if publisherImageLoader.isLoading {
ProgressView()
.frame(width: 32, height: 32)
} else if let image = publisherImageLoader.image {
image
.resizable()
.frame(width: 32, height: 32)
.clipShape(Circle())
} else if let errorMessage = publisherImageLoader.errorMessage {
Text("Failed: \(errorMessage)")
.font(.caption)
.foregroundColor(.red)
.frame(width: 32, height: 32)
} else {
Image(systemName: "person.circle.fill")
.resizable()
.frame(width: 32, height: 32)
.clipShape(Circle())
.foregroundColor(.gray)
}
Text("@\(post.publisher.name)")
.font(.headline)
}
// Use task(id:) to reload image when pictureId changes
.task(id: post.publisher.picture?.id) {
if let serverUrl = appState.serverUrl, let pictureId = post.publisher.picture?.id, let imageUrl = getAttachmentUrl(for: pictureId, serverUrl: serverUrl), let token = appState.token {
await publisherImageLoader.loadImage(from: imageUrl, token: token)
}
}
if let title = post.title, !title.isEmpty {
Text(title)
.font(.title2)
.bold()
}
if let content = post.content, !content.isEmpty {
Text(content)
.font(.body)
}
if !post.attachments.isEmpty {
Text("Attachments").font(.headline)
ForEach(post.attachments) { attachment in
AttachmentView(attachment: attachment)
}
}
if !post.tags.isEmpty {
Text("Tags").font(.headline)
FlowLayout(alignment: .leading, spacing: 4) {
ForEach(post.tags) { tag in
Text("#\(tag.name ?? tag.slug)")
.font(.caption)
.padding(.horizontal, 8)
.padding(.vertical, 3)
.background(Capsule().fill(Color.accentColor.opacity(0.2)))
.cornerRadius(5)
}
}
}
}
.padding()
}
.navigationTitle("Post")
}
}

View File

@@ -0,0 +1,132 @@
//
// StatusCreationView.swift
// WatchRunner Watch App
//
// Created by LittleSheep on 2025/10/30.
//
import SwiftUI
struct StatusCreationView: View {
@EnvironmentObject var appState: AppState
@Environment(\.dismiss) var dismiss
let initialStatus: SnAccountStatus?
@State private var attitude: Int
@State private var isInvisible: Bool
@State private var isNotDisturb: Bool
@State private var label: String
@State private var isSubmitting: Bool = false
@State private var error: Error? = nil
private let networkService = NetworkService()
init(initialStatus: SnAccountStatus? = nil) {
self.initialStatus = initialStatus
_attitude = State(initialValue: initialStatus?.attitude ?? 1)
_isInvisible = State(initialValue: initialStatus?.isInvisible ?? false)
_isNotDisturb = State(initialValue: initialStatus?.isNotDisturb ?? false)
_label = State(initialValue: initialStatus?.label ?? "")
}
var body: some View {
ScrollView {
VStack(spacing: 16) {
// Title
Text("Set Status")
.font(.headline)
.padding(.top)
// Label TextField
TextField("Status label", text: $label)
.textFieldStyle(.automatic)
.padding(.horizontal)
// Attitude Picker
VStack(alignment: .leading, spacing: 8) {
Text("Mood")
.font(.subheadline)
.foregroundColor(.secondary)
Picker("Attitude", selection: $attitude) {
Text("😊 Positive").tag(0)
Text("😐 Neutral").tag(1)
Text("😢 Negative").tag(2)
}
.pickerStyle(.wheel)
.frame(height: 80)
}
.padding(.horizontal)
// Toggles
VStack(spacing: 12) {
Toggle("Invisible", isOn: $isInvisible)
.padding(.horizontal)
Toggle("Do Not Disturb", isOn: $isNotDisturb)
.padding(.horizontal)
}
// Error message
if let error = error {
Text("Error: \(error.localizedDescription)")
.foregroundColor(.red)
.font(.caption)
.padding(.horizontal)
}
// Buttons
HStack(spacing: 12) {
Button("Cancel") {
dismiss()
}
.buttonStyle(.automatic)
Button(isSubmitting ? "Saving..." : "Save") {
Task {
await submitStatus()
}
}
.buttonStyle(.automatic)
.disabled(isSubmitting)
}
.padding(.horizontal)
.padding(.bottom)
}
}
.navigationTitle("Status")
.navigationBarTitleDisplayMode(.inline)
}
private func submitStatus() async {
guard let token = appState.token, let serverUrl = appState.serverUrl else {
error = NSError(domain: "StatusCreationView", code: 1, userInfo: [NSLocalizedDescriptionKey: "Authentication not available"])
return
}
isSubmitting = true
error = nil
do {
_ = try await networkService.createOrUpdateStatus(
attitude: attitude,
isInvisible: isInvisible,
isNotDisturb: isNotDisturb,
label: label.isEmpty ? nil : label,
token: token,
serverUrl: serverUrl
)
dismiss()
} catch {
self.error = error
}
isSubmitting = false
}
}
#Preview {
StatusCreationView()
.environmentObject(AppState())
}

View File

@@ -0,0 +1,12 @@
import SwiftUI
import AVKit
import AVFoundation
struct VideoPlayerView: View {
let videoUrl: URL
var body: some View {
VideoPlayer(player: AVPlayer(url: videoUrl))
.edgesIgnoringSafeArea(.all) // Make it full screen
}
}