summaryrefslogtreecommitdiff
path: root/apps/web/src/hooks/use-keybinding-conflicts.ts
blob: cc5dd34007715ae34ae80b049d6f19499300bb08 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"use client";

import { useMemo } from "react";
import { useKeybindingsStore } from "@/stores/keybindings-store";
import { ActionWithOptionalArgs } from "@/constants/actions";

export interface KeybindingConflictInfo {
  key: string;
  actions: ActionWithOptionalArgs[];
  isConflict: boolean;
}

export const useKeybindingConflicts = () => {
  const { keybindings } = useKeybindingsStore();

  const conflicts = useMemo(() => {
    const keyToActions: Record<string, ActionWithOptionalArgs[]> = {};
    const conflictList: KeybindingConflictInfo[] = [];

    // Group actions by key
    Object.entries(keybindings).forEach(([key, action]) => {
      if (!keyToActions[key]) {
        keyToActions[key] = [];
      }
      keyToActions[key].push(action);
    });

    // Find conflicts
    Object.entries(keyToActions).forEach(([key, actions]) => {
      const uniqueActions = [...new Set(actions)];
      conflictList.push({
        key,
        actions: uniqueActions,
        isConflict: uniqueActions.length > 1,
      });
    });

    return conflictList.filter((item) => item.isConflict);
  }, [keybindings]);

  const hasConflicts = conflicts.length > 0;

  const getConflictsForKey = (key: string): KeybindingConflictInfo | null => {
    return conflicts.find((conflict) => conflict.key === key) || null;
  };

  const getConflictsForAction = (
    action: ActionWithOptionalArgs
  ): KeybindingConflictInfo[] => {
    return conflicts.filter((conflict) => conflict.actions.includes(action));
  };

  return {
    conflicts,
    hasConflicts,
    getConflictsForKey,
    getConflictsForAction,
  };
};