All files / src/utils/hooks/slash useSlashCommand.tsx

30.76% Statements 8/26
0% Branches 0/6
18.18% Functions 2/11
28% Lines 7/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 60 61 62 63 64 65 66 67 68                              66x       4x   4x         4x                                       4x       4x                         4x        
import { useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { startsWithPropKey } from "@utils/StringUtils";
import { DisplayMode } from '@props/RecordProps';
import { getOriginalClassName } from "./alias";
 
type Command = {
  [propName: string]: (parameters: Array<string>) => void;
};
 
type UseSlashCommandReturnType = {
  processSlashCommand: (content: string) => void;
  isSlashCommand: (content: string) => boolean;
};
 
export const useSlashCommand = (
  handleSetConversationBarrier: () => void,
  setDisplay: (display: DisplayMode) => void,
): UseSlashCommandReturnType => {
  const navigate = useNavigate();
 
  const createSlashCmd = useCallback((parameters: Array<string>): void => {
    const domainName = getOriginalClassName(parameters[0]);
    navigate(`/${domainName}/create`);
  }, [navigate]);
 
  const commands: Command = useMemo(() => ({
    '/reset': handleSetConversationBarrier,
    '/bye': () => setDisplay("minimal"),
    '/expand': () => setDisplay("maximal"),
    '/collapse': () => setDisplay("normal"),
    // Follow slash commands are in internal alpha testing phase
    '/list': (parameters: Array<string>) => {
      const domainName = getOriginalClassName(parameters[0]);
      navigate(`/${domainName}/list`);
    },
    '/create': createSlashCmd,
    '/new': createSlashCmd,
    '/inbox': () => {
      navigate(`/inbox`);
    },
    '/dashboard': () => {
      navigate(`/`);
    },
  }), [setDisplay, navigate, handleSetConversationBarrier, createSlashCmd]);
 
  const isSlashCommand = useCallback((content: string) => {
    return startsWithPropKey(content, commands);
  }, [commands]);
 
  const processSlashCommand = useCallback((content: string) => {
    if (isSlashCommand(content)) {
      if (commands[content]) {
        commands[content]([]);
      } else if (content.includes(" ")) {
        const action = content.split(" ")[0];
        const parameters = content.split(" ").slice(1);
        commands[action]?.(parameters);
        setDisplay("normal");
      }
    }
  }, [commands, setDisplay, isSlashCommand]);
 
  return { processSlashCommand, isSlashCommand };
};
 
export default useSlashCommand;