hooks.tsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { useEffect, useState } from 'react';
  2. import { usePageAccessoriesModal, PageAccessoriesModalContents } from '~/stores/modal';
  3. function getURLQueryParamValue(key: string) {
  4. // window.location.href is page URL;
  5. const queryStr: URLSearchParams = new URL(window.location.href).searchParams;
  6. return queryStr.get(key);
  7. }
  8. // https://regex101.com/r/YHTDsr/1
  9. const queryCompareFormat = /^([0-9a-f]{24})...([0-9a-f]{24})$/i;
  10. export const useAutoOpenModalByQueryParam = (): void => {
  11. const [isArleadyMounted, setIsArleadyMounted] = useState(false);
  12. const { data: status, open: openPageAccessories } = usePageAccessoriesModal();
  13. useEffect(() => {
  14. if (isArleadyMounted) {
  15. return;
  16. }
  17. if (status == null || status.isOpened === true) {
  18. return;
  19. }
  20. const pageIdParams = getURLQueryParamValue('compare');
  21. if (pageIdParams != null) {
  22. const matches = pageIdParams.match(queryCompareFormat);
  23. if (matches == null) {
  24. return;
  25. }
  26. // open History
  27. openPageAccessories(PageAccessoriesModalContents.PageHistory);
  28. }
  29. setIsArleadyMounted(true);
  30. }, [openPageAccessories, status, isArleadyMounted]);
  31. };
  32. type ComparingRevisionIds = {
  33. sourceRevisionId: string,
  34. targetRevisionId: string,
  35. }
  36. export const useAutoComparingRevisionsByQueryParam = (): ComparingRevisionIds | null => {
  37. const [isArleadyMounted, setIsArleadyMounted] = useState(false);
  38. const [sourceRevisionId, setSourceRevisionId] = useState<string>();
  39. const [targetRevisionId, setTargetRevisionId] = useState<string>();
  40. useEffect(() => {
  41. if (isArleadyMounted) {
  42. return;
  43. }
  44. const pageIdParams = getURLQueryParamValue('compare');
  45. if (pageIdParams != null) {
  46. const matches = pageIdParams.match(queryCompareFormat);
  47. if (matches != null) {
  48. const [, source, target] = matches;
  49. setSourceRevisionId(source);
  50. setTargetRevisionId(target);
  51. }
  52. }
  53. setIsArleadyMounted(true);
  54. }, [isArleadyMounted]);
  55. return sourceRevisionId != null && targetRevisionId != null
  56. ? { sourceRevisionId, targetRevisionId }
  57. : null;
  58. };