yjs.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { useCallback } from 'react';
  2. import { useSWRStatic } from '@growi/core/dist/swr';
  3. import type { SWRResponse } from 'swr';
  4. import useSWRMutation, { type SWRMutationResponse } from 'swr/mutation';
  5. import { apiv3Get } from '~/client/util/apiv3-client';
  6. import type { CurrentPageYjsData } from '~/interfaces/yjs';
  7. import { useCurrentPageId } from './page';
  8. type CurrentPageYjsDataUtils = {
  9. updateHasRevisionBodyDiff(hasRevisionBodyDiff: boolean): void
  10. updateAwarenessStateSize(awarenessStateSize: number): void
  11. }
  12. export const useCurrentPageYjsData = (): SWRResponse<CurrentPageYjsData, Error> & CurrentPageYjsDataUtils => {
  13. const swrResponse = useSWRStatic<CurrentPageYjsData, Error>('currentPageYjsData', undefined);
  14. const updateHasRevisionBodyDiff = useCallback((hasRevisionBodyDiff: boolean) => {
  15. swrResponse.mutate({ ...swrResponse.data, hasRevisionBodyDiff });
  16. }, [swrResponse]);
  17. const updateAwarenessStateSize = useCallback((awarenessStateSize: number) => {
  18. swrResponse.mutate({ ...swrResponse.data, awarenessStateSize });
  19. }, [swrResponse]);
  20. return {
  21. ...swrResponse, updateHasRevisionBodyDiff, updateAwarenessStateSize,
  22. };
  23. };
  24. export const useSWRMUTxCurrentPageYjsData = (): SWRMutationResponse<CurrentPageYjsData, Error> => {
  25. const key = 'currentPageYjsData';
  26. const { data: currentPageId } = useCurrentPageId();
  27. return useSWRMutation(
  28. key,
  29. () => apiv3Get<{ yjsData: CurrentPageYjsData }>(`/page/${currentPageId}/yjs-data`).then(result => result.data.yjsData),
  30. { populateCache: true, revalidate: false },
  31. );
  32. };