Source

atoms/google-analytics/google-analytics.tsx

  1. import React from "react";
  2. import { withConfig } from "../../context";
  3. import { Analytics } from "../analytics";
  4. import { infiniteScrollExists } from "../../helpers";
  5. import get from "lodash.get";
  6. const DefaultGoogleAnalytics = ({ gaId, config }) => {
  7. if (typeof gaId !== "string") return null;
  8. const componentArr = gaId.split(",").map((id) => {
  9. const gaConfig = {
  10. vars: {
  11. account: id
  12. },
  13. triggers: {
  14. trackPageview: {
  15. on: infiniteScrollExists(config) ? "amp-next-page-scroll" : "visible",
  16. request: "pageview",
  17. scrollSpec: {
  18. useInitialPageSize: infiniteScrollExists(config)
  19. }
  20. }
  21. }
  22. };
  23. return <Analytics type="googleanalytics" targets={gaConfig} />;
  24. });
  25. return <>{componentArr}</>;
  26. };
  27. const GoogleAnalytics4 = ({ gaId, config }) => {
  28. if (typeof gaId !== "string") return null;
  29. const componentArr = gaId.split(",").map((id) => {
  30. const gaConfig = {
  31. vars: {
  32. gtag_id: id,
  33. config: {
  34. [id]: { groups: "default" }
  35. }
  36. },
  37. triggers: {
  38. trackPageview: {
  39. on: infiniteScrollExists(config) ? "amp-next-page-scroll" : "visible",
  40. request: "pageview",
  41. scrollSpec: {
  42. useInitialPageSize: infiniteScrollExists(config)
  43. }
  44. }
  45. }
  46. };
  47. return <Analytics type="gtag" targets={gaConfig} data-credentials="include" />;
  48. });
  49. return <>{componentArr}</>;
  50. };
  51. const GoogleAnalyticsBase = ({ config }) => {
  52. const gaIdFromAmpConfig = get(config, ["ampConfig", "google-analytics-tracking-id"], "");
  53. let gaId = get(config, ["opts", "featureConfig", "analytics", "googleAnalytics", "id"]);
  54. gaId = typeof gaId === "function" ? gaId(config) : gaId;
  55. const _gaId = gaId || gaIdFromAmpConfig || "";
  56. if (!_gaId) return null;
  57. const isGA3 = _gaId.startsWith("UA-");
  58. return isGA3 ? (
  59. <DefaultGoogleAnalytics gaId={_gaId} config={config} />
  60. ) : (
  61. <GoogleAnalytics4 gaId={_gaId} config={config} />
  62. );
  63. };
  64. /**
  65. * Google Analytics Component can be used for analytics purposes. This supports GA4 and the older version.
  66. * Id will be picked from Amp config of BOLD. `Settings > Configure > AMP > GA tracking id`.
  67. *
  68. * GA4 config will be picked up from `featureConfig`
  69. * Example:
  70. * ...
  71. * ampRoutes(app, {
  72. * featureConfig: {
  73. * analytics: {
  74. googleAnalytics: { id: "G-XXXXXXXX" }
  75. }
  76. * }
  77. * })
  78. * ...
  79. * ```
  80. * @category Atoms
  81. * @component
  82. *
  83. */
  84. const GoogleAnalytics = withConfig(GoogleAnalyticsBase);
  85. export { GoogleAnalytics, GoogleAnalyticsBase, DefaultGoogleAnalytics, GoogleAnalytics4 };