1 import { utf8ArrayToString } from '@proton/crypto/lib/utils'
11 } from '@proton/docs-shared'
12 import { CommentsMessageType } from '@proton/docs-shared'
13 import { Comment, CommentThread } from '../Models'
14 import type { LocalCommentsState } from '../Services/Comments/LocalCommentsState'
15 import type { LiveComments } from '../Realtime/LiveComments/LiveComments'
16 import { getErrorString } from '../Util/GetErrorString'
17 import type { SyncUseCaseInterface } from '../Domain/UseCase/SyncUseCaseInterface'
18 import { Result } from '@proton/docs-shared'
21 * Updates the local comment state after receiving a message from the RTS.
23 export class HandleRealtimeCommentsEvent implements SyncUseCaseInterface<void> {
24 execute(localCommentsState: LocalCommentsState, liveComments: LiveComments, content: Uint8Array): Result<void> {
26 const jsonString = utf8ArrayToString(content)
27 const { type, data } = JSON.parse(jsonString) as { type: CommentsMessageType; data: AnyCommentMessageData }
29 case CommentsMessageType.AddThread: {
30 const threadData = data as AddThreadData
31 const thread = CommentThread.fromPayload(threadData)
32 localCommentsState.addThread(thread, true)
35 case CommentsMessageType.AddComment: {
36 const commentData = data as AddCommentData
37 const comment = Comment.fromPayload(commentData.comment)
38 localCommentsState.addComment(comment, commentData.threadID, true)
41 case CommentsMessageType.EditComment:
42 ;(data as EditCommentData).markThreadUnread = true
43 localCommentsState.editComment(data as EditCommentData)
45 case CommentsMessageType.DeleteThread:
46 localCommentsState.deleteThread((data as DeleteThreadData).threadId)
48 case CommentsMessageType.DeleteComment:
49 localCommentsState.deleteComment(data as DeleteCommentData)
51 case CommentsMessageType.BeganTyping:
52 case CommentsMessageType.StoppedTyping:
53 liveComments.receiveTypingStatusMessage(type, data as BeganTypingData | StoppedTypingData)
55 case CommentsMessageType.ResolveThread:
56 localCommentsState.resolveThread((data as DeleteThreadData).threadId)
58 case CommentsMessageType.UnresolveThread:
59 localCommentsState.unresolveThread((data as DeleteThreadData).threadId)
66 return Result.fail(getErrorString(error) ?? 'Failed to handle a realtime comments event.')