Advertisement
YavorGrancharov

i18next hook

Oct 14th, 2023
788
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 1.96 KB | Software | 0 0
  1. import React from 'react';
  2. import { useAtom } from 'jotai';
  3. import { useTranslation } from 'react-i18next';
  4. import { GlobalNotificationAtom } from '@store';
  5.  
  6. type NotificationVariantType = 'info' | 'success' | 'warning' | 'error';
  7.  
  8. type i18nNamespaceType =
  9.   | 'common'
  10.   | 'decision_details'
  11.   | 'edge_details'
  12.   | 'error'
  13.   | 'login'
  14.   | 'navigation'
  15.   | 'node_details'
  16.   | 'snippet_create'
  17.   | 'snippet_details'
  18.   | 'snippet_list'
  19.   | 'workflow_create'
  20.   | 'workflow_details'
  21.   | 'workflow_list';
  22.  
  23. export const useNotification = (namespaces: i18nNamespaceType[] = []): ((
  24.   title: string,
  25.   message: string,
  26.   variant: NotificationVariantType,
  27.   params?:
  28.     | {
  29.         [key: string]: unknown;
  30.       }
  31.     | undefined,
  32. ) => void) => {
  33.   const [, setGlobalNotificationAtom] = useAtom(GlobalNotificationAtom);
  34.   const { t, i18n } = useTranslation([...(namespaces || {})]);
  35.  
  36.   const openNotification = React.useCallback(
  37.     (
  38.       title: string,
  39.       message: string,
  40.       variant: NotificationVariantType,
  41.       params?: { [key: string]: unknown },
  42.     ) => {
  43.       const titleFallback = t('error:missing-namespace');
  44.       const messageFallback = t('error:missing-namespace');
  45.  
  46.       if (namespaces.length > 0) {
  47.         for (let ns = 0; ns < namespaces.length; ns++) {
  48.           if (i18n.exists(`${namespaces[ns]}:${title}`)) {
  49.             title = `${namespaces[ns]}:${title}`;
  50.           }
  51.           if (i18n.exists(`${namespaces[ns]}:${message}`)) {
  52.             message = `${namespaces[ns]}:${message}`;
  53.           }
  54.         }
  55.       }
  56.  
  57.       title = !i18n.exists(title) ? titleFallback : title;
  58.       message = !i18n.exists(message) ? messageFallback : message;
  59.  
  60.       setGlobalNotificationAtom({
  61.         title: t(title, params),
  62.         variant: variant,
  63.         visible: true,
  64.         message: t(message, params),
  65.       });
  66.     },
  67.     [i18n, namespaces, setGlobalNotificationAtom, t],
  68.   );
  69.  
  70.   return openNotification;
  71. };
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement