Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assistant: Better management of providers, routes and browser back button #2228

Merged
merged 3 commits into from
Oct 28, 2024
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
53 changes: 22 additions & 31 deletions src/assistant/AssistantProvider.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import { CHAT_EVENTS_DOCTYPE, CHAT_CONVERSATIONS_DOCTYPE } from './queries'

export const AssistantContext = React.createContext()

export const makeConversationId = () =>
`${Date.now()}-${Math.floor(Math.random() * 90000) + 10000}`
Ldoppea marked this conversation as resolved.
Show resolved Hide resolved

export const useAssistant = () => {
const context = useContext(AssistantContext)

Expand All @@ -32,8 +35,7 @@ const AssistantProvider = ({ children }) => {
const [assistantState, setAssistantState] = useState({
message: '',
status: 'idle',
messagesId: [],
conversationId: undefined
messagesId: []
})

useRealtime(client, {
Expand All @@ -50,6 +52,7 @@ const AssistantProvider = ({ children }) => {
useRealtime(client, {
[CHAT_EVENTS_DOCTYPE]: {
created: res => {
// to exclude realtime messages if not relevant to the actual conversation
if (!isMessageForThisConversation(res, assistantState.messagesId)) {
return
}
Expand Down Expand Up @@ -77,50 +80,38 @@ const AssistantProvider = ({ children }) => {
}
})

const clearAssistant = useCallback(
() =>
setAssistantState({
message: '',
status: 'idle',
messagesId: []
}),
[]
)

const onAssistantExecute = useCallback(
async (inputValue, callback) => {
if (!inputValue) return
async ({ value, conversationId }, callback) => {
if (!value) return

callback?.()

setAssistantState(v => ({
...v,
message: '',
status: 'idle'
}))

const id =
assistantState.conversationId ||
`${Date.now()}-${Math.floor(Math.random() * 90000) + 10000}`
clearAssistant()

await client.stackClient.fetchJSON(
'POST',
`/ai/chat/conversations/${id}`,
`/ai/chat/conversations/${conversationId}`,
{
q: inputValue
q: value
}
)

setAssistantState(v => ({
...v,
message: '',
status: 'pending',
conversationId:
id !== assistantState.conversationId ? id : v.conversationId
status: 'pending'
}))
},
[client, assistantState.conversationId]
)

const clearAssistant = useCallback(
() =>
setAssistantState({
message: '',
status: 'idle',
messagesId: [],
conversationId: undefined
}),
[]
[client, clearAssistant]
)

const value = useMemo(
Expand Down
5 changes: 4 additions & 1 deletion src/assistant/AssistantWrapperDesktop.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import React from 'react'

import SearchBar from './Search/SearchBar'
import SearchProvider from './Search/SearchProvider'

const AssistantWrapperDesktop = () => {
return (
<div className="app-list-wrapper u-mb-3 u-mh-auto u-w-100">
<SearchBar />
<SearchProvider>
<SearchBar />
</SearchProvider>
</div>
)
}
Expand Down
8 changes: 3 additions & 5 deletions src/assistant/Conversations/ConversationBar.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useState, useRef } from 'react'
import { useParams } from 'react-router-dom'

import Icon from 'cozy-ui/transpiled/react/Icon'
import SearchBar from 'cozy-ui/transpiled/react/SearchBar'
Expand All @@ -11,17 +12,16 @@ import { useBreakpoints } from 'cozy-ui/transpiled/react/providers/Breakpoints'
import { useI18n } from 'cozy-ui/transpiled/react/providers/I18n'

import { useAssistant } from '../AssistantProvider'
import { useSearch } from '../Search/SearchProvider'

import styles from './styles.styl'

const ConversationBar = ({ assistantStatus }) => {
const { t } = useI18n()
const { isMobile } = useBreakpoints()
const { onAssistantExecute } = useAssistant()
const { clearSearch, delayedSetSearchValue } = useSearch()
const [inputValue, setInputValue] = useState('')
const inputRef = useRef()
const { conversationId } = useParams()

// to adjust input height for multiline when typing in it
useEventListener(inputRef.current, 'input', () => {
Expand All @@ -31,11 +31,9 @@ const ConversationBar = ({ assistantStatus }) => {

const handleClear = () => {
setInputValue('')
clearSearch()
}

const handleChange = ev => {
delayedSetSearchValue(ev.target.value)
setInputValue(ev.target.value)
}

Expand All @@ -45,7 +43,7 @@ const ConversationBar = ({ assistantStatus }) => {
}

const handleClick = () =>
onAssistantExecute(inputValue, () => {
onAssistantExecute({ value: inputValue, conversationId }, () => {
handleClear()
inputRef.current.style.height = 'auto'
})
Expand Down
7 changes: 4 additions & 3 deletions src/assistant/Search/SearchBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useNavigate } from 'react-router-dom'
import { useBreakpoints } from 'cozy-ui/transpiled/react/providers/Breakpoints'

import { useSearch } from './SearchProvider'
import { useAssistant } from '../AssistantProvider'
import { makeConversationId, useAssistant } from '../AssistantProvider'
import SearchBarMobile from './SearchBarMobile'
import SearchBarDesktop from './SearchBarDesktop'

Expand All @@ -21,8 +21,9 @@ const SearchBar = () => {
}

const handleClick = () => {
onAssistantExecute(inputValue)
navigate('assistant')
const conversationId = makeConversationId()
onAssistantExecute({ value: inputValue, conversationId })
navigate(`assistant/${conversationId}`)
// setTimeout usefull to prevent the field from emptying before the route is changed
// works because the modal appears on top of the view that carries the input and not instead of it.
setTimeout(() => {
Expand Down
11 changes: 4 additions & 7 deletions src/assistant/Views/AssistantDialog.jsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
import React from 'react'
import { useNavigate } from 'react-router-dom'
import { useNavigate, useParams } from 'react-router-dom'

import { FixedDialog } from 'cozy-ui/transpiled/react/CozyDialogs'
import { useBreakpoints } from 'cozy-ui/transpiled/react/providers/Breakpoints'

import { useSearch } from '../Search/SearchProvider'
import Conversation from '../Conversations/Conversation'
import ConversationBar from '../Conversations/ConversationBar'
import { useAssistant } from '../AssistantProvider'

const AssistantDialog = () => {
const { assistantState, clearAssistant } = useAssistant()
const { clearSearch } = useSearch()
const { assistantState } = useAssistant()
const { isMobile } = useBreakpoints()
const navigate = useNavigate()
const { conversationId } = useParams()

const onClose = () => {
navigate('..')
clearAssistant()
clearSearch()
}

return (
Expand All @@ -32,7 +29,7 @@ const AssistantDialog = () => {
divider: { className: 'u-dn' }
}}
title={isMobile ? ' ' : ' '}
content={<Conversation id={assistantState.conversationId} />}
content={<Conversation id={conversationId} />}
actions={<ConversationBar assistantStatus={assistantState.status} />}
onClose={onClose}
/>
Expand Down
22 changes: 15 additions & 7 deletions src/assistant/Views/SearchDialog.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { useNavigate } from 'react-router-dom'

import { FixedDialog } from 'cozy-ui/transpiled/react/CozyDialogs'

import { useAssistant } from '../AssistantProvider'
import SearchProvider from '../Search/SearchProvider'
import { makeConversationId, useAssistant } from '../AssistantProvider'
import ResultMenuContent from '../ResultMenu/ResultMenuContent'
import { useSearch } from '../Search/SearchProvider'
import SearchBar from '../Search/SearchBar'
Expand All @@ -12,16 +13,15 @@ import SearchSubmitFab from '../Search/SearchSubmitFab'
const SearchDialog = () => {
const { onAssistantExecute } = useAssistant()
const navigate = useNavigate()
const { searchValue, clearSearch } = useSearch()
const { searchValue } = useSearch()

const handleClick = () => {
onAssistantExecute(searchValue)
clearSearch()
navigate('../assistant', { replace: true })
const conversationId = makeConversationId()
onAssistantExecute({ value: searchValue, conversationId })
navigate(`../assistant/${conversationId}`, { replace: true })
}

const handleClose = () => {
clearSearch()
navigate('..')
}

Expand All @@ -48,4 +48,12 @@ const SearchDialog = () => {
)
}

export default SearchDialog
const SearchDialogWithProviders = () => {
return (
<SearchProvider>
<SearchDialog />
</SearchProvider>
)
}

export default SearchDialogWithProviders
29 changes: 13 additions & 16 deletions src/components/AppWrapper.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import { useWallpaperContext } from 'hooks/useWallpaperContext'
import schema from '../schema'
import { ConditionalWrapper } from './ConditionalWrapper'
import AssistantProvider from 'assistant/AssistantProvider'
import SearchProvider from 'assistant/Search/SearchProvider'
import { WallPaperProvider } from 'hooks/useWallpaperContext'
import { SectionsProvider } from './Sections/SectionsContext'
const dictRequire = lang => require(`locales/${lang}.json`)
Expand Down Expand Up @@ -118,22 +117,20 @@ const AppWrapper = ({ children }) => {
<ThemeProvider>
<AlertProvider>
<AssistantProvider>
<SearchProvider>
<ReduxProvider store={store}>
<ConditionalWrapper
condition={persistor}
wrapper={children => (
<PersistGate loading={null} persistor={persistor}>
{children}
</PersistGate>
)}
>
<Inner lang={lang} context={context}>
<ReduxProvider store={store}>
<ConditionalWrapper
condition={persistor}
wrapper={children => (
<PersistGate loading={null} persistor={persistor}>
{children}
</Inner>
</ConditionalWrapper>
</ReduxProvider>
</SearchProvider>
</PersistGate>
)}
>
<Inner lang={lang} context={context}>
{children}
</Inner>
</ConditionalWrapper>
</ReduxProvider>
</AssistantProvider>
</AlertProvider>
</ThemeProvider>
Expand Down
5 changes: 4 additions & 1 deletion src/containers/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,10 @@ const App = ({ accounts, konnectors, triggers }) => {
/>
}
>
<Route path="assistant" element={<AssistantDialog />} />
<Route
path="assistant/:conversationId"
element={<AssistantDialog />}
/>
<Route path="search" element={<SearchDialog />} />

<Route path=":konnectorSlug/*" element={<Konnector />} />
Expand Down
Loading