yjs.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. updateHasYdocsNewerThanLatestRevision(hasYdocsNewerThanLatestRevision: boolean): void
  10. updateAwarenessStateSize(awarenessStateSize: number): void
  11. }
  12. export const useCurrentPageYjsData = (): SWRResponse<CurrentPageYjsData, Error> & CurrentPageYjsDataUtils => {
  13. const { data: currentPageId } = useCurrentPageId();
  14. const key = currentPageId != null
  15. ? `/page/${currentPageId}/yjs-data`
  16. : null;
  17. const swrResponse = useSWRStatic<CurrentPageYjsData, Error>(key, undefined);
  18. const updateHasYdocsNewerThanLatestRevision = useCallback((hasYdocsNewerThanLatestRevision: boolean) => {
  19. swrResponse.mutate({ ...swrResponse.data, hasYdocsNewerThanLatestRevision });
  20. }, [swrResponse]);
  21. const updateAwarenessStateSize = useCallback((awarenessStateSize: number) => {
  22. swrResponse.mutate({ ...swrResponse.data, awarenessStateSize });
  23. }, [swrResponse]);
  24. return Object.assign(swrResponse, { updateHasYdocsNewerThanLatestRevision, updateAwarenessStateSize });
  25. };
  26. export const useSWRMUTxCurrentPageYjsData = (): SWRMutationResponse<CurrentPageYjsData, Error> => {
  27. const { data: currentPageId } = useCurrentPageId();
  28. const key = currentPageId != null
  29. ? `/page/${currentPageId}/yjs-data`
  30. : null;
  31. return useSWRMutation(
  32. key,
  33. endpoint => apiv3Get<{ yjsData: CurrentPageYjsData }>(endpoint).then(result => result.data.yjsData),
  34. { populateCache: true, revalidate: false },
  35. );
  36. };