hooks.tsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { useEffect, useState } from 'react';
  2. import { usePageAccessoriesModal, usePageAccessoriesModalActions, PageAccessoriesModalContents } from '~/states/ui/modal/page-accessories';
  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 status = usePageAccessoriesModal();
  13. const { open: openPageAccessories } = usePageAccessoriesModalActions();
  14. useEffect(() => {
  15. if (isArleadyMounted) {
  16. return;
  17. }
  18. if (status == null || status.isOpened === true) {
  19. return;
  20. }
  21. const pageIdParams = getURLQueryParamValue('compare');
  22. if (pageIdParams != null) {
  23. const matches = pageIdParams.match(queryCompareFormat);
  24. if (matches == null) {
  25. return;
  26. }
  27. // open History
  28. openPageAccessories(PageAccessoriesModalContents.PageHistory);
  29. }
  30. setIsArleadyMounted(true);
  31. }, [openPageAccessories, status, isArleadyMounted]);
  32. };
  33. type ComparingRevisionIds = {
  34. sourceRevisionId: string,
  35. targetRevisionId: string,
  36. }
  37. export const useAutoComparingRevisionsByQueryParam = (): ComparingRevisionIds | null => {
  38. const [isArleadyMounted, setIsArleadyMounted] = useState(false);
  39. const [sourceRevisionId, setSourceRevisionId] = useState<string>();
  40. const [targetRevisionId, setTargetRevisionId] = useState<string>();
  41. useEffect(() => {
  42. if (isArleadyMounted) {
  43. return;
  44. }
  45. const pageIdParams = getURLQueryParamValue('compare');
  46. if (pageIdParams != null) {
  47. const matches = pageIdParams.match(queryCompareFormat);
  48. if (matches != null) {
  49. const [, source, target] = matches;
  50. setSourceRevisionId(source);
  51. setTargetRevisionId(target);
  52. }
  53. }
  54. setIsArleadyMounted(true);
  55. }, [isArleadyMounted]);
  56. return sourceRevisionId != null && targetRevisionId != null
  57. ? { sourceRevisionId, targetRevisionId }
  58. : null;
  59. };