viewHooks.ts83 lines · main
| 1 | 'use client' |
| 2 | |
| 3 | import { useCallback, useLayoutEffect, useRef } from 'react' |
| 4 | import { useSnapshot } from 'valtio' |
| 5 | |
| 6 | import { useCommandContext } from '../../internal/Context' |
| 7 | import { type DialogSize } from '../../internal/state/viewState.types' |
| 8 | |
| 9 | const useCommandMenuInitiated = () => { |
| 10 | const { viewState } = useCommandContext() |
| 11 | const { initiated } = useSnapshot(viewState) |
| 12 | return initiated |
| 13 | } |
| 14 | |
| 15 | const useCommandMenuOpen = () => { |
| 16 | const { viewState } = useCommandContext() |
| 17 | const { open } = useSnapshot(viewState) |
| 18 | return open |
| 19 | } |
| 20 | |
| 21 | const useSetCommandMenuOpen = () => { |
| 22 | const { viewState } = useCommandContext() |
| 23 | const { setOpen } = useSnapshot(viewState) |
| 24 | return setOpen |
| 25 | } |
| 26 | |
| 27 | const useResetCommandMenu = () => { |
| 28 | const { queryState, pagesState } = useCommandContext() |
| 29 | return useCallback(() => { |
| 30 | queryState.setQuery('') |
| 31 | pagesState.pageStack.length = 0 |
| 32 | }, [queryState, pagesState]) |
| 33 | } |
| 34 | |
| 35 | const useToggleCommandMenu = () => { |
| 36 | const { viewState } = useCommandContext() |
| 37 | const { toggleOpen } = useSnapshot(viewState) |
| 38 | return toggleOpen |
| 39 | } |
| 40 | |
| 41 | const useCommandMenuSize = () => { |
| 42 | const { viewState } = useCommandContext() |
| 43 | const { size } = useSnapshot(viewState) |
| 44 | return size |
| 45 | } |
| 46 | |
| 47 | const useSetCommandMenuSize = (newSize: DialogSize) => { |
| 48 | const { viewState } = useCommandContext() |
| 49 | const { setSize, size } = useSnapshot(viewState) |
| 50 | |
| 51 | const originalSize = useRef(size) |
| 52 | |
| 53 | useLayoutEffect(() => { |
| 54 | setSize(newSize) |
| 55 | return () => setSize(originalSize.current) |
| 56 | }, [setSize]) |
| 57 | } |
| 58 | |
| 59 | const useSetupCommandMenuTouchEvents = () => { |
| 60 | const { viewState } = useCommandContext() |
| 61 | const { setTouchHandlers } = useSnapshot(viewState) |
| 62 | |
| 63 | return setTouchHandlers |
| 64 | } |
| 65 | |
| 66 | const useCommandMenuTouchGestures = () => { |
| 67 | const { viewState } = useCommandContext() |
| 68 | const { touchHandlers } = useSnapshot(viewState) |
| 69 | |
| 70 | return touchHandlers |
| 71 | } |
| 72 | |
| 73 | export { |
| 74 | useCommandMenuInitiated, |
| 75 | useCommandMenuOpen, |
| 76 | useResetCommandMenu, |
| 77 | useSetCommandMenuOpen, |
| 78 | useToggleCommandMenu, |
| 79 | useCommandMenuSize, |
| 80 | useSetCommandMenuSize, |
| 81 | useSetupCommandMenuTouchEvents, |
| 82 | useCommandMenuTouchGestures, |
| 83 | } |