File size: 2,126 Bytes
339aa1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import useMessages from './useMessages';
import { BROWSERS, OS_NAMES } from 'lib/constants';
import useLocale from './useLocale';
import useCountryNames from './useCountryNames';
import useLanguageNames from './useLanguageNames';
import regions from '../../../public/iso-3166-2.json';

export function useFormat() {
  const { formatMessage, labels } = useMessages();
  const { locale } = useLocale();
  const { countryNames } = useCountryNames(locale);
  const { languageNames } = useLanguageNames(locale);

  const formatOS = (value: string): string => {
    return OS_NAMES[value] || value;
  };

  const formatBrowser = (value: string): string => {
    return BROWSERS[value] || value;
  };

  const formatDevice = (value: string): string => {
    return formatMessage(labels[value] || labels.unknown);
  };

  const formatCountry = (value: string): string => {
    return countryNames[value] || value;
  };

  const formatRegion = (value: string): string => {
    const [country] = value.split('-');
    return regions[value] ? `${regions[value]}, ${countryNames[country]}` : value;
  };

  const formatCity = (value: string, country?: string): string => {
    return countryNames[country] ? `${value}, ${countryNames[country]}` : value;
  };

  const formatLanguage = (value: string): string => {
    return languageNames[value?.split('-')[0]] || value;
  };

  const formatValue = (value: string, type: string, data?: { [key: string]: any }): string => {
    switch (type) {
      case 'os':
        return formatOS(value);
      case 'browser':
        return formatBrowser(value);
      case 'device':
        return formatDevice(value);
      case 'country':
        return formatCountry(value);
      case 'region':
        return formatRegion(value);
      case 'city':
        return formatCity(value, data?.country);
      case 'language':
        return formatLanguage(value);
      default:
        return value;
    }
  };

  return {
    formatOS,
    formatBrowser,
    formatDevice,
    formatCountry,
    formatRegion,
    formatCity,
    formatLanguage,
    formatValue,
  };
}

export default useFormat;