PageModelNotification.tsx 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import React, {
  2. FC, useCallback,
  3. } from 'react';
  4. import type { IPage, HasObjectId } from '@growi/core';
  5. import { useRouter } from 'next/router';
  6. import { SupportedTargetModel } from '~/interfaces/activity';
  7. import type { IInAppNotification } from '~/interfaces/in-app-notification';
  8. import * as pageSerializers from '~/models/serializers/in-app-notification-snapshot/page';
  9. import { ModelNotification } from './ModelNotification';
  10. import { useActionMsgAndIconForModelNotification } from './useActionAndMsg';
  11. export interface ModelNotificationUtils {
  12. Notification: FC
  13. publishOpen: () => void
  14. }
  15. export const usePageModelNotification = (notification: IInAppNotification & HasObjectId): ModelNotificationUtils | null => {
  16. const router = useRouter();
  17. const { actionMsg, actionIcon } = useActionMsgAndIconForModelNotification(notification);
  18. const getActionUsers = useCallback(() => {
  19. const latestActionUsers = notification.actionUsers.slice(0, 3);
  20. const latestUsers = latestActionUsers.map((user) => {
  21. return `@${user.name}`;
  22. });
  23. let actionedUsers = '';
  24. const latestUsersCount = latestUsers.length;
  25. if (latestUsersCount === 1) {
  26. actionedUsers = latestUsers[0];
  27. }
  28. else if (notification.actionUsers.length >= 4) {
  29. actionedUsers = `${latestUsers.slice(0, 2).join(', ')} and ${notification.actionUsers.length - 2} others`;
  30. }
  31. else {
  32. actionedUsers = latestUsers.join(', ');
  33. }
  34. return actionedUsers;
  35. }, [notification.actionUsers]);
  36. const isPageModelNotification = (notification: IInAppNotification & HasObjectId): notification is IInAppNotification<IPage> & HasObjectId => {
  37. return notification.targetModel === SupportedTargetModel.MODEL_PAGE;
  38. };
  39. if (!isPageModelNotification(notification)) {
  40. return null;
  41. }
  42. const actionUsers = getActionUsers();
  43. notification.parsedSnapshot = pageSerializers.parseSnapshot(notification.snapshot);
  44. const Notification = () => {
  45. return (
  46. <ModelNotification
  47. notification={notification}
  48. actionMsg={actionMsg}
  49. actionIcon={actionIcon}
  50. actionUsers={actionUsers}
  51. />
  52. );
  53. };
  54. const publishOpen = () => {
  55. if (notification.target != null) {
  56. // jump to target page
  57. const targetPagePath = (notification.target as IPage).path;
  58. if (targetPagePath != null) {
  59. router.push(targetPagePath);
  60. }
  61. }
  62. };
  63. return {
  64. Notification,
  65. publishOpen,
  66. };
  67. };