comment.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { Nullable } from '@growi/core';
  2. import useSWR, { SWRResponse } from 'swr';
  3. import { apiGet, apiPost } from '~/client/util/apiv1-client';
  4. import { ICommentHasIdList, ICommentPostArgs } from '../interfaces/comment';
  5. import { useStaticSWR } from './use-static-swr';
  6. type IResponseComment = {
  7. comments: ICommentHasIdList,
  8. ok: boolean,
  9. }
  10. type CommentOperation = {
  11. update(comment: string, revisionId: string, commentId: string): Promise<void>,
  12. post(args: ICommentPostArgs): Promise<void>
  13. }
  14. export const useSWRxPageComment = (pageId: Nullable<string>): SWRResponse<ICommentHasIdList, Error> & CommentOperation => {
  15. const shouldFetch: boolean = pageId != null;
  16. const swrResponse = useSWR(
  17. shouldFetch ? ['/comments.get', pageId] : null,
  18. ([endpoint, pageId]) => apiGet(endpoint, { page_id: pageId }).then((response:IResponseComment) => response.comments),
  19. );
  20. const update = async(comment: string, revisionId: string, commentId: string) => {
  21. const { mutate } = swrResponse;
  22. await apiPost('/comments.update', {
  23. commentForm: {
  24. comment,
  25. revision_id: revisionId,
  26. comment_id: commentId,
  27. },
  28. });
  29. mutate();
  30. };
  31. const post = async(args: ICommentPostArgs) => {
  32. const { mutate } = swrResponse;
  33. const { commentForm, slackNotificationForm } = args;
  34. const { comment, revisionId, replyTo } = commentForm;
  35. const { isSlackEnabled, slackChannels } = slackNotificationForm;
  36. await apiPost('/comments.add', {
  37. commentForm: {
  38. comment,
  39. page_id: pageId,
  40. revision_id: revisionId,
  41. replyTo,
  42. },
  43. slackNotificationForm: {
  44. isSlackEnabled,
  45. slackChannels,
  46. },
  47. });
  48. mutate();
  49. };
  50. return {
  51. ...swrResponse,
  52. update,
  53. post,
  54. };
  55. };
  56. type EditingCommentsNumOperation = {
  57. increment(): Promise<number | undefined>,
  58. decrement(): Promise<number | undefined>,
  59. }
  60. export const useSWRxEditingCommentsNum = (): SWRResponse<number, Error> & EditingCommentsNumOperation => {
  61. const swrResponse = useStaticSWR<number, Error>('editingCommentsNum', undefined, { fallbackData: 0 });
  62. return {
  63. ...swrResponse,
  64. increment: () => swrResponse.mutate((swrResponse.data ?? 0) + 1),
  65. decrement: () => {
  66. const newValue = (swrResponse.data ?? 0) - 1;
  67. return swrResponse.mutate(Math.max(0, newValue));
  68. },
  69. };
  70. };