@atlaskit/editor-core
Version:
A package contains Atlassian editor core functionality
71 lines • 2.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var service_1 = require("./service");
/**
* Annotation for automatically tracking analytics event whenever a function is invoked.
*
* The @analytics annotation can only be used on methods and functions. It requires a single
* argument with the event name. It will relay the event via analytics/service and requires
* that desired provider is set in analytics/service.provider = provider.
*
* Usage:
*
* import analytics from 'analytics/annotation';
*
* class Component {
* @analytics('atlassian.component.click')
* onClick() { ... }
* }
*/
// PropertyDecorator | MethodDecorator
function analytics(name) {
return function (target, key, descriptor) {
if (!name) {
throw new SyntaxError('@analytics requires an event name as the first argument.');
}
if (!descriptor) {
// We're decorating a property (i.e. a method bound with an arrow => )
return {
set: function (primitiveOrFn) {
if (typeof primitiveOrFn === 'function') {
Object.defineProperty(this, key, { value: trackFunction(name, primitiveOrFn) });
}
else {
console.warn("@analytics decorator expects \"" + key + "\" to be a function, not a " + typeof primitiveOrFn + ".");
Object.defineProperty(this, key, { value: primitiveOrFn });
}
}
};
}
var fn = descriptor.value;
if (typeof fn !== 'function') {
throw new SyntaxError('@analytics can only be used on methods.');
}
// We're decorating a class method
return tslib_1.__assign({}, descriptor, { value: trackFunction(name, fn) });
};
}
exports.default = analytics;
/**
* Returns a sequence that will track analytics event before calling the passed function.
*/
function trackFunction(analyticsEventName, trackedFn) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var result = trackedFn.apply(void 0, args);
if (result) {
try {
service_1.default.trackEvent(analyticsEventName);
}
catch (e) {
console.error('An exception has been thrown when trying to track analytics event:', e);
}
}
return result;
};
}
//# sourceMappingURL=decorator.js.map