Skip to content
Repos

WO_DevPlaceIOS

Swift 2.3 KB80 lines Opens in site

Directory Raw Download

import Foundation
import Observation
import DevPlaceSwiftSDK

extension VoteView {
    @Observable final class ViewModel {
        let targetType: TargetType
        let targetId: String
        let api: DevPlaceApi

        var count: Int
        var currentVote: Vote

        var alertMessage: AlertMessage = .none()

        var isLoading = false

        var userCanVote: Bool {
            AppState.shared.isLoggedIn
        }

        init(
            targetType: TargetType,
            targetId: String,
            count: Int,
            vote: Vote,
            api: DevPlaceApi,
        ) {
            self.targetType = targetType
            self.targetId = targetId
            self.count = count
            self.currentVote = vote
            self.api = api
        }

        func voteUp() async {
            guard !isLoading else { return }
            let newVote: Vote = currentVote == .up ? .none : .up
            await apply(selectedVote: .up, newVote: newVote)
        }

        func voteDown() async {
            guard !isLoading else { return }
            let newVote: Vote = currentVote == .down ? .none : .down
            await apply(selectedVote: .down, newVote: newVote)
        }

        private func apply(selectedVote: Vote, newVote: Vote) async {
            isLoading = true
            defer { isLoading = false }

            let previousVote = currentVote
            let previousCount = count

            currentVote = newVote
            count = previousCount + newVote.value - previousVote.value
            syncToFeed()

            do {
                try await api.vote(targetType: targetType, targetId: targetId, vote: selectedVote)
            } catch {
                currentVote = previousVote
                count = previousCount
                syncToFeed()
                alertMessage = .presentedError(error)
            }
        }

        private func syncToFeed() {
            switch targetType {
            case .post:
                AppState.shared.updatePostVoteInFeed(postId: targetId, vote: currentVote, count: count)
            case .comment:
                AppState.shared.updateCommentVoteInFeed(commentId: targetId, vote: currentVote)
            default:
                break
            }
        }
    }
}
37.2ms