use-chat-pane.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { useLayoutContext } from '@/shared/context/layout-context'
  2. import useCollapsiblePanel from '@/features/ide-react/hooks/use-collapsible-panel'
  3. import useDebounce from '@/shared/hooks/use-debounce'
  4. import { useCallback, useEffect, useRef, useState } from 'react'
  5. import { ImperativePanelHandle } from 'react-resizable-panels'
  6. export const useChatPane = () => {
  7. const { chatIsOpen: isOpen, setChatIsOpen: setIsOpen } = useLayoutContext()
  8. const [resizing, setResizing] = useState(false)
  9. const panelRef = useRef<ImperativePanelHandle>(null)
  10. // Keep track of a debounced local state variable for panel openness and
  11. // only update the external openness state when the debounced value changes.
  12. // This prevents successive calls to onCollapse and onExpand from
  13. // react-resizable-panels updating the openness state multiple times in quick
  14. // succession, which causes confusing behaviour that is different in React 17
  15. // and 18. Collapsing the chat pane on initialization is necessary because
  16. // react-resizable-panels does not provide a way to specify both that a panel
  17. // should be collapsed and a default size for the panel when expanded.
  18. const [localIsOpen, setLocalIsOpen] = useState(isOpen)
  19. const debouncedLocalIsOpen = useDebounce(localIsOpen, 100)
  20. useCollapsiblePanel(isOpen, panelRef)
  21. const togglePane = useCallback(() => {
  22. setIsOpen(value => !value)
  23. }, [setIsOpen])
  24. const handlePaneExpand = useCallback(() => {
  25. setLocalIsOpen(true)
  26. }, [])
  27. const handlePaneCollapse = useCallback(() => {
  28. setLocalIsOpen(false)
  29. }, [])
  30. useEffect(() => {
  31. setIsOpen(debouncedLocalIsOpen)
  32. }, [debouncedLocalIsOpen, setIsOpen])
  33. return {
  34. isOpen,
  35. panelRef,
  36. resizing,
  37. setResizing,
  38. togglePane,
  39. handlePaneExpand,
  40. handlePaneCollapse,
  41. }
  42. }