<commit_before>// var bodyParser = require('body-parser');
var request = require('request');

// all routs are in this file
module.exports = function(app) {
	var auth_url= 'http://auth.hasura/user/account/info';
	var headers = {
                 'Content-Type' : 'application/json',
                 'X-Hasura-Role' : 'admin',
       		 	 'X-Hasura-User-Id' : 1
            };

	app.get('/test', function (req, res) {
		res.send(req.headers);
		console.log(req.headers);

		/*// Verify user token
		var options = {
			url : auth_url,
			method : 'POST',
			headers : headers
			body : JSON.stringify({
				type : 'select',
				args : {
					table : 'test',
					columns : ['*']
				}
			})
		}

		request(options, function(err, response, body){
			if(err) {
			  console.error("Could not connect to APIs : " + err);
			  res.status(500).send('Internal error : ' + err);
			  return;
			}

			if (response.statusCode !== 200) {
			  console.error('Auth API bad request');
			  res.status(500).send('Internal error : Could not connect to auth APIs');
			  return;
			}

			if (response.statusCode === 200) {
				let user = JSON.parse(body)

			}
		});*/

	});

	app.get('/', function (req, res) {
		res.render('base');
	});

	app.get('/app', function (req, res) {
		res.render('whiteboard');
	});

	app.get('/groups', function (req, res) {
		res.render('groups');
	});

	app.get('/profile', function(req,res) {
		res.render('profile');
	});

	app.get('/welcome-msg', function (req, res) {
		res.render('partials/welcome-msg');
	});
	app.get('/login-content', function (req, res) {
		res.render('partials/login-content');
	});
	app.get('/signup-content', function (req, res) {
		res.render('partials/signup-content');
	});
	app.get('/reset-pass-content', function (req, res) {
		res.render('partials/reset-pass-content');
	});

};
<commit_msg>Testing req headers<commit_after>// var bodyParser = require('body-parser');
var request = require('request');

// all routs are in this file
module.exports = function(app) {
	var auth_url= 'http://auth.hasura/user/account/info';
	var headers = {
                 'Content-Type' : 'application/json',
                 'X-Hasura-Role' : 'admin',
       		 	 'X-Hasura-User-Id' : 1
            };

	app.get('/test', function (req, res) {
		var user_auth_token = req.headers['x-hasura-session-id'];
		res.send(user_auth_token);

		/*// Verify user token
		var options = {
			url : auth_url,
			method : 'POST',
			headers : headers
			body : JSON.stringify({
				type : 'select',
				args : {
					table : 'test',
					columns : ['*']
				}
			})
		}

		request(options, function(err, response, body){
			if(err) {
			  console.error("Could not connect to APIs : " + err);
			  res.status(500).send('Internal error : ' + err);
			  return;
			}

			if (response.statusCode !== 200) {
			  console.error('Auth API bad request');
			  res.status(500).send('Internal error : Could not connect to auth APIs');
			  return;
			}

			if (response.statusCode === 200) {
				let user = JSON.parse(body)

			}
		});*/

	});

	app.get('/', function (req, res) {
		res.render('base');
	});

	app.get('/app', function (req, res) {
		res.render('whiteboard');
	});

	app.get('/groups', function (req, res) {
		res.render('groups');
	});

	app.get('/profile', function(req,res) {
		res.render('profile');
	});

	app.get('/welcome-msg', function (req, res) {
		res.render('partials/welcome-msg');
	});
	app.get('/login-content', function (req, res) {
		res.render('partials/login-content');
	});
	app.get('/signup-content', function (req, res) {
		res.render('partials/signup-content');
	});
	app.get('/reset-pass-content', function (req, res) {
		res.render('partials/reset-pass-content');
	});

};
<|endoftext|>


<commit_before>/**
 *
 * http://nodejs.org/api/repl.html
 *
 */

var net = require("net"),
    repl = require("repl"),
    fs = require('fs');

var socketPath = "/data/data/nl.sison.android.nodejs.repl/cache/node-repl-sock";

var localSocketServer = net.createServer(function (socket) {

  repl.start({
    prompt: "node via Unix socket> ",
    input: socket,
    output: socket
  }).on('exit', function() {
    socket.end();
  });

  socket.setTimeout(60000, function () {
    socket.destroy();
    fs.unlinkSync(socketPath);
  });

}).listen(socketPath);
<commit_msg>updated local unix socket script<commit_after>/**
 *
 * http://nodejs.org/api/repl.html
 *
 * [src](http://stackoverflow.com/questions/16178239/gracefully-shutdown-unix-socket-server-on-nodejs-running-under-forever)
 *
 */
var net = require("net"),
    repl = require("repl"),
    fs = require('fs');

var socketPath = "/data/data/nl.sison.android.nodejs.repl/cache/node-repl-sock";
//var socketPath = "/home/me/node-repl-sock";

var server = net.createServer(function(c) { //'connection' listener
    console.log('server connected');
    repl.start({
        prompt: "node via Unix socket> ",
        input: c,
        output: c
    }).on('exit', function() {
        socket.end();
    });

    c.setTimeout(60000, function () {
        c.destroy();
        fs.unlinkSync(socketPath);
    });

    c.on('end', function() {
        console.log('server disconnected');
    });

    c.write('hello\r\n');
    c.pipe(c);
});

server.on('error', function (e) {
    if (e.code == 'EADDRINUSE') {
        var clientSocket = new net.Socket();
        clientSocket.on('error', function(e) { // handle error trying to talk to server
            if (e.code == 'ECONNREFUSED') {  // No other server listening
                fs.unlinkSync(socketPath);
                server.listen(socketPath, function() { //'listening' listener
                    console.log('server recovered');
                });
            }
        });
        clientSocket.connect({path: socketPath}, function() {
            console.log('Server running, giving up...');
            process.exit();
        });
    }
});

server.listen(socketPath, function() { //'listening' listener
    console.log('server bound');
});
<|endoftext|>


<commit_before>WEB_SOCKET_SWF_LOCATION = 'res/WebSocketMain.swf';
WEB_SOCKET_DEBUG = true;

var sykosomatic;
if (!sykosomatic) {
    sykosomatic = {};
}

(function () {

     ///
     /// Utils
     ///
     function enable_input () {
         $('#user-input-area :input').attr('disabled', false);
     };

     function disable_input () {
         $('#user-input-area :input').attr('disabled', true);
     };

     function get_url_parameter(name) {
         return unescape(
             (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
         );
     }

     function current_char () {
         return get_url_parameter('char');
     }

     ///
     /// Websockets
     ///
     var ws;
     function init_websockets() {
         disable_input();
         ws = new WebSocket('ws://dagon.ath.cx:8889/chat');
         // When running as root, use this.
         // ws = new WebSocket('ws://dagon.ath.cx:843/chat');
         ws.onopen = function() {
             ws.send(JSON.stringify({useragent: navigator.userAgent, char: current_char()}));
             enable_input();
         };
         ws.onmessage = function(e) {
             dispatch_message(JSON.parse(e.data));
         };
         ws.onclose = function () {
             disable_input();
         };
     };

     function ws_send (obj) {
       ws.send(JSON.stringify(obj));
     };

     ///
     /// From client
     ///
     function request_char_description(charname) {
         ws_send(['char-desc',charname]);
     }

     function start_recording() {
         ws_send(["start-recording"]);
     }

     function stop_recording() {
         ws_send(["stop-recording"]);
     }

     function send_input() {
         var msg = $('#user-input').val();
         if (msg) {
             $('#user-input').val('');
             ws_send(['user-input',msg]);
         };
     };

     function ping() {
         $.get('pingme',on_ajax_success);
         ws_send(['ping']);
     }

     ///
     /// From server
     ///
     var dispatch_table = {
         'pong' : function(msg) { console.log('got a pong'); },
         'char-desc' : function(msg) { alert('Description: ' + msg[1]); },
         'parse-error' : function(msg) { alert('Parser error: ' + msg[1]); }
     };

     function dispatch_message (message) {
         var msg_callback = dispatch_table[message[0]];
         if (msg_callback) {
           msg_callback(message);
         };
     };

     function mk_dialogue(text) {
         return $("
"+text+"
");
     };
     function mk_paren(text) {
         return $("
("+text+")
");
     };

     function mk_unit() {
         return $("
");
     }
     function mk_character(name) {
         return $("
"
                  +name
                  +"
");
     }
     function mk_action(actor, action) {
         var html = "
";
         html = html+""+actor+"";
         html = html+" "+action;
         html = html+"
";
         return $(html);
     }
     var last_actor;
     var last_unit;
     dispatch_table['action'] = function (msg) {
         var actor = msg[1]['actor'];
         var action = msg[1]['action'];

         if ((last_actor == actor) && (last_unit == 'action')) {
             $('.unit:last > p.action').text(function (idx, text) {
                                                 return text + ' ' +actor+ ' ' + action;
                                             });
         } else {
             var unit = mk_unit();
             unit.append(mk_action(actor,action));
             $('#chat-box').append(unit);
         }
         var obj_div = document.getElementById('chat-box');
         obj_div.scrollTop = obj_div.scrollHeight;
         last_actor = actor;
         last_unit = 'action';
     };

     dispatch_table['dialogue'] = function (msg) {
         var actor = msg[1]['actor'];
         var dialogue = msg[1]['dialogue'];
         var paren = msg[1]['parenthetical'];

         if ((last_actor == actor) && (last_unit == 'dialogue')) {
             if (paren.length > 0) {
                 $('.unit:last').append(mk_paren(paren));
                 $('.unit:last').append(mk_dialogue(dialogue));
             }
             else {
                 $('.unit:last > p.dialogue:last').text(function (idx, text) {
                                                            return text + ' ' + dialogue;
                                                        });
             }
         } else {
             var unit = mk_unit();
             unit.append(mk_character(actor));
             if (paren.length > 0) {
                 unit.append(mk_paren(paren));
             };
             unit.append(mk_dialogue(dialogue));
             $('#chat-box').append(unit);
         };
         last_actor = actor;
         last_unit = 'dialogue';
         var obj_div = document.getElementById('chat-box');
         obj_div.scrollTop = obj_div.scrollHeight;
     };

     ///
     /// Init
     ///
     var interval_id;
     var num_ajax_failures = 0;
     function on_ajax_error() {
         num_failures = num_ajax_failures + 1;
         if (num_failures >= 5) {
             clearTimeout(interval_id);
         };
     };

     function on_ajax_success() {
         num_ajax_failures = 0;
     };

     function init() {
         if (window.WebSocket) {
             init_websockets();
         }
         // For some reason, doing this chained script loading seems to be preventing Flash from doing
         // its job.
         else {
             $.getScript('res/swfobject.js', function () {
                             $.getScript('res/web_socket.js', init_chat);
                         });
         };
         // ping the server to keep the session and websocket alive.
         interval_id = setInterval(ping,1000*60*5);
         $(document).ajaxError(on_ajax_error);
     }

     sykosomatic.init = init;
     sykosomatic.send_input = send_input;
     sykosomatic.start_recording = start_recording;
     sykosomatic.stop_recording = stop_recording;
     sykosomatic.request_char_description = request_char_description;
 })();

$(document).ready(sykosomatic.init);
<commit_msg>Nicer action-appending.<commit_after>WEB_SOCKET_SWF_LOCATION = 'res/WebSocketMain.swf';
WEB_SOCKET_DEBUG = true;

var sykosomatic;
if (!sykosomatic) {
    sykosomatic = {};
}

(function () {

     ///
     /// Utils
     ///
     function enable_input () {
         $('#user-input-area :input').attr('disabled', false);
     };

     function disable_input () {
         $('#user-input-area :input').attr('disabled', true);
     };

     function get_url_parameter(name) {
         return unescape(
             (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
         );
     }

     function current_char () {
         return get_url_parameter('char');
     }

     ///
     /// Websockets
     ///
     var ws;
     function init_websockets() {
         disable_input();
         ws = new WebSocket('ws://dagon.ath.cx:8889/chat');
         // When running as root, use this.
         // ws = new WebSocket('ws://dagon.ath.cx:843/chat');
         ws.onopen = function() {
             ws.send(JSON.stringify({useragent: navigator.userAgent, char: current_char()}));
             enable_input();
         };
         ws.onmessage = function(e) {
             dispatch_message(JSON.parse(e.data));
         };
         ws.onclose = function () {
             disable_input();
         };
     };

     function ws_send (obj) {
       ws.send(JSON.stringify(obj));
     };

     ///
     /// From client
     ///
     function request_char_description(charname) {
         ws_send(['char-desc',charname]);
     }

     function start_recording() {
         ws_send(["start-recording"]);
     }

     function stop_recording() {
         ws_send(["stop-recording"]);
     }

     function send_input() {
         var msg = $('#user-input').val();
         if (msg) {
             $('#user-input').val('');
             ws_send(['user-input',msg]);
         };
     };

     function ping() {
         $.get('pingme',on_ajax_success);
         ws_send(['ping']);
     }

     ///
     /// From server
     ///
     var dispatch_table = {
         'pong' : function(msg) { console.log('got a pong'); },
         'char-desc' : function(msg) { alert('Description: ' + msg[1]); },
         'parse-error' : function(msg) { alert('Parser error: ' + msg[1]); }
     };

     function dispatch_message (message) {
         var msg_callback = dispatch_table[message[0]];
         if (msg_callback) {
           msg_callback(message);
         };
     };

     function mk_dialogue(text) {
         return $("
"+text+"
");
     };
     function mk_paren(text) {
         return $("
("+text+")
");
     };

     function mk_unit() {
         return $("
");
     }
     function mk_character(name) {
         return $("
"
                  +name
                  +"
");
     }
     function mk_action(actor, action) {
         var html = "
";
         html = html+""+actor+"";
         html = html+" "+action;
         html = html+"
";
         return $(html);
     }
     function mk_append_action(actor, action) {
         return $(" "+actor+""
                  +" "+action+"");
     }
     var last_actor;
     var last_unit;
     dispatch_table['action'] = function (msg) {
         var actor = msg[1]['actor'];
         var action = msg[1]['action'];

         if ((last_actor == actor) && (last_unit == 'action')) {
             $('.unit:last > p.action').append(mk_append_action(actor,action));
// text(function (idx, text) {
//                                                  return text + ' ' +actor+ ' ' + action;
//                                              });
         } else {
             var unit = mk_unit();
             unit.append(mk_action(actor,action));
             $('#chat-box').append(unit);
         }
         var obj_div = document.getElementById('chat-box');
         obj_div.scrollTop = obj_div.scrollHeight;
         last_actor = actor;
         last_unit = 'action';
     };

     dispatch_table['dialogue'] = function (msg) {
         var actor = msg[1]['actor'];
         var dialogue = msg[1]['dialogue'];
         var paren = msg[1]['parenthetical'];

         if ((last_actor == actor) && (last_unit == 'dialogue')) {
             if (paren.length > 0) {
                 $('.unit:last').append(mk_paren(paren));
                 $('.unit:last').append(mk_dialogue(dialogue));
             }
             else {
                 $('.unit:last > p.dialogue:last').text(function (idx, text) {
                                                            return text + ' ' + dialogue;
                                                        });
             }
         } else {
             var unit = mk_unit();
             unit.append(mk_character(actor));
             if (paren.length > 0) {
                 unit.append(mk_paren(paren));
             };
             unit.append(mk_dialogue(dialogue));
             $('#chat-box').append(unit);
         };
         last_actor = actor;
         last_unit = 'dialogue';
         var obj_div = document.getElementById('chat-box');
         obj_div.scrollTop = obj_div.scrollHeight;
     };

     ///
     /// Init
     ///
     var interval_id;
     var num_ajax_failures = 0;
     function on_ajax_error() {
         num_failures = num_ajax_failures + 1;
         if (num_failures >= 5) {
             clearTimeout(interval_id);
         };
     };

     function on_ajax_success() {
         num_ajax_failures = 0;
     };

     function init() {
         if (window.WebSocket) {
             init_websockets();
         }
         // For some reason, doing this chained script loading seems to be preventing Flash from doing
         // its job.
         else {
             $.getScript('res/swfobject.js', function () {
                             $.getScript('res/web_socket.js', init_chat);
                         });
         };
         // ping the server to keep the session and websocket alive.
         interval_id = setInterval(ping,1000*60*5);
         $(document).ajaxError(on_ajax_error);
     }

     sykosomatic.init = init;
     sykosomatic.send_input = send_input;
     sykosomatic.start_recording = start_recording;
     sykosomatic.stop_recording = stop_recording;
     sykosomatic.request_char_description = request_char_description;
 })();

$(document).ready(sykosomatic.init);
<|endoftext|>


<commit_before>
pc.script.attribute('shapename','string','');

pc.script.create("shapetotem", function (context) {

    var ShapeTotem = function (entity) {
        this.entity = entity;
        this.rotationangle = 0;
        this.rotationspeed = 1; // degrees/second
    };

    ShapeTotem.prototype = {
        initialize: function () {
        },

        update: function (dt) {
            if (this.entity.getParent() === null) { return; } // just got destroyed

            this.rotationangle += (this.rotationspeed * dt);
            this.entity.setLocalEulerAngles(0,this.rotationangle,0);
        }
    };

    return ShapeTotem;
});
<commit_msg>Sped up totem rotation<commit_after>
pc.script.attribute('shapename','string','');

pc.script.create("shapetotem", function (context) {

    var ShapeTotem = function (entity) {
        this.entity = entity;
        this.rotationangle = 0;
        this.rotationspeed = 25; // degrees/second
    };

    ShapeTotem.prototype = {
        initialize: function () {
        },

        update: function (dt) {
            if (this.entity.getParent() === null) { return; } // just got destroyed

            this.rotationangle += (this.rotationspeed * dt);
            this.entity.setLocalEulerAngles(0,this.rotationangle,0);
        }
    };

    return ShapeTotem;
});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import cx from 'classnames';

import GeoAddressInput from './GeoAddressInput';
import styles from './DefaultGeoInput.css';

export const formatLatLng = (coordinates, precision = 4) =>
  `${coordinates.lat.toFixed(precision)}°N ${coordinates.lng.toFixed(precision)}° E`;

const rawVal = val => val;

const geoDestinationFields = [
  {
    label: 'Street',
    name: 'street',
    render: rawVal,
  },
  {
    label: 'Street Number',
    name: 'streetNumber',
    render: rawVal,
  },
  {
    label: 'Subpremise',
    name: 'subpremise',
    render: rawVal,
  },
  {
    label: 'City',
    name: 'city',
    render: rawVal,
  },
  {
    label: 'Country',
    name: 'country',
    render: rawVal,
  },
  {
    label: 'Postal Code',
    name: 'postalCode',
    render: rawVal,
  },
  {
    label: 'Coordinates',
    name: 'location',
    render: formatLatLng,
  },
];

const DefaultGeoInput = ({
  className,
  addressInput,
  geoDestinationInput,
  loadingGeoDestination,
  predictions,
  activeIndex,
  onPredictionClick,
  style,
}) => (

    <GeoAddressInput
      {...addressInput}
      className={cx(addressInput.className, styles.addressInput)}
      predictions={predictions}
      activeIndex={activeIndex}
      onPredictionClick={onPredictionClick}
    />

    {!!loadingGeoDestination && (

        Loading geolocation...

    )}

    {!loadingGeoDestination && geoDestinationInput.value && (

            {geoDestinationFields.map(field => (

                  {field.label}

                  {geoDestinationInput.value[field.name]
                    ? field.render(geoDestinationInput.value[field.name])
                    : '-'}

            ))}

    )}

);

DefaultGeoInput.propTypes = {
  activeIndex: PropTypes.number,
  addressInput: PropTypes.object.isRequired,
  className: PropTypes.string,
  geoDestinationInput: PropTypes.object.isRequired,
  loadingGeoDestination: PropTypes.bool,
  onPredictionClick: PropTypes.func.isRequired,
  predictions: PropTypes.array.isRequired,
  style: PropTypes.object,
};

DefaultGeoInput.defaultProps = {};

export default DefaultGeoInput;
<commit_msg>refactoring<commit_after>import React, { PropTypes } from 'react';
import cx from 'classnames';

import GeoAddressInput from './GeoAddressInput';
import styles from './DefaultGeoInput.css';

export const formatLatLng = (coordinates, precision = 4) =>
  `${coordinates.lat.toFixed(precision)}°N ${coordinates.lng.toFixed(precision)}° E`;

const rawVal = val => val;

const geoDestinationFields = [
  {
    label: 'Street',
    name: 'street',
    render: rawVal,
  },
  {
    label: 'Street Number',
    name: 'streetNumber',
    render: rawVal,
  },
  {
    label: 'Subpremise',
    name: 'subpremise',
    render: rawVal,
  },
  {
    label: 'City',
    name: 'city',
    render: rawVal,
  },
  {
    label: 'Country',
    name: 'country',
    render: rawVal,
  },
  {
    label: 'Postal Code',
    name: 'postalCode',
    render: rawVal,
  },
  {
    label: 'Coordinates',
    name: 'location',
    render: formatLatLng,
  },
];

const DefaultGeoInput = ({
  className,
  addressInput,
  geoDestinationInput,
  geoDestinationTableClassName,
  loadingGeoDestination,
  loadingElement,
  predictions,
  activeIndex,
  onPredictionClick,
  style,
}) => (

    <GeoAddressInput
      {...addressInput}
      className={cx(addressInput.className, styles.addressInput)}
      predictions={predictions}
      activeIndex={activeIndex}
      onPredictionClick={onPredictionClick}
    />

    {!!loadingGeoDestination && loadingElement}

    {!loadingGeoDestination && geoDestinationInput.value && (

            {geoDestinationFields.map(field => (

                  {field.label}

                  {geoDestinationInput.value[field.name]
                    ? field.render(geoDestinationInput.value[field.name])
                    : '-'}

            ))}

    )}

);

DefaultGeoInput.propTypes = {
  activeIndex: PropTypes.number,
  addressInput: PropTypes.object.isRequired,
  className: PropTypes.string,
  geoDestinationInput: PropTypes.object.isRequired,
  geoDestinationTableClassName: PropTypes.string,
  loadingElement: PropTypes.node,
  loadingGeoDestination: PropTypes.bool,
  onPredictionClick: PropTypes.func.isRequired,
  predictions: PropTypes.array.isRequired,
  style: PropTypes.object,
};

DefaultGeoInput.defaultProps = {
  loadingElement: (

      Loading geolocation...

  ),
};

export default DefaultGeoInput;
<|endoftext|>


<commit_before>var cdb = require('cartodb.js');
require('bootstrap-colorpicker');
var template = require('./template.tpl');

module.exports = cdb.core.View.extend({

  initialize: function (opts) {
    this.model = new cdb.core.Model({
      hex: opts.value,
      opacity: opts.opacity
    });

    this._initBinds();
  },

  render: function () {
    var rgba = this._hexToRGB(this.model.get('hex'));
    this.$el.append(template({
      hex: this.model.get('hex'),
      r: rgba.r,
      g: rgba.g,
      b: rgba.b,
      opacity: this.model.get('opacity')
    }));

    this.$('.js-colorPicker').colorpicker({
      color: this.model.get('hex'),
      container: true,
      horizontal: true,
      inline: true,
      customClass: 'ColorPicker',
      template: '
' +
        '

' +
          '

' +
            '

' +
              '

' +
                  '
',
      slidersHorz: {
        saturation: {
          maxLeft: 218,
          maxTop: 105,
          callLeft: 'setSaturation',
          callTop: 'setBrightness'
        },
        hue: {
          maxLeft: 180,
          maxTop: 0,
          callLeft: 'setHue',
          callTop: false
        },
        alpha: {
          maxLeft: 180,
          maxTop: 0,
          callLeft: 'setAlpha',
          callTop: false
        }
      }
    });

    var self = this;

    this.$('.js-colorPicker').colorpicker().on('changeColor', function (e) {
      var rgb = e.color.toRGB();
      var hex = e.color.toHex();
      self.model.set({ hex: hex, r: rgb.r, g: rgb.g, b: rgb.b, opacity: rgb.a });
      self.$('.js-color').css('opacity', rgb.a);
    });

    return this;
  },

  _initBinds: function () {
    this.model.bind('change:hex', this._onChangeColor, this);
    this.model.bind('change:r', this._onChangeColor, this);
    this.model.bind('change:g', this._onChangeColor, this);
    this.model.bind('change:b', this._onChangeColor, this);
    this.model.bind('change:opacity', this._onChangeColor, this);
  },

  _hexToRGB: function (hex) {
    hex = hex.replace('#', '');
    var r = parseInt(hex.substring(0, 2), 16);
    var g = parseInt(hex.substring(2, 4), 16);
    var b = parseInt(hex.substring(4, 6), 16);
    return { r: r, g: g, b: b };
  },

  _onChangeColor: function () {
    this.trigger('change', { opacity: this.model.get('opacity'), hex: this.model.get('hex') }, this);
    this.$('.js-hex').val(this.model.get('hex').substr(1));
    this.$('.js-r').val(this.model.get('r'));
    this.$('.js-g').val(this.model.get('g'));
    this.$('.js-b').val(this.model.get('b'));
    this.$('.js-a').val(this.model.get('opacity'));
  }
});

<commit_msg>Closes #7450<commit_after>var _ = require('underscore');
var cdb = require('cartodb.js');
require('bootstrap-colorpicker');
var template = require('./template.tpl');

module.exports = cdb.core.View.extend({

  initialize: function (opts) {
    this.model = new cdb.core.Model({
      hex: opts.value,
      opacity: opts.opacity
    });

    this._initBinds();
  },

  render: function () {
    var rgb = this._hexToRGB(this.model.get('hex'));

    var color = _.extend(rgb, {
      hex: this.model.get('hex'),
      opacity: this.model.get('opacity')
    });

    this.$el.append(template(color));

    var rgbaTemplate = _.template('rgba(<%- r %>, <%- g %>, <%- b %>, <%- opacity %>)');

    this.$('.js-colorPicker').colorpicker({
      color: rgbaTemplate(color),
      format: 'rgba',
      container: true,
      horizontal: true,
      inline: true,
      customClass: 'ColorPicker',
      template: '
' +
        '

' +
          '

' +
            '

' +
              '

' +
                  '
',
      slidersHorz: {
        saturation: {
          maxLeft: 218,
          maxTop: 105,
          callLeft: 'setSaturation',
          callTop: 'setBrightness'
        },
        hue: {
          maxLeft: 180,
          maxTop: 0,
          callLeft: 'setHue',
          callTop: false
        },
        alpha: {
          maxLeft: 180,
          maxTop: 0,
          callLeft: 'setAlpha',
          callTop: false
        }
      }
    });

    var self = this;

    this.$('.js-colorPicker').colorpicker().on('changeColor', function (e) {
      var rgb = e.color.toRGB();
      var hex = e.color.toHex();
      self.model.set({ hex: hex, r: rgb.r, g: rgb.g, b: rgb.b, opacity: rgb.a });
      self.$('.js-color').css('opacity', rgb.a);
    });

    return this;
  },

  _initBinds: function () {
    this.model.bind('change:hex', this._onChangeColor, this);
    this.model.bind('change:r', this._onChangeColor, this);
    this.model.bind('change:g', this._onChangeColor, this);
    this.model.bind('change:b', this._onChangeColor, this);
    this.model.bind('change:opacity', this._onChangeColor, this);
  },

  _hexToRGB: function (hex) {
    hex = hex.replace('#', '');
    var r = parseInt(hex.substring(0, 2), 16);
    var g = parseInt(hex.substring(2, 4), 16);
    var b = parseInt(hex.substring(4, 6), 16);
    return { r: r, g: g, b: b };
  },

  _onChangeColor: function () {
    this.trigger('change', { opacity: this.model.get('opacity'), hex: this.model.get('hex') }, this);
    this.$('.js-hex').val(this.model.get('hex').substr(1));
    this.$('.js-r').val(this.model.get('r'));
    this.$('.js-g').val(this.model.get('g'));
    this.$('.js-b').val(this.model.get('b'));
    this.$('.js-a').val(this.model.get('opacity'));
  }
});

<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

var EventDispatcher = function () {}

EventDispatcher.prototype = {

	constructor: EventDispatcher,

	addEventListener: function ( type, listener ) {

		if ( this._listeners === undefined ) this._listeners = {};

		var listeners = this._listeners;

		if ( listeners[ type ] === undefined ) {

			listeners[ type ] = [];

		}

		if ( listeners[ type ].indexOf( listener ) === - 1 ) {

			listeners[ type ].push( listener );

		}

	},

	removeEventListener: function ( type, listener ) {

		if ( this._listeners === undefined ) return;

		var listeners = this._listeners;
		var index = listeners[ type ].indexOf( listener );

		if ( index !== - 1 ) {

			listeners[ type ].splice( index, 1 );

		}

	},

	dispatchEvent: function ( event ) {

		if ( this._listeners === undefined ) return;

		var listeners = this._listeners;
		var listenerArray = listeners[ event.type ];

		if ( listenerArray !== undefined ) {

			event.target = this;

			for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {

				listenerArray[ i ].call( this, event );

			}

		}

	}

};
<commit_msg>Added .hasEventListener. Closes #4.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

var EventDispatcher = function () {}

EventDispatcher.prototype = {

	constructor: EventDispatcher,

	addEventListener: function ( type, listener ) {

		if ( this._listeners === undefined ) this._listeners = {};

		var listeners = this._listeners;

		if ( listeners[ type ] === undefined ) {

			listeners[ type ] = [];

		}

		if ( listeners[ type ].indexOf( listener ) === - 1 ) {

			listeners[ type ].push( listener );

		}

	},

	hasEventListener: function ( type, listener ) {

		if ( this._listeners === undefined ) return false;

		var listeners = this._listeners;

		if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {

			return true;

		}

		return false;

	},

	removeEventListener: function ( type, listener ) {

		if ( this._listeners === undefined ) return;

		var listeners = this._listeners;
		var index = listeners[ type ].indexOf( listener );

		if ( index !== - 1 ) {

			listeners[ type ].splice( index, 1 );

		}

	},

	dispatchEvent: function ( event ) {

		if ( this._listeners === undefined ) return;

		var listeners = this._listeners;
		var listenerArray = listeners[ event.type ];

		if ( listenerArray !== undefined ) {

			event.target = this;

			for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {

				listenerArray[ i ].call( this, event );

			}

		}

	}

};
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Dinosaur Comics Hidden Texts
// @author      Tailszefox
// @namespace   localhost
// @description Shows Dinosaur Comics hidden texts
// @icon        https://i.imgur.com/zRYAVvw.png
// @include     http://www.qwantz.com/index.php?comic=*
// @include     http://www.qwantz.com/index.php
// @include     http://qwantz.com/index.php
// @include     http://qwantz.com/
// @version     1
// @grant       none
// ==/UserScript==

div = document.createElement("div");

pAlt = document.createElement("p");
pEmail = document.createElement("p");
pRss = document.createElement("p");

iAlt = document.createElement("i");
iEmail = document.createElement("i");
iRss = document.createElement("i");

pAlt.appendChild(iAlt);
pEmail.appendChild(iEmail);
pRss.appendChild(iRss);

iAlt.appendChild(document.createTextNode("Alt text: "));
iEmail.appendChild(document.createTextNode("Email subject: "));
iRss.appendChild(document.createTextNode("RSS title: "));

mailTo = document.querySelector(".topnav > li:nth-child(5) > a:nth-child(1)").getAttribute("href").replace("mailto:ryan@qwantz.com?subject=", "");
rssTitle = document.getElementsByTagName("table")[0].parentNode.nextSibling.data.replace(" ", "").replace("", "");

pAlt.appendChild(document.createTextNode(document.getElementsByClassName("comic")[0].getAttribute("title")));
pEmail.appendChild(document.createTextNode(mailTo));
pRss.appendChild(document.createTextNode(rssTitle));

headerText = document.getElementsByClassName("headertext")[0];

div.appendChild(pAlt);
div.appendChild(pEmail);
div.appendChild(pRss);

headerText.appendChild(div);
<commit_msg>Dino: it works again now<commit_after>// ==UserScript==
// @name        Dinosaur Comics Hidden Texts
// @author      Tailszefox
// @namespace   localhost
// @description Shows Dinosaur Comics hidden texts
// @icon        https://i.imgur.com/zRYAVvw.png
// @include     http://www.qwantz.com/index.php?comic=*
// @include     http://www.qwantz.com/index.php
// @include     http://qwantz.com/index.php
// @include     http://qwantz.com/
// @version     1
// @grant       none
// ==/UserScript==

div = document.createElement("div");

pAlt = document.createElement("p");
pEmail = document.createElement("p");
pRss = document.createElement("p");

iAlt = document.createElement("i");
iEmail = document.createElement("i");
iRss = document.createElement("i");

pAlt.appendChild(iAlt);
pEmail.appendChild(iEmail);
pRss.appendChild(iRss);

iAlt.appendChild(document.createTextNode("Alt text: "));
iEmail.appendChild(document.createTextNode("Email subject: "));
iRss.appendChild(document.createTextNode("RSS title: "));

mailTo = document.querySelector(".topnav > li:nth-child(5) > a:nth-child(1)").getAttribute("href").replace("mailto:ryan@qwantz.com?subject=", "");
rssTitle = document.getElementsByTagName("table")[0].parentNode.nextSibling.data.replace(" ", "").replace("", "");

pAlt.appendChild(document.createTextNode(document.getElementsByClassName("comic")[0].getAttribute("title")));
pEmail.appendChild(document.createTextNode(mailTo));
pRss.appendChild(document.createTextNode(rssTitle));

headerText = document.querySelector("body > center");

div.appendChild(pAlt);
div.appendChild(pEmail);
div.appendChild(pRss);

headerText.appendChild(div);
<|endoftext|>


<commit_before>/*
  javascript.util is a port of selected parts of java.util to JavaScript which
  main purpose is to ease porting Java code to JavaScript.

  Copyright (C) 2011 by Björn Harrtell

  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.
*/
(function() {var c=null;function d(){return function(){}}function f(a,b){var e=a.split("."),h=window;!(e[0]in h)&&h.execScript&&h.execScript("var "+e[0]);for(var q;e.length&&(q=e.shift());)!e.length&&b!==void 0?h[q]=b:h=h[q]?h[q]:h[q]={}}f("javascript.util.version","0.7.0");function g(a){this.message=a||""}f("javascript.util.OperationNotSupported",g);g.prototype=Error();g.prototype.name="OperationNotSupported";g.prototype.name=g.prototype.name;function i(a){this.message=a||""}
f("javascript.util.IndexOutOfBoundsException",i);i.prototype=Error();i.prototype.name="IndexOutOfBoundsException";i.prototype.name=i.prototype.name;function j(a){this.message=a||""}f("javascript.util.NoSuchElementException",j);j.prototype=Error();j.prototype.name="NoSuchElementException";j.prototype.name=j.prototype.name;function k(a){this.message=a||""}f("javascript.util.EmptyStackException",k);k.prototype=Error();k.prototype.name="EmptyStackException";k.prototype.name=k.prototype.name;
function l(){}f("javascript.util.Iterator",l);l.prototype.d=d();l.prototype.hasNext=l.prototype.d;l.prototype.next=d();l.prototype.next=l.prototype.next;l.prototype.remove=d();l.prototype.remove=l.prototype.remove;function m(){}f("javascript.util.Collection",m);m.prototype.add=d();m.prototype.add=m.prototype.add;m.prototype.f=d();m.prototype.isEmpty=m.prototype.f;m.prototype.e=d();m.prototype.iterator=m.prototype.e;m.prototype.size=d();m.prototype.size=m.prototype.size;m.prototype.b=d();
m.prototype.toArray=m.prototype.b;function n(){}f("javascript.util.List",n);n.prototype=new m;n.prototype.get=d();n.prototype.get=n.prototype.get;n.prototype.g=d();n.prototype.addAll=n.prototype.g;function o(a){this.a=[];a instanceof m&&this.g(a)}f("javascript.util.ArrayList",o);o.prototype=new n;o.prototype.a=c;o.prototype.add=function(a){this.a.push(a);return!0};o.prototype.add=o.prototype.add;o.prototype.g=function(a){for(a=a.e();a.d();)this.add(a.next());return!0};o.prototype.addAll=o.prototype.g;
o.prototype.e=function(){return new p(this)};o.prototype.iterator=o.prototype.e;o.prototype.get=function(a){if(a<0||a>=this.size())throw new i;return this.a[a]};o.prototype.get=o.prototype.get;o.prototype.f=function(){return this.a.length===0};o.prototype.isEmpty=o.prototype.f;o.prototype.size=function(){return this.a.length};o.prototype.size=o.prototype.size;o.prototype.b=function(){for(var a=[],b=0;b<this.a.length;b++)a.push(this.a[b]);return a};o.prototype.toArray=o.prototype.b;
function p(a){this.h=a}o.Iterator=p;p.prototype.h=c;p.prototype.position=0;p.prototype.next=function(){if(this.position===this.h.size())throw new j;return this.h.get(this.position++)};p.prototype.next=p.prototype.next;p.prototype.d=function(){return this.position<this.h.size()?!0:!1};p.prototype.hasNext=p.prototype.d;p.prototype.remove=function(){throw new g;};p.prototype.remove=p.prototype.remove;function r(){}f("javascript.util.Map",r);r.prototype.get=d();r.prototype.get=r.prototype.get;
r.prototype.put=d();r.prototype.put=r.prototype.put;r.prototype.size=d();r.prototype.size=r.prototype.size;r.prototype.c=d();r.prototype.values=r.prototype.c;function s(){}f("javascript.util.Arrays",s);
s.sort=function(){var a=arguments[0],b,e;if(arguments.length===1)a.sort();else if(arguments.length===2)e=arguments[1],a.sort(function(a,b){return e.compare(a,b)});else if(arguments.length===3){b=a.slice(arguments[1],arguments[2]);b.sort();var h=a.slice(0,arguments[1]).concat(b,a.slice(arguments[2],a.length));a.splice(0,a.length);for(b=0;b<h.length;b++)a.push(h[b])}else if(arguments.length===4){b=a.slice(arguments[1],arguments[2]);e=arguments[3];b.sort(function(a,b){return e.compare(a,b)});h=a.slice(0,
arguments[1]).concat(b,a.slice(arguments[2],a.length));a.splice(0,a.length);for(b=0;b<h.length;b++)a.push(h[b])}};s.asList=function(a){for(var b=new o,e=0;e<a.length;e++)b.add(a[e]);return b};f("javascript.util.SortedMap",d());function t(){this.object={}}f("javascript.util.HashMap",t);t.prototype.object=c;t.prototype.get=function(a){return this.object[a]||c};t.prototype.get=t.prototype.get;t.prototype.put=function(a,b){return this.object[a]=b};t.prototype.put=t.prototype.put;
t.prototype.c=function(){var a=new o,b;for(b in this.object)this.object.hasOwnProperty(b)&&a.add(this.object[b]);return a};t.prototype.values=t.prototype.c;t.prototype.size=function(){return this.c().size()};t.prototype.size=t.prototype.size;function u(){}f("javascript.util.Set",u);u.prototype.contains=d();u.prototype.contains=u.prototype.contains;f("javascript.util.SortedSet",d());function v(){this.a=[]}f("javascript.util.TreeSet",v);v.prototype.a=c;
v.prototype.contains=function(a){for(var b=0;b<this.a.length;b++)if(this.a[b].compareTo(a)===0)return!0;return!1};v.prototype.contains=v.prototype.contains;v.prototype.add=function(a){if(this.contains(a))return!1;for(var b=0;b<this.a.length;b++)if(this.a[b].compareTo(a)===1)return this.a.splice(b,0,a),!0;this.a.push(a);return!0};v.prototype.add=v.prototype.add;v.prototype.size=function(){return this.a.length};v.prototype.size=v.prototype.size;v.prototype.f=function(){return this.a.length===0};
v.prototype.isEmpty=v.prototype.f;v.prototype.b=function(){for(var a=[],b=0;b<this.a.length;b++)a.push(this.a[b]);return a};v.prototype.toArray=v.prototype.b;v.prototype.e=function(){return new w(this)};v.prototype.iterator=v.prototype.e;function w(a){this.i=a}v.Iterator=w;w.prototype.i=c;w.prototype.position=0;w.prototype.next=function(){if(this.position===this.i.size())throw new j;return this.i.a[this.position++]};w.prototype.next=w.prototype.next;
w.prototype.d=function(){return this.position<this.i.size()?!0:!1};w.prototype.hasNext=w.prototype.d;w.prototype.remove=function(){throw new g;};w.prototype.remove=w.prototype.remove;function x(){this.a=[]}f("javascript.util.Stack",x);x.prototype=new n;x.prototype.a=c;x.prototype.push=function(a){this.a.push(a);return a};x.prototype.push=x.prototype.push;x.prototype.pop=function(){if(this.a.length===0)throw new k;return this.a.pop()};x.prototype.pop=x.prototype.pop;
x.prototype.j=function(){if(this.a.length===0)throw new k;return this.a[this.a.length-1]};x.prototype.peek=x.prototype.j;x.prototype.empty=function(){return this.a.length===0?!0:!1};x.prototype.empty=x.prototype.empty;x.prototype.search=function(a){return this.a.indexOf(a)};x.prototype.search=x.prototype.search;x.prototype.size=function(){return this.a.length};x.prototype.size=x.prototype.size;x.prototype.b=function(){for(var a=[],b=0;b<this.a.length;b++)a.push(this.a[b]);return a};
x.prototype.toArray=x.prototype.b;function y(){this.a=[]}f("javascript.util.TreeMap",y);y.prototype.a=c;y.prototype.get=function(a){for(var b=0;b<this.a.length;b++){var e=this.a[b];if(e.key.compareTo(a)===0)return e.value}return c};y.prototype.get=y.prototype.get;y.prototype.put=function(a,b){var e=this.get(a);if(e){var h=e.value;e.value=b;return h}for(var h={key:a,value:b},q=0;q<this.a.length;q++)if(e=this.a[q],e.key.compareTo(a)===1)return this.a.splice(q,0,h),c;this.a.push({key:a,value:b});return c};
y.prototype.put=y.prototype.put;y.prototype.c=function(){for(var a=new o,b=0;b<this.a.length;b++)a.add(this.a[b].value);return a};y.prototype.values=y.prototype.c;y.prototype.size=function(){return this.c().size()};y.prototype.size=y.prototype.size;})();
<commit_msg>New build of javascript.util<commit_after>/*
  javascript.util is a port of selected parts of java.util to JavaScript which
  main purpose is to ease porting Java code to JavaScript.

  Copyright (C) 2011 by Björn Harrtell

  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.
*/
(function() {var c=!0,e=null,f=!1;function g(){return function(){}}function h(a,b){var d=a.split("."),j=window;!(d[0]in j)&&j.execScript&&j.execScript("var "+d[0]);for(var r;d.length&&(r=d.shift());)!d.length&&void 0!==b?j[r]=b:j=j[r]?j[r]:j[r]={}}h("javascript.util.version","0.7.0");function i(a){this.message=a||""}h("javascript.util.OperationNotSupported",i);i.prototype=Error();i.prototype.name="OperationNotSupported";i.prototype.name=i.prototype.name;function k(a){this.message=a||""}
h("javascript.util.IndexOutOfBoundsException",k);k.prototype=Error();k.prototype.name="IndexOutOfBoundsException";k.prototype.name=k.prototype.name;function l(a){this.message=a||""}h("javascript.util.NoSuchElementException",l);l.prototype=Error();l.prototype.name="NoSuchElementException";l.prototype.name=l.prototype.name;function m(a){this.message=a||""}h("javascript.util.EmptyStackException",m);m.prototype=Error();m.prototype.name="EmptyStackException";m.prototype.name=m.prototype.name;
function n(){}h("javascript.util.Iterator",n);n.prototype.c=g();n.prototype.hasNext=n.prototype.c;n.prototype.next=g();n.prototype.next=n.prototype.next;n.prototype.remove=g();n.prototype.remove=n.prototype.remove;function o(){}h("javascript.util.Collection",o);o.prototype.add=g();o.prototype.add=o.prototype.add;o.prototype.g=g();o.prototype.isEmpty=o.prototype.g;o.prototype.d=g();o.prototype.iterator=o.prototype.d;o.prototype.size=g();o.prototype.size=o.prototype.size;o.prototype.e=g();
o.prototype.toArray=o.prototype.e;o.prototype.remove=g();o.prototype.remove=o.prototype.remove;function p(){}h("javascript.util.List",p);p.prototype=new o;p.prototype.get=g();p.prototype.get=p.prototype.get;p.prototype.b=g();p.prototype.addAll=p.prototype.b;function q(a){this.a=[];a instanceof o&&this.b(a)}h("javascript.util.ArrayList",q);q.prototype=new p;q.prototype.a=e;q.prototype.add=function(a){this.a.push(a);return c};q.prototype.add=q.prototype.add;
q.prototype.b=function(a){for(a=a.d();a.c();)this.add(a.next());return c};q.prototype.addAll=q.prototype.b;q.prototype.d=function(){return new s(this)};q.prototype.iterator=q.prototype.d;q.prototype.get=function(a){if(0>a||a>=this.size())throw new k;return this.a[a]};q.prototype.get=q.prototype.get;q.prototype.g=function(){return 0===this.a.length};q.prototype.isEmpty=q.prototype.g;q.prototype.size=function(){return this.a.length};q.prototype.size=q.prototype.size;
q.prototype.e=function(){for(var a=[],b=0;b<this.a.length;b++)a.push(this.a[b]);return a};q.prototype.toArray=q.prototype.e;q.prototype.remove=function(a){for(var b=f,d=0;d<this.a.length;d++)if(this.a[d]===a){this.a.splice(d,1);b=c;break}return b};q.prototype.remove=q.prototype.remove;function s(a){this.h=a}q.Iterator=s;s.prototype.h=e;s.prototype.position=0;s.prototype.next=function(){if(this.position===this.h.size())throw new l;return this.h.get(this.position++)};s.prototype.next=s.prototype.next;
s.prototype.c=function(){return this.position<this.h.size()?c:f};s.prototype.hasNext=s.prototype.c;s.prototype.remove=function(){throw new i;};s.prototype.remove=s.prototype.remove;function t(){}h("javascript.util.Map",t);t.prototype.get=g();t.prototype.get=t.prototype.get;t.prototype.put=g();t.prototype.put=t.prototype.put;t.prototype.size=g();t.prototype.size=t.prototype.size;t.prototype.f=g();t.prototype.values=t.prototype.f;function u(){}h("javascript.util.Arrays",u);
u.sort=function(){var a=arguments[0],b,d;if(1===arguments.length)a.sort();else if(2===arguments.length)d=arguments[1],a.sort(function(a,b){return d.compare(a,b)});else if(3===arguments.length){b=a.slice(arguments[1],arguments[2]);b.sort();var j=a.slice(0,arguments[1]).concat(b,a.slice(arguments[2],a.length));a.splice(0,a.length);for(b=0;b<j.length;b++)a.push(j[b])}else if(4===arguments.length){b=a.slice(arguments[1],arguments[2]);d=arguments[3];b.sort(function(a,b){return d.compare(a,b)});j=a.slice(0,
arguments[1]).concat(b,a.slice(arguments[2],a.length));a.splice(0,a.length);for(b=0;b<j.length;b++)a.push(j[b])}};u.asList=function(a){for(var b=new q,d=0;d<a.length;d++)b.add(a[d]);return b};h("javascript.util.SortedMap",g());function v(){this.object={}}h("javascript.util.HashMap",v);v.prototype.object=e;v.prototype.get=function(a){return this.object[a]||e};v.prototype.get=v.prototype.get;v.prototype.put=function(a,b){return this.object[a]=b};v.prototype.put=v.prototype.put;
v.prototype.f=function(){var a=new q,b;for(b in this.object)this.object.hasOwnProperty(b)&&a.add(this.object[b]);return a};v.prototype.values=v.prototype.f;v.prototype.size=function(){return this.f().size()};v.prototype.size=v.prototype.size;function w(){}h("javascript.util.Set",w);w.prototype.contains=g();w.prototype.contains=w.prototype.contains;h("javascript.util.SortedSet",g());function x(a){this.a=[];a instanceof o&&this.b(a)}h("javascript.util.TreeSet",x);x.prototype.a=e;
x.prototype.contains=function(a){for(var b=0;b<this.a.length;b++)if(0===this.a[b].compareTo(a))return c;return f};x.prototype.contains=x.prototype.contains;x.prototype.add=function(a){if(this.contains(a))return f;for(var b=0;b<this.a.length;b++)if(1===this.a[b].compareTo(a))return this.a.splice(b,0,a),c;this.a.push(a);return c};x.prototype.add=x.prototype.add;x.prototype.b=function(a){for(a=a.d();a.c();)this.add(a.next());return c};x.prototype.addAll=x.prototype.b;x.prototype.size=function(){return this.a.length};
x.prototype.size=x.prototype.size;x.prototype.g=function(){return 0===this.a.length};x.prototype.isEmpty=x.prototype.g;x.prototype.e=function(){for(var a=[],b=0;b<this.a.length;b++)a.push(this.a[b]);return a};x.prototype.toArray=x.prototype.e;x.prototype.d=function(){return new y(this)};x.prototype.iterator=x.prototype.d;function y(a){this.i=a}x.Iterator=y;y.prototype.i=e;y.prototype.position=0;y.prototype.next=function(){if(this.position===this.i.size())throw new l;return this.i.a[this.position++]};
y.prototype.next=y.prototype.next;y.prototype.c=function(){return this.position<this.i.size()?c:f};y.prototype.hasNext=y.prototype.c;y.prototype.remove=function(){throw new i;};y.prototype.remove=y.prototype.remove;function z(){this.a=[]}h("javascript.util.Stack",z);z.prototype=new p;z.prototype.a=e;z.prototype.push=function(a){this.a.push(a);return a};z.prototype.push=z.prototype.push;z.prototype.pop=function(){if(0===this.a.length)throw new m;return this.a.pop()};z.prototype.pop=z.prototype.pop;
z.prototype.j=function(){if(0===this.a.length)throw new m;return this.a[this.a.length-1]};z.prototype.peek=z.prototype.j;z.prototype.empty=function(){return 0===this.a.length?c:f};z.prototype.empty=z.prototype.empty;z.prototype.search=function(a){return this.a.indexOf(a)};z.prototype.search=z.prototype.search;z.prototype.size=function(){return this.a.length};z.prototype.size=z.prototype.size;z.prototype.e=function(){for(var a=[],b=0;b<this.a.length;b++)a.push(this.a[b]);return a};
z.prototype.toArray=z.prototype.e;function A(){this.a=[]}h("javascript.util.TreeMap",A);A.prototype.a=e;A.prototype.get=function(a){for(var b=0;b<this.a.length;b++){var d=this.a[b];if(0===d.key.compareTo(a))return d.value}return e};A.prototype.get=A.prototype.get;A.prototype.put=function(a,b){var d=this.get(a);if(d){var j=d.value;d.value=b;return j}for(var j={key:a,value:b},r=0;r<this.a.length;r++)if(d=this.a[r],1===d.key.compareTo(a))return this.a.splice(r,0,j),e;this.a.push({key:a,value:b});return e};
A.prototype.put=A.prototype.put;A.prototype.f=function(){for(var a=new q,b=0;b<this.a.length;b++)a.add(this.a[b].value);return a};A.prototype.values=A.prototype.f;A.prototype.size=function(){return this.f().size()};A.prototype.size=A.prototype.size;})();
<|endoftext|>


<commit_before>/**
 * A table view row that can add an arbitrary number of data entry rows
 *
 * @package   Swat
 * @copyright 2004-2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */

/**
 * A table view row that can add an arbitrary number of data entry rows
 *
 * @param String id the identifier of this row.
 * @param String row_string the XML string to use when inserting a new row. The
 *                           XML string can contain '%s' placeholders. Before
 *                           a new row is added, the placeholders are replaced
 *                           with the new row index.
 */
function SwatTableViewInputRow(id, row_string)
{
	this.id = id;

	// decode string
	row_string = row_string.replace(/</g, '<').replace(/>/g, '>');
	row_string = row_string.replace(/"/g, '"').replace(/'/g, "'");
	row_string = row_string.replace(/&/g, '&');

	/*
	 * Pack row string in an XHTML document
	 *
	 * We purposly do not specify a DTD here as Internet Explorer is too slow
	 * when given a DTD. The XML string is encoded in UTF-8 with no special
	 * entities at this point.
	 */
	this.row_string = "<?xml version='1.0' encoding='UTF-8'?>\n" +
		'' +
		'<title>row</title>
' +
		row_string +
		'
';

	this.enter_row = document.getElementById(this.id + '_enter_row');

	// get table node belonging to the enter row
	this.table = this.enter_row;
	while (this.table.nodeName.toLowerCase() != 'table')
		this.table = this.table.parentNode;

	this.replicators = null;
	this.replicators_input = null;
}

/**
 * Gets an XML parser with a loadXML() method
 */
function SwatTableViewInputRow_getXMLParser()
{
	var parser = null;
	var is_ie = true;

	try {
		var dom = new ActiveXObject('Msxml2.XMLDOM');
	} catch (err1) {
		try {
			var dom = new ActiveXObject('Microsoft.XMLDOM');
		} catch (err2) {
			is_ie = false;
		}
	}

	if (is_ie) {
		/*
		 * Internet Explorer's XMLDOM object has a proprietary loadXML()
		 * method. Our method returns the document.
		 */
		parser = function() {}
		parser.loadXML = function(document_string)
		{
			if (!dom.loadXML(document_string))
				alert(dom.parseError.reason);

			return dom;
		}
	}

	if (parser === null && typeof DOMParser != 'undefined') {
		/*
		 * Mozilla, Safari and Opera have a proprietary DOMParser()
		 * class.
		 */
		dom_parser = new DOMParser();

		// Cannot add loadXML method to a newly created DOMParser because it
		// crashes Safari
		parser = function() {}
		parser.loadXML = function(document_string)
		{
			return dom_parser.parseFromString(document_string, 'text/xml');
		}
	}

	return parser;
}

/**
 * The XML parser used by this widget
 *
 * @var Object
 */
SwatTableViewInputRow.parser = SwatTableViewInputRow_getXMLParser();

/*
 * If the browser does not support the importNode() method then we need to
 * manually copy nodes from one document to the current document. These methods
 * parse a HTMLTableRowNode in one document into a table row in this document.
 */
if (!document.importNode) {

	/**
	 * Parses a table row from one document into another
	 *
	 * Internet Explorer does not allow writing to the innerHTML property for
	 * table row nodes so the table cells are individually inserted and cloned.
	 *
	 * @param HTMLTableRowNode source_tr the table row from the source document.
	 * @param HTMLTableRowNode dest_tr the table row in the destination
	 *                                  document.
	 */
	function SwatTableViewInputRow_parseTableRow(source_tr, dest_tr)
	{
		var child_node;
		var dest_td;
		for (var i = 0; i < source_tr.childNodes.length; i++) {
			child_node = source_tr.childNodes[i];
			if (child_node.nodeType == 1 && child_node.nodeName == 'td') {
				dest_td = dest_tr.insertCell(-1);
				source_attributes = child_node.attributes;
				for (var j = 0; j < source_attributes.length; j++) {
					if (source_attributes[j].name == 'class') {
						dest_td.className = source_attributes[j].value;
					} else {
						dest_td.setAttribute(source_attributes[j].name,
							source_attributes[j].value);
					}
				}
				SwatTableViewInputRow_parseTableCell(child_node, dest_td);
			}
		}
	}

	/**
	 * Parses a table cell from one document into another
	 *
	 * @param HTMLTableRowNode source_td the table cell from the source
	 *                                    document.
	 * @param HTMLTableRowNode dest_td the table cell in the destination
	 *                                  document.
	 */
	function SwatTableViewInputRow_parseTableCell(source_td, dest_td)
	{
		// Internet Explorer does not have an innerHTML property set on
		// imported DOM nodes even if the imported document is XHTML.
		if (source_td.innerHTML)
			dest_td.innerHTML = source_td.innerHTML;
		else
			dest_td.innerHTML = source_td.xml;
	}
}

/**
 * Initializes the replicator array
 *
 * @return boolean true if the replicators were successfully initialized and
 *          false if they were not.
 */
SwatTableViewInputRow.prototype.initReplicators = function()
{
	if (this.replicators === null) {
		this.replicators_input = document.getElementsByName(this.id +
			'_replicators')[0];

		if (this.replicators_input === null)
			return false;

		if (this.replicators_input.value == "")
			this.replicators = [];
		else
			this.replicators = this.replicators_input.value.split(',');
	}
	return true;
}

/**
 * Adds a new data row to the table
 */
SwatTableViewInputRow.prototype.addRow = function()
{
	if (!this.initReplicators())
		return;

	var replicator_id;
	if (this.replicators.length > 0)
		replicator_id = (parseInt(
			this.replicators[this.replicators.length - 1]) + 1).toString();
	else
		replicator_id = '0';

	this.replicators.push(replicator_id);
	this.replicators_input.value = this.replicators.join(',');

	var document_string = this.row_string.replace(/%s/g, replicator_id);
	var dom = SwatTableViewInputRow.parser.loadXML(document_string);
	var source_tr = dom.documentElement.getElementsByTagName('tr')[0];

	if (document.importNode) {
		var dest_tr = document.importNode(source_tr, true);
		this.enter_row.parentNode.insertBefore(dest_tr, this.enter_row);
	} else {
		// Internet Explorer specific code
		// Uses the table object model instead of the DOM
		var dest_tr = this.table.insertRow(this.enter_row.rowIndex);
		SwatTableViewInputRow_parseTableRow(source_tr, dest_tr);
	}

	dest_tr.className = 'swat-table-view-input-row';
	dest_tr.id = this.id + '_row_' + replicator_id;

	// run scripts
	// a better way to do this might be to remvoe the script nodes from the
	// document and then run the scripts. This way we can ensure the scripts
	// are only run once.
	var scripts = dom.documentElement.getElementsByTagName('script');
	for (var i = 0; i < scripts.length; i++)
		if (scripts[0].getAttribute('type') == 'text/javascript' &&
			scripts[0].childNodes.length > 0)
				eval(scripts[i].firstChild.nodeValue);
}

/**
 * Remvoes a data row from the table
 */
SwatTableViewInputRow.prototype.removeRow = function(replicator_id)
{
	if (!this.initReplicators())
		return;

	// remove replicator_id from replicators array
	var replicator_index = -1;
	for (var i = 0; i < this.replicators.length; i++) {
		if (this.replicators[i] == replicator_id) {
			replicator_index = i;
			break;
		}
	}
	if (replicator_index != -1) {
		this.replicators.splice(replicator_index, 1);
		this.replicators_input.value = this.replicators.join(',');
	}

	// remove row from document
	var row_id = this.id + '_row_' + replicator_id;
	var row = document.getElementById(row_id);
	if (row && row.parentNode !== null) {
		row.parentNode.removeChild(row);
	}
}
<commit_msg>Safari's importNode() does not work properly. Some td attributes are dropped and the anchor tag does not get imported. As such, we use the IE table object model hacks for Safari as well.<commit_after>/**
 * A table view row that can add an arbitrary number of data entry rows
 *
 * @package   Swat
 * @copyright 2004-2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */

/**
 * A table view row that can add an arbitrary number of data entry rows
 *
 * @param String id the identifier of this row.
 * @param String row_string the XML string to use when inserting a new row. The
 *                           XML string can contain '%s' placeholders. Before
 *                           a new row is added, the placeholders are replaced
 *                           with the new row index.
 */
function SwatTableViewInputRow(id, row_string)
{
	this.id = id;

	// decode string
	row_string = row_string.replace(/</g, '<').replace(/>/g, '>');
	row_string = row_string.replace(/"/g, '"').replace(/'/g, "'");
	row_string = row_string.replace(/&/g, '&');

	/*
	 * Pack row string in an XHTML document
	 *
	 * We purposly do not specify a DTD here as Internet Explorer is too slow
	 * when given a DTD. The XML string is encoded in UTF-8 with no special
	 * entities at this point.
	 */
	this.row_string = "<?xml version='1.0' encoding='UTF-8'?>\n" +
		'' +
		'<title>row</title>
' +
		row_string +
		'
';

	this.enter_row = document.getElementById(this.id + '_enter_row');

	// get table node belonging to the enter row
	this.table = this.enter_row;
	while (this.table.nodeName.toLowerCase() != 'table')
		this.table = this.table.parentNode;

	this.replicators = null;
	this.replicators_input = null;
}

/**
 * Check if the browser is Safari
 *
 * Safari's DOM importNode() method is broken so we use the IE table object
 * model hack for it as well.
 *
 * @var boolean
 */
SwatTableViewInputRow.isSafari = (navigator.userAgent.indexOf('Safari') != -1);

/**
 * Gets an XML parser with a loadXML() method
 */
function SwatTableViewInputRow_getXMLParser()
{
	var parser = null;
	var is_ie = true;

	try {
		var dom = new ActiveXObject('Msxml2.XMLDOM');
	} catch (err1) {
		try {
			var dom = new ActiveXObject('Microsoft.XMLDOM');
		} catch (err2) {
			is_ie = false;
		}
	}

	if (is_ie) {
		/*
		 * Internet Explorer's XMLDOM object has a proprietary loadXML()
		 * method. Our method returns the document.
		 */
		parser = function() {}
		parser.loadXML = function(document_string)
		{
			if (!dom.loadXML(document_string))
				alert(dom.parseError.reason);

			return dom;
		}
	}

	if (parser === null && typeof DOMParser != 'undefined') {
		/*
		 * Mozilla, Safari and Opera have a proprietary DOMParser()
		 * class.
		 */
		dom_parser = new DOMParser();

		// Cannot add loadXML method to a newly created DOMParser because it
		// crashes Safari
		parser = function() {}
		parser.loadXML = function(document_string)
		{
			return dom_parser.parseFromString(document_string, 'text/xml');
		}
	}

	return parser;
}

/**
 * The XML parser used by this widget
 *
 * @var Object
 */
SwatTableViewInputRow.parser = SwatTableViewInputRow_getXMLParser();

/*
 * If the browser does not support the importNode() method then we need to
 * manually copy nodes from one document to the current document. These methods
 * parse a HTMLTableRowNode in one document into a table row in this document.
 */
if (!document.importNode || SwatTableViewInputRow.isSafari) {

	/**
	 * Parses a table row from one document into another
	 *
	 * Internet Explorer does not allow writing to the innerHTML property for
	 * table row nodes so the table cells are individually inserted and cloned.
	 *
	 * @param HTMLTableRowNode source_tr the table row from the source document.
	 * @param HTMLTableRowNode dest_tr the table row in the destination
	 *                                  document.
	 */
	function SwatTableViewInputRow_parseTableRow(source_tr, dest_tr)
	{
		var child_node;
		var dest_td;
		for (var i = 0; i < source_tr.childNodes.length; i++) {
			child_node = source_tr.childNodes[i];
			if (child_node.nodeType == 1 && child_node.nodeName == 'td') {
				dest_td = dest_tr.insertCell(-1);
				source_attributes = child_node.attributes;
				for (var j = 0; j < source_attributes.length; j++) {
					if (source_attributes[j].name == 'class') {
						dest_td.className = source_attributes[j].value;
					} else {
						dest_td.setAttribute(source_attributes[j].name,
							source_attributes[j].value);
					}
				}
				SwatTableViewInputRow_parseTableCell(child_node, dest_td);
			}
		}
	}

	/**
	 * Parses a table cell from one document into another
	 *
	 * @param HTMLTableRowNode source_td the table cell from the source
	 *                                    document.
	 * @param HTMLTableRowNode dest_td the table cell in the destination
	 *                                  document.
	 */
	function SwatTableViewInputRow_parseTableCell(source_td, dest_td)
	{
		// Internet Explorer does not have an innerHTML property set on
		// imported DOM nodes even if the imported document is XHTML.
		if (source_td.innerHTML)
			dest_td.innerHTML = source_td.innerHTML;
		else
			dest_td.innerHTML = source_td.xml;
	}
}

/**
 * Initializes the replicator array
 *
 * @return boolean true if the replicators were successfully initialized and
 *          false if they were not.
 */
SwatTableViewInputRow.prototype.initReplicators = function()
{
	if (this.replicators === null) {
		this.replicators_input = document.getElementsByName(this.id +
			'_replicators')[0];

		if (this.replicators_input === null)
			return false;

		if (this.replicators_input.value == "")
			this.replicators = [];
		else
			this.replicators = this.replicators_input.value.split(',');
	}
	return true;
}

/**
 * Adds a new data row to the table
 */
SwatTableViewInputRow.prototype.addRow = function()
{
	if (!this.initReplicators())
		return;

	var replicator_id;
	if (this.replicators.length > 0)
		replicator_id = (parseInt(
			this.replicators[this.replicators.length - 1]) + 1).toString();
	else
		replicator_id = '0';

	this.replicators.push(replicator_id);
	this.replicators_input.value = this.replicators.join(',');

	var document_string = this.row_string.replace(/%s/g, replicator_id);
	var dom = SwatTableViewInputRow.parser.loadXML(document_string);
	var source_tr = dom.documentElement.getElementsByTagName('tr')[0];

	if (document.importNode && !SwatTableViewInputRow.isSafari) {
		var dest_tr = document.importNode(source_tr, true);
		this.enter_row.parentNode.insertBefore(dest_tr, this.enter_row);
	} else {
		/*
		 * Internet Explorer and Safari specific code
		 *
		 * Uses the table object model instead of the DOM. IE does not
		 * implement importNode() and Safari's importNode() implementation is
		 * broken.
		 */
		var dest_tr = this.table.insertRow(this.enter_row.rowIndex);
		SwatTableViewInputRow_parseTableRow(source_tr, dest_tr);
	}

	dest_tr.className = 'swat-table-view-input-row';
	dest_tr.id = this.id + '_row_' + replicator_id;

	// run scripts
	// a better way to do this might be to remvoe the script nodes from the
	// document and then run the scripts. This way we can ensure the scripts
	// are only run once.
	var scripts = dom.documentElement.getElementsByTagName('script');
	for (var i = 0; i < scripts.length; i++)
		if (scripts[0].getAttribute('type') == 'text/javascript' &&
			scripts[0].childNodes.length > 0)
				eval(scripts[i].firstChild.nodeValue);
}

/**
 * Remvoes a data row from the table
 */
SwatTableViewInputRow.prototype.removeRow = function(replicator_id)
{
	if (!this.initReplicators())
		return;

	// remove replicator_id from replicators array
	var replicator_index = -1;
	for (var i = 0; i < this.replicators.length; i++) {
		if (this.replicators[i] == replicator_id) {
			replicator_index = i;
			break;
		}
	}
	if (replicator_index != -1) {
		this.replicators.splice(replicator_index, 1);
		this.replicators_input.value = this.replicators.join(',');
	}

	// remove row from document
	var row_id = this.id + '_row_' + replicator_id;
	var row = document.getElementById(row_id);
	if (row && row.parentNode !== null) {
		row.parentNode.removeChild(row);
	}
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
*/

'use strict';

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Remarkable from 'remarkable';
// TODO: switch back to the upstream version of react-live
// once https://github.com/FormidableLabs/react-live/issues/37 is fixed.
import {LiveProvider, LiveEditor} from '@gaearon/react-live';
import {colors, media} from 'theme';
import MetaTitle from 'templates/components/MetaTitle';

const compile = code =>
  Babel.transform(code, {presets: ['es2015', 'react']}).code; // eslint-disable-line no-undef

class CodeEditor extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = this._updateState(props.code);
  }

  componentDidMount() {
    // Initial render() will always be a no-op,
    // Because the mountNode ref won't exist yet.
    this._render();
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.compiled !== this.state.compiled) {
      this._render();
    }
  }

  render() {
    const {children, code} = this.props;
    const {error} = this.state;

    return (
      <LiveProvider code={code} mountStylesheet={false}>
        <div
          css={{
            [media.greaterThan('xlarge')]: {
              display: 'flex',
              flexDirection: 'row',
            },

            [media.lessThan('large')]: {
              display: 'block',
            },
          }}>
          {children &&
            <div
              css={{
                flex: '0 0 33%',

                [media.lessThan('xlarge')]: {
                  marginBottom: 20,
                },

                '& h3': {
                  color: colors.dark,
                  maxWidth: '11em',
                  paddingTop: 0,
                },

                '& p': {
                  marginTop: 15,
                  marginRight: 40,
                  lineHeight: 1.7,

                  [media.greaterThan('xlarge')]: {
                    marginTop: 25,
                  },
                },
              }}>
              {children}
            </div>}

          <div
            css={{
              [media.greaterThan('medium')]: {
                flex: '0 0 67%',
                display: 'flex',
                alignItems: 'stretch',
                flexDirection: 'row',
              },

              [media.lessThan('small')]: {
                display: 'block',
              },
            }}>
            <div
              css={{
                flex: '0 0 70%',
                overflow: 'hidden',
                borderRadius: '10px 0 0 10px',

                [media.lessThan('small')]: {
                  borderRadius: '10px 10px 0 0',
                },
              }}>
              <div
                css={{
                  padding: '0px 10px',
                  background: colors.darker,
                  color: colors.white,
                }}>
                <MetaTitle onDark={true}>Live JSX Editor</MetaTitle>
              </div>
              <div
                css={{
                  height: '100%',
                  width: '100%',
                  borderRadius: '0',
                  marginTop: '0 !important',
                  marginLeft: '0 !important',
                  paddingLeft: '0 !important',
                  marginRight: '0 !important',
                  paddingRight: '0 !important',

                  '& pre.prism-code[contenteditable]': {
                    maxHeight: '280px !important',
                    outline: 0,
                  },
                }}
                className="gatsby-highlight">
                <LiveEditor onChange={this._onChange} />
              </div>
            </div>
            {error &&
              <div
                css={{
                  flex: '0 0 30%',
                  overflow: 'hidden',
                  border: `1px solid ${colors.error}`,
                  borderRadius: '0 10px 10px 0',
                  fontSize: 12,
                  lineHeight: 1.5,

                  [media.lessThan('small')]: {
                    borderRadius: '0 0 10px 10px',
                  },
                }}>
                <div
                  css={{
                    padding: '0px 10px',
                    background: colors.error,
                    color: colors.white,
                  }}>
                  <MetaTitle
                    cssProps={{
                      color: colors.white,
                    }}>
                    Error
                  </MetaTitle>
                </div>
                <pre
                  css={{
                    whiteSpace: 'pre-wrap',
                    wordBreak: 'break-word',
                    color: colors.error,
                    padding: 10,
                  }}>
                  {error.message}
                </pre>
              </div>}
            {!error &&
              <div
                css={{
                  flex: '0 0 30%',
                  overflow: 'hidden',
                  border: `1px solid ${colors.divider}`,
                  borderRadius: '0 10px 10px 0',

                  [media.lessThan('small')]: {
                    borderRadius: '0 0 10px 10px',
                  },
                }}>
                <div
                  css={{
                    padding: '0 10px',
                    backgroundColor: colors.divider,
                  }}>
                  <MetaTitle>Result</MetaTitle>
                </div>
                <div
                  css={{
                    padding: 10,

                    '& input': {
                      width: '100%',
                      display: 'block',
                      border: '1px solid #ccc', // TODO
                      padding: 5,
                    },

                    '& button': {
                      marginTop: 10,
                      padding: '5px 10px',
                    },

                    '& textarea': {
                      width: '100%',
                      marginTop: 10,
                      height: 60,
                      padding: 5,
                    },
                  }}
                  ref={this._setMountRef}
                />
              </div>}
          </div>
        </div>
      </LiveProvider>
    );
  }

  _render() {
    if (!this._mountNode) {
      return;
    }

    const {compiled} = this.state;

    try {
      // Example code requires React, ReactDOM, and Remarkable to be within scope.
      // It also requires a "mountNode" variable for ReactDOM.render()
      // eslint-disable-next-line no-new-func
      new Function('React', 'ReactDOM', 'Remarkable', 'mountNode', compiled)(
        React,
        ReactDOM,
        Remarkable,
        this._mountNode,
      );
    } catch (error) {
      console.error(error);

      this.setState({
        compiled: null,
        error,
      });
    }
  }

  _setMountRef = ref => {
    this._mountNode = ref;
  };

  _updateState(code) {
    try {
      return {
        compiled: compile(code),
        error: null,
      };
    } catch (error) {
      console.error(error);

      return {
        compiled: null,
        error,
      };
    }
  }

  _onChange = code => {
    this.setState(this._updateState(code));
  };
}

export default CodeEditor;
<commit_msg>Live code editor ignores tab key for improved a11y (#10992)<commit_after>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
*/

'use strict';

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Remarkable from 'remarkable';
// TODO: switch back to the upstream version of react-live
// once https://github.com/FormidableLabs/react-live/issues/37 is fixed.
import {LiveProvider, LiveEditor} from '@gaearon/react-live';
import {colors, media} from 'theme';
import MetaTitle from 'templates/components/MetaTitle';

const compile = code =>
  Babel.transform(code, {presets: ['es2015', 'react']}).code; // eslint-disable-line no-undef

class CodeEditor extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = this._updateState(props.code);
  }

  componentDidMount() {
    // Initial render() will always be a no-op,
    // Because the mountNode ref won't exist yet.
    this._render();
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.compiled !== this.state.compiled) {
      this._render();
    }
  }

  render() {
    const {children, code} = this.props;
    const {error} = this.state;

    return (
      <LiveProvider code={code} mountStylesheet={false}>
        <div
          css={{
            [media.greaterThan('xlarge')]: {
              display: 'flex',
              flexDirection: 'row',
            },

            [media.lessThan('large')]: {
              display: 'block',
            },
          }}>
          {children &&
            <div
              css={{
                flex: '0 0 33%',

                [media.lessThan('xlarge')]: {
                  marginBottom: 20,
                },

                '& h3': {
                  color: colors.dark,
                  maxWidth: '11em',
                  paddingTop: 0,
                },

                '& p': {
                  marginTop: 15,
                  marginRight: 40,
                  lineHeight: 1.7,

                  [media.greaterThan('xlarge')]: {
                    marginTop: 25,
                  },
                },
              }}>
              {children}
            </div>}

          <div
            css={{
              [media.greaterThan('medium')]: {
                flex: '0 0 67%',
                display: 'flex',
                alignItems: 'stretch',
                flexDirection: 'row',
              },

              [media.lessThan('small')]: {
                display: 'block',
              },
            }}>
            <div
              css={{
                flex: '0 0 70%',
                overflow: 'hidden',
                borderRadius: '10px 0 0 10px',

                [media.lessThan('small')]: {
                  borderRadius: '10px 10px 0 0',
                },
              }}>
              <div
                css={{
                  padding: '0px 10px',
                  background: colors.darker,
                  color: colors.white,
                }}>
                <MetaTitle onDark={true}>Live JSX Editor</MetaTitle>
              </div>
              <div
                css={{
                  height: '100%',
                  width: '100%',
                  borderRadius: '0',
                  marginTop: '0 !important',
                  marginLeft: '0 !important',
                  paddingLeft: '0 !important',
                  marginRight: '0 !important',
                  paddingRight: '0 !important',

                  '& pre.prism-code[contenteditable]': {
                    maxHeight: '280px !important',
                    outline: 0,
                  },
                }}
                className="gatsby-highlight">
                <LiveEditor onChange={this._onChange} ignoreTabKey={true} />
              </div>
            </div>
            {error &&
              <div
                css={{
                  flex: '0 0 30%',
                  overflow: 'hidden',
                  border: `1px solid ${colors.error}`,
                  borderRadius: '0 10px 10px 0',
                  fontSize: 12,
                  lineHeight: 1.5,

                  [media.lessThan('small')]: {
                    borderRadius: '0 0 10px 10px',
                  },
                }}>
                <div
                  css={{
                    padding: '0px 10px',
                    background: colors.error,
                    color: colors.white,
                  }}>
                  <MetaTitle
                    cssProps={{
                      color: colors.white,
                    }}>
                    Error
                  </MetaTitle>
                </div>
                <pre
                  css={{
                    whiteSpace: 'pre-wrap',
                    wordBreak: 'break-word',
                    color: colors.error,
                    padding: 10,
                  }}>
                  {error.message}
                </pre>
              </div>}
            {!error &&
              <div
                css={{
                  flex: '0 0 30%',
                  overflow: 'hidden',
                  border: `1px solid ${colors.divider}`,
                  borderRadius: '0 10px 10px 0',

                  [media.lessThan('small')]: {
                    borderRadius: '0 0 10px 10px',
                  },
                }}>
                <div
                  css={{
                    padding: '0 10px',
                    backgroundColor: colors.divider,
                  }}>
                  <MetaTitle>Result</MetaTitle>
                </div>
                <div
                  css={{
                    padding: 10,

                    '& input': {
                      width: '100%',
                      display: 'block',
                      border: '1px solid #ccc', // TODO
                      padding: 5,
                    },

                    '& button': {
                      marginTop: 10,
                      padding: '5px 10px',
                    },

                    '& textarea': {
                      width: '100%',
                      marginTop: 10,
                      height: 60,
                      padding: 5,
                    },
                  }}
                  ref={this._setMountRef}
                />
              </div>}
          </div>
        </div>
      </LiveProvider>
    );
  }

  _render() {
    if (!this._mountNode) {
      return;
    }

    const {compiled} = this.state;

    try {
      // Example code requires React, ReactDOM, and Remarkable to be within scope.
      // It also requires a "mountNode" variable for ReactDOM.render()
      // eslint-disable-next-line no-new-func
      new Function('React', 'ReactDOM', 'Remarkable', 'mountNode', compiled)(
        React,
        ReactDOM,
        Remarkable,
        this._mountNode,
      );
    } catch (error) {
      console.error(error);

      this.setState({
        compiled: null,
        error,
      });
    }
  }

  _setMountRef = ref => {
    this._mountNode = ref;
  };

  _updateState(code) {
    try {
      return {
        compiled: compile(code),
        error: null,
      };
    } catch (error) {
      console.error(error);

      return {
        compiled: null,
        error,
      };
    }
  }

  _onChange = code => {
    this.setState(this._updateState(code));
  };
}

export default CodeEditor;
<|endoftext|>