command.ts 674 B

12345678910111213141516171819202122232425262728
  1. import { useSearchParams } from "react-router-dom";
  2. type Command = (param: string) => void;
  3. interface Commands {
  4. fill?: Command;
  5. submit?: Command;
  6. mask?: Command;
  7. }
  8. export function useCommand(commands: Commands = {}) {
  9. const [searchParams, setSearchParams] = useSearchParams();
  10. if (commands === undefined) return;
  11. let shouldUpdate = false;
  12. searchParams.forEach((param, name) => {
  13. const commandName = name as keyof Commands;
  14. if (typeof commands[commandName] === "function") {
  15. commands[commandName]!(param);
  16. searchParams.delete(name);
  17. shouldUpdate = true;
  18. }
  19. });
  20. if (shouldUpdate) {
  21. setSearchParams(searchParams);
  22. }
  23. }