useCommandMenuTelemetry.ts83 lines · main
| 1 | 'use client' |
| 2 | |
| 3 | import type { |
| 4 | CommandMenuClosedEvent, |
| 5 | CommandMenuCommandClickedEvent, |
| 6 | CommandMenuOpenedEvent, |
| 7 | CommandMenuSearchSubmittedEvent, |
| 8 | } from 'common/telemetry-constants' |
| 9 | import { useCallback } from 'react' |
| 10 | |
| 11 | import { useCommandMenuTelemetryContext } from './useCommandMenuTelemetryContext' |
| 12 | import { useCommandMenuOpen } from './viewHooks' |
| 13 | |
| 14 | export type CommandMenuTelemetryCallback = ( |
| 15 | event: |
| 16 | | CommandMenuOpenedEvent |
| 17 | | CommandMenuClosedEvent |
| 18 | | CommandMenuCommandClickedEvent |
| 19 | | CommandMenuSearchSubmittedEvent |
| 20 | ) => void |
| 21 | |
| 22 | export interface UseCommandMenuTelemetryOptions { |
| 23 | /** |
| 24 | * The app where the command menu is being used |
| 25 | */ |
| 26 | app: 'studio' | 'docs' | 'www' |
| 27 | /** |
| 28 | * Optional callback to send telemetry events |
| 29 | */ |
| 30 | onTelemetry?: CommandMenuTelemetryCallback |
| 31 | } |
| 32 | |
| 33 | export function useCommandMenuTelemetry({ app, onTelemetry }: UseCommandMenuTelemetryOptions) { |
| 34 | const sendTelemetry = useCallback( |
| 35 | ( |
| 36 | triggerType: 'keyboard_shortcut' | 'search_input' = 'search_input', |
| 37 | groups: Partial<CommandMenuOpenedEvent['groups']> = {}, |
| 38 | triggerLocation?: string |
| 39 | ) => { |
| 40 | if (!onTelemetry) return |
| 41 | |
| 42 | const event: CommandMenuOpenedEvent = { |
| 43 | action: 'command_menu_opened', |
| 44 | properties: { |
| 45 | trigger_type: triggerType, |
| 46 | trigger_location: triggerLocation, |
| 47 | app, |
| 48 | }, |
| 49 | groups: groups as CommandMenuOpenedEvent['groups'], |
| 50 | } |
| 51 | |
| 52 | onTelemetry(event) |
| 53 | }, |
| 54 | [app, onTelemetry] |
| 55 | ) |
| 56 | |
| 57 | return { sendTelemetry } |
| 58 | } |
| 59 | |
| 60 | export const useCommandMenuOpenedTelemetry: ( |
| 61 | trigger?: 'keyboard_shortcut' | 'search_input' |
| 62 | ) => () => void = (trigger = 'search_input') => { |
| 63 | const telemetryContext = useCommandMenuTelemetryContext() |
| 64 | const open = useCommandMenuOpen() |
| 65 | |
| 66 | const sendTelemetry = useCallback(() => { |
| 67 | if (!open && telemetryContext?.onTelemetry) { |
| 68 | const event = { |
| 69 | action: 'command_menu_opened' as const, |
| 70 | properties: { |
| 71 | trigger_type: trigger, |
| 72 | trigger_location: 'user_dropdown_menu', |
| 73 | app: telemetryContext.app, |
| 74 | }, |
| 75 | groups: {}, |
| 76 | } |
| 77 | |
| 78 | telemetryContext.onTelemetry(event) |
| 79 | } |
| 80 | }, [open, trigger, telemetryContext]) |
| 81 | |
| 82 | return sendTelemetry |
| 83 | } |