|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { useEffect, useRef } from 'react' |
| 4 | +import { LandingPromptStorage } from '@/lib/browser-storage' |
| 5 | +import { createLogger } from '@/lib/logs/console/logger' |
| 6 | + |
| 7 | +const logger = createLogger('useLandingPrompt') |
| 8 | + |
| 9 | +interface UseLandingPromptProps { |
| 10 | + /** |
| 11 | + * Whether the copilot is fully initialized and ready to receive input |
| 12 | + */ |
| 13 | + isInitialized: boolean |
| 14 | + |
| 15 | + /** |
| 16 | + * Callback to set the input value in the copilot |
| 17 | + */ |
| 18 | + setInputValue: (value: string) => void |
| 19 | + |
| 20 | + /** |
| 21 | + * Callback to focus the copilot input |
| 22 | + */ |
| 23 | + focusInput: () => void |
| 24 | + |
| 25 | + /** |
| 26 | + * Whether a message is currently being sent (prevents overwriting during active chat) |
| 27 | + */ |
| 28 | + isSendingMessage: boolean |
| 29 | + |
| 30 | + /** |
| 31 | + * Current input value (to avoid overwriting if user has already typed) |
| 32 | + */ |
| 33 | + currentInputValue: string |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * Custom hook to handle landing page prompt retrieval and population |
| 38 | + * |
| 39 | + * When a user enters a prompt on the landing page and signs up/logs in, |
| 40 | + * this hook retrieves that prompt from localStorage and populates it |
| 41 | + * in the copilot input once the copilot is initialized. |
| 42 | + * |
| 43 | + * @param props - Configuration for landing prompt handling |
| 44 | + */ |
| 45 | +export function useLandingPrompt(props: UseLandingPromptProps) { |
| 46 | + const { isInitialized, setInputValue, focusInput, isSendingMessage, currentInputValue } = props |
| 47 | + |
| 48 | + const hasCheckedRef = useRef(false) |
| 49 | + |
| 50 | + useEffect(() => { |
| 51 | + // Only check once when copilot is first initialized |
| 52 | + if (!isInitialized || hasCheckedRef.current || isSendingMessage) { |
| 53 | + return |
| 54 | + } |
| 55 | + |
| 56 | + // If user has already started typing, don't override |
| 57 | + if (currentInputValue && currentInputValue.trim().length > 0) { |
| 58 | + hasCheckedRef.current = true |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + // Try to retrieve the stored prompt (max age: 24 hours) |
| 63 | + const prompt = LandingPromptStorage.consume() |
| 64 | + |
| 65 | + if (prompt) { |
| 66 | + logger.info('Retrieved landing page prompt, populating copilot input') |
| 67 | + setInputValue(prompt) |
| 68 | + |
| 69 | + // Focus the input after a brief delay to ensure DOM is ready |
| 70 | + setTimeout(() => { |
| 71 | + focusInput() |
| 72 | + }, 150) |
| 73 | + } |
| 74 | + |
| 75 | + hasCheckedRef.current = true |
| 76 | + }, [isInitialized, setInputValue, focusInput, isSendingMessage, currentInputValue]) |
| 77 | +} |
0 commit comments