editor.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import type { Nullable } from '@growi/core';
  2. import { type SWRResponseWithUtils, withUtils } from '@growi/core/dist/swr';
  3. import type { EditorSettings } from '@growi/editor';
  4. import useSWR, { type SWRResponse } from 'swr';
  5. import useSWRImmutable from 'swr/immutable';
  6. import { apiGet } from '~/client/util/apiv1-client';
  7. import { apiv3Get, apiv3Put } from '~/client/util/apiv3-client';
  8. import type { SlackChannels } from '~/interfaces/user-trigger-notification';
  9. import { useIsGuestUser, useIsReadOnlyUser } from '~/states/context';
  10. import { useCurrentUser } from '~/states/global';
  11. type EditorSettingsOperation = {
  12. update: (updateData: Partial<EditorSettings>) => Promise<void>;
  13. };
  14. // TODO: Enable localStorageMiddleware
  15. // - Unabling localStorageMiddleware occurrs a flickering problem when loading theme.
  16. // - see: https://github.com/growilabs/growi/pull/6781#discussion_r1000285786
  17. export const useEditorSettings = (): SWRResponseWithUtils<
  18. EditorSettingsOperation,
  19. EditorSettings,
  20. Error
  21. > => {
  22. const currentUser = useCurrentUser();
  23. const isGuestUser = useIsGuestUser();
  24. const isReadOnlyUser = useIsReadOnlyUser();
  25. const swrResult = useSWRImmutable(
  26. isGuestUser || isReadOnlyUser
  27. ? null
  28. : ['/personal-setting/editor-settings', currentUser?.username],
  29. ([endpoint]) => {
  30. return apiv3Get(endpoint).then((result) => result.data);
  31. },
  32. {
  33. // use: [localStorageMiddleware], // store to localStorage for initialization fastly
  34. // fallbackData: undefined,
  35. },
  36. );
  37. return withUtils<EditorSettingsOperation, EditorSettings, Error>(swrResult, {
  38. update: async (updateData) => {
  39. const { data, mutate } = swrResult;
  40. if (data == null) {
  41. return;
  42. }
  43. mutate({ ...data, ...updateData }, false);
  44. // invoke API
  45. await apiv3Put('/personal-setting/editor-settings', updateData);
  46. },
  47. });
  48. };
  49. /*
  50. * Slack Notification
  51. */
  52. export const useSWRxSlackChannels = (
  53. currentPagePath: Nullable<string>,
  54. ): SWRResponse<string[], Error> => {
  55. const shouldFetch: boolean = currentPagePath != null;
  56. return useSWR(
  57. shouldFetch ? ['/pages.updatePost', currentPagePath] : null,
  58. ([endpoint, path]) =>
  59. apiGet(endpoint, { path }).then(
  60. (response: SlackChannels) => response.updatePost,
  61. ),
  62. {
  63. revalidateOnFocus: false,
  64. fallbackData: [''],
  65. },
  66. );
  67. };
  68. export type IPageTagsForEditorsOption = {
  69. sync: (tags?: string[]) => void;
  70. };