<commit_before>feature_name2id_list = {};
vizu_features = {};
attribute2id_list = {}

function make_style_getter(){
    var current = 0;
    var name2color = {};
    var colorlist = [
'#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', '#9edae5', '#98df8a', '#aec7e8', '#ffbb78', '#ff9896', '#c5b0d5', '#c49c94', '#f7b6d2', '#c7c7c7', '#dbdb8d'
        ];
    return function(name){
        if (!(name in name2color))
        {
            name2color[name] = colorlist[current++ % 10];
        }
        return {
                strokeWidth: 5,
                strokeColor: name2color[name],
                fillColor: 'black',
                cursor: 'pointer',
                fillOpacity : 0.1,
                pointRadius: 6
        };
    };
};
function makeHighlightCtrl() {
    hctrl = new OpenLayers.Control.SelectFeature(
        map.getControl('selectcontrol').layers.concat(map.getLayersByName('Marking Layer')[0]),
        {
            hover: true,
            highlightOnly: true,
            multiple: true,
            renderIntent: 'highlight',
            eventListeners: {
                featurehighlighted: show_feature_popup,
                featureunhighlighted: hide_feature_popup
            }
        }
    );
    return hctrl;
}
function toggleVisibility(e){
    var display = e.target.checked ? 'true' : 'none';
    var id_list = feature_name2id_list[e.target.id];
    var f;
    for (var i=0; i < id_list.length; i++){
        f = vizu_features[id_list[i]];
        f.style['display'] = display;
    }
    var markingLayer = map.getLayersByName('Marking Layer')[0].redraw();
}
function toggleVisibilityByAttribute(e){
    var display = e.target.checked ? 'true' : 'none';
    var id_list = attribute2id_list[e.target.id];
    var f;
    for (var i=0; i < id_list.length; i++){
        f = vizu_features[id_list[i]];
        f.style['display'] = display;
    }
    var markingLayer = map.getLayersByName('Marking Layer')[0].redraw();
}
var seen_hashes = {};
var str2hash = {};
function simple_hash(s){
    if (s in str2hash){
        return str2hash[s];
    }
    var hash = 0;
    if (s.length == 0) return hash;
    for (i = 0; i < s.length; i++) {
        char = s.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    hash = Math.abs(hash).toString();
    if (!(hash in seen_hashes)){
        seen_hashes[hash] = s;
        str2hash[s] = hash;
    } else {
        if (s != seen_hashes[hash]){
            str2hash[s] = hash;
        }
    }
    return hash;
}
function parse_features(data){
    if (data.features) {
        var markingLayer = map.getLayersByName('Marking Layer')[0];
        var get_style_for_name = make_style_getter();
        var gf = new OpenLayers.Format.GeoJSON(),
            i,
            source_proj = new OpenLayers.Projection(data.crs.properties.code),
            target_proj = new OpenLayers.Projection(map.getProjection());

        $('.loading').remove();
        $('#analysis-ctrl').prepend($('

').addClass('analysis-ctrl-main'));
        $('#analysis-ctrl').prepend('
Choose features to show
');
        var seen_f_a_keys = {};
        for (i = 0; i < data.features.length; i += 1) {
            var feature = gf.parseFeature(data.features[i]);
            var f_name = feature.attributes.name;
            feature.geometry.transform(source_proj, target_proj);
            feature.lonlat = gnt.questionnaire.get_popup_lonlat(feature.geometry);
            feature.style = get_style_for_name(f_name);
            feature = restyle_form_values(feature);
            vizu_features[i] = feature;
            if (!(f_name in feature_name2id_list)){
                feature_name2id_list[f_name] = Array();
                $('ul.analysis-ctrl-main')
                    .css('list-style','none')
                    .append(
                    $('

')
                        .append(
                            $('<input type="checkbox">')
                            .css('margin-right','5px')
                            .addClass('feature-level-ctrl')
                            .attr('id',f_name)
                            .attr('value',f_name)
                            .attr('checked','checked')
                            .change(toggleVisibility)
                        ).append(
                            $('')
                            .css('color',feature.style.strokeColor)
                            .text(f_name)
                            .attr('for',f_name)
                        ).append(
                            $('

')
                            .addClass(f_name)
                        )
                    );
            }
            for (var a_name in feature.attributes.form_values){
                var f_a_key = simple_hash([f_name, a_name].join('-AND-'));

                if (!(f_a_key in seen_f_a_keys)){
                    seen_f_a_keys[f_a_key] = true;
                    $('.'+f_name).append(
                        $('

')
                        .addClass('attr-ctrl')
                        .append($('

')
                            .css('color',feature.style.strokeColor)
                            .html(a_name))
                        .append($('

')
                            .css('list-style','none')
                            .css('padding',0)
                            .addClass(f_a_key))
                    );
                }
                for (var a_value in feature.attributes.form_values[a_name]){
                    var a_v_key = simple_hash([f_name, a_name, a_value].join('-AND-'));

                    if (!(a_v_key in attribute2id_list)){
                        attribute2id_list[a_v_key] = Array();
                        $('.'+f_a_key).append(
                            $('

')
                                .append(
                                    $('<input type="checkbox">')
                                    .css('margin-right','5px')
                                    .addClass('attribute-level-ctrl')
                                    .attr('id',a_v_key)
                                    .attr('value',a_v_key)
                                    .attr('checked','checked')
                                    .change(toggleVisibilityByAttribute)
                                ).append(
                                    $('')
                                    .css('color',feature.style.strokeColor)
                                    .text(a_value)
                                    .attr('for',a_v_key)
                                )
                        )
                    }
                    attribute2id_list[a_v_key].push(i);
                }
            }
            feature_name2id_list[f_name].push(i);
            markingLayer.addFeatures(feature);
        }
        $('.attr-ctrl').filter(function(){
            return $(this).find('li').length < 2;
        }).remove();
    }
}
function show_feedback() {
    map.getLayersByName('Route Layer')[0].setVisibility(false);
    map.getLayersByName('Point Layer')[0].setVisibility(false);
    map.getLayersByName('Area Layer')[0].setVisibility(false);
    var markingLayer = new OpenLayers.Layer.Vector("Marking Layer", {
            styleMap: new OpenLayers.StyleMap({
                'default': {
                        strokeWidth: 3,
                        strokeColor: 'red',
                        cursor: 'pointer',
                        fillColor: '#aaaaff',
                        fillOpacity: 0.3,
                        pointRadius: 5
                    },
                'highlight': {
                        strokeWidth: 3,
                        strokeColor: '#555555',
                        cursor: 'pointer',
                        fillColor: '#555555',
                        fillOpacity: 0.3,
                        pointRadius: 5
                    }
                })
        });
    map.addLayer(markingLayer);
    // The select_control needs to be deactivated and activated to make
    // hover and select on different layers to work together (done by setLayer)
    var select_control = map.getControl('selectcontrol');
    select_control.setLayer((select_control.layers).concat(markingLayer));

    $('#main #content').append(
            $('

')
            .attr('id','analysis-ctrl')
            ).append('
Loading...
');
    gnt.geo.get_features('@all',
                         data_group,
                         '',
        {'success': parse_features});
    var highlightCtrl = makeHighlightCtrl();
    map.addControl(highlightCtrl);
    highlightCtrl.activate();
}

function hide_feature_popup(e){
    $('div.feature_comments').hide();
}
function show_feature_popup(e){
    $('.feature_comments').html('').hide();
    $('.feature_comments').append('
'+e.feature.attributes.name+'
');
    var form_values = e.feature.attributes.form_values;
    for (var name in form_values) {
        $('.feature_comments').append('
'+name+'
');
        var ul = $('

');
        for (var value in form_values[name]) {
            ul.append(
                $('

').html(value)
                );
        }
        $('.feature_comments').append(ul);
    }
    $('.feature_comments').show();
}
function restyle_form_values(feature){
    var new_vals = {};
    var form_values = feature.attributes.form_values;
    for (i = 0; i < form_values.length; i += 1) {
        var v = form_values[i];
        if (!(v.name in new_vals)){
            new_vals[v.name] = {};
        }
        new_vals[v.name][v.value] = true;
    }
    feature.attributes.form_values = new_vals;
    return feature;
}
<commit_msg>bug fix<commit_after>feature_name2id_list = {};
vizu_features = {};
attribute2id_list = {}

function make_style_getter(){
    var current = 0;
    var name2color = {};
    var colorlist = [
'#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', '#9edae5', '#98df8a', '#aec7e8', '#ffbb78', '#ff9896', '#c5b0d5', '#c49c94', '#f7b6d2', '#c7c7c7', '#dbdb8d'
        ];
    return function(name){
        if (!(name in name2color))
        {
            name2color[name] = colorlist[current++ % 10];
        }
        return {
                strokeWidth: 5,
                strokeColor: name2color[name],
                fillColor: 'black',
                cursor: 'pointer',
                fillOpacity : 0.1,
                pointRadius: 6
        };
    };
};
function makeHighlightCtrl() {
    hctrl = new OpenLayers.Control.SelectFeature(
        map.getControl('selectcontrol').layers.concat(map.getLayersByName('Marking Layer')[0]),
        {
            hover: true,
            highlightOnly: true,
            multiple: true,
            renderIntent: 'highlight',
            eventListeners: {
                featurehighlighted: show_feature_popup,
                featureunhighlighted: hide_feature_popup
            }
        }
    );
    return hctrl;
}
function toggleVisibility(e){
    var display = e.target.checked ? 'true' : 'none';
    var id_list = feature_name2id_list[e.target.id];
    var f;
    for (var i=0; i < id_list.length; i++){
        f = vizu_features[id_list[i]];
        f.style['display'] = display;
    }
    var markingLayer = map.getLayersByName('Marking Layer')[0].redraw();
}
function toggleVisibilityByAttribute(e){
    var display = e.target.checked ? 'true' : 'none';
    var id_list = attribute2id_list[e.target.id];
    var f;
    for (var i=0; i < id_list.length; i++){
        f = vizu_features[id_list[i]];
        f.style['display'] = display;
    }
    var markingLayer = map.getLayersByName('Marking Layer')[0].redraw();
}
var seen_hashes = {};
var str2hash = {};
function simple_hash(s){
    if (s in str2hash){
        return str2hash[s];
    }
    var hash = 0;
    if (s.length == 0) return hash;
    for (i = 0; i < s.length; i++) {
        char = s.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    hash = Math.abs(hash).toString();
    if (!(hash in seen_hashes)){
        seen_hashes[hash] = s;
        str2hash[s] = hash;
    } else {
        if (s != seen_hashes[hash]){
            str2hash[s] = hash;
        }
    }
    return hash;
}
function parse_features(data){
    if (data.features) {
        var markingLayer = map.getLayersByName('Marking Layer')[0];
        var get_style_for_name = make_style_getter();
        var gf = new OpenLayers.Format.GeoJSON(),
            i,
            source_proj = new OpenLayers.Projection(data.crs.properties.code),
            target_proj = new OpenLayers.Projection(map.getProjection());

        $('.loading').remove();
        $('#analysis-ctrl').prepend($('

').addClass('analysis-ctrl-main'));
        $('#analysis-ctrl').prepend('
Choose features to show
');
        var seen_f_a_keys = {};
        for (i = 0; i < data.features.length; i += 1) {
            var feature = gf.parseFeature(data.features[i]);
            var f_name = feature.attributes.name;
            feature.geometry.transform(source_proj, target_proj);
            feature.lonlat = gnt.questionnaire.get_popup_lonlat(feature.geometry);
            feature.style = get_style_for_name(f_name);
            feature = restyle_form_values(feature);
            vizu_features[i] = feature;
            if (!(f_name in feature_name2id_list)){
                feature_name2id_list[f_name] = Array();
                $('ul.analysis-ctrl-main')
                    .css('list-style','none')
                    .append(
                    $('

')
                        .append(
                            $('<input type="checkbox">')
                            .css('margin-right','5px')
                            .addClass('feature-level-ctrl')
                            .attr('id',f_name)
                            .attr('value',f_name)
                            .attr('checked','checked')
                            .change(toggleVisibility)
                        ).append(
                            $('')
                            .css('color',feature.style.strokeColor)
                            .text(f_name)
                            .attr('for',f_name)
                        ).append(
                            $('

')
                            .addClass(f_name)
                        )
                    );
            }
            for (var a_name in feature.attributes.form_values){
                var f_a_key = simple_hash([f_name, a_name].join('-AND-'));

                if (!(f_a_key in seen_f_a_keys)){
                    seen_f_a_keys[f_a_key] = true;
                    $('.'+f_name).append(
                        $('

')
                        .addClass('attr-ctrl')
                        .append($('

')
                            .css('color',feature.style.strokeColor)
                            .html(a_name))
                        .append($('

')
                            .css('list-style','none')
                            .css('padding',0)
                            .addClass(f_a_key))
                    );
                }
                for (var a_value in feature.attributes.form_values[a_name]){
                    if (a_value.indexOf(' ') != -1 || !(isNaN(Number(a_value)))){
                        console.log('open question: ' + a_value);
                        continue;
                    }
                    var a_v_key = simple_hash([f_name, a_name, a_value].join('-AND-'));

                    if (!(a_v_key in attribute2id_list)){
                        attribute2id_list[a_v_key] = Array();
                        $('.'+f_a_key).append(
                            $('

')
                                .append(
                                    $('<input type="checkbox">')
                                    .css('margin-right','5px')
                                    .addClass('attribute-level-ctrl')
                                    .attr('id',a_v_key)
                                    .attr('value',a_v_key)
                                    .attr('checked','checked')
                                    .change(toggleVisibilityByAttribute)
                                ).append(
                                    $('')
                                    .css('color',feature.style.strokeColor)
                                    .text(a_value)
                                    .attr('for',a_v_key)
                                )
                        )
                    }
                    attribute2id_list[a_v_key].push(i);
                }
            }
            feature_name2id_list[f_name].push(i);
            markingLayer.addFeatures(feature);
        }
        $('.attr-ctrl').filter(function(){
            return $(this).find('li').length < 2;
        }).remove();
    }
}
function show_feedback() {
    map.getLayersByName('Route Layer')[0].setVisibility(false);
    map.getLayersByName('Point Layer')[0].setVisibility(false);
    map.getLayersByName('Area Layer')[0].setVisibility(false);
    var markingLayer = new OpenLayers.Layer.Vector("Marking Layer", {
            styleMap: new OpenLayers.StyleMap({
                'default': {
                        strokeWidth: 3,
                        strokeColor: 'red',
                        cursor: 'pointer',
                        fillColor: '#aaaaff',
                        fillOpacity: 0.3,
                        pointRadius: 5
                    },
                'highlight': {
                        strokeWidth: 3,
                        strokeColor: '#555555',
                        cursor: 'pointer',
                        fillColor: '#555555',
                        fillOpacity: 0.3,
                        pointRadius: 5
                    }
                })
        });
    map.addLayer(markingLayer);
    // The select_control needs to be deactivated and activated to make
    // hover and select on different layers to work together (done by setLayer)
    var select_control = map.getControl('selectcontrol');
    select_control.setLayer((select_control.layers).concat(markingLayer));

    $('#main #content').append(
            $('

')
            .attr('id','analysis-ctrl')
            ).append('
Loading...
');
    gnt.geo.get_features('@all',
                         data_group,
                         '',
        {'success': parse_features});
    var highlightCtrl = makeHighlightCtrl();
    map.addControl(highlightCtrl);
    highlightCtrl.activate();
}

function hide_feature_popup(e){
    $('div.feature_comments').hide();
}
function show_feature_popup(e){
    $('.feature_comments').html('').hide();
    $('.feature_comments').append('
'+e.feature.attributes.name+'
');
    var form_values = e.feature.attributes.form_values;
    for (var name in form_values) {
        $('.feature_comments').append('
'+name+'
');
        var ul = $('

');
        for (var value in form_values[name]) {
            ul.append(
                $('

').html(value)
                );
        }
        $('.feature_comments').append(ul);
    }
    $('.feature_comments').show();
}
function restyle_form_values(feature){
    var new_vals = {};
    var form_values = feature.attributes.form_values;
    for (i = 0; i < form_values.length; i += 1) {
        var v = form_values[i];
        if (!(v.name in new_vals)){
            new_vals[v.name] = {};
        }
        new_vals[v.name][v.value] = true;
    }
    feature.attributes.form_values = new_vals;
    return feature;
}
<|endoftext|>


<commit_before>
import React, {PropTypes, Component} from 'react'
import {connect} from './connect'

import * as actions from '../actions'

import Icon from './icon'

/**
 * Unapologetically and heavily inspired from Google Chrome's "shit went wrong" tab
 */
export class Toast extends Component {
  constructor () {
    super()
    this.state = {
      expanded: false
    }

    this.toggleExpand = ::this.toggleExpand
    this.sendFeedback = ::this.sendFeedback
    this.reload = ::this.reload
  }

  toggleExpand () {
    this.setState({
      expanded: !this.state.expanded
    })
  }

  sendFeedback () {
    const {reportIssue, data} = this.props
    const {error, stack} = data

    reportIssue({log: error + '\n\nstack:\n' + stack})
  }

  reload (e) {
    const {evolveTab, data, tabId} = this.props
    const {path} = data
    const untoastedPath = path.replace(/^toast\//, '')

    evolveTab({id: tabId, path: untoastedPath, quick: true})
  }

  render () {
    const {t, data = {}} = this.props

    return

      <Icon icon='heart-broken' classes='leader'/>

{t('toast.title')}

{t('toast.message')} {t('toast.call_to_action')}

	<Icon icon='repeat'/> {t('toast.actions.reload')}

      {t('toast.actions.learn_more')}

      {this.state.expanded
      ?
{data.error}

      : ''}

      {t('toast.actions.report')}

  }
}

Toast.propTypes = {
  t: PropTypes.func.isRequired,
  data: PropTypes.string.isRequired,
  tabId: PropTypes.string.isRequired,

  evolveTab: PropTypes.func.isRequired,
  reportIssue: PropTypes.func.isRequired
}

const mapStateToProps = (state) => ({})

const mapDispatchToProps = (dispatch) => ({
  evolveTab: (data) => dispatch(actions.evolveTab(data)),
  reportIssue: (payload) => dispatch(actions.reportIssue(payload))
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Toast)
<commit_msg>:shirt: more lint<commit_after>
import React, {PropTypes, Component} from 'react'
import {connect} from './connect'

import * as actions from '../actions'

import Icon from './icon'

/**
 * Unapologetically and heavily inspired from Google Chrome's "shit went wrong" tab
 */
export class Toast extends Component {
  constructor () {
    super()
    this.state = {
      expanded: false
    }

    this.toggleExpand = ::this.toggleExpand
    this.sendFeedback = ::this.sendFeedback
    this.reload = ::this.reload
  }

  toggleExpand () {
    this.setState({
      expanded: !this.state.expanded
    })
  }

  sendFeedback () {
    const {reportIssue, data} = this.props
    const {error, stack} = data

    reportIssue({log: error + '\n\nstack:\n' + stack})
  }

  reload (e) {
    const {evolveTab, data, tabId} = this.props
    const {path} = data
    const untoastedPath = path.replace(/^toast\//, '')

    evolveTab({id: tabId, path: untoastedPath, quick: true})
  }

  render () {
    const {t, data = {}} = this.props

    return

      <Icon icon='heart-broken' classes='leader'/>

{t('toast.title')}

{t('toast.message')} {t('toast.call_to_action')}

        <Icon icon='repeat'/> {t('toast.actions.reload')}

      {t('toast.actions.learn_more')}

      {this.state.expanded
      ?
{data.error}

      : ''}

      {t('toast.actions.report')}

  }
}

Toast.propTypes = {
  t: PropTypes.func.isRequired,
  data: PropTypes.string.isRequired,
  tabId: PropTypes.string.isRequired,

  evolveTab: PropTypes.func.isRequired,
  reportIssue: PropTypes.func.isRequired
}

const mapStateToProps = (state) => ({})

const mapDispatchToProps = (dispatch) => ({
  evolveTab: (data) => dispatch(actions.evolveTab(data)),
  reportIssue: (payload) => dispatch(actions.reportIssue(payload))
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Toast)
<|endoftext|>


<commit_before>import { Color } from '../math/Color.js';
import { Vector2 } from '../math/Vector2.js';
import { Vector3 } from '../math/Vector3.js';
import { Vector4 } from '../math/Vector4.js';
import { Matrix3 } from '../math/Matrix3.js';
import { Matrix4 } from '../math/Matrix4.js';
import { FileLoader } from './FileLoader.js';
import { Loader } from './Loader.js';
import * as Materials from '../materials/Materials.js';

/**
 * @author mrdoob / http://mrdoob.com/
 */

function MaterialLoader( manager ) {

	Loader.call( this, manager );

	this.textures = {};

}

MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: MaterialLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var loader = new FileLoader( scope.manager );
		loader.setPath( scope.path );
		loader.load( url, function ( text ) {

			onLoad( scope.parse( JSON.parse( text ) ) );

		}, onProgress, onError );

	},

	parse: function ( json ) {

		var textures = this.textures;

		function getTexture( name ) {

			if ( textures[ name ] === undefined ) {

				console.warn( 'THREE.MaterialLoader: Undefined texture', name );

			}

			return textures[ name ];

		}

		var material = new Materials[ json.type ]();

		if ( json.uuid !== undefined ) material.uuid = json.uuid;
		if ( json.name !== undefined ) material.name = json.name;
		if ( json.color !== undefined ) material.color.setHex( json.color );
		if ( json.roughness !== undefined ) material.roughness = json.roughness;
		if ( json.metalness !== undefined ) material.metalness = json.metalness;
		if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
		if ( json.specular !== undefined ) material.specular.setHex( json.specular );
		if ( json.shininess !== undefined ) material.shininess = json.shininess;
		if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
		if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
		if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
		if ( json.fog !== undefined ) material.fog = json.fog;
		if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
		if ( json.blending !== undefined ) material.blending = json.blending;
		if ( json.combine !== undefined ) material.combine = json.combine;
		if ( json.side !== undefined ) material.side = json.side;
		if ( json.opacity !== undefined ) material.opacity = json.opacity;
		if ( json.transparent !== undefined ) material.transparent = json.transparent;
		if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
		if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
		if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
		if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
		if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
		if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
		if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
		if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;

		if ( json.rotation !== undefined ) material.rotation = json.rotation;

		if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
		if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
		if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
		if ( json.scale !== undefined ) material.scale = json.scale;

		if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
		if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
		if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;

		if ( json.skinning !== undefined ) material.skinning = json.skinning;
		if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
		if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
		if ( json.dithering !== undefined ) material.dithering = json.dithering;

		if ( json.visible !== undefined ) material.visible = json.visible;

		if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;

		if ( json.userData !== undefined ) material.userData = json.userData;

		// Shader Material

		if ( json.uniforms !== undefined ) {

			for ( var name in json.uniforms ) {

				var uniform = json.uniforms[ name ];

				material.uniforms[ name ] = {};

				switch ( uniform.type ) {

					case 't':
						material.uniforms[ name ].value = getTexture( uniform.value );
						break;

					case 'c':
						material.uniforms[ name ].value = new Color().setHex( uniform.value );
						break;

					case 'v2':
						material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
						break;

					case 'v3':
						material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
						break;

					case 'v4':
						material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
						break;

					case 'm3':
						material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );

					case 'm4':
						material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
						break;

					default:
						material.uniforms[ name ].value = uniform.value;

				}

			}

		}

		if ( json.defines !== undefined ) material.defines = json.defines;
		if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
		if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;

		if ( json.extensions !== undefined ) {

			for ( var key in json.extensions ) {

				material.extensions[ key ] = json.extensions[ key ];

			}

		}

		// Deprecated

		if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading

		// for PointsMaterial

		if ( json.size !== undefined ) material.size = json.size;
		if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;

		// maps

		if ( json.map !== undefined ) material.map = getTexture( json.map );
		if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );

		if ( json.alphaMap !== undefined ) {

			material.alphaMap = getTexture( json.alphaMap );
			material.transparent = true;

		}

		if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
		if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;

		if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
		if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
		if ( json.normalScale !== undefined ) {

			var normalScale = json.normalScale;

			if ( Array.isArray( normalScale ) === false ) {

				// Blender exporter used to export a scalar. See #7459

				normalScale = [ normalScale, normalScale ];

			}

			material.normalScale = new Vector2().fromArray( normalScale );

		}

		if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
		if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
		if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;

		if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
		if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );

		if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
		if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;

		if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );

		if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
		if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;

		if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
		if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;

		if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
		if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;

		if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
		if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;

		if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );

		if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
		if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );

		return material;

	},

	setTextures: function ( value ) {

		this.textures = value;
		return this;

	}

} );

export { MaterialLoader };
<commit_msg>Update MaterialLoader<commit_after>import { Color } from '../math/Color.js';
import { Vector2 } from '../math/Vector2.js';
import { Vector3 } from '../math/Vector3.js';
import { Vector4 } from '../math/Vector4.js';
import { Matrix3 } from '../math/Matrix3.js';
import { Matrix4 } from '../math/Matrix4.js';
import { FileLoader } from './FileLoader.js';
import { Loader } from './Loader.js';
import * as Materials from '../materials/Materials.js';

/**
 * @author mrdoob / http://mrdoob.com/
 */

function MaterialLoader( manager ) {

	Loader.call( this, manager );

	this.textures = {};

}

MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: MaterialLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var loader = new FileLoader( scope.manager );
		loader.setPath( scope.path );
		loader.load( url, function ( text ) {

			onLoad( scope.parse( JSON.parse( text ) ) );

		}, onProgress, onError );

	},

	parse: function ( json ) {

		var textures = this.textures;

		function getTexture( name ) {

			if ( textures[ name ] === undefined ) {

				console.warn( 'THREE.MaterialLoader: Undefined texture', name );

			}

			return textures[ name ];

		}

		var material = new Materials[ json.type ]();

		if ( json.uuid !== undefined ) material.uuid = json.uuid;
		if ( json.name !== undefined ) material.name = json.name;
		if ( json.color !== undefined ) material.color.setHex( json.color );
		if ( json.roughness !== undefined ) material.roughness = json.roughness;
		if ( json.metalness !== undefined ) material.metalness = json.metalness;
		if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
		if ( json.specular !== undefined ) material.specular.setHex( json.specular );
		if ( json.shininess !== undefined ) material.shininess = json.shininess;
		if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
		if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
		if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
		if ( json.fog !== undefined ) material.fog = json.fog;
		if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
		if ( json.blending !== undefined ) material.blending = json.blending;
		if ( json.combine !== undefined ) material.combine = json.combine;
		if ( json.side !== undefined ) material.side = json.side;
		if ( json.opacity !== undefined ) material.opacity = json.opacity;
		if ( json.transparent !== undefined ) material.transparent = json.transparent;
		if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
		if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
		if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
		if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;

		if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
		if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
		if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
		if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
		if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
		if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
		if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
		if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;

		if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
		if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
		if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
		if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;

		if ( json.rotation !== undefined ) material.rotation = json.rotation;

		if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
		if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
		if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
		if ( json.scale !== undefined ) material.scale = json.scale;

		if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
		if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
		if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;

		if ( json.skinning !== undefined ) material.skinning = json.skinning;
		if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
		if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
		if ( json.dithering !== undefined ) material.dithering = json.dithering;

		if ( json.visible !== undefined ) material.visible = json.visible;

		if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;

		if ( json.userData !== undefined ) material.userData = json.userData;

		// Shader Material

		if ( json.uniforms !== undefined ) {

			for ( var name in json.uniforms ) {

				var uniform = json.uniforms[ name ];

				material.uniforms[ name ] = {};

				switch ( uniform.type ) {

					case 't':
						material.uniforms[ name ].value = getTexture( uniform.value );
						break;

					case 'c':
						material.uniforms[ name ].value = new Color().setHex( uniform.value );
						break;

					case 'v2':
						material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
						break;

					case 'v3':
						material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
						break;

					case 'v4':
						material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
						break;

					case 'm3':
						material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );

					case 'm4':
						material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
						break;

					default:
						material.uniforms[ name ].value = uniform.value;

				}

			}

		}

		if ( json.defines !== undefined ) material.defines = json.defines;
		if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
		if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;

		if ( json.extensions !== undefined ) {

			for ( var key in json.extensions ) {

				material.extensions[ key ] = json.extensions[ key ];

			}

		}

		// Deprecated

		if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading

		// for PointsMaterial

		if ( json.size !== undefined ) material.size = json.size;
		if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;

		// maps

		if ( json.map !== undefined ) material.map = getTexture( json.map );
		if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );

		if ( json.alphaMap !== undefined ) {

			material.alphaMap = getTexture( json.alphaMap );
			material.transparent = true;

		}

		if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
		if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;

		if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
		if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
		if ( json.normalScale !== undefined ) {

			var normalScale = json.normalScale;

			if ( Array.isArray( normalScale ) === false ) {

				// Blender exporter used to export a scalar. See #7459

				normalScale = [ normalScale, normalScale ];

			}

			material.normalScale = new Vector2().fromArray( normalScale );

		}

		if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
		if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
		if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;

		if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
		if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );

		if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
		if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;

		if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );

		if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
		if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;

		if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
		if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;

		if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
		if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;

		if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
		if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;

		if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );

		if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
		if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );

		return material;

	},

	setTextures: function ( value ) {

		this.textures = value;
		return this;

	}

} );

export { MaterialLoader };
<|endoftext|>


<commit_before>import { fetchBuilder, extractData, buildWith } from './model_builder';

function postProcess(response, urlExtra) {
  let data = extractData(response);

  if (Array.isArray(data) && data.length === 0) {
    data = [];
  }

  return {[urlExtra]: data};
}

const customActions = {
  fetch: function (vuexObject, {year, quarter}) {
    return fetchBuilder(
      '/api/v1/myplan/', postProcess, 'json'
    )(vuexObject, `${year}/${quarter}`);
  },
};

export default buildWith(
  { customActions },
);<commit_msg>Changed the default type for myplan data<commit_after>import { fetchBuilder, extractData, buildWith } from './model_builder';

function postProcess(response, urlExtra) {
  let data = extractData(response);

  if (Array.isArray(data) && data.length === 0) {
    data = {};
  }

  return {[urlExtra]: data};
}

const customActions = {
  fetch: function (vuexObject, {year, quarter}) {
    return fetchBuilder(
      '/api/v1/myplan/', postProcess, 'json'
    )(vuexObject, `${year}/${quarter}`);
  },
};

export default buildWith(
  { customActions },
);<|endoftext|>


<commit_before>var MyGradCard = {
    name: 'MyGradCard',
    dom_target: undefined,

    render_init: function() {
        WSData.fetch_mygrad_data(MyGradCard.render_upon_data, MyGradCard.show_error);
    },

    render_upon_data: function() {
        if (!MyGradCard._has_all_data()) {
            return;
        }
        MyGradCard._render(WSData.mygrad_data());
    },

    _render: function (mygrad_data) {
        var source = $("#mygrad_card_content").html();
        var template = Handlebars.compile(source);
        if (!mygrad_data.degrees && !mygrad_data.committees && !mygrad_data.leaves && !mygrad_data.petitions) {
            MyGradCard.dom_target.hide();
            return;
        }

        for (var i = 0; i < mygrad_data.committees.length; i += 1) {
            var members = mygrad_data.committees[i].members;
            for (var j = 0; j < members.length; j += 1) {
                if (members[j].member_type === "member") {
                    members[j].member_type = null;
                }
            }
        }
        MyGradCard.dom_target.html(template(mygrad_data));
    },

    _has_all_data: function () {
        if (WSData.mygrad_data()) {
            return true;
        }
        return false;
    },

    show_error: function() {
        MyGradCard.dom_target.html(CardWithError.render("MyGrad"));
    }

};
<commit_msg>Fix bug my last commit 45ec0a7 - handle the case where committee is null.<commit_after>var MyGradCard = {
    name: 'MyGradCard',
    dom_target: undefined,

    render_init: function() {
        WSData.fetch_mygrad_data(MyGradCard.render_upon_data, MyGradCard.show_error);
    },

    render_upon_data: function() {
        if (!MyGradCard._has_all_data()) {
            return;
        }
        MyGradCard._render(WSData.mygrad_data());
    },

    _render: function (mygrad_data) {
        var source = $("#mygrad_card_content").html();
        var template = Handlebars.compile(source);
        if (!mygrad_data.degrees && !mygrad_data.committees && !mygrad_data.leaves && !mygrad_data.petitions) {
            MyGradCard.dom_target.hide();
            return;
        }
        if (mygrad_data.committees !== null) {
            for (var i = 0; i < mygrad_data.committees.length; i += 1) {
                var members = mygrad_data.committees[i].members;
                for (var j = 0; j < members.length; j += 1) {
                    if (members[j].member_type === "member") {
                        members[j].member_type = null;
                    }
                }
            }
        }
        MyGradCard.dom_target.html(template(mygrad_data));
    },

    _has_all_data: function () {
        if (WSData.mygrad_data()) {
            return true;
        }
        return false;
    },

    show_error: function() {
        MyGradCard.dom_target.html(CardWithError.render("MyGrad"));
    }

};
<|endoftext|>


<commit_before>import React from 'react';
import { skinnable, contains } from 'revenge';
import { t, props } from 'tcomb-react';
import mapKeys from 'lodash/mapKeys';
import mapValues from 'lodash/mapValues';
import reduce from 'lodash/reduce';
import pick from 'lodash/pick';
import omit from 'lodash/omit';
import displayName from './displayName';

export default function localizePropsDecorator({ containerNamespace, local }) {

  const localKeys = Object.keys(local);
  const globalizedLocalKeys = localKeys.map(k => `${containerNamespace}${k}`);

  const globalizeLocalKeys = obj => mapKeys(obj, (_, k) => {
    if (local[k]) {
      return `${containerNamespace}${k}`;
    }
    return k;
  });

  const globalizedLocalTypes = globalizeLocalKeys(mapValues(local, ty => {
    return t.maybe(t.dict(t.String, ty));
  }) || {});

  const decorator = Component => {
    @skinnable(contains(Component))
    @props({
      ___local: t.maybe(t.interface(globalizedLocalTypes, { strict: false })),
      transition: t.Function
    }, { strict: false })
    class LocalizePropsWrapper extends React.Component {
      static displayName = displayName(Component, 'localizeProps');

      static _instanceCount = 0;

      globalizeLocalState = obj => reduce(obj, (acc, v, k) => {
        const globalKey = `${containerNamespace}${k}`;

        const { ___local = {} } = this.props;

        return {
          ...acc,
          [globalKey]: {
            ...___local[globalKey],
            [this.instanceNamespace]: v
          }
        };
      }, {});

      localizeLocalState = obj => reduce(obj, (acc, v, k) => {
        const localKey = k.replace(containerNamespace, '');
        return {
          ...acc,
          [localKey]: local[localKey] && v ? v[this.instanceNamespace] : v
        };
      }, {});

      transitionWithLocal = (...args) => {
        if (args.length === 1 && t.Object.is(args[0])) {
          const patch = args[0];
          const localProps = this.globalizeLocalState(pick(patch, localKeys));
          const globalProps = omit(patch, localKeys);

          return this.props.transition(oldstate => ({
            ...oldstate,
            ...globalProps,
            ___local: {
              ...oldstate.___local,
              ...localProps
            }
          }));
        }
        throw new Error(`Sorry, local transitions do not yet support arguments ${args.map(v => typeof v).join(',')}`);
      }

      localizeProps = ({ ___local = {}, ...props }) => ({
        ...props,
        ...this.localizeLocalState(pick(___local, globalizedLocalKeys)),
        transition: this.transitionWithLocal
      });

      getLocals = this.localizeProps;

      componentWillMount = () => {
        LocalizePropsWrapper._instanceCount += 1; // eslint-disable-line operator-assignment
        this.instanceNamespace = `instance-${LocalizePropsWrapper._instanceCount}`;
      }

      componentWillUnmount = () => {
        // cleanup local keys when dead
        setTimeout(() => {
          this.transitionWithLocal(mapValues(local, () => undefined));
        });
      }
    }
    return LocalizePropsWrapper;
  };
  decorator.GlobalDeclaration = globalizedLocalTypes;
  decorator.Type = { ...local, transition: t.Function };

  return decorator;
}
<commit_msg>omit nil (instances) values, omit empty (container namespaced dictionaries)<commit_after>import React from 'react';
import { skinnable, contains } from 'revenge';
import { t, props } from 'tcomb-react';
import mapKeys from 'lodash/mapKeys';
import mapValues from 'lodash/mapValues';
import reduce from 'lodash/reduce';
import pick from 'lodash/pick';
import omit from 'lodash/omit';
import omitByF from 'lodash/fp/omitBy';
import isEqualF from 'lodash/fp/isEqual';
import isNil from 'lodash/isNil';
import displayName from './displayName';

const omitNils = omitByF(isNil);
const omitEmpties = omitByF(isEqualF({}));

export default function localizePropsDecorator({ containerNamespace, local }) {

  const localKeys = Object.keys(local);
  const globalizedLocalKeys = localKeys.map(k => `${containerNamespace}${k}`);

  const globalizeLocalKeys = obj => mapKeys(obj, (_, k) => {
    if (local[k]) {
      return `${containerNamespace}${k}`;
    }
    return k;
  });

  const globalizedLocalTypes = globalizeLocalKeys(mapValues(local, ty => {
    return t.maybe(t.dict(t.String, ty));
  }) || {});

  const decorator = Component => {
    @skinnable(contains(Component))
    @props({
      ___local: t.maybe(t.interface(globalizedLocalTypes, { strict: false })),
      transition: t.Function
    }, { strict: false })
    class LocalizePropsWrapper extends React.Component {
      static displayName = displayName(Component, 'localizeProps');

      static _instanceCount = 0;

      globalizeLocalState = obj => reduce(obj, (acc, v, k) => {
        const globalKey = `${containerNamespace}${k}`;

        const { ___local = {} } = this.props;

        return {
          ...acc,
          [globalKey]: omitNils({
            ...___local[globalKey],
            [this.instanceNamespace]: v
          })
        };
      }, {});

      localizeLocalState = obj => reduce(obj, (acc, v, k) => {
        const localKey = k.replace(containerNamespace, '');
        return {
          ...acc,
          [localKey]: local[localKey] && v ? v[this.instanceNamespace] : v
        };
      }, {});

      transitionWithLocal = (...args) => {
        if (args.length === 1 && t.Object.is(args[0])) {
          const patch = args[0];
          const localProps = this.globalizeLocalState(pick(patch, localKeys));
          const globalProps = omit(patch, localKeys);

          return this.props.transition(oldstate => ({
            ...oldstate,
            ...globalProps,
            ___local: omitEmpties({
              ...oldstate.___local,
              ...localProps
            })
          }));
        }
        throw new Error(`Sorry, local transitions do not yet support arguments ${args.map(v => typeof v).join(',')}`);
      }

      localizeProps = ({ ___local = {}, ...props }) => ({
        ...props,
        ...this.localizeLocalState(pick(___local, globalizedLocalKeys)),
        transition: this.transitionWithLocal
      });

      getLocals = this.localizeProps;

      componentWillMount = () => {
        LocalizePropsWrapper._instanceCount += 1; // eslint-disable-line operator-assignment
        this.instanceNamespace = `instance-${LocalizePropsWrapper._instanceCount}`;
      }

      componentWillUnmount = () => {
        // cleanup local keys when dead
        setTimeout(() => {
          this.transitionWithLocal(mapValues(local, () => undefined));
        });
      }
    }
    return LocalizePropsWrapper;
  };
  decorator.GlobalDeclaration = globalizedLocalTypes;
  decorator.Type = { ...local, transition: t.Function };

  return decorator;
}
<|endoftext|>


<commit_before>module.exports = {
    core: {
        tracking: {
            trackingId: 'UA-66924051-1'
        }
    },

    assets: {
        modulesOptions : {
            search: {
                autoFocusOnNavigationPage: false
            }
        }
    }
};<commit_msg>fix main page autofocus<commit_after>module.exports = {
    core: {
        tracking: {
            trackingId: 'UA-66924051-1'
        }
    },

    assets: {
        modulesOptions : {
            search: {
                autofocusOnNavigationPage: false
            }
        }
    }
};
<|endoftext|>


<commit_before>//  Copyright 2010 Henry A Schimke
//  See license.txt for details

/**
 * Saves options to localStorage.
 */
function save_options_select() {
    var id_hold = $('#folder-list option:selected').val();
    var quick_click_mode = $('#use-quick-click-mode-cb').attr('checked');

    localStorage["queue_folder_id"] = id_hold;
    localStorage["use_quick_click_mode"] = quick_click_mode;

    chrome.extension.getBackgroundPage().title_folder_id = id_hold;
    chrome.extension.getBackgroundPage().set_folder_parent();

    populate_select();
}

/**
 * Recurse over bookmarks and add folders to the dropdown list
 */
function traverse_bookmarks( results ){
	for (var j = 0; j < results.length; j++) {
		var res = results[j];

		add_option_bkmrk( res );

		chrome.bookmarks.getChildren( res.id, traverse_bookmarks );
	}

	if( results.length == 0 ){
		restore_options();
	}
}

/**
 * If a bookmark is a folder (has no url) add it to the dropdown list
 */
function add_option_bkmrk( mark ){
	if( mark.id != "0" ){
		if( mark.url == undefined ){
			add_option( mark.title, mark.id );
		}
	}
}

/**
 * Add an option to the folder-list dropdown box
 * @param {String} opt_text Text for the new item in the dropdown list
 * @param {String} opt_val Select value for the new item in the dropdown list
 */
function add_option( opt_text, opt_val ) {
    $('<option></option>', {
        'value': opt_val,
        'text': opt_text
    }).appendTo( $('#folder-list') );
}

/**
 * Clear and then fill the folder-list dropdown list with bookmarks
 */
function populate_select() {
	$('#folder-list').html("");
	chrome.bookmarks.getTree( traverse_bookmarks );
}

/**
 * Set the source folder for queued links in the dropdown list
 */
function restore_options_2( bkmrk ){
    $('#folder-list').val( bkmrk[0].id );
}

/**
 * If a folder has been saved, load the select optoins and set the selected folder
 */
function restore_options() {
	var saved_id = localStorage["queue_folder_id"];
	if (!saved_id) {
		return;
	}

	chrome.bookmarks.get( saved_id, restore_options_2 );
}

/**
 * Initialize the page
 */
function start_up(){
	populate_select();
	if( localStorage["use_quick_click_mode"] == true || localStorage["use_quick_click_mode"] == 'true' ) {
	    $('#use-quick-click-mode-cb').attr("checked", true);
//	    quick_click_select.checked = true;
	}
}

$(function() {
    start_up();
    $('#save-button').click(
        function() {
            save_options_select();
        } );
});
<commit_msg>Added save of keyboard bindings<commit_after>//  Copyright 2010 Henry A Schimke
//  See license.txt for details

/**
 * Saves options to localStorage.
 */
function save_options_select() {
    var id_hold = $('#folder-list option:selected').val();
    var quick_click_mode = $('#use-quick-click-mode-cb').attr('checked');

    localStorage["queue_folder_id"] = id_hold;
    localStorage["use_quick_click_mode"] = quick_click_mode;

    // Keyboard Bindings
    var kb_a_mod_1 = $('#kb-binding-a-mod-1 option:selected').val();
    var kb_a_mod_2 = $('#kb-binding-a-mod-2 option:selected').val();
    var kb_a_key = $('#kb-binding-a-key').val();

    var kb_b_mod_1 = $('#kb-binding-b-mod-1 option:selected').val();
    var kb_b_mod_1 = $('#kb-binding-b-mod-2 option:selected').val();
    var kb_b_key = $('#kb-binding-b-key').val();

    localStorage["kb_a_mod_1"] = kb_a_mod_1;
    localStorage["kb_a_mod_2"] = kb_a_mod_2;
    localStorage["kb_a_key"] = kb_a_key;

    localStorage["kb_b_mod_1"] = kb_b_mod_1;
    localStorage["kb_b_mod_2"] = kb_b_mod_1;
    localStorage["kb_b_key"] = kb_b_key;

    // Update bg script settings
    chrome.extension.getBackgroundPage().title_folder_id = id_hold;
    chrome.extension.getBackgroundPage().set_folder_parent();

    // Reset folder list drop down
    populate_select();
}

/**
 * Recurse over bookmarks and add folders to the dropdown list
 */
function traverse_bookmarks( results ){
	for (var j = 0; j < results.length; j++) {
		var res = results[j];

		add_option_bkmrk( res );

		chrome.bookmarks.getChildren( res.id, traverse_bookmarks );
	}

	if( results.length == 0 ){
		restore_options();
	}
}

/**
 * If a bookmark is a folder (has no url) add it to the dropdown list
 */
function add_option_bkmrk( mark ){
	if( mark.id != "0" ){
		if( mark.url == undefined ){
			add_option( mark.title, mark.id );
		}
	}
}

/**
 * Add an option to the folder-list dropdown box
 * @param {String} opt_text Text for the new item in the dropdown list
 * @param {String} opt_val Select value for the new item in the dropdown list
 */
function add_option( opt_text, opt_val ) {
    $('<option></option>', {
        'value': opt_val,
        'text': opt_text
    }).appendTo( $('#folder-list') );
}

/**
 * Clear and then fill the folder-list dropdown list with bookmarks
 */
function populate_select() {
	$('#folder-list').html("");
	chrome.bookmarks.getTree( traverse_bookmarks );
}

/**
 * Set the source folder for queued links in the dropdown list
 */
function restore_options_2( bkmrk ){
    $('#folder-list').val( bkmrk[0].id );
}

/**
 * If a folder has been saved, load the select optoins and set the selected folder
 */
function restore_options() {
	var saved_id = localStorage["queue_folder_id"];
	if (!saved_id) {
		return;
	}

	chrome.bookmarks.get( saved_id, restore_options_2 );
}

/**
 * Initialize the page
 */
function start_up(){
	populate_select();
	if( localStorage["use_quick_click_mode"] == true || localStorage["use_quick_click_mode"] == 'true' ) {
	    $('#use-quick-click-mode-cb').attr("checked", true);
//	    quick_click_select.checked = true;
	}
}

$(function() {
    start_up();
    $('#save-button').click(
        function() {
            save_options_select();
        } );
});
<|endoftext|>


<commit_before>'use strict'
const Vec2 = require('pex-math/Vec2')
const Vec3 = require('pex-math/Vec3')
const Mat4 = require('pex-math/Mat4')
const Ray = require('pex-geom/Ray')
const clamp = require('pex-math/Utils').clamp

function getViewRay (camera, x, y, windowWidth, windowHeight) {
  const hNear = 2 * Math.tan(camera.fov / 2) * camera.near
  const wNear = hNear * camera.aspect
  let px = (x - windowWidth / 2) / (windowWidth / 2)
  let py = -(y - windowHeight / 2) / (windowHeight / 2)
  px *= wNear / 2
  py *= hNear / 2
  const origin = [0, 0, 0]
  const direction = Vec3.normalize([px, py, -camera.near])
  return [origin, direction]
}

function latLonToXyz (lat, lon, out) {
  out = out || [0, 0, 0]
  const theta = lat
  const phi = lon
  out[0] = Math.cos(theta) * Math.cos(phi)
  out[1] = Math.sin(theta)
  out[2] = Math.cos(theta) * Math.sin(phi)
  return out
}

function xyzToLatLon (normalizedPosition, out) {
  out = out || [0, 0]
  out[0] = Math.asin(normalizedPosition[1])// + Math.PI / 2 // lat
  out[1] = Math.atan2(normalizedPosition[2], normalizedPosition[0])// + Math.PI / 2 // lon
  return out
}

function createOrbiter (opts) {
  // TODO: split into internal state and public state
  const initialState = {
    camera: opts.camera,
    invViewMatrix: Mat4.create(),
    dragging: false,
    lat: 0, // Y
    lon: 0, // XZ
    element: opts.element || window,
    width: 0,
    height: 0,
    clickPosWindow: [0, 0],
    dragPos: [0, 0, 0],
    dragPosWindow: [0, 0],
    distance: 1,
    minDistance: 1,
    maxDistance: 1,
    zoom: true,
    // enabled: true,
    clickTarget: [0, 0, 0],
    clickPosPlane: [0, 0, 0],
    dragPosPlane: [0, 0, 0],
    clickPosWorld: [0, 0, 0],
    dragPosWorld: [0, 0, 0],
    panPlane: null
  }

  function orbiter (opts) {
    Object.assign(orbiter, opts)

    if (opts.camera) {
      const distance = Vec3.distance(opts.camera.position, opts.camera.target)
      const latLon = xyzToLatLon(Vec3.normalize(Vec3.sub(Vec3.copy(opts.camera.position), opts.camera.target)))
      orbiter.lat = latLon[0]
      orbiter.lon = latLon[1]
      orbiter.distance = distance
      orbiter.minDistance = distance / 10
      orbiter.maxDistance = distance * 10
    }

    return orbiter
  }

  function updateWindowSize () {
    const width = orbiter.element.clientWidth || orbiter.element.innerWidth
    const height = orbiter.element.clientHeight || orbiter.element.innerHeight
    if (width !== orbiter.width) {
      orbiter.width = width
      orbiter.height = height
      orbiter.radius = Math.min(orbiter.width / 2, orbiter.height / 2)
      orbiter.center = [orbiter.width / 2, orbiter.height / 2]
    }
  }

  function updateCamera () {
    // instad of rotating the object we want to move camera around it
    // state.currRot[3] *= -1

    const position = orbiter.camera.position
    const target = orbiter.camera.target

    // set new camera position according to the current
    // rotation at distance relative to target
    latLonToXyz(orbiter.lat, orbiter.lon, position)
    Vec3.scale(position, orbiter.distance)
    Vec3.add(position, target)

    orbiter.camera({
      position: position
    })
  }

  function down (x, y, shift) {
    orbiter.dragging = true
    orbiter.dragPos[0] = x
    orbiter.dragPos[1] = y
    if (shift) {
      Vec2.set2(orbiter.clickPosWindow, x, y)
      Vec3.set(orbiter.clickTarget, orbiter.camera.target)
      const targetInViewSpace = Vec3.multMat4(Vec3.copy(orbiter.clickTarget), orbiter.camera.viewMatrix)
      orbiter.panPlane = [targetInViewSpace, [0, 0, 1]]
      Ray.hitTestPlane(
        getViewRay(orbiter.camera, orbiter.clickPosWindow[0], orbiter.clickPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.clickPosPlane
      )
      Ray.hitTestPlane(
        getViewRay(orbiter.camera, orbiter.dragPosWindow[0], orbiter.dragPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.dragPosPlane
      )
    } else {
      orbiter.panPlane = null
    }
  }

  function move (x, y, shift) {
    if (!orbiter.dragging) {
      return
    }
    if (shift && orbiter.panPlane) {
      Vec2.set2(orbiter.dragPosWindow, x, y)
      Ray.hitTestPlane(
        getViewRay(orbiter.camera, orbiter.clickPosWindow[0], orbiter.clickPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.clickPosPlane
      )
      Ray.hitTestPlane(
        getViewRay(orbiter.camera, orbiter.dragPosWindow[0], orbiter.dragPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.dragPosPlane
      )
      Mat4.set(orbiter.invViewMatrix, orbiter.camera.viewMatrix)
      Mat4.invert(orbiter.invViewMatrix)
      Vec3.multMat4(Vec3.set(orbiter.clickPosWorld, orbiter.clickPosPlane), orbiter.invViewMatrix)
      Vec3.multMat4(Vec3.set(orbiter.dragPosWorld, orbiter.dragPosPlane), orbiter.invViewMatrix)
      const diffWorld = Vec3.sub(Vec3.copy(orbiter.dragPosWorld), orbiter.clickPosWorld)
      const target = Vec3.sub(Vec3.copy(orbiter.clickTarget), diffWorld)
      orbiter.camera({ target: target })
      updateCamera()
    } else {
      const dx = x - orbiter.dragPos[0]
      const dy = y - orbiter.dragPos[1]
      orbiter.dragPos[0] = x
      orbiter.dragPos[1] = y

      // TODO: how to have resolution independed scaling? will this code behave differently with retina/pixelRatio=2?
      orbiter.lat = clamp(orbiter.lat + dy / 200, -Math.PI / 2, Math.PI / 2)

      orbiter.lon += dx / 200
      orbiter.lon = orbiter.lon % (2 * Math.PI)

      updateCamera()
    }
  }

  function up () {
    orbiter.dragging = false
    orbiter.panPlane = null
  }

  function scroll (dy) {
    if (!orbiter.zoom) {
      return
    }
    orbiter.distance = orbiter.distance + dy / 50
    orbiter.distance = clamp(orbiter.distance, orbiter.minDistance, orbiter.maxDistance)
    updateCamera()
  }

  function onMouseDown (e) {
    updateWindowSize()
    down(
      e.offsetX || e.clientX || (e.touches ? e.touches[0].clientX : 0),
      e.offsetY || e.clientY || (e.touches ? e.touches[0].clientY : 0),
      e.shiftKey || (e.touches && e.touches.length === 2)
    )
  }

  function onMouseMove (e) {
    move(
      e.offsetX || e.clientX || (e.touches ? e.touches[0].clientX : 0),
      e.offsetY || e.clientY || (e.touches ? e.touches[0].clientY : 0),
      e.shiftKey || (e.touches && e.touches.length === 2)
    )
  }

  function onMouseUp (e) {
    up()
  }

  function onWheel (e) {
    scroll(e.deltaY)
    e.preventDefault()
  }

  Object.assign(orbiter, initialState)
  var o = orbiter(opts)

  orbiter.element.addEventListener('mousedown', onMouseDown)
  orbiter.element.addEventListener('touchstart', (e) => {
    e.preventDefault()
    onMouseDown(e)
  })
  window.addEventListener('mousemove', onMouseMove)
  window.addEventListener('touchmove', onMouseMove)
  window.addEventListener('mouseup', onMouseUp)
  window.addEventListener('touchend', onMouseUp)
  orbiter.element.addEventListener('wheel', onWheel)

  updateCamera()

  return o
}

module.exports = createOrbiter
module.exports.latLonToXyz = latLonToXyz
module.exports.xyzToLatLon = xyzToLatLon
<commit_msg>Add panning on/off option<commit_after>'use strict'
const Vec2 = require('pex-math/Vec2')
const Vec3 = require('pex-math/Vec3')
const Mat4 = require('pex-math/Mat4')
const Ray = require('pex-geom/Ray')
const clamp = require('pex-math/Utils').clamp

function getViewRay (camera, x, y, windowWidth, windowHeight) {
  const hNear = 2 * Math.tan(camera.fov / 2) * camera.near
  const wNear = hNear * camera.aspect
  let px = (x - windowWidth / 2) / (windowWidth / 2)
  let py = -(y - windowHeight / 2) / (windowHeight / 2)
  px *= wNear / 2
  py *= hNear / 2
  const origin = [0, 0, 0]
  const direction = Vec3.normalize([px, py, -camera.near])
  return [origin, direction]
}

function latLonToXyz (lat, lon, out) {
  out = out || [0, 0, 0]
  const theta = lat
  const phi = lon
  out[0] = Math.cos(theta) * Math.cos(phi)
  out[1] = Math.sin(theta)
  out[2] = Math.cos(theta) * Math.sin(phi)
  return out
}

function xyzToLatLon (normalizedPosition, out) {
  out = out || [0, 0]
  out[0] = Math.asin(normalizedPosition[1])// + Math.PI / 2 // lat
  out[1] = Math.atan2(normalizedPosition[2], normalizedPosition[0])// + Math.PI / 2 // lon
  return out
}

function createOrbiter (opts) {
  // TODO: split into internal state and public state
  const initialState = {
    camera: opts.camera,
    invViewMatrix: Mat4.create(),
    dragging: false,
    lat: 0, // Y
    lon: 0, // XZ
    element: opts.element || window,
    width: 0,
    height: 0,
    clickPosWindow: [0, 0],
    dragPos: [0, 0, 0],
    dragPosWindow: [0, 0],
    distance: 1,
    minDistance: 1,
    maxDistance: 1,
    zoom: true,
    pan: true,
    // enabled: true,
    clickTarget: [0, 0, 0],
    clickPosPlane: [0, 0, 0],
    dragPosPlane: [0, 0, 0],
    clickPosWorld: [0, 0, 0],
    dragPosWorld: [0, 0, 0],
    panPlane: null
  }

  function orbiter (opts) {
    Object.assign(orbiter, opts)

    if (opts.camera) {
      const distance = Vec3.distance(opts.camera.position, opts.camera.target)
      const latLon = xyzToLatLon(Vec3.normalize(Vec3.sub(Vec3.copy(opts.camera.position), opts.camera.target)))
      orbiter.lat = latLon[0]
      orbiter.lon = latLon[1]
      orbiter.distance = distance
      orbiter.minDistance = distance / 10
      orbiter.maxDistance = distance * 10
    }

    return orbiter
  }

  function updateWindowSize () {
    const width = orbiter.element.clientWidth || orbiter.element.innerWidth
    const height = orbiter.element.clientHeight || orbiter.element.innerHeight
    if (width !== orbiter.width) {
      orbiter.width = width
      orbiter.height = height
      orbiter.radius = Math.min(orbiter.width / 2, orbiter.height / 2)
      orbiter.center = [orbiter.width / 2, orbiter.height / 2]
    }
  }

  function updateCamera () {
    // instad of rotating the object we want to move camera around it
    // state.currRot[3] *= -1

    const position = orbiter.camera.position
    const target = orbiter.camera.target

    // set new camera position according to the current
    // rotation at distance relative to target
    latLonToXyz(orbiter.lat, orbiter.lon, position)
    Vec3.scale(position, orbiter.distance)
    Vec3.add(position, target)

    orbiter.camera({
      position: position
    })
  }

  function down (x, y, shift) {
    orbiter.dragging = true
    orbiter.dragPos[0] = x
    orbiter.dragPos[1] = y
    if (shift && orbiter.pan) {
      Vec2.set2(orbiter.clickPosWindow, x, y)
      Vec3.set(orbiter.clickTarget, orbiter.camera.target)
      const targetInViewSpace = Vec3.multMat4(Vec3.copy(orbiter.clickTarget), orbiter.camera.viewMatrix)
      orbiter.panPlane = [targetInViewSpace, [0, 0, 1]]
      Ray.hitTestPlane(
        getViewRay(orbiter.camera, orbiter.clickPosWindow[0], orbiter.clickPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.clickPosPlane
      )
      Ray.hitTestPlane(
        getViewRay(orbiter.camera, orbiter.dragPosWindow[0], orbiter.dragPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.dragPosPlane
      )
    } else {
      orbiter.panPlane = null
    }
  }

  function move (x, y, shift) {
    if (!orbiter.dragging) {
      return
    }
    if (shift && orbiter.panPlane) {
      Vec2.set2(orbiter.dragPosWindow, x, y)
      Ray.hitTestPlane(
        getViewRay(orbiter.camera, orbiter.clickPosWindow[0], orbiter.clickPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.clickPosPlane
      )
      Ray.hitTestPlane(
        getViewRay(orbiter.camera, orbiter.dragPosWindow[0], orbiter.dragPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.dragPosPlane
      )
      Mat4.set(orbiter.invViewMatrix, orbiter.camera.viewMatrix)
      Mat4.invert(orbiter.invViewMatrix)
      Vec3.multMat4(Vec3.set(orbiter.clickPosWorld, orbiter.clickPosPlane), orbiter.invViewMatrix)
      Vec3.multMat4(Vec3.set(orbiter.dragPosWorld, orbiter.dragPosPlane), orbiter.invViewMatrix)
      const diffWorld = Vec3.sub(Vec3.copy(orbiter.dragPosWorld), orbiter.clickPosWorld)
      const target = Vec3.sub(Vec3.copy(orbiter.clickTarget), diffWorld)
      orbiter.camera({ target: target })
      updateCamera()
    } else {
      const dx = x - orbiter.dragPos[0]
      const dy = y - orbiter.dragPos[1]
      orbiter.dragPos[0] = x
      orbiter.dragPos[1] = y

      // TODO: how to have resolution independed scaling? will this code behave differently with retina/pixelRatio=2?
      orbiter.lat = clamp(orbiter.lat + dy / 200, -Math.PI / 2, Math.PI / 2)

      orbiter.lon += dx / 200
      orbiter.lon = orbiter.lon % (2 * Math.PI)

      updateCamera()
    }
  }

  function up () {
    orbiter.dragging = false
    orbiter.panPlane = null
  }

  function scroll (dy) {
    if (!orbiter.zoom) {
      return
    }
    orbiter.distance = orbiter.distance + dy / 50
    orbiter.distance = clamp(orbiter.distance, orbiter.minDistance, orbiter.maxDistance)
    updateCamera()
  }

  function onMouseDown (e) {
    updateWindowSize()
    down(
      e.offsetX || e.clientX || (e.touches ? e.touches[0].clientX : 0),
      e.offsetY || e.clientY || (e.touches ? e.touches[0].clientY : 0),
      e.shiftKey || (e.touches && e.touches.length === 2)
    )
  }

  function onMouseMove (e) {
    move(
      e.offsetX || e.clientX || (e.touches ? e.touches[0].clientX : 0),
      e.offsetY || e.clientY || (e.touches ? e.touches[0].clientY : 0),
      e.shiftKey || (e.touches && e.touches.length === 2)
    )
  }

  function onMouseUp (e) {
    up()
  }

  function onWheel (e) {
    scroll(e.deltaY)
    e.preventDefault()
  }

  Object.assign(orbiter, initialState)
  var o = orbiter(opts)

  orbiter.element.addEventListener('mousedown', onMouseDown)
  orbiter.element.addEventListener('touchstart', (e) => {
    e.preventDefault()
    onMouseDown(e)
  })
  window.addEventListener('mousemove', onMouseMove)
  window.addEventListener('touchmove', onMouseMove)
  window.addEventListener('mouseup', onMouseUp)
  window.addEventListener('touchend', onMouseUp)
  orbiter.element.addEventListener('wheel', onWheel)

  updateCamera()

  return o
}

module.exports = createOrbiter
module.exports.latLonToXyz = latLonToXyz
module.exports.xyzToLatLon = xyzToLatLon
<|endoftext|>


<commit_before>import React from 'react';
import { Link as AppLink, graphql } from 'gatsby';
import get from 'lodash/get';
import { Flex, Box, Text, Link } from 'rebass';
import Layout from '../components/Layout';
import SEO from '../components/SEO';
import { formatReadingTime, getGreeting } from '../utils';

const Section = props => (
	<Flex as="section" mt={5} flexWrap="wrap" {...props} />
);

const ListTitle = ({ children }) => (
	<Box as="header" width={[1, 1 / 4, 1, 1 / 4]}>
		<Text as="h3" m={0} fontSize={2}>
			{children}
		</Text>
	</Box>
);

const List = ({ children, ...props }) => (
	<Box
		as="ul"
		m={0}
		p={0}
		mt={[2, 0, 2, 0]}
		width={[1, 3 / 4, 1, 3 / 4]}
		role="list"
	>
		{children}
	</Box>
);

const ListItem = ({ children, indented = false, ...props }) => (
	<Text
		as="li"
		role="listitem"
		css={{ listStyle: 'none' }}
		pl={indented ? 3 : 0}
		mt={2}
		{...props}
	>
		{children}
	</Text>
);

const Separator = () => (
	<Text as="span" color="lightgray">
		/
	</Text>
);

const greeting = getGreeting();

const BlogIndex = ({ data }) => {
	const siteTitle = get(data, 'site.siteMetadata.title');
	const posts = get(data, 'allMarkdownRemark.edges');

	return (
		<Layout title={siteTitle}>
			<SEO />
			<Flex
				px={[4, 5, 5, 6]}
				pt={[5, 5, 5, 6]}
				flexWrap="wrap"
				justifyContent="flex-end"
			>
				<Box
					as="header"
					pr={[0, 0, 5, 5]}
					mt={[0, 0, 3, 0]}
					width={[1, 1, 1 / 2, 1 / 2]}
				>
					<Text as="h1" m={0} fontSize={2} fontWeight="normal">
						Hey there, I'm Pete.
					</Text>
					<Text as="h2" m={0} mt={2} fontSize={2} fontWeight="normal">
						{greeting}
					</Text>
					<Text as="small" color="gray" mt={4} css={{ display: 'block' }}>
						Co-Founder, CTO of Appital
					</Text>
					<Text as="small" color="gray" mt={2} css={{ display: 'block' }}>
						Engineering Lead, Global Innovation at EY
					</Text>
				</Box>
				<Box mt={[5, 5, 3, 0]} width={[1, 1, 1 / 2, 1 / 2]}>

						<ListTitle>Work</ListTitle>
						<List>
							<ListItem mt={0}>
								<Link href="https://appital.io">Appital</Link>
							</ListItem>
							<ListItem>
								<Link href="https://ey.com">Ernst & Young</Link>
							</ListItem>
							<ListItem>
								<Link href="https://fath.om">Fathom London</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://commerzbank.com">Commerzbank</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://alixpartners.com">AlixPartners</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://accessfintech.com">Access Fintech</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://aimia.com">Aimia Inc</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://gsma.com">GSMA</Link>
							</ListItem>
							<ListItem>
								<Link href="https://barclays.co.uk">Barclays</Link>
							</ListItem>
							<ListItem>
								<Link href="https://www.seymourpowell.com">Seymourpowell</Link>
							</ListItem>
							<ListItem>
								<Link href="http://umbrellium.co.uk">Umbrellium</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://www.thingful.net">Thingful</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://youtube.com/watch?v=MjoumVT070A">
									Burble Paris <Separator /> Samsung
								</Link>
							</ListItem>
							<ListItem>
								<Link href="https://xively.com">
									Xively <Separator /> Google
								</Link>
							</ListItem>
							<ListItem>
								<Link href="https://www.telecom.pt/en-us">
									Portugal Telecom
								</Link>
							</ListItem>
							<ListItem>
								<Link color="gray" href="https://linkedin.com/in/petecorreia/">
									More →
								</Link>
							</ListItem>
						</List>

						<ListTitle>OSS</ListTitle>
						<List>
							<ListItem mt={0}>
								<Link href="https://react-circular-input.now.sh/">
									react-circular-input
								</Link>
							</ListItem>
							<ListItem>
								<Link href="https://tsx-docs.now.sh/">tsx-docs</Link>
							</ListItem>
							<ListItem>
								<Link href="https://github.com/petecorreia/analyze-cra-bundle">
									analyze-cra-bundle
								</Link>
							</ListItem>
						</List>

						<ListTitle>Writing</ListTitle>
						<List>
							{posts.map(({ node }, index) => {
								const title =
									get(node, 'frontmatter.title') || node.fields.slug;
								return (
									<ListItem key={node.fields.slug} mt={!index ? 0 : 3}>
										<AppLink to={node.fields.slug} css={{ lineHeight: 1.4 }}>
											{title}
										</AppLink>
										<Text
											as="small"
											color="gray"
											mt={1}
											css={{ display: 'block' }}
										>
											{node.frontmatter.date}
											{` — ${formatReadingTime(node.timeToRead)}`}
										</Text>
									</ListItem>
								);
							})}
						</List>

						<ListTitle>Stack</ListTitle>
						<List>
							<ListItem mt={0}>React</ListItem>
							<ListItem>Typescript</ListItem>
							<ListItem>Styled Components</ListItem>
							<ListItem>
								Dataviz <Separator /> D3
							</ListItem>
							<ListItem>GraphQL</ListItem>
							<ListItem>Design Systems</ListItem>
						</List>

						<ListTitle>Links</ListTitle>
						<List>
							<ListItem mt={0}>
								<Link href="https://twitter.com/petecorreia">Twitter</Link>
							</ListItem>
							<ListItem>
								<Link href="https://github.com/petecorreia">Github</Link>
							</ListItem>
							<ListItem>
								<Link href="https://linkedin.com/in/petecorreia/">
									LinkedIn
								</Link>
							</ListItem>
							<ListItem>
								<Link href="/rss.xml">RSS</Link>
							</ListItem>
						</List>

				</Box>
			</Flex>
		</Layout>
	);
};

export default BlogIndex;

export const pageQuery = graphql`
	query {
		site {
			siteMetadata {
				title
				description
			}
		}
		allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
			edges {
				node {
					fields {
						slug
					}
					timeToRead
					frontmatter {
						date(formatString: "MMMM DD, YYYY")
						title
						spoiler
					}
				}
			}
		}
	}
`;
<commit_msg>Update index.js<commit_after>import React from 'react';
import { Link as AppLink, graphql } from 'gatsby';
import get from 'lodash/get';
import { Flex, Box, Text, Link } from 'rebass';
import Layout from '../components/Layout';
import SEO from '../components/SEO';
import { formatReadingTime, getGreeting } from '../utils';

const Section = props => (
	<Flex as="section" mt={5} flexWrap="wrap" {...props} />
);

const ListTitle = ({ children }) => (
	<Box as="header" width={[1, 1 / 4, 1, 1 / 4]}>
		<Text as="h3" m={0} fontSize={2}>
			{children}
		</Text>
	</Box>
);

const List = ({ children, ...props }) => (
	<Box
		as="ul"
		m={0}
		p={0}
		mt={[2, 0, 2, 0]}
		width={[1, 3 / 4, 1, 3 / 4]}
		role="list"
	>
		{children}
	</Box>
);

const ListItem = ({ children, indented = false, ...props }) => (
	<Text
		as="li"
		role="listitem"
		css={{ listStyle: 'none' }}
		pl={indented ? 3 : 0}
		mt={2}
		{...props}
	>
		{children}
	</Text>
);

const Separator = () => (
	<Text as="span" color="lightgray">
		/
	</Text>
);

const greeting = getGreeting();

const BlogIndex = ({ data }) => {
	const siteTitle = get(data, 'site.siteMetadata.title');
	const posts = get(data, 'allMarkdownRemark.edges');

	return (
		<Layout title={siteTitle}>
			<SEO />
			<Flex
				px={[4, 5, 5, 6]}
				pt={[5, 5, 5, 6]}
				flexWrap="wrap"
				justifyContent="flex-end"
			>
				<Box
					as="header"
					pr={[0, 0, 5, 5]}
					mt={[0, 0, 3, 0]}
					width={[1, 1, 1 / 2, 1 / 2]}
				>
					<Text as="h1" m={0} fontSize={2} fontWeight="normal">
						Hey there, I'm Pete.
					</Text>
					<Text as="h2" m={0} mt={2} fontSize={2} fontWeight="normal">
						{greeting}
					</Text>
					<Text as="small" color="gray" mt={4} css={{ display: 'block' }}>
						Co-Founder of Appital
					</Text>
					<Text as="small" color="gray" mt={2} css={{ display: 'block' }}>
						Engineering Lead, Global Innovation at EY
					</Text>
				</Box>
				<Box mt={[5, 5, 3, 0]} width={[1, 1, 1 / 2, 1 / 2]}>

						<ListTitle>Work</ListTitle>
						<List>
							<ListItem mt={0}>
								<Link href="https://appital.io">Appital</Link>
							</ListItem>
							<ListItem>
								<Link href="https://ey.com">Ernst & Young</Link>
							</ListItem>
							<ListItem>
								<Link href="https://fath.om">Fathom London</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://commerzbank.com">Commerzbank</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://alixpartners.com">AlixPartners</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://accessfintech.com">Access Fintech</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://aimia.com">Aimia Inc</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://gsma.com">GSMA</Link>
							</ListItem>
							<ListItem>
								<Link href="https://barclays.co.uk">Barclays</Link>
							</ListItem>
							<ListItem>
								<Link href="https://www.seymourpowell.com">Seymourpowell</Link>
							</ListItem>
							<ListItem>
								<Link href="http://umbrellium.co.uk">Umbrellium</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://www.thingful.net">Thingful</Link>
							</ListItem>
							<ListItem indented>
								<Link href="https://youtube.com/watch?v=MjoumVT070A">
									Burble Paris <Separator /> Samsung
								</Link>
							</ListItem>
							<ListItem>
								<Link href="https://xively.com">
									Xively <Separator /> Google
								</Link>
							</ListItem>
							<ListItem>
								<Link href="https://www.telecom.pt/en-us">
									Portugal Telecom
								</Link>
							</ListItem>
							<ListItem>
								<Link color="gray" href="https://linkedin.com/in/petecorreia/">
									More →
								</Link>
							</ListItem>
						</List>

						<ListTitle>OSS</ListTitle>
						<List>
							<ListItem mt={0}>
								<Link href="https://react-circular-input.now.sh/">
									react-circular-input
								</Link>
							</ListItem>
							<ListItem>
								<Link href="https://tsx-docs.now.sh/">tsx-docs</Link>
							</ListItem>
							<ListItem>
								<Link href="https://github.com/petecorreia/analyze-cra-bundle">
									analyze-cra-bundle
								</Link>
							</ListItem>
						</List>

						<ListTitle>Writing</ListTitle>
						<List>
							{posts.map(({ node }, index) => {
								const title =
									get(node, 'frontmatter.title') || node.fields.slug;
								return (
									<ListItem key={node.fields.slug} mt={!index ? 0 : 3}>
										<AppLink to={node.fields.slug} css={{ lineHeight: 1.4 }}>
											{title}
										</AppLink>
										<Text
											as="small"
											color="gray"
											mt={1}
											css={{ display: 'block' }}
										>
											{node.frontmatter.date}
											{` — ${formatReadingTime(node.timeToRead)}`}
										</Text>
									</ListItem>
								);
							})}
						</List>

						<ListTitle>Stack</ListTitle>
						<List>
							<ListItem mt={0}>React</ListItem>
							<ListItem>Typescript</ListItem>
							<ListItem>Styled Components</ListItem>
							<ListItem>
								Dataviz <Separator /> D3
							</ListItem>
							<ListItem>GraphQL</ListItem>
							<ListItem>Design Systems</ListItem>
						</List>

						<ListTitle>Links</ListTitle>
						<List>
							<ListItem mt={0}>
								<Link href="https://twitter.com/petecorreia">Twitter</Link>
							</ListItem>
							<ListItem>
								<Link href="https://github.com/petecorreia">Github</Link>
							</ListItem>
							<ListItem>
								<Link href="https://linkedin.com/in/petecorreia/">
									LinkedIn
								</Link>
							</ListItem>
							<ListItem>
								<Link href="/rss.xml">RSS</Link>
							</ListItem>
						</List>

				</Box>
			</Flex>
		</Layout>
	);
};

export default BlogIndex;

export const pageQuery = graphql`
	query {
		site {
			siteMetadata {
				title
				description
			}
		}
		allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
			edges {
				node {
					fields {
						slug
					}
					timeToRead
					frontmatter {
						date(formatString: "MMMM DD, YYYY")
						title
						spoiler
					}
				}
			}
		}
	}
`;
<|endoftext|>


<commit_before>var path = require('path');
var source = require('vinyl-source-stream');
var minimist = require('minimist');
var gulpif = require('gulp-if');
var gulp = require('gulp');
var gutil = require('gulp-util');
var preprocess = require('gulp-preprocess');
var watchify = require('watchify');
var browserify = require('browserify');
var babelify = require('babelify');
var tsify = require('tsify');
var stylus = require('gulp-stylus');
var minifyCss = require('gulp-minify-css');
var streamify = require('gulp-streamify');
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');

// command line options
var minimistOptions = {
  string: ['env', 'mode'],
  default: { env: 'env.json', mode: 'dev' }
};
var options = minimist(process.argv.slice(2), minimistOptions);

var paths = {
  styles: ['src/styl/reset.styl', 'src/styl/common.styl', 'src/styl/form.styl',
    'src/styl/overlay.styl', 'src/styl/overlay-popup.styl', 'src/styl/*.styl'
  ]
};

var tsConfig = {
  allowJs: true,
  target: 'es2015',
  module: 'commonjs',
  noImplicitAny: true,
  noImplicitThis: true,
  jsx: 'preserve'
};

function buildHtml(src, dest, context) {
  console.log(context);
  return gulp.src(path.join(src, 'index.html'))
    .pipe(preprocess({context: context}))
    .pipe(gulp.dest(dest));
}

function buildStyl(src, dest, mode) {
  return gulp.src(src)
    .pipe(stylus())
    .pipe(streamify(autoprefixer()))
    .pipe(gulpif(mode === 'prod', minifyCss()))
    .pipe(rename('app.css'))
    .pipe(gulp.dest(dest + '/css/compiled/'));
}

function buildScripts(src, dest, mode) {
  var opts = (mode === 'dev') ? { debug: true } : {};

  return browserify(src + '/js/main.ts', opts)
    .plugin(tsify, tsConfig)
    .transform(babelify, {extensions: ['.tsx', '.ts', '.js', '.jsx']}, {presets: ['es2015']})
    .bundle()
    .on('error', function(error) { gutil.log(gutil.colors.red(error.message)); })
    .pipe(source('app.js'))
    .pipe(gulp.dest(dest));
}

gulp.task('html', function() {
  var context = require('./' + options.env);
  context.MODE = options.mode;

  return buildHtml('src', 'www', context);
});

gulp.task('styl', function() {
  return buildStyl('src/styl/index.styl', 'www', options.mode);
});

gulp.task('scripts', function() {
  return buildScripts('./src', 'www', options.mode);
});

gulp.task('watch-scripts', function() {
  var opts = watchify.args;
  opts.debug = true;

  var bundleStream = watchify(
    browserify('./src/js/main.ts', opts)
    .plugin(tsify, tsConfig)
    .transform(babelify, {extensions: ['.tsx', '.ts', '.js', '.jsx']}, {presets: ['es2015']})
  );

  function rebundle() {
    return bundleStream
      .bundle()
      .on('error', function(error) { gutil.log(gutil.colors.red(error.message)); })
      .pipe(source('app.js'))
      .pipe(gulp.dest('./www'));
  }

  bundleStream.on('update', rebundle);
  bundleStream.on('log', gutil.log);

  return rebundle();
});

// Watch Files For Changes
gulp.task('launch-watch', function() {
  gulp.watch(paths.styles, ['styl']);
  gulp.watch(['src/index.html', 'env.json'], ['html']);
});

gulp.task('default', ['html', 'styl', 'scripts']);
gulp.task('watch', ['html', 'styl', 'watch-scripts', 'launch-watch']);

module.exports = {
  buildHtml: buildHtml,
  buildStyl: buildStyl,
  buildScripts: buildScripts
};
<commit_msg>Fix build<commit_after>var path = require('path');
var source = require('vinyl-source-stream');
var minimist = require('minimist');
var gulpif = require('gulp-if');
var gulp = require('gulp');
var gutil = require('gulp-util');
var preprocess = require('gulp-preprocess');
var watchify = require('watchify');
var browserify = require('browserify');
var babelify = require('babelify');
var tsify = require('tsify');
var stylus = require('gulp-stylus');
var minifyCss = require('gulp-minify-css');
var streamify = require('gulp-streamify');
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');

// command line options
var minimistOptions = {
  string: ['env', 'mode'],
  default: { env: 'env.json', mode: 'dev' }
};
var options = minimist(process.argv.slice(2), minimistOptions);

var paths = {
  styles: ['src/styl/reset.styl', 'src/styl/common.styl', 'src/styl/form.styl',
    'src/styl/overlay.styl', 'src/styl/overlay-popup.styl', 'src/styl/*.styl'
  ]
};

var tsConfig = {
  allowJs: true,
  target: 'es2015',
  module: 'commonjs',
  noImplicitAny: true,
  noImplicitThis: true,
  jsx: 'preserve'
};

function buildHtml(src, dest, context) {
  console.log(context);
  return gulp.src(path.join(src, 'index.html'))
    .pipe(preprocess({context: context}))
    .pipe(gulp.dest(dest));
}

function buildStyl(src, dest, mode) {
  return gulp.src(src)
    .pipe(stylus())
    .pipe(streamify(autoprefixer()))
    .pipe(gulpif(mode === 'prod', minifyCss()))
    .pipe(rename('app.css'))
    .pipe(gulp.dest(dest + '/css/compiled/'));
}

function buildScripts(src, dest, mode) {
  var opts = (mode === 'dev') ? { debug: true } : {};

  return browserify(src + '/js/main.ts', opts)
    .plugin(tsify, tsConfig)
    .transform(babelify, {
      extensions: ['.tsx', '.ts', '.js', '.jsx'],
      presets: ['es2015']
    })
    .bundle()
    .on('error', function(error) { gutil.log(gutil.colors.red(error.message)); })
    .pipe(source('app.js'))
    .pipe(gulp.dest(dest));
}

gulp.task('html', function() {
  var context = require('./' + options.env);
  context.MODE = options.mode;

  return buildHtml('src', 'www', context);
});

gulp.task('styl', function() {
  return buildStyl('src/styl/index.styl', 'www', options.mode);
});

gulp.task('scripts', function() {
  return buildScripts('./src', 'www', options.mode);
});

gulp.task('watch-scripts', function() {
  var opts = watchify.args;
  opts.debug = true;

  var bundleStream = watchify(
    browserify('./src/js/main.ts', opts)
    .plugin(tsify, tsConfig)
    .transform(babelify, {
      extensions: ['.tsx', '.ts', '.js', '.jsx'],
      presets: ['es2015']
    })
  );

  function rebundle() {
    return bundleStream
      .bundle()
      .on('error', function(error) { gutil.log(gutil.colors.red(error.message)); })
      .pipe(source('app.js'))
      .pipe(gulp.dest('./www'));
  }

  bundleStream.on('update', rebundle);
  bundleStream.on('log', gutil.log);

  return rebundle();
});

// Watch Files For Changes
gulp.task('launch-watch', function() {
  gulp.watch(paths.styles, ['styl']);
  gulp.watch(['src/index.html', 'env.json'], ['html']);
});

gulp.task('default', ['html', 'styl', 'scripts']);
gulp.task('watch', ['html', 'styl', 'watch-scripts', 'launch-watch']);

module.exports = {
  buildHtml: buildHtml,
  buildStyl: buildStyl,
  buildScripts: buildScripts
};
<|endoftext|>