<commit_before>define([
    'uijet_dir/uijet',
    'resources',
    'controllers/NodesList'
], function (uijet, resources) {

    uijet.Resource('NodesSearchResult', resources.Nodes);

    return [{
        type    : 'List',
        config  : {
            element     : '#nodes_list_header',
            horizontal  : true,
            position    : 'top:27px fluid',
            signals     : {
                pre_select  : function ($selected) {
                    if ( this.$selected && $selected[0] === this.$selected[0] ) {
                        this.$selected.toggleClass('desc');
                    }
                    return {
                        column  : $selected.attr('data-column'),
                        desc    : $selected.hasClass('desc')
                    };
                }
            }
        }
    }, {
        type    : 'List',
        config  : {
            element         : '#nodes_list',
            mixins          : ['Templated', 'Scrolled'],
            adapters        : ['jqWheelScroll', 'Spin', 'NodesList'],
            resource        : 'LatestSheet',
            position        : 'fluid',
            fetch_options   : {
                remove  : false,
                cache   : true,
                merge   : false,
                expires : 8 * 3600,
                data    : {
                    page_by : 4000,
                    parents : 'none'
                }
            },
            search          : {
                fields  : {
                    name        : 10,
                    description : 1,
                    code        : 20
                }
            },
            filters         : {
                search  : 'search',
                selected: function (state) {
                    //TODO: copy-pasted from old nodes_list, need to rewrite
                    if ( state === true )
                        return this.resource.where({ selected : 'selected' })
                                            .map(uijet.utils.prop('id'));
                    else
                        return null;
                }
            },
            sorting         : {
                name        : 'name',
                '-name'     : resources.utils.reverseSorting('name'),
                code        : resources.utils.nestingSort,
                '-code'     : resources.utils.reverseNestingSort,
                direction   : 'direction',
                '-direction': resources.utils.reverseSorting('direction')
            },
            data_events     : {
                request : function (resource, xhr, options) {
                    if ( this.last_request && this.last_request.state() == 'pending' ) {
                        this.last_request.abort();
                    }
                    this.last_request = xhr;
                    this.spin();
                },
                reset   : function () {
                    delete this.$original_children;
                },
                sync    : function (response) {
                    var scope_changed = this.scope_changed,
                        search_result;
                    // after we had to reset because of entity change make sure turn reset off again
                    if ( this.options.fetch_options.reset ) {
                        this.options.fetch_options.reset = false;
                    }
                    if ( this.search_active ) {
                        search_result = uijet.Resource('NodesSearchResult');
                        search_result.reset(response.results);
                        this.setContext({
                            filtered: search_result.byAncestor(this.scope),
                            filter  : null
                        });
                    }
                    else {
                        this.setContext({
                            filter      : 'byParent',
                            filter_args : [this.scope]
                        });
                    }

                    if ( scope_changed ) {
                        this.scope_changed = false;
                        this._publishScope();
                    }
                    if ( this.template_changed ) {
                        this.template_changed = false;
                        //TODO: check if we need to explicitly handle
//                        scope_changed || this.publish('sheet_changed', null);
                    }

                    this.spinOff();
                },
                error   : 'spinOff'
            },
            signals         : {
                post_init       : function () {
                    var state_model = uijet.Resource('NodesListState');

                    this.scope = null;
                    this.index();

                    this.listenTo(state_model, 'change', function (model, options) {
                        var changed = model.changedAttributes(),
                            fetch_ops_data = this.options.fetch_options.data,
                            search = model.get('search') || null,
                            entity_id, scope,
                            prev, prev_templates, prev_template, cached_template;

                        if ( ! changed )
                            return;

                        if ( 'search' in changed ) {
                            if ( ! search ) {
                                prev = state_model.previous('search');
                                if ( ! prev ) {
                                    // clean search to be `null` instead of empty string
                                    state_model.set('search', null, { silent : true });
                                    return;
                                }
                            }
                        }

                        if ( 'selection' in changed ) {
                            //TODO: this was copy-pasted from old nodes_list, need to check and fix
                            if ( 'scope' in this.getContext() ) {
                                this.resetSelection(changed.selection)
                                    .publish('selection', { reset : true });
                            }
                            else {
                                this.reselect = true;
                            }
                        }

                        if ( 'entity_id' in changed ) {
                            prev = model.previous('entity_id');

                            // make sure we cache the previous template
                            if ( prev ) {
                                prev_templates = uijet.Resource('PreviousSheets');

                                // assigning in purpose to reuse as previous template
                                if ( prev_template = prev_templates.get(prev) ) {
                                    // update cache of previous Nodes collection with current LatestSheet state
                                    prev_template.get('nodes').set(this.resource.models, { remove : false });
                                }
                                else {
                                    prev_templates.add({
                                        id      : prev,
                                        nodes   : this.resource.clone()
                                    });
                                }
                            }
                            entity_id = model.get('entity_id');
                        }
                        else if ( 'scope' in changed ) {
                            scope = model.get('scope');
                        }
                        else if ( ! ('search' in changed) ) {
                            // move along people, nothing to see here
                            return;
                        }

                        if ( entity_id ) {
                            if ( cached_template = uijet.Resource('PreviousSheets').get(entity_id) ) {
                                // register current collection as the new instance
                                this.setResource(cached_template.get('nodes'));
                                scope = scope === -1 ?
                                    this.resource.findWhere(model.get('scope')).get('id') :
                                    scope;
                            }
                            else {
                                // instantiate a new collection and register it
                                this.setResource(new resources.Nodes());
                            }
                        }
                        // if for some reason scope is still unknown reset it to `null`
                        if ( scope === -1 ) {
                            scope = null;
                        }

                        this.search_active = !!search;

                        // ensure cleaning of last search results
                        delete this.getContext().filtered;

                        if ( entity_id ) {
                            this.template_changed = true;
                            fetch_ops_data.entity_id = entity_id;
                        }

                        if ( search ) {
                            fetch_ops_data.search = search;
                            delete fetch_ops_data.parents;
                        }
                        else {
                            delete fetch_ops_data.search;
                            fetch_ops_data.parents = scope || 'none';
                        }

                        // set scope if it's defined in the context
                        this.setScope(scope);

                        this._finally()
                            .resource.fetch(this.options.fetch_options)
                            .then(this.wake.bind(this, {
                                entity_id   : entity_id,
                                search      : search,
                                scope       : scope === void 0 ? model.get('scope') : scope || null
                            }));
                    });
                },
                pre_wake        : function () {
                    // usually on first load, just bail out
                    if ( ! ('scope' in this.getContext() ) ) return false;
                },
                post_render     : function () {
                    this.$children = this.$element.children();
                    if ( this.search_active ) {
                        var search_term = uijet.Resource('NodesListState').get('search');

                        this.publish('filter_count', this.$children.length)
                            ._prepareScrolledSize();

                        uijet.utils.requestAnimFrame( this.toggleHighlight.bind(this, search_term) );
                        uijet.utils.requestAnimFrame( this.scroll.bind(this) );
                    }
                    else {
                        this.scroll();
                    }

                    this._finally();
                },
                pre_select      : function ($selected, event) {
                    var id = $selected.attr('data-id');
                    if ( uijet.$(event.target).hasClass('selectbox') ) {
                        this.updateSelection(id)
                            .publish('selection');
                        return false;
                    }
                    else {
                        return ! $selected[0].hasAttribute('data-leaf') && id;
                    }
                },
                post_select     : function ($selected) {
                    uijet.Resource('NodesListState').set('scope', $selected.attr('data-id'));
                }
            },
            app_events      : {
                'nodes_breadcrumbs.selected': 'post_select+',
                'nodes_list_header.selected': 'sortNodes+',
                'picker_done.clicked'       : function () {
                    /*
                     * Make sure that every time we hit "done" we cache current template state
                     * in `PreviousSheets` resource.
                     */
                    var prev_templates = uijet.Resource('PreviousSheets'),
                        entity_id = uijet.Resource('NodesListState').get('entity_id'),
                        prev_template;
                    if ( prev_template = prev_templates.get(entity_id) ) {
                        prev_template.get('nodes').set(this.resource.models, { remove : false });
                    }
                    else {
                        prev_templates.add({
                            id: entity_id,
                            nodes: this.resource.clone()
                        });
                    }
                },
                'nodes_list.selection'      : function () {
                    var resource = this.resource;
                    //update DOM with collection's state
                    this.$children.each(function (i, node) {
                        var $node = uijet.$(node),
                            id = $node.attr('data-id'),
                            state = resource.get(id).get('selected');
                        $node.attr('data-selected', state);
                    });
                }
            }
        }
    }];

});
<commit_msg>Adding with_ancestors=true<commit_after>define([
    'uijet_dir/uijet',
    'resources',
    'controllers/NodesList'
], function (uijet, resources) {

    uijet.Resource('NodesSearchResult', resources.Nodes);

    return [{
        type    : 'List',
        config  : {
            element     : '#nodes_list_header',
            horizontal  : true,
            position    : 'top:27px fluid',
            signals     : {
                pre_select  : function ($selected) {
                    if ( this.$selected && $selected[0] === this.$selected[0] ) {
                        this.$selected.toggleClass('desc');
                    }
                    return {
                        column  : $selected.attr('data-column'),
                        desc    : $selected.hasClass('desc')
                    };
                }
            }
        }
    }, {
        type    : 'List',
        config  : {
            element         : '#nodes_list',
            mixins          : ['Templated', 'Scrolled'],
            adapters        : ['jqWheelScroll', 'Spin', 'NodesList'],
            resource        : 'LatestSheet',
            position        : 'fluid',
            fetch_options   : {
                remove  : false,
                cache   : true,
                merge   : false,
                expires : 8 * 3600,
                data    : {
                    page_by         : 4000,
                    parents         : 'none',
                    with_ancestors  : 'true'
                }
            },
            search          : {
                fields  : {
                    name        : 10,
                    description : 1,
                    code        : 20
                }
            },
            filters         : {
                search  : 'search',
                selected: function (state) {
                    //TODO: copy-pasted from old nodes_list, need to rewrite
                    if ( state === true )
                        return this.resource.where({ selected : 'selected' })
                                            .map(uijet.utils.prop('id'));
                    else
                        return null;
                }
            },
            sorting         : {
                name        : 'name',
                '-name'     : resources.utils.reverseSorting('name'),
                code        : resources.utils.nestingSort,
                '-code'     : resources.utils.reverseNestingSort,
                direction   : 'direction',
                '-direction': resources.utils.reverseSorting('direction')
            },
            data_events     : {
                request : function (resource, xhr, options) {
                    if ( this.last_request && this.last_request.state() == 'pending' ) {
                        this.last_request.abort();
                    }
                    this.last_request = xhr;
                    this.spin();
                },
                reset   : function () {
                    delete this.$original_children;
                },
                sync    : function (response) {
                    var scope_changed = this.scope_changed,
                        search_result;
                    // after we had to reset because of entity change make sure turn reset off again
                    if ( this.options.fetch_options.reset ) {
                        this.options.fetch_options.reset = false;
                    }
                    if ( this.search_active ) {
                        search_result = uijet.Resource('NodesSearchResult');
                        search_result.reset(response.results);
                        this.setContext({
                            filtered: search_result.byAncestor(this.scope),
                            filter  : null
                        });
                    }
                    else {
                        this.setContext({
                            filter      : 'byParent',
                            filter_args : [this.scope]
                        });
                    }

                    if ( scope_changed ) {
                        this.scope_changed = false;
                        this._publishScope();
                    }
                    if ( this.template_changed ) {
                        this.template_changed = false;
                        //TODO: check if we need to explicitly handle
//                        scope_changed || this.publish('sheet_changed', null);
                    }

                    this.spinOff();
                },
                error   : 'spinOff'
            },
            signals         : {
                post_init       : function () {
                    var state_model = uijet.Resource('NodesListState');

                    this.scope = null;
                    this.index();

                    this.listenTo(state_model, 'change', function (model, options) {
                        var changed = model.changedAttributes(),
                            fetch_ops_data = this.options.fetch_options.data,
                            search = model.get('search') || null,
                            entity_id, scope,
                            prev, prev_templates, prev_template, cached_template;

                        if ( ! changed )
                            return;

                        if ( 'search' in changed ) {
                            if ( ! search ) {
                                prev = state_model.previous('search');
                                if ( ! prev ) {
                                    // clean search to be `null` instead of empty string
                                    state_model.set('search', null, { silent : true });
                                    return;
                                }
                            }
                        }

                        if ( 'selection' in changed ) {
                            //TODO: this was copy-pasted from old nodes_list, need to check and fix
                            if ( 'scope' in this.getContext() ) {
                                this.resetSelection(changed.selection)
                                    .publish('selection', { reset : true });
                            }
                            else {
                                this.reselect = true;
                            }
                        }

                        if ( 'entity_id' in changed ) {
                            prev = model.previous('entity_id');

                            // make sure we cache the previous template
                            if ( prev ) {
                                prev_templates = uijet.Resource('PreviousSheets');

                                // assigning in purpose to reuse as previous template
                                if ( prev_template = prev_templates.get(prev) ) {
                                    // update cache of previous Nodes collection with current LatestSheet state
                                    prev_template.get('nodes').set(this.resource.models, { remove : false });
                                }
                                else {
                                    prev_templates.add({
                                        id      : prev,
                                        nodes   : this.resource.clone()
                                    });
                                }
                            }
                            entity_id = model.get('entity_id');
                        }
                        else if ( 'scope' in changed ) {
                            scope = model.get('scope');
                        }
                        else if ( ! ('search' in changed) ) {
                            // move along people, nothing to see here
                            return;
                        }

                        if ( entity_id ) {
                            if ( cached_template = uijet.Resource('PreviousSheets').get(entity_id) ) {
                                // register current collection as the new instance
                                this.setResource(cached_template.get('nodes'));
                                scope = scope === -1 ?
                                    this.resource.findWhere(model.get('scope')).get('id') :
                                    scope;
                            }
                            else {
                                // instantiate a new collection and register it
                                this.setResource(new resources.Nodes());
                            }
                        }
                        // if for some reason scope is still unknown reset it to `null`
                        if ( scope === -1 ) {
                            scope = null;
                        }

                        this.search_active = !!search;

                        // ensure cleaning of last search results
                        delete this.getContext().filtered;

                        if ( entity_id ) {
                            this.template_changed = true;
                            fetch_ops_data.entity_id = entity_id;
                        }

                        if ( search ) {
                            fetch_ops_data.search = search;
                            delete fetch_ops_data.parents;
                        }
                        else {
                            delete fetch_ops_data.search;
                            fetch_ops_data.parents = scope || 'none';
                        }

                        // set scope if it's defined in the context
                        this.setScope(scope);

                        this._finally()
                            .resource.fetch(this.options.fetch_options)
                            .then(this.wake.bind(this, {
                                entity_id   : entity_id,
                                search      : search,
                                scope       : scope === void 0 ? model.get('scope') : scope || null
                            }));
                    });
                },
                pre_wake        : function () {
                    // usually on first load, just bail out
                    if ( ! ('scope' in this.getContext() ) ) return false;
                },
                post_render     : function () {
                    this.$children = this.$element.children();
                    if ( this.search_active ) {
                        var search_term = uijet.Resource('NodesListState').get('search');

                        this.publish('filter_count', this.$children.length)
                            ._prepareScrolledSize();

                        uijet.utils.requestAnimFrame( this.toggleHighlight.bind(this, search_term) );
                        uijet.utils.requestAnimFrame( this.scroll.bind(this) );
                    }
                    else {
                        this.scroll();
                    }

                    this._finally();
                },
                pre_select      : function ($selected, event) {
                    var id = $selected.attr('data-id');
                    if ( uijet.$(event.target).hasClass('selectbox') ) {
                        this.updateSelection(id)
                            .publish('selection');
                        return false;
                    }
                    else {
                        return ! $selected[0].hasAttribute('data-leaf') && id;
                    }
                },
                post_select     : function ($selected) {
                    uijet.Resource('NodesListState').set('scope', $selected.attr('data-id'));
                }
            },
            app_events      : {
                'nodes_breadcrumbs.selected': 'post_select+',
                'nodes_list_header.selected': 'sortNodes+',
                'picker_done.clicked'       : function () {
                    /*
                     * Make sure that every time we hit "done" we cache current template state
                     * in `PreviousSheets` resource.
                     */
                    var prev_templates = uijet.Resource('PreviousSheets'),
                        entity_id = uijet.Resource('NodesListState').get('entity_id'),
                        prev_template;
                    if ( prev_template = prev_templates.get(entity_id) ) {
                        prev_template.get('nodes').set(this.resource.models, { remove : false });
                    }
                    else {
                        prev_templates.add({
                            id: entity_id,
                            nodes: this.resource.clone()
                        });
                    }
                },
                'nodes_list.selection'      : function () {
                    var resource = this.resource;
                    //update DOM with collection's state
                    this.$children.each(function (i, node) {
                        var $node = uijet.$(node),
                            id = $node.attr('data-id'),
                            state = resource.get(id).get('selected');
                        $node.attr('data-selected', state);
                    });
                }
            }
        }
    }];

});
<|endoftext|>


<commit_before>
var multiplier = 1;
var cir_dim = 600 * multiplier;
var sq_dim = 450 * multiplier;
var offset = 100 * multiplier;
var canvasSize = 500 * multiplier;

function setup() {
  createCanvas(canvasSize+offset, canvasSize+offset);
  frameRate(2); // Attempt to refresh at starting FPS
  stroke(255);
  noFill();
}

function draw() {

  background(255);
  stroke(0);
  strokeWeight(4);

  ellipse((canvasSize+offset)/2, (canvasSize+offset)/2, canvasSize+offset, canvasSize+offset);
  rect(0, 0, cir_dim, cir_dim); // better rect

  translate(offset*(sq_dim/cir_dim), offset*(sq_dim/cir_dim));
  print(mouseX, mouseY)

  // rect(cir_dim/18, cir_dim/18, sq_dim - 2*cir_dim/18, sq_dim - 2*cir_dim/18); // bigger rect - complique
  // rect(0, 0, (sq_dim/cir_dim)*sq_dim, (sq_dim/cir_dim)*sq_dim); // better rect
  rect(0, 0, sq_dim, sq_dim); // better rect
}<commit_msg>[ADD] basic animation for rect 1<commit_after>
var multiplier = 1;
var cir_dim = 600 * multiplier;
var sq_dim = 450 * multiplier;
var offset = 100 * multiplier;
var canvasSize = 500 * multiplier;

function setup() {
  createCanvas(canvasSize+offset, canvasSize+offset);
  frameRate(2); // Attempt to refresh at starting FPS
  stroke(255);
  noFill();
}

function draw() {

  background(255);
  stroke(0);
  strokeWeight(4);

  rect(0, 0, cir_dim, cir_dim); // outer, circumscribing rect
  ellipse((canvasSize+offset)/2, (canvasSize+offset)/2, canvasSize+offset, canvasSize+offset);

  translate(offset*(sq_dim/cir_dim), offset*(sq_dim/cir_dim));
  print(mouseX, mouseY)

  // rect(cir_dim/18, cir_dim/18, sq_dim - 2*cir_dim/18, sq_dim - 2*cir_dim/18); // inner rect - complique
  rect(0, 0, sq_dim, sq_dim); // better rect

  // rect 1 (left top/rect2

  // randomly select a bounding line for rect1
  rect1_lower_bound_y = random(50, 300)
  rect1_offset_from_top = random(0,rect1_lower_bound_y)
  line(0, rect1_lower_bound_y, sq_dim, rect1_lower_bound_y);
  rect1_height = rect1_lower_bound_y - rect1_offset_from_top
  rect(0, rect1_offset_from_top, rect1_height, rect1_height);

  // rect 2 (right rect1/rect3)
  // rect 3 (bottom rect2)

}<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var DomEvent = {
	add: function(el, events) {
		for (var type in events) {
			var func = events[type];
			if (el.addEventListener) {
				el.addEventListener(type, func, false);
			} else if (el.attachEvent) {
				// Make a bound closure that calls on the right object and
				// passes on the global event object as a parameter.
				el.attachEvent('on' + type, func.bound = function() {
					func.call(el, window.event);
				});
			}
		}
	},

	remove: function(el, events) {
		for (var type in events) {
			var func = events[type];
			if (el.removeEventListener) {
				el.removeEventListener(type, func, false);
			} else if (el.detachEvent) {
				// Remove the bound closure instead of func itself
				el.detachEvent('on' + type, func.bound);
			}
		}
	},

	getPoint: function(event) {
		var pos = event.targetTouches
				? event.targetTouches.length
					? event.targetTouches[0]
					: event.changedTouches[0]
				: event;
		return Point.create(
			pos.pageX || pos.clientX + document.documentElement.scrollLeft,
			pos.pageY || pos.clientY + document.documentElement.scrollTop
		);
	},

	getElement: function(event) {
		return event.target || event.srcElement;
	},

	getOffset: function(event) {
		// Remove target offsets from page coordinates
		return DomEvent.getPoint(event).subtract(
				DomElement.getOffset(DomEvent.getElement(event), true));
	},

	preventDefault: function(event) {
		if (event.preventDefault) {
			event.preventDefault();
		} else {
			// IE
			event.returnValue = false;
		}
	},

	stopPropagation: function(event) {
		if (event.stopPropagation) {
			event.stopPropagation();
		} else {
			event.cancelBubble = true;
		}
	},

	stop: function(event) {
		DomEvent.stopPropagation(event);
		DomEvent.preventDefault(event);
	},
};

DomEvent.requestAnimationFrame = new function() {
	var part = 'equestAnimationFrame',
		request = window['r' + part] || window['webkitR' + part]
			|| window['mozR' + part] || window['oR' + part]
			|| window['msR' + part];
	if (request) {
		// Chrome shipped without the time arg in m10. We need to check if time
		// is defined in callbacks, and if not, clear request again so we won't
		// use the faulty method.
		request(function(time) {
			if (time == undefined)
				request = null;
		});
	}

	// So we need to fake it. Define helper functions first:
	var callbacks = [],
		focused = true,
		timer;

	DomEvent.add(window, {
		focus: function() {
			focused = true;
		},
		blur: function() {
			focused = false;
		}
	});

	return function(callback, element) {
		// See if we can handle natively first
		if (request)
			return request(callback, element);
		// If not, do the callback handling ourself:
		callbacks.push([callback, element]);
		if (!timer) {
			// Installs interval timer that checks all callbacks. This results
			// in faster animations than repeatedly installing timout timers.
			timer = window.setInterval(function() {
				// Checks all installed callbacks for element visibility and
				// execute if needed.
				for (var i = callbacks.length - 1; i >= 0; i--) {
					var entry = callbacks[i],
						func = entry[0],
						element = entry[1];
					if (!element || element.getAttribute('keepalive') == 'true'
							|| focused && DomElement.isVisible(element)) {
						// Handle callback and remove it from callbacks list.
						callbacks.splice(i, 1);
						func(Date.now());
					}
				}
			}, 1000 / 60);
		}
	};
};
<commit_msg>Allow the optional overriding of target in DomEvent.getOffset().<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var DomEvent = {
	add: function(el, events) {
		for (var type in events) {
			var func = events[type];
			if (el.addEventListener) {
				el.addEventListener(type, func, false);
			} else if (el.attachEvent) {
				// Make a bound closure that calls on the right object and
				// passes on the global event object as a parameter.
				el.attachEvent('on' + type, func.bound = function() {
					func.call(el, window.event);
				});
			}
		}
	},

	remove: function(el, events) {
		for (var type in events) {
			var func = events[type];
			if (el.removeEventListener) {
				el.removeEventListener(type, func, false);
			} else if (el.detachEvent) {
				// Remove the bound closure instead of func itself
				el.detachEvent('on' + type, func.bound);
			}
		}
	},

	getPoint: function(event) {
		var pos = event.targetTouches
				? event.targetTouches.length
					? event.targetTouches[0]
					: event.changedTouches[0]
				: event;
		return Point.create(
			pos.pageX || pos.clientX + document.documentElement.scrollLeft,
			pos.pageY || pos.clientY + document.documentElement.scrollTop
		);
	},

	getElement: function(event) {
		return event.target || event.srcElement;
	},

	getOffset: function(event, target) {
		// Remove target offsets from page coordinates
		return DomEvent.getPoint(event).subtract(
				DomElement.getOffset(target || DomEvent.getElement(event), true));
	},

	preventDefault: function(event) {
		if (event.preventDefault) {
			event.preventDefault();
		} else {
			// IE
			event.returnValue = false;
		}
	},

	stopPropagation: function(event) {
		if (event.stopPropagation) {
			event.stopPropagation();
		} else {
			event.cancelBubble = true;
		}
	},

	stop: function(event) {
		DomEvent.stopPropagation(event);
		DomEvent.preventDefault(event);
	},
};

DomEvent.requestAnimationFrame = new function() {
	var part = 'equestAnimationFrame',
		request = window['r' + part] || window['webkitR' + part]
			|| window['mozR' + part] || window['oR' + part]
			|| window['msR' + part];
	if (request) {
		// Chrome shipped without the time arg in m10. We need to check if time
		// is defined in callbacks, and if not, clear request again so we won't
		// use the faulty method.
		request(function(time) {
			if (time == undefined)
				request = null;
		});
	}

	// So we need to fake it. Define helper functions first:
	var callbacks = [],
		focused = true,
		timer;

	DomEvent.add(window, {
		focus: function() {
			focused = true;
		},
		blur: function() {
			focused = false;
		}
	});

	return function(callback, element) {
		// See if we can handle natively first
		if (request)
			return request(callback, element);
		// If not, do the callback handling ourself:
		callbacks.push([callback, element]);
		if (!timer) {
			// Installs interval timer that checks all callbacks. This results
			// in faster animations than repeatedly installing timout timers.
			timer = window.setInterval(function() {
				// Checks all installed callbacks for element visibility and
				// execute if needed.
				for (var i = callbacks.length - 1; i >= 0; i--) {
					var entry = callbacks[i],
						func = entry[0],
						element = entry[1];
					if (!element || element.getAttribute('keepalive') == 'true'
							|| focused && DomElement.isVisible(element)) {
						// Handle callback and remove it from callbacks list.
						callbacks.splice(i, 1);
						func(Date.now());
					}
				}
			}, 1000 / 60);
		}
	};
};
<|endoftext|>


<commit_before>var config = require('../config');

if (config.environment !== 'development')
  throw 'This script must only be run locally.';

if (__dirname !== require('helper').rootDir + '/scripts')
  throw 'This script must only be run locally.';
<commit_msg>Updates sanity check for enforcing the local running of dangerous scripts<commit_after>var config = require('../config');

if (config.environment !== 'development')
  throw 'This script must only be run locally.';

if (__dirname.toLowerCase() !== require('helper').rootDir.toLowerCase() + '/scripts')
  throw 'This script must only be run locally.';
<|endoftext|>


<commit_before>/**
 * @flow
 *
 * Building Hours view. This component loads data from either GitHub or
 * the local copy as a fallback, and renders the list of buildings.
 */

import * as React from 'react'
import {NoticeView} from '../components/notice'
import {BuildingHoursList} from './list'
import {type ReduxState} from '../../flux'
import {connect} from 'react-redux'
import moment from 'moment-timezone'
import type {TopLevelViewPropsType} from '../types'
import type {BuildingType} from './types'
import * as defaultData from '../../../docs/building-hours.json'
import {reportNetworkProblem} from '../../lib/report-network-problem'
import toPairs from 'lodash/toPairs'
import groupBy from 'lodash/groupBy'
import delay from 'delay'

import {CENTRAL_TZ} from './lib'
const githubBaseUrl =
  'https://stodevx.github.io/AAO-React-Native/building-hours.json'

const groupBuildings = (
  buildings: BuildingType[],
  favoriteBuildings: string[],
) => {
  let favoriteBuildingsGroup = {title: 'Favorites', data: Array()}
  for (let i = 0; i < buildings.length; i++) {
    if (favoriteBuildings.includes(buildings[i].name)) {
      favoriteBuildingsGroup.data.push(buildings[i])
    }
  }
  const grouped = groupBy(buildings, b => b.category || 'Other')
  const groupedBuildings = toPairs(grouped).map(([key, value]) => ({
    title: key,
    data: value,
  }))
  let allGroups = Array()
  if (favoriteBuildings.length > 0) {
    allGroups.push(favoriteBuildingsGroup)
  }
  for (let i = 0; i < groupedBuildings.length; i++) {
    allGroups.push(groupedBuildings[i])
  }
  return allGroups
}

type ReduxStateProps = {
  favoriteBuildings: Array<string>,
}

type Props = TopLevelViewPropsType & ReduxStateProps

type State = {
  error: ?Error,
  loading: boolean,
  now: moment,
  buildings: Array<{title: string, data: BuildingType[]}>,
  intervalId: number,
}

export class BuildingHoursView extends React.Component<Props, State> {
  static navigationOptions = {
    title: 'Building Hours',
    headerBackTitle: 'Hours',
  }

  state = {
    error: null,
    loading: false,
    // now: moment.tz('Wed 7:25pm', 'ddd h:mma', null, CENTRAL_TZ),
    now: moment.tz(CENTRAL_TZ),
    buildings: groupBuildings(defaultData.data, this.props.favoriteBuildings),
    intervalId: 0,
  }

  componentWillMount() {
    this.fetchData()

    // This updates the screen every second, so that the building
    // info statuses are updated without needing to leave and come back.
    this.setState({intervalId: setInterval(this.updateTime, 1000)})
  }

  componentWillUnmount() {
    clearTimeout(this.state.intervalId)
  }

  updateTime = () => {
    this.setState(() => ({now: moment.tz(CENTRAL_TZ)}))
  }

  refresh = async (): any => {
    let start = Date.now()
    this.setState(() => ({loading: true}))

    await this.fetchData()

    // wait 0.5 seconds – if we let it go at normal speed, it feels broken.
    let elapsed = Date.now() - start
    if (elapsed < 500) {
      await delay(500 - elapsed)
    }

    this.setState(() => ({loading: false}))
  }

  fetchData = async () => {
    let {data: buildings} = await fetchJson(githubBaseUrl).catch(err => {
      reportNetworkProblem(err)
      return defaultData
    })
    if (process.env.NODE_ENV === 'development') {
      buildings = defaultData.data
    }
    this.setState(() => ({
      buildings: groupBuildings(buildings, this.props.favoriteBuildings),
      now: moment.tz(CENTRAL_TZ),
    }))
  }

  render() {
    this.fetchData()
    if (this.state.error) {
      return <NoticeView text={`Error: ${this.state.error.message}`} />
    }

    return (
      <BuildingHoursList
        buildings={this.state.buildings}
        favoriteBuildings={this.props.favoriteBuildings}
        loading={this.state.loading}
        navigation={this.props.navigation}
        now={this.state.now}
        onRefresh={this.refresh}
      />
    )
  }
}

function mapStateToProps(state: ReduxState): ReduxStateProps {
  return {
    favoriteBuildings: state.buildings ? state.buildings.favoriteBuildings : [],
  }
}

export const ConnectedBuildingHoursView = connect(mapStateToProps)(
  BuildingHoursView,
)
<commit_msg>switch to functional array manipulation in groupBuildings<commit_after>/**
 * @flow
 *
 * Building Hours view. This component loads data from either GitHub or
 * the local copy as a fallback, and renders the list of buildings.
 */

import * as React from 'react'
import {NoticeView} from '../components/notice'
import {BuildingHoursList} from './list'
import {type ReduxState} from '../../flux'
import {connect} from 'react-redux'
import moment from 'moment-timezone'
import type {TopLevelViewPropsType} from '../types'
import type {BuildingType} from './types'
import * as defaultData from '../../../docs/building-hours.json'
import {reportNetworkProblem} from '../../lib/report-network-problem'
import toPairs from 'lodash/toPairs'
import groupBy from 'lodash/groupBy'
import delay from 'delay'

import {CENTRAL_TZ} from './lib'
const githubBaseUrl =
  'https://stodevx.github.io/AAO-React-Native/building-hours.json'

const groupBuildings = (
  buildings: BuildingType[],
  favoriteBuildings: string[],
) => {
  const favoritesGroup = {
    title: 'Favorites',
    data: buildings.filter(b => favoriteBuildings.includes(b.name)),
  }

  const grouped = groupBy(buildings, b => b.category || 'Other')
  let groupedBuildings = toPairs(grouped).map(([key, value]) => ({
    title: key,
    data: value,
  }))

  if (favoritesGroup.data.length > 0) {
    groupedBuildings = [favoritesGroup, ...groupedBuildings]
  }

  return groupedBuildings
}

type ReduxStateProps = {
  favoriteBuildings: Array<string>,
}

type Props = TopLevelViewPropsType & ReduxStateProps

type State = {
  error: ?Error,
  loading: boolean,
  now: moment,
  buildings: Array<{title: string, data: BuildingType[]}>,
  intervalId: number,
}

export class BuildingHoursView extends React.Component<Props, State> {
  static navigationOptions = {
    title: 'Building Hours',
    headerBackTitle: 'Hours',
  }

  state = {
    error: null,
    loading: false,
    // now: moment.tz('Wed 7:25pm', 'ddd h:mma', null, CENTRAL_TZ),
    now: moment.tz(CENTRAL_TZ),
    buildings: groupBuildings(defaultData.data, this.props.favoriteBuildings),
    intervalId: 0,
  }

  componentWillMount() {
    this.fetchData()

    // This updates the screen every second, so that the building
    // info statuses are updated without needing to leave and come back.
    this.setState({intervalId: setInterval(this.updateTime, 1000)})
  }

  componentWillUnmount() {
    clearTimeout(this.state.intervalId)
  }

  updateTime = () => {
    this.setState(() => ({now: moment.tz(CENTRAL_TZ)}))
  }

  refresh = async (): any => {
    let start = Date.now()
    this.setState(() => ({loading: true}))

    await this.fetchData()

    // wait 0.5 seconds – if we let it go at normal speed, it feels broken.
    let elapsed = Date.now() - start
    if (elapsed < 500) {
      await delay(500 - elapsed)
    }

    this.setState(() => ({loading: false}))
  }

  fetchData = async () => {
    let {data: buildings} = await fetchJson(githubBaseUrl).catch(err => {
      reportNetworkProblem(err)
      return defaultData
    })
    if (process.env.NODE_ENV === 'development') {
      buildings = defaultData.data
    }
    this.setState(() => ({
      buildings: groupBuildings(buildings, this.props.favoriteBuildings),
      now: moment.tz(CENTRAL_TZ),
    }))
  }

  render() {
    this.fetchData()
    if (this.state.error) {
      return <NoticeView text={`Error: ${this.state.error.message}`} />
    }

    return (
      <BuildingHoursList
        buildings={this.state.buildings}
        favoriteBuildings={this.props.favoriteBuildings}
        loading={this.state.loading}
        navigation={this.props.navigation}
        now={this.state.now}
        onRefresh={this.refresh}
      />
    )
  }
}

function mapStateToProps(state: ReduxState): ReduxStateProps {
  return {
    favoriteBuildings: state.buildings ? state.buildings.favoriteBuildings : [],
  }
}

export const ConnectedBuildingHoursView = connect(mapStateToProps)(
  BuildingHoursView,
)
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule Image
 * @flow
 */
'use strict';

var NativeMethodsMixin = require('NativeMethodsMixin');
var NativeModules = require('NativeModules');
var ImageResizeMode = require('ImageResizeMode');
var ImageStylePropTypes = require('ImageStylePropTypes');
var PropTypes = require('ReactPropTypes');
var React = require('React');
var ReactNativeViewAttributes = require('ReactNativeViewAttributes');
var StyleSheet = require('StyleSheet');
var StyleSheetPropType = require('StyleSheetPropType');
var View = require('View');

var createReactNativeComponentClass = require('createReactNativeComponentClass');
var flattenStyle = require('flattenStyle');
var invariant = require('invariant');
var merge = require('merge');
var resolveAssetSource = require('resolveAssetSource');

/**
 * <Image> - A react component for displaying different types of images,
 * including network images, static resources, temporary local images, and
 * images from local disk, such as the camera roll.  Example usage:
 *
 *   renderImages: function() {
 *     return (
 *       <View>
 *         <Image
 *           style={styles.icon}
 *           source={require('image!myIcon')}
 *         />
 *         <Image
 *           style={styles.logo}
 *           source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}
 *         />
 *       </View>
 *     );
 *   },
 *
 * More example code in ImageExample.js
 */

var ImageViewAttributes = merge(ReactNativeViewAttributes.UIView, {
  src: true,
  resizeMode: true,
});

var Image = React.createClass({
  propTypes: {
    /**
     * `uri` is a string representing the resource identifier for the image, which
     * could be an http address, a local file path, or the name of a static image
     * resource (which should be wrapped in the `require('image!name')` function).
     */
    source: PropTypes.oneOfType([
      PropTypes.shape({
        uri: PropTypes.string,
      }),
      // Opaque type returned by require('./image.jpg')
      PropTypes.number,
    ]).isRequired,
    style: StyleSheetPropType(ImageStylePropTypes),
    /**
     * Used to locate this view in end-to-end tests.
     */
    testID: PropTypes.string,
  },

  statics: {
    resizeMode: ImageResizeMode,
  },

  mixins: [NativeMethodsMixin],

  /**
   * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
   * make `this` look like an actual native component class. Since it can render
   * as 3 different native components we need to update viewConfig accordingly
   */
  viewConfig: {
    uiViewClassName: 'RCTView',
    validAttributes: ReactNativeViewAttributes.RKView
  },

  _updateViewConfig: function(props) {
    if (props.children) {
      this.viewConfig = {
        uiViewClassName: 'RCTView',
        validAttributes: ReactNativeViewAttributes.RKView,
      };
    } else {
      this.viewConfig = {
        uiViewClassName: 'RCTImageView',
        validAttributes: ImageViewAttributes,
      };
    }
  },

  componentWillMount: function() {
    this._updateViewConfig(this.props);
  },

  componentWillReceiveProps: function(nextProps) {
    this._updateViewConfig(nextProps);
  },

  contextTypes: {
    isInAParentText: React.PropTypes.bool
  },

  render: function() {
    var source = resolveAssetSource(this.props.source);

    // As opposed to the ios version, here it render `null`
    // when no source or source.uri... so let's not break that.

    if (source && source.uri === '') {
      console.warn('source.uri should not be an empty string');
    }

    if (source && source.uri) {
      var {width, height} = source;
      var style = flattenStyle([{width, height}, styles.base, this.props.style]);

      var nativeProps = merge(this.props, {
        style,
        src: source.uri,
      });

      if (nativeProps.children) {
        // TODO(6033040): Consider implementing this as a separate native component
        var imageProps = merge(nativeProps, {
          style: styles.absoluteImage,
          children: undefined,
        });
        return (
          <View style={nativeProps.style}>
            <RKImage {...imageProps}/>
            {this.props.children}
          </View>
        );
      } else {
        if (this.context.isInAParentText) {
          return <RCTTextInlineImage {...nativeProps}/>;
        } else {
          return <RKImage {...nativeProps}/>;
        }
      }
    }
    return null;
  }
});

var styles = StyleSheet.create({
  base: {
    overflow: 'hidden',
  },
  absoluteImage: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    position: 'absolute'
  }
});

var RKImage = createReactNativeComponentClass({
  validAttributes: ImageViewAttributes,
  uiViewClassName: 'RCTImageView',
});
var RCTTextInlineImage = createReactNativeComponentClass({
  validAttributes: ImageViewAttributes,
  uiViewClassName: 'RCTTextInlineImage',
});

module.exports = Image;
<commit_msg>enabling progressive Jpeg rendering (part 2/2)<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule Image
 * @flow
 */
'use strict';

var NativeMethodsMixin = require('NativeMethodsMixin');
var NativeModules = require('NativeModules');
var ImageResizeMode = require('ImageResizeMode');
var ImageStylePropTypes = require('ImageStylePropTypes');
var PropTypes = require('ReactPropTypes');
var React = require('React');
var ReactNativeViewAttributes = require('ReactNativeViewAttributes');
var StyleSheet = require('StyleSheet');
var StyleSheetPropType = require('StyleSheetPropType');
var View = require('View');

var createReactNativeComponentClass = require('createReactNativeComponentClass');
var flattenStyle = require('flattenStyle');
var invariant = require('invariant');
var merge = require('merge');
var resolveAssetSource = require('resolveAssetSource');

/**
 * <Image> - A react component for displaying different types of images,
 * including network images, static resources, temporary local images, and
 * images from local disk, such as the camera roll.  Example usage:
 *
 *   renderImages: function() {
 *     return (
 *       <View>
 *         <Image
 *           style={styles.icon}
 *           source={require('image!myIcon')}
 *         />
 *         <Image
 *           style={styles.logo}
 *           source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}
 *         />
 *       </View>
 *     );
 *   },
 *
 * More example code in ImageExample.js
 */

var ImageViewAttributes = merge(ReactNativeViewAttributes.UIView, {
  src: true,
  resizeMode: true,
  progressiveRenderingEnabled: true,
  fadeDuration: true,
});

var Image = React.createClass({
  propTypes: {
    /**
     * `uri` is a string representing the resource identifier for the image, which
     * could be an http address, a local file path, or the name of a static image
     * resource (which should be wrapped in the `require('image!name')` function).
     */
    source: PropTypes.oneOfType([
      PropTypes.shape({
        uri: PropTypes.string,
      }),
      // Opaque type returned by require('./image.jpg')
      PropTypes.number,
    ]).isRequired,
    progressiveRenderingEnabled: PropTypes.bool,
    fadeDuration: PropTypes.number,
    style: StyleSheetPropType(ImageStylePropTypes),
    /**
     * Used to locate this view in end-to-end tests.
     */
    testID: PropTypes.string,
  },

  statics: {
    resizeMode: ImageResizeMode,
  },

  mixins: [NativeMethodsMixin],

  /**
   * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
   * make `this` look like an actual native component class. Since it can render
   * as 3 different native components we need to update viewConfig accordingly
   */
  viewConfig: {
    uiViewClassName: 'RCTView',
    validAttributes: ReactNativeViewAttributes.RKView
  },

  _updateViewConfig: function(props) {
    if (props.children) {
      this.viewConfig = {
        uiViewClassName: 'RCTView',
        validAttributes: ReactNativeViewAttributes.RKView,
      };
    } else {
      this.viewConfig = {
        uiViewClassName: 'RCTImageView',
        validAttributes: ImageViewAttributes,
      };
    }
  },

  componentWillMount: function() {
    this._updateViewConfig(this.props);
  },

  componentWillReceiveProps: function(nextProps) {
    this._updateViewConfig(nextProps);
  },

  contextTypes: {
    isInAParentText: React.PropTypes.bool
  },

  render: function() {
    var source = resolveAssetSource(this.props.source);

    // As opposed to the ios version, here it render `null`
    // when no source or source.uri... so let's not break that.

    if (source && source.uri === '') {
      console.warn('source.uri should not be an empty string');
    }

    if (source && source.uri) {
      var {width, height} = source;
      var style = flattenStyle([{width, height}, styles.base, this.props.style]);

      var nativeProps = merge(this.props, {
        style,
        src: source.uri,
      });

      if (nativeProps.children) {
        // TODO(6033040): Consider implementing this as a separate native component
        var imageProps = merge(nativeProps, {
          style: styles.absoluteImage,
          children: undefined,
        });
        return (
          <View style={nativeProps.style}>
            <RKImage {...imageProps}/>
            {this.props.children}
          </View>
        );
      } else {
        if (this.context.isInAParentText) {
          return <RCTTextInlineImage {...nativeProps}/>;
        } else {
          return <RKImage {...nativeProps}/>;
        }
      }
    }
    return null;
  }
});

var styles = StyleSheet.create({
  base: {
    overflow: 'hidden',
  },
  absoluteImage: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    position: 'absolute'
  }
});

var RKImage = createReactNativeComponentClass({
  validAttributes: ImageViewAttributes,
  uiViewClassName: 'RCTImageView',
});
var RCTTextInlineImage = createReactNativeComponentClass({
  validAttributes: ImageViewAttributes,
  uiViewClassName: 'RCTTextInlineImage',
});

module.exports = Image;
<|endoftext|>


<commit_before>var React = require('react');
var Icon = require('react-icons');

var App = React.createClass({
	render () {
		return (
			<Icon name="circle" className="test-this-out" />
		);
	}
});

React.render(<App />, document.getElementById('app'));
<commit_msg>use test case and update props for example<commit_after>var React = require('react');
var Icon = require('react-icons');

var App = React.createClass({
	render () {
		return (
			<Icon name="test" size={128} color="white" className="can-haz-custom-classname" />
		);
	}
});

React.render(<App />, document.getElementById('app'));
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { withRouter, Link } from 'react-router';
import PostSingleContent from './PostSingleContent';
import Icon from './../widgets/Icon';
import './PostSingleModal.scss';

@withRouter
export default class PostSingleModal extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave);
    // manipulate address bar to show the article's address
    if (window && window.history) {
      const { content } = this.props;
      const postPath = `/${content.parent_permlink}/@${content.author}/${content.permlink}`;
      window.history.pushState({}, content.title, postPath);
    }

    if (window) {
      // freeze scroll in the feed
      window.document.querySelector('body').style.overflow = 'hidden';
      window.onpopstate = () => this.routerWillLeave();
    }
  }

  componentWillUnmount() {
    if (window) {
      window.onpopstate = null;
    }
  }

  routerWillLeave = () => {
    this.props.closePostModal();
    // un-freeze scroll in the feed
    if (window) {
      window.document.querySelector('body').style.overflow = 'initial';
    }
    return true;
  };

  handleClose = (e) => {
    this.routerWillLeave();
    // fix the manipulated URL
    if (window && window.history) {
      window.history.back();
    }
  };

  render() {
    const { content, sidebarIsVisible } = this.props;

    return (

<Link to="/" onlyActiveOnIndex activeClassName="active"></Link>

              clear

          {this.props.children &&
{this.props.children}
}

        <PostSingleContent
          content={content}
        />

    );
  }
}
<commit_msg>add TriggerPost to post modal<commit_after>import React, { Component } from 'react';
import { withRouter, Link } from 'react-router';
import PostSingleContent from './PostSingleContent';
import Icon from './../widgets/Icon';
import './PostSingleModal.scss';
import TriggerPost from './../app/Trigger/TriggerPost';

@withRouter
export default class PostSingleModal extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave);
    // manipulate address bar to show the article's address
    if (window && window.history) {
      const { content } = this.props;
      const postPath = `/${content.parent_permlink}/@${content.author}/${content.permlink}`;
      window.history.pushState({}, content.title, postPath);
    }

    if (window) {
      // freeze scroll in the feed
      window.document.querySelector('body').style.overflow = 'hidden';
      window.onpopstate = () => this.routerWillLeave();
    }
  }

  componentWillUnmount() {
    if (window) {
      window.onpopstate = null;
    }
  }

  routerWillLeave = () => {
    this.props.closePostModal();
    // un-freeze scroll in the feed
    if (window) {
      window.document.querySelector('body').style.overflow = 'initial';
    }
    return true;
  };

  handleClose = (e) => {
    this.routerWillLeave();
    // fix the manipulated URL
    if (window && window.history) {
      window.history.back();
    }
  };

  render() {
    const { content, sidebarIsVisible } = this.props;

    return (

        <TriggerPost
          reblog={reblog}
          isReblogged={isReblogged}
        />

<Link to="/" onlyActiveOnIndex activeClassName="active"></Link>

              clear

          {this.props.children &&
{this.props.children}
}

        <PostSingleContent
          content={content}
        />

    );
  }
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2016-2017 DrSmugleaf
//

// https://github.com/Gawdl3y/discord.js-commando/blob/master/src/providers/sqlite.js
"use strict"
const DB = require("../util/db")
const Discord = require("discord.js")
const SettingProvider = require("discord.js-commando").SettingProvider

class PostgreSQLProvider extends SettingProvider {
  constructor() {
    super()

    this.db = new DB()

    Object.defineProperty(this, "client", { value: null, writable: true })

    this.guildSettings = new Map()
    this.guildListeners = new Map()

    this.userSettings = new Map()
  }

  async init(client) {
    this.client = client

    Promise.all([
      this.guildInit(),
      this.userInit()
    ]).then(() => this.client.emit("dbReady"))
  }

  async guildInit() {
    await this.db.query("CREATE TABLE IF NOT EXISTS settings (guild BIGINT PRIMARY KEY, settings TEXT)")

    const rows = await this.db.query("SELECT CAST(guild as TEXT) as guild, settings FROM settings")
    for(const row of rows) {
      let settings
      try {
        settings = JSON.parse(row.settings)
      } catch(e) {
        this.client.emit("warn", `PostgreSQLProvider couldn't parse the settings stored for guild ${row.guild}`)
        continue
      }

      const guild = row.guild !== "0" ? row.guild : "global"
      this.guildSettings.set(guild, settings)
      if(guild !== "global" && !this.client.guilds.has(row.guild)) continue
      this.setupGuild(guild, settings)
    }

    this.guildListeners
      .set("commandPrefixChange", (guild, prefix) => this.set(guild, "prefix", prefix))
      .set("commandStatusChange", (guild, command, enabled) => this.set(guild, `cmd-${command.name}`, enabled))
      .set("groupStatusChange", (guild, group, enabled) => this.set(guild, `grp-${group.id}`, enabled))
      .set("guildCreate", (guild) => {
        const settings = this.guildSettings.get(guild.id)
        if(!settings) return
        this.setupGuild(guild.id, settings)
      })
      .set("commandRegister", (command) => {
        for(const [guild, settings] of this.guildSettings) {
          if(guild !== "global" && !this.client.guilds.has(guild)) continue
          this.setupGuildCommand(this.client.guilds.get(guild), command, settings)
        }
      })
      .set("groupRegister", (group) => {
        for(const [guild, settings] of this.guildSettings) {
          if(guild !== "global" && !this.client.guilds.has(guild)) continue
          this.setupGuildGroup(this.client.guilds.get(guild), group, settings)
        }
      })

    for(const [event, listener] of this.guildListeners) this.client.on(event, listener)
  }

  async userInit() {
    await this.db.query("CREATE TABLE IF NOT EXISTS users (id BIGINT PRIMARY KEY, settings TEXT)")

    const rows = await this.db.query("SELECT CAST(user as TEXT) as id, settings FROM users")
    for(const row of rows) {
      let settings
      try {
        settings = JSON.parse(row.settings)
      } catch(e) {
        this.client.emit("warn", `PostgreSQLProvider couldn't parse the settings stored for user ${row.user}`)
        continue
      }

      const user = row.user
      this.userSettings.set(user, settings)
    }
  }

  destroy() {
    for(const [event, listener] of this.guildListeners) this.client.removeListener(event, listener)
    this.guildListeners.clear()
  }

  get(unit, key, defVal) {
    var settings
    if(unit instanceof Discord.Guild) {
      settings = this.guildSettings.get(this.constructor.getGuildID(unit))
    } else if(unit instanceof Discord.GuildMember || unit instanceof Discord.User) {
      settings = this.userSettings.get(this.getUserID(unit))
    } else {
      throw new TypeError("Unit must be an instance of Discord.Guild, Discord.GuildMember or Discord.User")
    }

    return settings ? typeof settings[key] !== "undefined" ? settings[key] : defVal : defVal
  }

  async set(unit, key, val) {
    if(unit instanceof Discord.Guild) {
      const guild = this.constructor.getGuildID(unit)
      let settings = this.guildSettings.get(guild)
      if(!settings) {
        settings = {}
        this.guildSettings.set(guild, settings)
      }

      settings[key] = val
      await this.db.query(
        "INSERT INTO settings VALUES ($1, $2) ON CONFLICT (guild) DO UPDATE SET guild = $1, settings = $2",
        [guild !== "global" ? guild : 0, JSON.stringify(settings)]
      )
      if(guild === "global") this.updateOtherShards(key, val)
      return val
    } else if(unit instanceof Discord.GuildMember || unit instanceof Discord.User) {
      const user = this.getUserID(unit)
      let settings = this.userSettings.get(user)
      if(!settings) {
        settings = {}
        this.userSettings.set(user, settings)
      }

      settings[key] = val
      await this.db.query(
        "INSERT INTO users VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET id = $1, settings = $2",
        [user, JSON.stringify(settings)]
      )
      this.updateOtherShards(key, val)
      return val
    } else {
      throw new TypeError("Unit must be an instance of Discord.Guild, Discord.GuildMember or Discord.User")
    }
  }

  async remove(unit, key) {
    if(unit instanceof Discord.Guild) {
      const guild = this.constructor.getGuildID(unit)
      const settings = this.guildSettings.get(guild)
      if(!settings || typeof settings[key] === "undefined") return undefined

      const val = settings[key]
      settings[key] = undefined
      await this.db.query(
        "INSERT INTO settings VALUES ($1, $2) ON CONFLICT (guild) DO UPDATE SET guild = $1, settings = $2",
        [guild !== "global" ? guild : 0, JSON.stringify(settings)]
      )
      if(guild === "global") this.updateOtherShards(key, undefined)
      return val
    } else if(unit instanceof Discord.GuildMember || unit instanceof Discord.User) {
      const user = this.getUserID(unit)
      const settings = this.userSettings.get(user)
      if(!settings || typeof settings[key] === "undefined") return undefined

      const val = settings[key]
      settings[key] = undefined
      await this.db.query(
        "INSERT INTO users VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET id = $1, settings = $2",
        [user, JSON.stringify(settings)]
      )
      this.updateOtherShards(key, undefined)
      return val
    }
  }

  async clear(unit) {
    if(unit instanceof Discord.Guild) {
      const guild = this.constructor.getGuildID(guild)
      if(!this.guildSettings.has(guild)) return
      this.guildSettings.delete(guild)
      await this.db.query(
        "DELETE FROM settings WHERE guild = $1",
        [guild !== "global" ? guild : 0]
      )
    } else if(unit instanceof Discord.GuildMember || unit instanceof Discord.User) {
      const user = this.getUserID(unit)
      if(!this.userSettings.has(user)) return
      this.userSettings.delete(user)
      await this.db.query(
        "DELETE FROM users WHERE user = $1",
        [user]
      )
    }
  }

  setupGuild(guild, settings) {
    if(typeof guild !== "string") throw new TypeError("The guild must be a guild ID or 'global'.")
    guild = this.client.guilds.get(guild) || null

    if(typeof settings.prefix !== "undefined") {
      if(guild) guild._commandPrefix = settings.prefix
      else this.client._commandPrefix = settings.prefix
    }

    for(const command of this.client.registry.commands.values()) this.setupGuildCommand(guild, command, settings)
    for(const group of this.client.registry.groups.values()) this.setupGuildGroup(guild, group, settings)
  }

  setupGuildCommand(guild, command, settings) {
    if(typeof settings[`cmd-${command.name}`] === "undefined") return
    if(guild) {
      if(!guild._commandsEnabled) guild._commandsEnabled = {}
      guild._commandsEnabled[command.name] = settings[`cmd-${command.name}`]
    } else {
      command._globalEnabled = settings[`cmd-${command.name}`]
    }
  }

  setupGuildGroup(guild, group, settings) {
    if(typeof settings[`grp-${group.id}`] === "undefined") return
    if(guild) {
      if(!guild._groupsEnabled) guild._groupsEnabled = {}
      guild._groupsEnabled[group.id] = settings[`grp-${group.id}`]
    } else {
      group._globalEnabled = settings[`grp-${group.id}`]
    }
  }

  getUserID(user) {
    return user.id
  }

  updateOtherShards(key, val) {
    if(!this.client.shard) return
    key = JSON.stringify(key)
    val = typeof val !== "undefined" ? JSON.stringify(val) : "undefined"
    this.client.shard.broadcastEval(`
      if(this.shard.id !== ${this.client.shard.id} && this.provider && this.provider.settings) {
        this.provider.settings.global[${key}] = ${val}
      }
    `)
  }
}

module.exports = PostgreSQLProvider
<commit_msg>Fixed an error when trying to clear server settings<commit_after>//
// Copyright (c) 2016-2017 DrSmugleaf
//

// https://github.com/Gawdl3y/discord.js-commando/blob/master/src/providers/sqlite.js
"use strict"
const DB = require("../util/db")
const Discord = require("discord.js")
const SettingProvider = require("discord.js-commando").SettingProvider

class PostgreSQLProvider extends SettingProvider {
  constructor() {
    super()

    this.db = new DB()

    Object.defineProperty(this, "client", { value: null, writable: true })

    this.guildSettings = new Map()
    this.guildListeners = new Map()

    this.userSettings = new Map()
  }

  async init(client) {
    this.client = client

    Promise.all([
      this.guildInit(),
      this.userInit()
    ]).then(() => this.client.emit("dbReady"))
  }

  async guildInit() {
    await this.db.query("CREATE TABLE IF NOT EXISTS settings (guild BIGINT PRIMARY KEY, settings TEXT)")

    const rows = await this.db.query("SELECT CAST(guild as TEXT) as guild, settings FROM settings")
    for(const row of rows) {
      let settings
      try {
        settings = JSON.parse(row.settings)
      } catch(e) {
        this.client.emit("warn", `PostgreSQLProvider couldn't parse the settings stored for guild ${row.guild}`)
        continue
      }

      const guild = row.guild !== "0" ? row.guild : "global"
      this.guildSettings.set(guild, settings)
      if(guild !== "global" && !this.client.guilds.has(row.guild)) continue
      this.setupGuild(guild, settings)
    }

    this.guildListeners
      .set("commandPrefixChange", (guild, prefix) => this.set(guild, "prefix", prefix))
      .set("commandStatusChange", (guild, command, enabled) => this.set(guild, `cmd-${command.name}`, enabled))
      .set("groupStatusChange", (guild, group, enabled) => this.set(guild, `grp-${group.id}`, enabled))
      .set("guildCreate", (guild) => {
        const settings = this.guildSettings.get(guild.id)
        if(!settings) return
        this.setupGuild(guild.id, settings)
      })
      .set("commandRegister", (command) => {
        for(const [guild, settings] of this.guildSettings) {
          if(guild !== "global" && !this.client.guilds.has(guild)) continue
          this.setupGuildCommand(this.client.guilds.get(guild), command, settings)
        }
      })
      .set("groupRegister", (group) => {
        for(const [guild, settings] of this.guildSettings) {
          if(guild !== "global" && !this.client.guilds.has(guild)) continue
          this.setupGuildGroup(this.client.guilds.get(guild), group, settings)
        }
      })

    for(const [event, listener] of this.guildListeners) this.client.on(event, listener)
  }

  async userInit() {
    await this.db.query("CREATE TABLE IF NOT EXISTS users (id BIGINT PRIMARY KEY, settings TEXT)")

    const rows = await this.db.query("SELECT CAST(user as TEXT) as id, settings FROM users")
    for(const row of rows) {
      let settings
      try {
        settings = JSON.parse(row.settings)
      } catch(e) {
        this.client.emit("warn", `PostgreSQLProvider couldn't parse the settings stored for user ${row.user}`)
        continue
      }

      const user = row.user
      this.userSettings.set(user, settings)
    }
  }

  destroy() {
    for(const [event, listener] of this.guildListeners) this.client.removeListener(event, listener)
    this.guildListeners.clear()
  }

  get(unit, key, defVal) {
    var settings
    if(unit instanceof Discord.Guild) {
      settings = this.guildSettings.get(this.constructor.getGuildID(unit))
    } else if(unit instanceof Discord.GuildMember || unit instanceof Discord.User) {
      settings = this.userSettings.get(this.getUserID(unit))
    } else {
      throw new TypeError("Unit must be an instance of Discord.Guild, Discord.GuildMember or Discord.User")
    }

    return settings ? typeof settings[key] !== "undefined" ? settings[key] : defVal : defVal
  }

  async set(unit, key, val) {
    if(unit instanceof Discord.Guild) {
      const guild = this.constructor.getGuildID(unit)
      let settings = this.guildSettings.get(guild)
      if(!settings) {
        settings = {}
        this.guildSettings.set(guild, settings)
      }

      settings[key] = val
      await this.db.query(
        "INSERT INTO settings VALUES ($1, $2) ON CONFLICT (guild) DO UPDATE SET guild = $1, settings = $2",
        [guild !== "global" ? guild : 0, JSON.stringify(settings)]
      )
      if(guild === "global") this.updateOtherShards(key, val)
      return val
    } else if(unit instanceof Discord.GuildMember || unit instanceof Discord.User) {
      const user = this.getUserID(unit)
      let settings = this.userSettings.get(user)
      if(!settings) {
        settings = {}
        this.userSettings.set(user, settings)
      }

      settings[key] = val
      await this.db.query(
        "INSERT INTO users VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET id = $1, settings = $2",
        [user, JSON.stringify(settings)]
      )
      this.updateOtherShards(key, val)
      return val
    } else {
      throw new TypeError("Unit must be an instance of Discord.Guild, Discord.GuildMember or Discord.User")
    }
  }

  async remove(unit, key) {
    if(unit instanceof Discord.Guild) {
      const guild = this.constructor.getGuildID(unit)
      const settings = this.guildSettings.get(guild)
      if(!settings || typeof settings[key] === "undefined") return undefined

      const val = settings[key]
      settings[key] = undefined
      await this.db.query(
        "INSERT INTO settings VALUES ($1, $2) ON CONFLICT (guild) DO UPDATE SET guild = $1, settings = $2",
        [guild !== "global" ? guild : 0, JSON.stringify(settings)]
      )
      if(guild === "global") this.updateOtherShards(key, undefined)
      return val
    } else if(unit instanceof Discord.GuildMember || unit instanceof Discord.User) {
      const user = this.getUserID(unit)
      const settings = this.userSettings.get(user)
      if(!settings || typeof settings[key] === "undefined") return undefined

      const val = settings[key]
      settings[key] = undefined
      await this.db.query(
        "INSERT INTO users VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET id = $1, settings = $2",
        [user, JSON.stringify(settings)]
      )
      this.updateOtherShards(key, undefined)
      return val
    }
  }

  async clear(unit) {
    if(unit instanceof Discord.Guild) {
      const guild = this.constructor.getGuildID(unit)
      if(!this.guildSettings.has(guild)) return
      this.guildSettings.delete(guild)
      await this.db.query(
        "DELETE FROM settings WHERE guild = $1",
        [guild !== "global" ? guild : 0]
      )
    } else if(unit instanceof Discord.GuildMember || unit instanceof Discord.User) {
      const user = this.getUserID(unit)
      if(!this.userSettings.has(user)) return
      this.userSettings.delete(user)
      await this.db.query(
        "DELETE FROM users WHERE user = $1",
        [user]
      )
    }
  }

  setupGuild(guild, settings) {
    if(typeof guild !== "string") throw new TypeError("The guild must be a guild ID or 'global'.")
    guild = this.client.guilds.get(guild) || null

    if(typeof settings.prefix !== "undefined") {
      if(guild) guild._commandPrefix = settings.prefix
      else this.client._commandPrefix = settings.prefix
    }

    for(const command of this.client.registry.commands.values()) this.setupGuildCommand(guild, command, settings)
    for(const group of this.client.registry.groups.values()) this.setupGuildGroup(guild, group, settings)
  }

  setupGuildCommand(guild, command, settings) {
    if(typeof settings[`cmd-${command.name}`] === "undefined") return
    if(guild) {
      if(!guild._commandsEnabled) guild._commandsEnabled = {}
      guild._commandsEnabled[command.name] = settings[`cmd-${command.name}`]
    } else {
      command._globalEnabled = settings[`cmd-${command.name}`]
    }
  }

  setupGuildGroup(guild, group, settings) {
    if(typeof settings[`grp-${group.id}`] === "undefined") return
    if(guild) {
      if(!guild._groupsEnabled) guild._groupsEnabled = {}
      guild._groupsEnabled[group.id] = settings[`grp-${group.id}`]
    } else {
      group._globalEnabled = settings[`grp-${group.id}`]
    }
  }

  getUserID(user) {
    return user.id
  }

  updateOtherShards(key, val) {
    if(!this.client.shard) return
    key = JSON.stringify(key)
    val = typeof val !== "undefined" ? JSON.stringify(val) : "undefined"
    this.client.shard.broadcastEval(`
      if(this.shard.id !== ${this.client.shard.id} && this.provider && this.provider.settings) {
        this.provider.settings.global[${key}] = ${val}
      }
    `)
  }
}

module.exports = PostgreSQLProvider
<|endoftext|>


<commit_before>define(function () {
  /**
   * Constructor wrapper that makes mixins and proxying easier
   * @param {Function} constructor
   */
  function PrimalClay(constructor) {
    // Create a set of mixins for this constructor
    var mixins = {};

    // Create and expose helper method to add new mixins
    function addMixin(name, fn) {
      mixins[name] = fn;
    }
    constructor.addMixin = addMixin;
    constructor.mixins = mixins;

    // Proxy over constructor
    // TODO: Use a unified proxy (shared by models and controllers for params.start/stop adjustments)
    // TODO: Move mixin bindings into separate exposed function
    var retFn = function (params) {
      // If there are mixins
      var mixinKey = params.mixin,
          mixinKeys = mixinKey,
          mixin,
          i,
          len;
      if (mixinKeys) {
        // If the mixinKeys are a string, upcast to an array
        if (typeof mixinKeys === 'string') {
          mixinKeys = [mixinKey];
        }

        // Iterate the mixinKeys and attach them to params
        for (i = 0, len = mixinKeys.length; i < len; i++) {
          mixinKey = mixinKeys[i];
          mixin = MIXINS[mixinKey];

          // If the mixin exists, attach it to params
          if (mixin) {
            params = mixin(params) || params;
          }
        }
      }

      // Call and return the original function
      return constructor.apply(this, arguments);
    };
  }

  // Return PrimalClay
  return PrimalClay;
});<commit_msg>Test passes but lint is failing<commit_after>define(function () {
  /**
   * Constructor wrapper that makes mixins and proxying easier
   * @param {Function} constructor
   */
  function PrimalClay(constructor) {
    // Create a set of mixins for this constructor
    var mixins = {};

    // Proxy over constructor
    // TODO: Use a unified proxy (shared by models and controllers for params.start/stop adjustments)
    // TODO: Move mixin bindings into separate exposed function
    var retFn = function (params) {
      // If there are mixins
      var mixinKey = params.mixin,
          mixinKeys = mixinKey,
          mixin,
          i,
          len;
      if (mixinKeys) {
        // If the mixinKeys are a string, upcast to an array
        if (typeof mixinKeys === 'string') {
          mixinKeys = [mixinKey];
        }

        // Iterate the mixinKeys and attach them to params
        for (i = 0, len = mixinKeys.length; i < len; i++) {
          mixinKey = mixinKeys[i];
          mixin = MIXINS[mixinKey];

          // If the mixin exists, attach it to params
          if (mixin) {
            params = mixin(params) || params;
          }
        }
      }

      // Call and return the original function
      return constructor.apply(this, arguments);
    };

    // Create and expose helper method to add new mixins
    function addMixin(name, fn) {
      mixins[name] = fn;
    }
    retFn.addMixin = addMixin;
    retFn.mixins = mixins;

    // Return the retFn
    return retFn;
  }

  // Return PrimalClay
  return PrimalClay;
});<|endoftext|>


<commit_before>module.exports = {
  'env': {
    'es6': true
  },
  'parserOptions': {
    'ecmaVersion': 6,
    'sourceType': 'module',
    'ecmaFeatures': {
      'generators': false,
      'objectLiteralDuplicateProperties': false
    }
  },
  'plugins': [
    'import'
  ],

  'rules': {
    // enforces no braces where they can be omitted
    // http://eslint.org/docs/rules/arrow-body-style
    'arrow-body-style': [2, 'as-needed'],

    // require parens in arrow function arguments
    'arrow-parens': 0,

    // require space before/after arrow function's arrow
    // http://eslint.org/docs/rules/arrow-spacing
    'arrow-spacing': [2, { 'before': true, 'after': true }],

    // require trailing commas in multiline object literals
    'comma-dangle': [2, 'always-multiline'],

    // verify super() callings in constructors
    'constructor-super': 0,

    // enforce the spacing around the * in generator functions
    'generator-star-spacing': 0,

    // disallow modifying variables of class declarations
    // http://eslint.org/docs/rules/no-class-assign
    'no-class-assign': 2,

    // disallow arrow functions where they could be confused with comparisons
    // http://eslint.org/docs/rules/no-confusing-arrow
    'no-confusing-arrow': [2, {
      'allowParens': true,
    }],

    // disallow modifying variables that are declared using const
    'no-const-assign': 2,

    // disallow duplicate class members
    // http://eslint.org/docs/rules/no-dupe-class-members
    'no-dupe-class-members': 2,

    // disallow importing from the same path more than once
    // http://eslint.org/docs/rules/no-duplicate-imports
    'no-duplicate-imports': 2,

    // disallow symbol constructor
    // http://eslint.org/docs/rules/no-new-symbol
    'no-new-symbol': 2,

    // disallow specific globals
    'no-restricted-globals': 0,

    // disallow specific imports
    // http://eslint.org/docs/rules/no-restricted-imports
    'no-restricted-imports': 0,

    // disallow to use this/super before super() calling in constructors.
    'no-this-before-super': 0,

    // require let or const instead of var
    'no-var': 2,

    // disallow useless computed property keys
    // http://eslint.org/docs/rules/no-useless-computed-key
    'no-useless-computed-key': 2,

    // disallow unnecessary constructor
    // http://eslint.org/docs/rules/no-useless-constructor
    'no-useless-constructor': 2,

    // require method and property shorthand syntax for object literals
    // http://eslint.org/docs/rules/object-shorthand
    'object-shorthand': [2, 'always', {
      'ignoreConstructors': false,
      'avoidQuotes': false, // TODO: enable
    }],

    // suggest using arrow functions as callbacks
    'prefer-arrow-callback': [2, {
      'allowNamedFunctions': false,
      'allowUnboundThis': true,
    }],

    // suggest using of const declaration for variables that are never modified after declared
    'prefer-const': [2, {
      'destructuring': 'any',
      'ignoreReadBeforeAssign': false, // TODO: make true
    }],

    // suggest using the spread operator instead of .apply()
    'prefer-spread': 0,

    // suggest using Reflect methods where applicable
    'prefer-reflect': 0,

    // use rest parameters instead of arguments
    // http://eslint.org/docs/rules/prefer-rest-params
    'prefer-rest-params': 2,

    // suggest using template literals instead of string concatenation
    // http://eslint.org/docs/rules/prefer-template
    'prefer-template': 2,

    // disallow generator functions that do not have yield
    'require-yield': 0,

    // import sorting
    // http://eslint.org/docs/rules/sort-imports
    'sort-imports': 0,

    // enforce usage of spacing in template strings
    // http://eslint.org/docs/rules/template-curly-spacing
    'template-curly-spacing': 2,

    // enforce spacing around the * in yield* expressions
    // http://eslint.org/docs/rules/yield-star-spacing
    'yield-star-spacing': [2, 'after'],

    // disallow invalid exports, e.g. multiple defaults
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/export.md
    'import/export': 2,

    // ensure default import coupled with default export
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it
    'import/default': 0,

    // Ensure consistent use of file extension within the import path
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md
    // TODO: enable
    'import/extensions': [0, 'never'],

    // ensure named imports coupled with named exports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it
    'import/named': 0,

    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/namespace.md
    'import/namespace': 0,

    // Forbid the use of extraneous packages
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md
    // TODO: enable
    'import/no-extraneous-dependencies': [0, {
      'devDependencies': false,
      'optionalDependencies': false,
    }],

    // ensure imports point to files/modules that can be resolved
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
    'import/no-unresolved': [2, { 'commonjs': true }],

    // do not allow a default import name to match a named export
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default.md
    // TODO: enable
    'import/no-named-as-default': 0,

    // disallow require()
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-commonjs.md
    'import/no-commonjs': 0,

    // disallow AMD require/define
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-amd.md
    'import/no-amd': 2,

    // disallow non-import statements appearing before import statements
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/imports-first.md
    // TODO: enable?
    'import/imports-first': [0, 'absolute-first'],

    // disallow duplicate imports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md
    'import/no-duplicates': 2,

    // disallow use of jsdoc-marked-deprecated imports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md
    'import/no-deprecated': 0,

    // disallow namespace imports
    // TODO: enable?
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-namespace.md
    'import/no-namespace': 0,

    // warn on accessing default export property names that are also named exports
    // TODO: enable?
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default-member.md
    'import/no-named-as-default-member': 0,

    // No Node.js builtin modules
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-nodejs-modules.md
    'import/no-nodejs-modules': 0,

    // Enforce a convention in module import order
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md
    // TODO: enable?
    'import/order': [0, {
      'groups': ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'],
      'newlines-between': 'never',
    }],

    // Require modules with a single export to use a default export
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md
    // TODO: enable
    'import/prefer-default-export': 0,

    // Require a newline after the last import/require in a group
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md
    // TODO: enable
    'import/newline-after-import': 0,

    // Forbid mutable exports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md
    'import/no-mutable-exports': 2,
  },

  'settings': {
    'import/resolver': {
      'node': {
        'extensions': ['.js', '.json']
      }
    }
  }
};
<commit_msg>[eslint config] [base] [patch] Loosen `prefer-const` to not warn when the variable is “read” before being assigned to.<commit_after>module.exports = {
  'env': {
    'es6': true
  },
  'parserOptions': {
    'ecmaVersion': 6,
    'sourceType': 'module',
    'ecmaFeatures': {
      'generators': false,
      'objectLiteralDuplicateProperties': false
    }
  },
  'plugins': [
    'import'
  ],

  'rules': {
    // enforces no braces where they can be omitted
    // http://eslint.org/docs/rules/arrow-body-style
    'arrow-body-style': [2, 'as-needed'],

    // require parens in arrow function arguments
    'arrow-parens': 0,

    // require space before/after arrow function's arrow
    // http://eslint.org/docs/rules/arrow-spacing
    'arrow-spacing': [2, { 'before': true, 'after': true }],

    // require trailing commas in multiline object literals
    'comma-dangle': [2, 'always-multiline'],

    // verify super() callings in constructors
    'constructor-super': 0,

    // enforce the spacing around the * in generator functions
    'generator-star-spacing': 0,

    // disallow modifying variables of class declarations
    // http://eslint.org/docs/rules/no-class-assign
    'no-class-assign': 2,

    // disallow arrow functions where they could be confused with comparisons
    // http://eslint.org/docs/rules/no-confusing-arrow
    'no-confusing-arrow': [2, {
      'allowParens': true,
    }],

    // disallow modifying variables that are declared using const
    'no-const-assign': 2,

    // disallow duplicate class members
    // http://eslint.org/docs/rules/no-dupe-class-members
    'no-dupe-class-members': 2,

    // disallow importing from the same path more than once
    // http://eslint.org/docs/rules/no-duplicate-imports
    'no-duplicate-imports': 2,

    // disallow symbol constructor
    // http://eslint.org/docs/rules/no-new-symbol
    'no-new-symbol': 2,

    // disallow specific globals
    'no-restricted-globals': 0,

    // disallow specific imports
    // http://eslint.org/docs/rules/no-restricted-imports
    'no-restricted-imports': 0,

    // disallow to use this/super before super() calling in constructors.
    'no-this-before-super': 0,

    // require let or const instead of var
    'no-var': 2,

    // disallow useless computed property keys
    // http://eslint.org/docs/rules/no-useless-computed-key
    'no-useless-computed-key': 2,

    // disallow unnecessary constructor
    // http://eslint.org/docs/rules/no-useless-constructor
    'no-useless-constructor': 2,

    // require method and property shorthand syntax for object literals
    // http://eslint.org/docs/rules/object-shorthand
    'object-shorthand': [2, 'always', {
      'ignoreConstructors': false,
      'avoidQuotes': false, // TODO: enable
    }],

    // suggest using arrow functions as callbacks
    'prefer-arrow-callback': [2, {
      'allowNamedFunctions': false,
      'allowUnboundThis': true,
    }],

    // suggest using of const declaration for variables that are never modified after declared
    'prefer-const': [2, {
      'destructuring': 'any',
      'ignoreReadBeforeAssign': true,
    }],

    // suggest using the spread operator instead of .apply()
    'prefer-spread': 0,

    // suggest using Reflect methods where applicable
    'prefer-reflect': 0,

    // use rest parameters instead of arguments
    // http://eslint.org/docs/rules/prefer-rest-params
    'prefer-rest-params': 2,

    // suggest using template literals instead of string concatenation
    // http://eslint.org/docs/rules/prefer-template
    'prefer-template': 2,

    // disallow generator functions that do not have yield
    'require-yield': 0,

    // import sorting
    // http://eslint.org/docs/rules/sort-imports
    'sort-imports': 0,

    // enforce usage of spacing in template strings
    // http://eslint.org/docs/rules/template-curly-spacing
    'template-curly-spacing': 2,

    // enforce spacing around the * in yield* expressions
    // http://eslint.org/docs/rules/yield-star-spacing
    'yield-star-spacing': [2, 'after'],

    // disallow invalid exports, e.g. multiple defaults
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/export.md
    'import/export': 2,

    // ensure default import coupled with default export
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it
    'import/default': 0,

    // Ensure consistent use of file extension within the import path
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md
    // TODO: enable
    'import/extensions': [0, 'never'],

    // ensure named imports coupled with named exports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it
    'import/named': 0,

    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/namespace.md
    'import/namespace': 0,

    // Forbid the use of extraneous packages
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md
    // TODO: enable
    'import/no-extraneous-dependencies': [0, {
      'devDependencies': false,
      'optionalDependencies': false,
    }],

    // ensure imports point to files/modules that can be resolved
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
    'import/no-unresolved': [2, { 'commonjs': true }],

    // do not allow a default import name to match a named export
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default.md
    // TODO: enable
    'import/no-named-as-default': 0,

    // disallow require()
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-commonjs.md
    'import/no-commonjs': 0,

    // disallow AMD require/define
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-amd.md
    'import/no-amd': 2,

    // disallow non-import statements appearing before import statements
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/imports-first.md
    // TODO: enable?
    'import/imports-first': [0, 'absolute-first'],

    // disallow duplicate imports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md
    'import/no-duplicates': 2,

    // disallow use of jsdoc-marked-deprecated imports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md
    'import/no-deprecated': 0,

    // disallow namespace imports
    // TODO: enable?
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-namespace.md
    'import/no-namespace': 0,

    // warn on accessing default export property names that are also named exports
    // TODO: enable?
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default-member.md
    'import/no-named-as-default-member': 0,

    // No Node.js builtin modules
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-nodejs-modules.md
    'import/no-nodejs-modules': 0,

    // Enforce a convention in module import order
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md
    // TODO: enable?
    'import/order': [0, {
      'groups': ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'],
      'newlines-between': 'never',
    }],

    // Require modules with a single export to use a default export
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md
    // TODO: enable
    'import/prefer-default-export': 0,

    // Require a newline after the last import/require in a group
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md
    // TODO: enable
    'import/newline-after-import': 0,

    // Forbid mutable exports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md
    'import/no-mutable-exports': 2,
  },

  'settings': {
    'import/resolver': {
      'node': {
        'extensions': ['.js', '.json']
      }
    }
  }
};
<|endoftext|>