Docs
Usage
Static Commands

Static Commands

Static commands are command structures that are run at the time of user input. For example, you can create special structures that are triggered when the user enters @.

magic-input provides two main structures for defining static commands: keys and custom. These structures allow you to create flexible and powerful input interactions.

Keys:

The keys structure is designed for defining fixed command patterns. These commands can include parameters and are pre-configured to perform specific actions when invoked. For example:

const magic: MagicItem[] = [
  {
    keys: [
      {
        name: "Hello",
        parameters: [],
        fn: (params, context) => {
          if (context.value.length > 0) {
            setInputValue(context.value);
            setParameters(params);
            setFunctionName(context.functionName);
          }
        },
        type: "static",
      },
      {
        name: "username",
        parameters: [%<Username>%, %<Message>%],
        fn: (params, context) => {
          setOutput(`${params[0]} says ${params[1]}`);
        },
        type: "static",
      },
    ],
  },
];
 
<MagicInput magic={magic} placeholder="Type a command..." />;

Custom:

The custom structure allows for more advanced and flexible command definitions. Using regex, you can define multiple command patterns and fully customize their behavior. This structure is ideal when you need to create dynamic and complex input handling scenarios.

const magic: MagicItem[] = [
  {
    custom: [
      {
        functionName: "CustomGreeting",
        regex: /\/hello/g,
        fn: (context) => {
          if (context.regexMatched) {
            setOutput(`Custom greeting: ${context.value}`);
          }
        },
        type: "static",
        parameters: false,
        dynamicFunc: false,
      },
      {
        functionName: "SendButton",
        regex: /%ACTIVE_SEND_BUTTON%/,
        fn: async (context) => {
          setRunCommand(context?.regexMatched || false);
        },
        type: "static",
        parameters: false,
        dynamicFunc: true,
      },
    ],
  },
];
 
<MagicInput
  magic={magic}
  placeholder="Type a custom command..."
/>

In this example:

  • CustomGreeting: A custom command that triggers when the input matches the /hello pattern.
  • SendButton: A dynamic command that activates a send button based on user input.

Summary:

  • Keys: Ideal for fixed, pre-defined command structures with or without parameters.
  • Custom: Best for creating highly customizable commands using regex to match and process complex input patterns.

These structures give you the flexibility to build user-friendly inputs that cater to a wide range of use cases in your React applications.