Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/components/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# @baseapp-frontend/components

## 1.0.26

### Patch Changes

- Use optimistic update when sending message

## 1.0.25

### Patch Changes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import { Disposable, UseMutationConfig, graphql, useMutation } from 'react-relay
import { SendMessageMutation } from '../../../../../__generated__/SendMessageMutation.graphql'

export const SendMessageMutationQuery = graphql`
mutation SendMessageMutation($input: ChatRoomSendMessageInput!, $connections: [ID!]!) {
mutation SendMessageMutation($input: ChatRoomSendMessageInput!, $connections: [ID!]!)
@raw_response_type {
chatRoomSendMessage(input: $input) {
message @prependEdge(connections: $connections) {
node {
id
messageType
...MessageItemFragment
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { useMemo } from 'react'
import { ConnectionHandler, graphql, useSubscription } from 'react-relay'

export const newMessageSubscription = graphql`
subscription useMessagesListSubscription($roomId: ID!, $connections: [ID!]!) {
chatRoomOnMessage(roomId: $roomId) {
subscription useMessagesListSubscription($roomId: ID!, $profileId: ID!, $connections: [ID!]!) {
chatRoomOnMessage(roomId: $roomId, profileId: $profileId) {
message @prependEdge(connections: $connections) {
node {
...MessageItemFragment
Expand All @@ -17,13 +17,14 @@ export const newMessageSubscription = graphql`
}
`

export const useMessagesListSubscription = (roomId: string) => {
export const useMessagesListSubscription = (roomId: string, profileId: string) => {
const config = useMemo(() => {
const connectionID = ConnectionHandler.getConnectionID(roomId, 'chatRoom_allMessages')
return {
subscription: newMessageSubscription,
variables: {
roomId,
profileId,
connections: [connectionID],
},
onError: console.error,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ const MessagesList: FC<MessagesListProps> = ({
}
}, [room?.id, room?.unreadMessages?.count, currentProfile])

useMessagesListSubscription(room?.id)
useMessagesListSubscription(room.id, currentProfile?.id!)
// TODO: Is there a safer way to ensure the current profile id is not undefined?

const renderLoadingState = () => {
if (!isLoadingNext) return <Box sx={{ height: 50 }} />
Expand Down
44 changes: 35 additions & 9 deletions packages/components/modules/messages/web/SendMessage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { forwardRef } from 'react'

import { useCurrentProfile } from '@baseapp-frontend/authentication'
import { setFormRelayErrors } from '@baseapp-frontend/utils'
import { setFormRelayErrors, useNotification } from '@baseapp-frontend/utils'

import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
Expand All @@ -15,7 +15,7 @@ import {
SocialUpsertForm,
} from '../../../__shared__/common'
import { SocialInput as DefaultSocialInput } from '../../../__shared__/web'
import { useSendMessageMutation } from '../../common'
import { MESSAGE_TYPE, useSendMessageMutation } from '../../common'
import { SendMessageProps } from './types'

let nextClientMutationId = 0
Expand Down Expand Up @@ -76,6 +76,7 @@ let nextClientMutationId = 0
const SendMessage = forwardRef<HTMLInputElement, SendMessageProps>(
({ roomId, SocialInput = DefaultSocialInput, SocialInputProps = {} }, ref) => {
const { currentProfile } = useCurrentProfile()
const { sendToast } = useNotification()

const form = useForm<SocialUpsertForm>({
defaultValues: DEFAULT_SOCIAL_UPSERT_FORM_VALUES,
Expand All @@ -90,32 +91,57 @@ const SendMessage = forwardRef<HTMLInputElement, SendMessageProps>(
const clientMutationId = nextClientMutationId.toString()

const connectionID = ConnectionHandler.getConnectionID(roomId, 'chatRoom_allMessages')
const content = data.body

commitMutation({
variables: {
input: {
content: data.body,
content,
profileId: currentProfile?.id,
roomId,
clientMutationId,
},
connections: [connectionID],
},
optimisticResponse: {
chatRoomSendMessage: {
message: {
node: {
id: `client:new_message:${Date.now()}`,
content,
created: new Date(Date.now()).toISOString(),
deleted: false,
extraData: null,
messageType: MESSAGE_TYPE.user,
inReplyTo: null,
isRead: true,
pk: 0, // This property is required, so we need to provide something to keep typescript happy
profile: {
id: currentProfile.id,
},
verb: 'SENT_MESSAGE',
},
},
errors: [],
},
},
onCompleted: (response, errors) => {
if (errors) {
// TODO: handle errors
console.error(errors)
sendToast('Your last message could not be sent. Please try again.', { type: 'error' })
}
const mutationErrors = response?.chatRoomSendMessage?.errors
setFormRelayErrors(form, mutationErrors)

if (!mutationErrors?.length) {
form.reset()
if (mutationErrors) {
setFormRelayErrors(form, mutationErrors)
sendToast('Your last message could not be sent. Please try again.', { type: 'error' })
}
},
// TODO: handle errors
onError: console.error,
onError: () => {
sendToast('Your last message could not be sent. Please try again.', { type: 'error' })
},
})
form.reset()
}

return (
Expand Down
2 changes: 1 addition & 1 deletion packages/components/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@baseapp-frontend/components",
"description": "BaseApp components modules such as comments, notifications, messages, and more.",
"version": "1.0.25",
"version": "1.0.26",
"sideEffects": false,
"scripts": {
"babel:transpile": "babel modules -d tmp-babel --extensions .ts,.tsx --ignore '**/__tests__/**','**/__storybook__/**'",
Expand Down
2 changes: 1 addition & 1 deletion packages/components/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -1679,7 +1679,7 @@ type RoleUpdatePayload {
}

type Subscription {
chatRoomOnMessage(roomId: ID!): ChatRoomOnMessage
chatRoomOnMessage(profileId: ID!, roomId: ID!): ChatRoomOnMessage
chatRoomOnRoomUpdate(profileId: ID!): ChatRoomOnRoomUpdate
chatRoomOnMessagesCountUpdate(profileId: ID!): ChatRoomOnMessagesCountUpdate
onNotificationChange: OnNotificationChange
Expand Down
Loading