UNPKG

react-split-test

Version:
53 lines (45 loc) 1.86 kB
'use strict'; var React = require('react'); var cookieLogic = '\n for( var i = 0; i < cookies.length; i++ ) {\n var cookie = cookies[i].split( \'=\' );\n if ( cookie[0] !== cookieName ) continue;\n variation = cookie[1];\n }\n document.cookie = cookieName + \'=\' + variation;\n'; var showVariation = '\n if ( variation && variation !== \'false\' ) {\n var htmlTag = document.getElementsByTagName( \'html\' )[0]\n if ( htmlTag ) htmlTag.style.visibility = \'hidden\';\n }\n'; var _React$PropTypes = React.PropTypes; var array = _React$PropTypes.array; var string = _React$PropTypes.string; var SplitTestScript = React.createClass({ displayName: 'SplitTestScript', propTypes: { variations: array.isRequired, cookieName: string.isRequired }, getDefaultProps: function getDefaultProps() { return { cookieName: 'variation' }; }, getScript: function getScript() { var _props = this.props; var cookieName = _props.cookieName; var variations = _props.variations; var script = []; var getCookieName = 'var cookies = document.cookie.split( \'; \');var cookieName = "' + cookieName + '";'; script.push('var variation = false;'); script.push('var percent = Math.random( );'); var scriptLength = script.length; variations.map(function (item) { if (!item.percent) return; script.push('if ( percent < ' + item.percent + ' ) variation = "' + item.id + '";'); }); if (script.length === scriptLength) { return; } script.push(cookieLogic); script.push(showVariation); return getCookieName + script.join(''); }, render: function render() { var script = this.getScript(); if (!script) return null; return React.createElement('script', { dangerouslySetInnerHTML: { __html: script } }); } }); module.exports = SplitTestScript;