aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/providers/ackee-provider/ackee-provider.tsx
blob: 8cd29cd71cfebfb2276051e663557c9ab2c4d5ed (plain)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { useRouter } from 'next/router';
import {
  type FC,
  type ReactNode,
  createContext,
  type Dispatch,
  type SetStateAction,
  useMemo,
} from 'react';
import { useAckee } from 'use-ackee';
import type { AckeeTrackerValue } from '../../../types';
import { useLocalStorage } from '../../hooks';

type AckeeContextProps = {
  tracking: AckeeTrackerValue;
  setTracking: Dispatch<SetStateAction<AckeeTrackerValue>>;
};

export const AckeeContext = createContext<AckeeContextProps>({
  setTracking: (value) => value,
  tracking: 'full',
});

const validator = (value: unknown): value is AckeeTrackerValue =>
  value === 'full' || value === 'partial';

export type AckeeProviderProps = {
  /**
   * The provider children.
   */
  children?: ReactNode;
  /**
   *  The id given by Ackee for this domain.
   */
  domainId: string;
  /**
   * Should we track visits from localhost?
   *
   * @default false
   */
  isLocalhostTracked?: boolean;
  /**
   * Should we track our own visits?
   *
   * @default false
   */
  isOwnVisitsTracked?: boolean;
  /**
   * An URL that points to your Ackee installation (without trailing slash).
   */
  server: string;
  /**
   * The key to use in local storage.
   */
  storageKey: string;
  /**
   * Should the tracking be detailed (full) or not (partial)?
   */
  tracking: AckeeTrackerValue;
};

export const AckeeProvider: FC<AckeeProviderProps> = ({
  children,
  domainId,
  isLocalhostTracked = false,
  isOwnVisitsTracked = false,
  server,
  storageKey,
  tracking: tracker,
}) => {
  const [tracking, setTracking] = useLocalStorage<AckeeTrackerValue>(
    storageKey,
    tracker,
    validator
  );
  const { asPath } = useRouter();

  useAckee(
    asPath,
    { domainId, server },
    {
      detailed: tracking === 'full',
      ignoreLocalhost: !isLocalhostTracked,
      ignoreOwnVisits: !isOwnVisitsTracked,
    }
  );

  const value = useMemo(() => {
    return { setTracking, tracking };
  }, [setTracking, tracking]);

  return (
    <AckeeContext.Provider value={value}>{children}</AckeeContext.Provider>
  );
};