Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript
7.5 KB
Raw Blame
// src/hooks/useMenuActions.ts
import {useEffect} from 'react';
import {useNavigate} from 'react-router-dom';
import {useTranslation} from 'react-i18next';
import {useAppDispatch, useAppSelector} from '@/store';
import {camerasConnectOrUpdate, closeCameras, detectCameras, pauseUnpauseCameras} from '@/store/slices/cameras';
import {stopRecording} from '@/store/slices/recording';
import {selectVideoLoadFolder} from '@/store/slices/videos';
import {activeRecordingCleared, activeRecordingSet} from '@/store/slices/active-recording';
import {calibrationConfigUpdated} from '@/store/slices/calibration/calibration-slice';
import {pipelineSnackbarShown} from '@/store/slices/pipelines';
// import { localeChanged, selectLocale, localeToggled } from '@/store/slices/settings';
import {isElectron, useElectronIPC} from '@/services/electron-ipc/electron-ipc';
import {recordingsDirFromBaseFolder} from '@/utils/dataFolder';
import {SUPPORTED_LOCALES} from '@/i18n';
import {useTutorial} from '@/components/tutorial';
import type {MenuAction} from '../../electron/main/services/menu-builder';

// i18n keys that the menu builder needs for translated labels
const MENU_LABEL_KEYS = [
    'menuFile',
    'menuView',
    'menuCamera',
    'menuRecording',
    'menuData',
    'menuLoadTestData',
    'menuClearActiveRecording',
    'menuHelp',
    'menuTakeTour',
    'menuDetectCameras',
    'menuConnectCameras',
    'menuCloseAllCameras',
    'menuOpenRecordingFolder',
    'menuToggleSidebar',
    'menuToggleTheme',
    'menuToggleFullScreen',
    'menuPauseUnpause',
    'menuConnectApplySettings',
    'menuCloseAll',
    'menuDocumentation',
    'menuGitHubRepository',
    'menuReportIssue',
    'menuAbout',
    'menuCheckForUpdates',
    'menuPlayback',
    'menuShowPipelineProgress',
    'home',
    'cameras',
    'settings',
    'startRecording',
    'stopRecording',
    'language',
] as const;

// Build the locale entries array from the SUPPORTED_LOCALES config (once)
const LOCALE_ENTRIES = Object.entries(SUPPORTED_LOCALES).map(([code, { label }]) => ({
    code,
    label,
}));

interface UseMenuActionsParams {
    onToggleSidebar: () => void;
}

export function useMenuActions({ onToggleSidebar }: UseMenuActionsParams): void {
    const dispatch = useAppDispatch();
    const navigate = useNavigate();
    const { t, i18n } = useTranslation();
    const { api } = useElectronIPC();
    const { startTour } = useTutorial();

    const isRecording = useAppSelector((state) => state.recording.isRecording);
    // const currentLocale = useAppSelector(selectLocale);

    // Send translated menu labels + locale list to the main process whenever the language changes
    useEffect(() => {
        if (!isElectron() || !window.electronAPI?.sendMenuLabels) return;

        const labels: Record<string, string> = {};
        for (const key of MENU_LABEL_KEYS) {
            labels[key] = t(key);
        }
        window.electronAPI.sendMenuLabels({
            labels,
            locales: LOCALE_ENTRIES,
            // currentLocale,
        });
    }, [t, i18n.language]);//, currentLocale]);

    // Listen for menu actions dispatched from the native menu
    useEffect(() => {
        if (!isElectron() || !window.electronAPI?.onMenuAction) return;

        const cleanup = window.electronAPI.onMenuAction(async (action: string) => {
            // Handle locale change actions (dynamic pattern: "change-locale:xx")
            if (action.startsWith('change-locale:')) {
                const localeCode = action.slice('change-locale:'.length);
                // if (localeCode in SUPPORTED_LOCALES) {
                //     dispatch(localeChanged(localeCode as SupportedLocale));
                // }
                return;
            }

            const menuAction = action as MenuAction;

            switch (menuAction) {
                // Navigation
                case 'navigate-home':
                    navigate('/');
                    break;
                case 'navigate-cameras':
                    navigate('/cameras');
                    break;
                case 'navigate-playback':
                    navigate('/playback');
                    break;
                case 'navigate-settings':
                    window.dispatchEvent(new CustomEvent('open-settings'));
                    break;

                // View
                case 'toggle-sidebar':
                    onToggleSidebar();
                    break;
                case 'toggle-fullscreen': {
                    if (document.fullscreenElement) {
                        document.exitFullscreen();
                    } else {
                        document.documentElement.requestFullscreen();
                    }
                    break;
                }

                // Camera actions
                case 'detect-cameras':
                    dispatch(detectCameras());
                    break;
                case 'connect-cameras':
                    dispatch(camerasConnectOrUpdate());
                    break;
                case 'close-cameras':
                    dispatch(closeCameras());
                    break;
                case 'pause-unpause-cameras':
                    dispatch(pauseUnpauseCameras());
                    break;

                // Locale toggle
                case 'toggle-locale':
                    // dispatch(localeToggled());
                    break;

                // Recording actions
                case 'start-recording':
                    if (!isRecording) {
                        navigate('/cameras');
                    }
                    break;
                case 'stop-recording':
                    if (isRecording) {
                        dispatch(stopRecording());
                    }
                    break;

                // Updates
                case 'check-for-updates':
                    window.dispatchEvent(new CustomEvent('check-for-updates'));
                    break;

                // Help
                case 'start-tutorial':
                    startTour('getting-started');
                    break;

                // File actions
                case 'open-recording-folder':
                    dispatch(selectVideoLoadFolder());
                    navigate('/playback');
                    break;
                case 'show-pipeline-progress':
                    dispatch(pipelineSnackbarShown());
                    break;

                // Data actions
                case 'load-test-data': {
                    if (!api) break;
                    try {
                        const baseFolder: string = await api.fileSystem.getBaseDataFolder.query();
                        const baseDirectory = recordingsDirFromBaseFolder(baseFolder);
                        dispatch(activeRecordingSet({
                            baseDirectory,
                            recordingName: 'freemocap_test_data',
                            origin: 'browsed',
                        }));
                        dispatch(calibrationConfigUpdated({
                            charucoBoard: { squares_x: 7, squares_y: 5, square_length_mm: 58 },
                        }));
                    } catch (error) {
                        console.error('Failed to resolve home directory for test data:', error);
                    }
                    break;
                }
                case 'clear-active-recording':
                    dispatch(activeRecordingCleared());
                    break;
            }
        });

        return cleanup;
    }, [dispatch, navigate, isRecording, onToggleSidebar, api, startTour]);
}