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

Mixpanel improvements #115

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 8 additions & 0 deletions packages/analytics-plugin-mixpanel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,13 @@
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.3.1"
},
"peerDependencies": {
"mixpanel-browser": "^2.0.0"
},
"peerDependenciesMeta": {
"mixpanel-browser": {
"optional": true
}
}
}
208 changes: 96 additions & 112 deletions packages/analytics-plugin-mixpanel/src/browser.js
Original file line number Diff line number Diff line change
@@ -1,122 +1,97 @@
import browserLoadMixpanel from './browserLoadMixpanel';

/**
* @typedef {Object} MixpanelPluginConfig - Plugin settings for Mixpanel plugin
* @property {String} [token] - The mixpanel token associated to a mixpanel project
* @property {Object} [mixpanel] - The mixpanel instance - use this
* to use the plugin with a mixpanel instance instantiated elsewhere, for
* example when using a mixpanel npm package.
* @property {Object} [context] - The context object where mixpanel
* instance is found and assigned to when instantiated. Defaults to window.
* @property {Object} [config] - Mixpanel config passed to `mixpanel.init()`
* in `initialize` step.
* If mixpanel instance already exists, it is updated with this config
* using `mixpanel.set_config()`.
* @property {String} [pageEvent] - Mixpanel doesn't have a 'page'
* function, so we are using the `mixpanel.track()` method. Use this option
* to override the event name. Defaults to `'page'`.
*/

/**
* Get mixpanel instance from config
* @param {MixpanelPluginConfig} config
* @returns {Object} Mixpanel instance
*/
const resolveMixpanel = (config = {}) => {
const { context = window, mixpanel: givenMixpanel } = config;
return givenMixpanel || context.mixpanel;
}

/**
* Mixpanel Analytics plugin
* @link https://getanalytics.io/plugins/mixpanel/
* @param {object} pluginConfig - Plugin settings
* @param {string} pluginConfig.token - The mixpanel token associated to a mixpanel project
* @return {object} Analytics plugin
* @param {MixpanelPluginConfig} pluginConfig - Plugin settings
* @return {AnalyticsPlugin} Analytics plugin
* @example
*
* // Load Mixpanel instance to `window`
* mixpanelPlugin({
* token: 'abcdef123'
* })
* token: 'abcdef123',
* });
*
* // Load Mixpanel instance to `context` object instead of `window`
* const myContext = {};
* mixpanelPlugin({
* token: 'abcdef123',
* context: myContext,
* });
*
* // Use existing mixpanel instance
* import mixpanel from 'mixpanel-browser';
* mixpanelPlugin({
* mixpanel: mixpanel.init('abcdef123'),
* });
*
* // Pass mixpanel config
* mixpanelPlugin({
* token: 'abcdef123',
* config: {
* api_host: 'https://api-eu.mixpanel.com',
* },
* });
*/
function mixpanelPlugin(pluginConfig = {}) {
return {
const plugin = {
NAMESPACE: "mixpanel",
config: pluginConfig,
/* https://developer.mixpanel.com/docs/javascript-full-api-reference#mixpanelinit */
initialize: ({ config }) => {
const { token } = config;
if (!token) {
throw new Error("No mixpanel token defined");
}
const {
token,
context = window,
config: mixpanelConfig,
} = config || {};

let mixpanel = resolveMixpanel(config);

// NoOp if mixpanel already loaded by external source or already loaded
if (typeof window.mixpanel !== 'undefined') {
return;
const hasMixpanel = Boolean(mixpanel);
const shouldApplyConfig = Boolean(mixpanelConfig);

if (hasMixpanel) {
// NoOp if mixpanel already loaded by external source or already loaded
if (!shouldApplyConfig) return;
// Update mixpanel to config passed to the plugin
mixpanel.set_config(mixpanelConfig);
}

// Load mixpanel library
(function(c, a) {
if (!a.__SV) {
var b = window;
try {
var d,
m,
j,
k = b.location,
f = k.hash;
d = function(a, b) {
return (m = a.match(RegExp(b + "=([^&]*)"))) ? m[1] : null;
};
f &&
d(f, "state") &&
((j = JSON.parse(decodeURIComponent(d(f, "state")))),
"mpeditor" === j.action &&
(b.sessionStorage.setItem("_mpcehash", f),
history.replaceState(
j.desiredHash || "",
c.title,
k.pathname + k.search
)));
} catch (n) {}
var l, h;
window.mixpanel = a;
a._i = [];
a.init = function(b, d, g) {
function c(b, i) {
var a = i.split(".");
2 == a.length && ((b = b[a[0]]), (i = a[1]));
b[i] = function() {
b.push([i].concat(Array.prototype.slice.call(arguments, 0)));
};
}
var e = a;
"undefined" !== typeof g ? (e = a[g] = []) : (g = "mixpanel");
e.people = e.people || [];
e.toString = function(b) {
var a = "mixpanel";
"mixpanel" !== g && (a += "." + g);
b || (a += " (stub)");
return a;
};
e.people.toString = function() {
return e.toString(1) + ".people (stub)";
};
l = "disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split(
" "
);
for (h = 0; h < l.length; h++) c(e, l[h]);
var f = "set set_once union unset remove delete".split(" ");
e.get_group = function() {
function a(c) {
b[c] = function() {
call2_args = arguments;
call2 = [c].concat(Array.prototype.slice.call(call2_args, 0));
e.push([d, call2]);
};
}
for (
var b = {},
d = ["get_group"].concat(
Array.prototype.slice.call(arguments, 0)
),
c = 0;
c < f.length;
c++
)
a(f[c]);
return b;
};
a._i.push([b, d, g]);
};
a.__SV = 1.2;
b = c.createElement("script");
b.type = "text/javascript";
b.async = !0;
b.src =
"undefined" !== typeof MIXPANEL_CUSTOM_LIB_URL
? MIXPANEL_CUSTOM_LIB_URL
: "file:" === c.location.protocol &&
"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)
? "https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js"
: "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";
d = c.getElementsByTagName("script")[0];
d.parentNode.insertBefore(b, d);
if (!hasMixpanel) {
if (!token) {
throw new Error("No mixpanel token defined");
}
})(document, window.mixpanel || []);

mixpanel.init(config.token, { batch_requests: true });
mixpanel = browserLoadMixpanel(context);
mixpanel.init(token, { batch_requests: true, ...mixpanelConfig });
}
},
/**
* Identify a visitor in mixpanel
Expand All @@ -125,8 +100,10 @@ function mixpanelPlugin(pluginConfig = {}) {
* Mixpanel doesn't allow to set properties directly in identify, so mixpanel.people.set is
* also called if properties are passed
*/
identify: ({ payload }) => {
identify: ({ config, payload }) => {
const mixpanel = resolveMixpanel(config);
const { userId, traits } = payload;

if (typeof userId === "string") {
mixpanel.identify(userId);
}
Expand All @@ -135,23 +112,25 @@ function mixpanelPlugin(pluginConfig = {}) {
}
},
/**
* Mixpanel doesn't have a "page" function, so we are using the track method by sending
* the path as tracked event and search parameters as properties
* Mixpanel doesn't have a "page" function, so we are using the track method.
*/
page: ({ payload }) => {
mixpanel.track(payload.properties.path, {
search: payload.properties.search,
});
page: ({ config, payload }) => {
const mixpanel = resolveMixpanel(config);
const pageEvent = config.pageEvent || 'page';
mixpanel.track(pageEvent, payload.properties);
},
/* https://developer.mixpanel.com/docs/javascript-full-api-reference#mixpaneltrack */
track: ({ payload }) => {
track: ({ config, payload }) => {
const mixpanel = resolveMixpanel(config);
mixpanel.track(payload.event, payload.properties);
},
loaded: () => {
return !!window.mixpanel;
const mixpanel = resolveMixpanel(plugin.config);
return !!mixpanel;
},
/* Clears super properties and generates a new random distinct_id for this instance. Useful for clearing data when a user logs out. */
reset: () => {
reset: ({ config }) => {
const mixpanel = resolveMixpanel(config);
mixpanel.reset();
},
/* Custom methods to add .alias call */
Expand All @@ -164,10 +143,15 @@ function mixpanelPlugin(pluginConfig = {}) {
* @param {string} [original] - The current identifier being used for this user.
*/
alias(alias, original) {
const mixpanel = resolveMixpanel(pluginConfig);
mixpanel.alias(alias, original);
},
getMixpanel() {
return resolveMixpanel(pluginConfig);
},
},
};
return plugin;
}

export default mixpanelPlugin;
Loading