All Downloads are FREE. Search and download functionalities are using the official Maven repository.

web.lib.core.analytics.analytics-context.ts Maven / Gradle / Ivy

There is a newer version: 37
Show newest version
import React, {useContext, useState} from 'react';
import { Analytics } from './analytics';

class LoggingAnalytics implements Analytics {
  init() {
    console.log('analytics>init');
  }

  pageview(path: string) {
    console.log(`analytics>pageview(${path})`);
  }

  event(event: string, context: object): void {
    console.log(`analytics>event(${event}, ${JSON.stringify(context)})`);
  }
}

export const AnalyticsContext = React.createContext(new LoggingAnalytics());

export function createLinkTracker(analytic: Analytics, attr = 'href', context: object = {}) {
  return (e: any) => {
    const attrVal = e.target?.getAttribute?.(attr);
    if (!!attrVal) {
      analytic.event('Click', { label: attrVal, ...context });
    }
  };
}

export function useAnalyticsEditionField(id: string, onChange: any, context: object = {}): [boolean, (event: any) => void] {
  const [ isDirty, setIsDirty ] = useState(false);
  const analytics = useAnalytics();
  const onChangeWithDirty = (event: any) => {
    if (!isDirty) {
      analytics.event('Edit field', { field: id, ...context });
    }
    setIsDirty(true);
    if (onChange) {
      onChange(event);
    }
  };
  return [ isDirty, onChangeWithDirty ];
}

export function useAnalytics(): Analytics {
  return useContext(AnalyticsContext);
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy