Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Google Analytics tracking #81

Merged
merged 3 commits into from
Sep 26, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .flowconfig
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
[include]

[libs]
./flow-typed/npm

[options]

Expand Down
148 changes: 148 additions & 0 deletions flow-typed/npm/react-router-dom_v4.x.x.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// flow-typed signature: 4d8e947f2e396ef2f26ecbd1ed7f04ab
// flow-typed version: 97d98ab83e/react-router-dom_v4.x.x/flow_>=v0.53.x

declare module 'react-router-dom' {
declare export class BrowserRouter extends React$Component<{
basename?: string,
forceRefresh?: boolean,
getUserConfirmation?: GetUserConfirmation,
keyLength?: number,
children?: React$Node,
}> {}

declare export class HashRouter extends React$Component<{
basename?: string,
getUserConfirmation?: GetUserConfirmation,
hashType?: 'slash' | 'noslash' | 'hashbang',
children?: React$Node,
}> {}

declare export class Link extends React$Component<{
to: string | LocationShape,
replace?: boolean,
children?: React$Node,
}> {}

declare export class NavLink extends React$Component<{
to: string | LocationShape,
activeClassName?: string,
className?: string,
activeStyle?: Object,
style?: Object,
isActive?: (match: Match, location: Location) => boolean,
children?: React$Node,
exact?: boolean,
strict?: boolean,
}> {}

// NOTE: Below are duplicated from react-router. If updating these, please
// update the react-router and react-router-native types as well.
declare export type Location = {
pathname: string,
search: string,
hash: string,
state?: any,
key?: string,
};

declare export type LocationShape = {
pathname?: string,
search?: string,
hash?: string,
state?: any,
};

declare export type HistoryAction = 'PUSH' | 'REPLACE' | 'POP';

declare export type RouterHistory = {
length: number,
location: Location,
action: HistoryAction,
listen(callback: (location: Location, action: HistoryAction) => void): () => void,
push(path: string | LocationShape, state?: any): void,
replace(path: string | LocationShape, state?: any): void,
go(n: number): void,
goBack(): void,
goForward(): void,
canGo?: (n: number) => boolean,
block(callback: (location: Location, action: HistoryAction) => boolean): void,
// createMemoryHistory
index?: number,
entries?: Array<Location>,
};

declare export type Match = {
params: { [key: string]: ?string },
isExact: boolean,
path: string,
url: string,
};

declare export type ContextRouter = {|
history: RouterHistory,
location: Location,
match: Match,
|};

declare export type GetUserConfirmation = (message: string, callback: (confirmed: boolean) => void) => void;

declare type StaticRouterContext = {
url?: string,
};

declare export class StaticRouter extends React$Component<{
basename?: string,
location?: string | Location,
context: StaticRouterContext,
children?: React$Node,
}> {}

declare export class MemoryRouter extends React$Component<{
initialEntries?: Array<LocationShape | string>,
initialIndex?: number,
getUserConfirmation?: GetUserConfirmation,
keyLength?: number,
children?: React$Node,
}> {}

declare export class Router extends React$Component<{
history: RouterHistory,
children?: React$Node,
}> {}

declare export class Prompt extends React$Component<{
message: string | ((location: Location) => string | true),
when?: boolean,
}> {}

declare export class Redirect extends React$Component<{
to: string | LocationShape,
push?: boolean,
}> {}

declare export class Route extends React$Component<{
component?: React$ComponentType<*>,
render?: (router: ContextRouter) => React$Node,
children?: React$ComponentType<ContextRouter> | React$Node,
path?: string,
exact?: boolean,
strict?: boolean,
}> {}

declare export class Switch extends React$Component<{
children?: React$Node,
}> {}

declare export function withRouter<P>(
Component: React$ComponentType<{| ...ContextRouter, ...P |}>
): React$ComponentType<P>;

declare type MatchPathOptions = {
path?: string,
exact?: boolean,
sensitive?: boolean,
strict?: boolean,
};

declare export function matchPath(pathname: string, options?: MatchPathOptions | string): null | Match;
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
"test": "react-scripts test --env=jsdom",
"coverage": "npm run test -- --coverage",
"lint": "npm run eslint && npm run prettier && npm run flow",
"eslint": "eslint .",
"eslint": "eslint src",
"prettier": "prettier --single-quote --trailing-comma es5 --print-width 110 --write \"src/**/*.js\"",
"flow": "flow; test $? -eq 0 -o $? -eq 2",
"set-homepage": "json -I -f package.json -e 'this.homepage=process.env.HOMEPAGE'",
Expand Down
3 changes: 2 additions & 1 deletion src/components/App/Page.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ import TopNav from './TopNav';

import './Page.css';

export default function JaegerUIPage({ children }) {
export default function JaegerUIPage(props) {
const { children } = props;
return (
<section className="jaeger-ui-page" id="jaeger-ui">
<Helmet title="Jaeger UI" />
Expand Down
19 changes: 10 additions & 9 deletions src/components/App/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import React, { Component } from 'react';
import createHistory from 'history/createBrowserHistory';
import PropTypes from 'prop-types';
import { metrics } from 'react-metrics';
import { Provider } from 'react-redux';
import { Route, Redirect, Switch } from 'react-router-dom';
import { ConnectedRouter } from 'react-router-redux';
Expand All @@ -30,20 +29,22 @@ import 'semantic-ui-css/semantic.min.css';

import Page from './Page';
import NotFound from './NotFound';
import trackedComponentEnahncer from './tracked-component-enhancer';
import { ConnectedDependencyGraphPage } from '../DependencyGraph';
import { ConnectedSearchTracePage } from '../SearchTracePage';
import { ConnectedTracePage } from '../TracePage';
import JaegerAPI, { DEFAULT_API_ROOT } from '../../api/jaeger';
import configureStore from '../../utils/configure-store';
import metricConfig from '../../utils/metrics';
import prefixUrl from '../../utils/prefix-url';

import './App.css';

const PageWithMetrics = metrics(metricConfig)(Page);

const defaultHistory = createHistory();

const TrackedSearchPage = trackedComponentEnahncer(ConnectedSearchTracePage);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why break this up? If we do it at the top level container, we don't have to add it to each page.

If our concern is that the Page only mounts once, I would hook into React router page change event and do it there.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Scratch my comment, didn't realize we were on react router v4.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if we can do something similar to this helper library
https://github.com/pshrmn/rrc/blob/master/docs/OnUpdate.md

It would be nice if we could listen to all changes on the location without explicitly putting it on each page component. That way, when a new page is added, it will automatically start tracking it without having to use this HOC. Thoughts?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, could possibly connect it to the store and use state.location instead... I'll look into that.

Copy link
Member Author

@tiffon tiffon Sep 22, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@saminzadeh Moved tracking into Page.

const TrackedTracePage = trackedComponentEnahncer(ConnectedTracePage);
const TrackedDependencyPage = trackedComponentEnahncer(ConnectedDependencyGraphPage);

export default class JaegerUIApp extends Component {
static get propTypes() {
return {
Expand All @@ -70,17 +71,17 @@ export default class JaegerUIApp extends Component {
return (
<Provider store={store}>
<ConnectedRouter history={history}>
<PageWithMetrics>
<Page>
<Switch>
<Route path={prefixUrl('/search')} component={ConnectedSearchTracePage} />
<Route path={prefixUrl('/trace/:id')} component={ConnectedTracePage} />
<Route path={prefixUrl('/dependencies')} component={ConnectedDependencyGraphPage} />
<Route path={prefixUrl('/search')} component={TrackedSearchPage} />
<Route path={prefixUrl('/trace/:id')} component={TrackedTracePage} />
<Route path={prefixUrl('/dependencies')} component={TrackedDependencyPage} />
<Redirect exact path="/" to={prefixUrl('/search')} />
<Redirect exact path={prefixUrl()} to={prefixUrl('/search')} />
<Redirect exact path={prefixUrl('/')} to={prefixUrl('/search')} />
<Route component={NotFound} />
</Switch>
</PageWithMetrics>
</Page>
</ConnectedRouter>
</Provider>
);
Expand Down
60 changes: 60 additions & 0 deletions src/components/App/tracked-component-enhancer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// @flow

// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

import * as React from 'react';
import type { Location } from 'react-router-dom';

import { trackPageView } from '../../utils/metrics';

type TrackedComponentProps = {
location: Location,
};

/**
* Wrap `Component` to add tracking based on changes in
* `props.location.pathname` and `props.location.search`. If either change, a
* page-view is tracked.
*/
export default function trackedComponentEnhancer(Component: any) {
class TrackedComponent extends React.Component<TrackedComponentProps> {
props: TrackedComponentProps;

componentDidMount() {
const { pathname, search } = this.props.location;
trackPageView(pathname, search);
}

componentWillReceiveProps(nextProps: TrackedComponentProps) {
const { pathname, search } = this.props.location;
const { pathname: nextPathname, search: nextSearch } = nextProps.location;
if (pathname !== nextPathname || search !== nextSearch) {
trackPageView(nextPathname, nextSearch);
}
}

render() {
return <Component {...this.props} />;
}
}

return TrackedComponent;
}
6 changes: 4 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,19 @@ import { document } from 'global';
import 'basscss/css/basscss.css';

import JaegerUIApp from './components/App';
import { init as initTracking } from './utils/metrics';

/* istanbul ignore if */
if (process.env.NODE_ENV === 'development') {
require.ensure(['global/window', 'react-addons-perf'], require => {
const window = require('global/window');
/* eslint-disable import/no-extraneous-dependencies */
// eslint-disable-next-line import/no-extraneous-dependencies
window.Perf = require('react-addons-perf');
/* eslint-enable import/no-extraneous-dependencies */
});
}

initTracking();

const UI_ROOT_ID = 'jaeger-ui-root';

/* istanbul ignore if */
Expand Down
47 changes: 9 additions & 38 deletions src/utils/metrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,43 +20,14 @@

import ReactGA from 'react-ga';

if (process.env.NODE_ENV === 'production' && process.env.REACT_APP_GA_TRACKING_ID) {
const GA_CODE = process.env.REACT_APP_GA_TRACKING_ID;
ReactGA.initialize(GA_CODE);
export function init() {
if (process.env.NODE_ENV === 'production' && process.env.REACT_APP_GA_TRACKING_ID) {
const GA_CODE = process.env.REACT_APP_GA_TRACKING_ID;
ReactGA.initialize(GA_CODE);
}
}

const GoogleAnalytics = {
pageView(event, fields) {
ReactGA.set({
page: fields.page,
});
ReactGA.pageview(fields.pathname);
},
track(eventName, params) {
ReactGA.event({
category: params.page,
action: eventName,
label: params.label,
value: params.value,
});
},
};

export default {
enabled: process.env.NODE_ENV === 'production',
debug: process.env.NODE_ENV === 'development',
vendors: [
{
name: 'Google Analytics',
api: GoogleAnalytics,
},
],
pageDefaults(routeState) {
const paths = routeState.pathname.substr(1).split('/');
return {
pathname: routeState.pathname,
query: routeState.query,
page: !paths[0] ? 'landing' : paths[0],
};
},
};
export function trackPageView(pathname, search) {
const pagePath = search ? `${pathname}?${search}` : pathname;
ReactGA.pageview(pagePath);
}