<commit_before>/**
 * @author Loris Tissino / http://loris.tissino.it
 * @package RoboThree
 * @release 0.60
 * @license The MIT License (MIT)
 * @see http://www.espruino.com/Reference
*/

var hcsr04 = require("HC-SR04");
var ir = require("IRReceiver");

var IRR = function ( pin, codesMap, leftSubtract ) {
    this.codesMap = codesMap;
    this.pin = pin;
    this.received = '';
    this.leftSubtract = leftSubtract;
    this.code = '';  // we keep track of the last code executed for managing kept pressed keys
    this.interval = false;
    var self = this;
};

IRR.prototype.enable = function ( callback ) {
    var self = this;
    this.callback = callback;
    ir.connect(this.pin, function ( receivedCode ) {
        self.received = receivedCode;
		if ( self.received.length > 1 ) {
			// new code
			var decimalValue = parseInt(self.received.substring(self.leftSubtract), 2);
			if ( decimalValue > 1 ) {
				self.code = decimalValue.toString();
			}
		}
    });
    this.interval = setInterval ( function () {
		if ( self.received == '1' ) {
			self.received = '';
		}
		else if (self.received.length <= 1) {
			self.code = '0';
		}
		self.callback();

	}, 200);
};

var Sonar = function ( triggerPin, echoPin, frequency ) {
    this.triggerPin = triggerPin;
    this.echoPin = echoPin;
    this.frequency = frequency;
    this.distance = Infinity;
    this.interval = undefined;
};

Sonar.prototype.enable = function () {
    var sonar = this;
    this.connection = hcsr04.connect ( this.triggerPin, this.echoPin, function ( dist ) {
        sonar.distance = dist;
    });
    this.interval = setInterval ( function () {
        sonar.connection.trigger();
    }, this.frequency );
};

Sonar.prototype.disable = function () {
    if ( typeof this.interval !== 'undefined' ) {
        clearInterval( this.interval );
    }
    this.distance = Infinity;
    this.interval = undefined;
};

var Wheel = function ( enablePin, controlPins, calibrationFactor) {
    this.enablePin = enablePin;
    this.controlPins = controlPins;
    this.calibrationFactor = calibrationFactor; // a value which is multiplied by speed before applying
    this.setSpeed(0);
};

// speed is assumed to be a number between 0.0 and 1.0
Wheel.prototype.setSpeed = function ( speed ) {
    this._speed = speed;
    analogWrite( this.enablePin, this._speed * this.calibrationFactor, { freq: 100 } );
    return this;
};

Wheel.prototype.getSpeed = function () {
    return this._speed;
};

Wheel.prototype.writeToControlPins = function (v0, v1) {
    this.controlPins[0].write(v0);
    this.controlPins[1].write(v1);
};

Wheel.prototype.forward = function () {
    this.writeToControlPins( 0, 1 );
};

Wheel.prototype.backward = function () {
    this.writeToControlPins( 1, 0 );
};

Wheel.prototype.stop = function () {
    this.writeToControlPins( 0, 0 );
};

var Led = function ( pin, blinkingTime ) {
    this.pin = pin;
    this.blinkingTime = blinkingTime;
    this.status = 0;
    this.pin.write( this.status );
    this.interval = false;
};

Led.prototype.toggle = function () {
    this.pin.write( this.status = 1 - this.status );
};

Led.prototype.clearInterval = function () {
    console.log ( this );
    if ( this.interval !== false ) {
        clearInterval ( this.interval );
    }
    this.interval = false;
};

Led.prototype.switchOn = function () {
    this.pin.write( this.status = 1 );
    this.clearInterval();
};

Led.prototype.switchOff = function () {
    this.pin.write( this.status = 0 );
    this.clearInterval();
};

var Buzzer = function ( pin, frequency, duration ) {
    this.pin = pin;
    this.defaultFrequency = frequency;
    this.defaultDuration = duration;
    this.status = 0;  // 0: off;  1: beeping;  2: replicated
};

Buzzer.prototype.beep = function ( frequency, duration ) {
    var self = this;
    this.frequency = frequency || this.defaultFrequency;
    this.duration = duration || this.defaultDuration;
    if ( this.status !== 1 ) {
        analogWrite(self.pin, 0.5, { freq: self.frequency } );
        this.status = 1;
        setTimeout ( function() {
            digitalWrite(self.pin, 0);
            this.status = 0;
        }, self.duration );
    }
};

var ThreeWheelDistanceSensingRobotBehavior = function ( id ) {
    this.id = id;
    this.data = {};
    this.config = {};
    this.playing = false;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.setup = function ( options ) {
    this.infraredReader = new IRR ( B3, {
            '16605343': { exec: 'moveForward', repeatOnKeptPressed: true },
            '16607383': { exec: 'moveBackward', repeatOnKeptPressed: true },
            '16603813': { exec: 'turnLeft', repeatOnKeptPressed: true },
            '16635943': { exec: 'turnRight', repeatOnKeptPressed: true },
            '16603303': { exec: 'stop', repeatOnKeptPressed: false },
            '66502975': { exec: 'decreaseSpeed', repeatOnKeptPressed: true },
            '66462175': { exec: 'increaseSpeed', repeatOnKeptPressed: true },
            '66478495': { exec: 'stop', repeatOnKeptPressed: false },
            '0'       : { exec: 'stop', repeatOnKeptPressed: false },
            '16597693': { exec: 'toggleLedBlinking1', repeatOnKeptPressed: false },
            '16581373': { exec: 'toggleLedBlinking2', repeatOnKeptPressed: false },
            '16629823': { exec: 'toggleLedBlinking3', repeatOnKeptPressed: false },
            '16599733': { exec: 'rightForward', repeatOnKeptPressed: true },
            '16607893': { exec: 'rightBackward', repeatOnKeptPressed: true },
            '16631863': { exec: 'leftForward', repeatOnKeptPressed: true },
            '16640023': { exec: 'leftBackward', repeatOnKeptPressed: true },
            '16609423': { exec: 'play', repeatOnKeptPressed: false },
            '16599223': { exec: 'pause', repeatOnKeptPressed: false },
        },
        1
    );
    this.leftWheel = new Wheel ( A2, [ A4, A3 ], 1);
    this.rightWheel = new Wheel ( A7, [ A5, A6 ], 0.75);
    this.speed = 0;
    this.leds = {
        '1': new Led ( LED1, 700 ),
        '2': new Led ( LED2, 500 ),
        '3': new Led ( LED3, 300 )
    };
    this.sonars = {
        'left': new Sonar ( C1, C0, 1000 ),
        'front': new Sonar ( C3, C2, 1000 ),
        'right': new Sonar ( C4, C5, 1000 )
    };
    this.buzzer = new Buzzer( B6, 110, 100 );

    this.checkForObstacles = { enabled: false };

    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.enableInfraredReader = function () {
    this.infraredReader.enable ( this.handleInfraredReaderCode.bind(this) );
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.handleInfraredReaderCode = function () {
    if ( typeof this.infraredReader.code === 'undefined') {
        return;
    }
    if ( this.infraredReader.codesMap.hasOwnProperty ( this.infraredReader.code ) ) {
        var action = this.infraredReader.codesMap[this.infraredReader.code];
        if ( action.repeatOnKeptPressed === true || this.infraredReader.received != '1' ) {
            this[action.exec]();
        }
    }
    else {
        console.log ( 'IR code read: ' + this.infraredReader.code + ' (not handled)');
    }
};

ThreeWheelDistanceSensingRobotBehavior.prototype.moveForward = function () {
    this.leftWheel.forward();
    this.rightWheel.forward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.moveBackward = function () {
    this.leftWheel.backward();
    this.rightWheel.backward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.turnLeft = function () {
    this.leftWheel.backward();
    this.rightWheel.forward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.turnRight = function () {
    this.leftWheel.forward();
    this.rightWheel.backward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.leftForward = function () {
    this.leftWheel.forward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.leftBackward = function () {
    this.leftWheel.backward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.rightForward = function () {
    this.rightWheel.forward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.rightBackward = function () {
    this.rightWheel.backward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.stop = function stop () {
    this.leftWheel.stop();
    this.rightWheel.stop();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.backup = function () {
    this.inManeuver = true;
    this.beep();
    var self = this;
    var lr = self.sonars.left.distance > self.sonars.right.distance ? 'L': 'R';
    self.moveBackward();
    setTimeout( function() {
        lr == 'L' ? self.turnLeft(): self.turnRight();
        setTimeout( function() {
            self.inManeuver = false;
            self.moveForward(); // forward again
        }, 500);
    }, 2000);
};

ThreeWheelDistanceSensingRobotBehavior.prototype.setSpeed = function ( speed ) {
    this.speed = E.clip ( speed, 0.0, 1.0 );
    this.leftWheel.setSpeed(this.speed);
    this.rightWheel.setSpeed(this.speed);
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.decreaseSpeed = function ( ) {
    return this.setSpeed ( this.speed - 0.05 );
};

ThreeWheelDistanceSensingRobotBehavior.prototype.increaseSpeed = function ( ) {
    return this.setSpeed ( this.speed + 0.05 );
};

ThreeWheelDistanceSensingRobotBehavior.prototype.toggleLedBlinking = function ( led ) {
    var robot = this;
    if ( this.leds[led].interval === false ) {
        this.leds[led].interval = setInterval ( function() {
            robot.leds[led].toggle();
        }, this.leds[led].blinkingTime );
    }
    else {
        robot.leds[led].switchOff();
        this.leds[led].clearInterval();
    }
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.toggleLedBlinking1 = function ( ) {
    return this.toggleLedBlinking( '1' );
};

ThreeWheelDistanceSensingRobotBehavior.prototype.toggleLedBlinking2 = function ( ) {
    return this.toggleLedBlinking( '2' );
};

ThreeWheelDistanceSensingRobotBehavior.prototype.toggleLedBlinking3 = function ( ) {
    return this.toggleLedBlinking( '3' );
};

ThreeWheelDistanceSensingRobotBehavior.prototype.enableSonars = function ( ) {
    for ( var key in this.sonars ) {
        this.sonars[key].enable();
    }
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.beep = function ( ) {
    this.buzzer.beep();
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.play = function () {
    var self = this;
    this.inManeuver = false;
    if (!this.playing) {
        this.moveForward();
        this.playing = setInterval(function() {
            if ( self.sonars.front.distance < 20 && !self.inManeuver ) {
                self.backup();
            }
        }, 50);
    }
};

ThreeWheelDistanceSensingRobotBehavior.prototype.pause = function () {
    this.stop();
    if ( this.playing ) {
        clearInterval( this.playing );
        this.playing = false;
    }
};

module.exports = ThreeWheelDistanceSensingRobotBehavior;
<commit_msg>Little changes on example behavior<commit_after>/**
 * @author Loris Tissino / http://loris.tissino.it
 * @package RoboThree
 * @release 0.60
 * @license The MIT License (MIT)
 * @see http://www.espruino.com/Reference
*/

var hcsr04 = require("HC-SR04");
var ir = require("IRReceiver");

var IRR = function ( pin, codesMap, leftSubtract ) {
    this.codesMap = codesMap;
    this.pin = pin;
    this.received = '';
    this.leftSubtract = leftSubtract;
    this.code = '';  // we keep track of the last code executed for managing kept pressed keys
    this.interval = false;
    var self = this;
};

IRR.prototype.enable = function ( callback ) {
    var self = this;
    this.callback = callback;
    ir.connect(this.pin, function ( receivedCode ) {
        self.received = receivedCode;
		if ( self.received.length > 1 ) {
			// new code
			var decimalValue = parseInt(self.received.substring(self.leftSubtract), 2);
			if ( decimalValue > 1 ) {
				self.code = decimalValue.toString();
			}
		}
    });
    this.interval = setInterval ( function () {
		if ( self.received == '1' ) {
			self.received = '';
		}
		else if (self.received.length <= 1) {
			self.code = '0';
		}
		self.callback();

	}, 200);
};

var Sonar = function ( triggerPin, echoPin, frequency ) {
    this.triggerPin = triggerPin;
    this.echoPin = echoPin;
    this.frequency = frequency;
    this.distance = Infinity;
    this.interval = false;
};

Sonar.prototype.enable = function () {
    var sonar = this;
    this.connection = hcsr04.connect ( this.triggerPin, this.echoPin, function ( dist ) {
        sonar.distance = dist;
    });
    this.interval = setInterval ( function () {
        sonar.connection.trigger();
    }, this.frequency );
};

Sonar.prototype.disable = function () {
    if ( this.interval !== false ) {
        clearInterval( this.interval );
    }
    this.distance = Infinity;
    this.interval = false;
};

var Wheel = function ( enablePin, controlPins, calibrationFactor) {
    this.enablePin = enablePin;
    this.controlPins = controlPins;
    this.calibrationFactor = calibrationFactor; // a value which is multiplied by speed before applying
    this.setSpeed(0);
};

// speed is assumed to be a number between 0.0 and 1.0
Wheel.prototype.setSpeed = function ( speed ) {
    this._speed = speed;
    analogWrite( this.enablePin, this._speed * this.calibrationFactor, { freq: 100 } );
    return this;
};

Wheel.prototype.getSpeed = function () {
    return this._speed;
};

Wheel.prototype.writeToControlPins = function (v0, v1) {
    this.controlPins[0].write(v0);
    this.controlPins[1].write(v1);
};

Wheel.prototype.forward = function () {
    this.writeToControlPins( 0, 1 );
};

Wheel.prototype.backward = function () {
    this.writeToControlPins( 1, 0 );
};

Wheel.prototype.stop = function () {
    this.writeToControlPins( 0, 0 );
};

var Led = function ( pin, blinkingTime ) {
    this.pin = pin;
    this.blinkingTime = blinkingTime;
    this.status = 0;
    this.pin.write( this.status );
    this.interval = false;
};

Led.prototype.toggle = function () {
    this.pin.write( this.status = 1 - this.status );
};

Led.prototype.clearInterval = function () {
    console.log ( this );
    if ( this.interval !== false ) {
        clearInterval ( this.interval );
    }
    this.interval = false;
};

Led.prototype.switchOn = function () {
    this.pin.write( this.status = 1 );
    this.clearInterval();
};

Led.prototype.switchOff = function () {
    this.pin.write( this.status = 0 );
    this.clearInterval();
};

var Buzzer = function ( pin, frequency, duration ) {
    this.pin = pin;
    this.defaultFrequency = frequency;
    this.defaultDuration = duration;
    this.status = 0;  // 0: off;  1: beeping;  2: replicated
};

Buzzer.prototype.beep = function ( frequency, duration ) {
    var self = this;
    this.frequency = frequency || this.defaultFrequency;
    this.duration = duration || this.defaultDuration;
    if ( this.status !== 1 ) {
        analogWrite(self.pin, 0.5, { freq: self.frequency } );
        this.status = 1;
        setTimeout ( function() {
            digitalWrite(self.pin, 0);
            this.status = 0;
        }, self.duration );
    }
};

var ThreeWheelDistanceSensingRobotBehavior = function ( id ) {
    this.id = id;
    this.data = {};
    this.config = {};
    this.playing = false;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.setup = function ( options ) {
    this.infraredReader = new IRR ( B3, {
            '16605343': { exec: 'moveForward', repeatOnKeptPressed: true },
            '16607383': { exec: 'moveBackward', repeatOnKeptPressed: true },
            '16603813': { exec: 'turnLeft', repeatOnKeptPressed: true },
            '16635943': { exec: 'turnRight', repeatOnKeptPressed: true },
            '16603303': { exec: 'stop', repeatOnKeptPressed: false },
            '66502975': { exec: 'decreaseSpeed', repeatOnKeptPressed: true },
            '66462175': { exec: 'increaseSpeed', repeatOnKeptPressed: true },
            '66478495': { exec: 'stop', repeatOnKeptPressed: false },
            '0'       : { exec: 'stop', repeatOnKeptPressed: false },
            '16597693': { exec: 'toggleLedBlinking1', repeatOnKeptPressed: false },
            '16581373': { exec: 'toggleLedBlinking2', repeatOnKeptPressed: false },
            '16629823': { exec: 'toggleLedBlinking3', repeatOnKeptPressed: false },
            '16599733': { exec: 'rightForward', repeatOnKeptPressed: true },
            '16607893': { exec: 'rightBackward', repeatOnKeptPressed: true },
            '16631863': { exec: 'leftForward', repeatOnKeptPressed: true },
            '16640023': { exec: 'leftBackward', repeatOnKeptPressed: true },
            '16609423': { exec: 'play', repeatOnKeptPressed: false },
            '16599223': { exec: 'pause', repeatOnKeptPressed: false },
        },
        1
    );
    this.leftWheel = new Wheel ( A2, [ A4, A3 ], 1);
    this.rightWheel = new Wheel ( A7, [ A5, A6 ], 0.75);
    this.speed = 0;
    this.leds = {
        '1': new Led ( LED1, 700 ),
        '2': new Led ( LED2, 500 ),
        '3': new Led ( LED3, 300 )
    };
    this.sonars = {
        'left': new Sonar ( C1, C0, 250 ),
        'front': new Sonar ( C3, C2, 250 ),
        'right': new Sonar ( C4, C5, 250 )
    };
    this.buzzer = new Buzzer( B6, 110, 100 );

    this.checkForObstacles = { enabled: false };

    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.enableInfraredReader = function () {
    this.infraredReader.enable ( this.handleInfraredReaderCode.bind(this) );
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.handleInfraredReaderCode = function () {
    if ( typeof this.infraredReader.code === 'undefined') {
        return;
    }
    if ( this.infraredReader.codesMap.hasOwnProperty ( this.infraredReader.code ) ) {
        var action = this.infraredReader.codesMap[this.infraredReader.code];
        if ( action.repeatOnKeptPressed === true || this.infraredReader.received != '1' ) {
            this[action.exec]();
        }
    }
    else {
        console.log ( 'IR code read: ' + this.infraredReader.code + ' (not handled)');
    }
};

ThreeWheelDistanceSensingRobotBehavior.prototype.moveForward = function () {
    this.leftWheel.forward();
    this.rightWheel.forward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.moveBackward = function () {
    this.leftWheel.backward();
    this.rightWheel.backward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.turnLeft = function () {
    this.leftWheel.backward();
    this.rightWheel.forward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.turnRight = function () {
    this.leftWheel.forward();
    this.rightWheel.backward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.leftForward = function () {
    this.leftWheel.forward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.leftBackward = function () {
    this.leftWheel.backward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.rightForward = function () {
    this.rightWheel.forward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.rightBackward = function () {
    this.rightWheel.backward();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.stop = function stop () {
    this.leftWheel.stop();
    this.rightWheel.stop();
};

ThreeWheelDistanceSensingRobotBehavior.prototype.backup = function () {
    this.inManeuver = true;
    this.beep();
    var self = this;
    var lr = self.sonars.left.distance > self.sonars.right.distance ? 'L': 'R';
    self.moveBackward();
    setTimeout( function() {
        lr == 'L' ? self.turnLeft(): self.turnRight();
        setTimeout( function() {
            self.inManeuver = false;
            self.moveForward(); // forward again
        }, 500);
    }, 2000);
};

ThreeWheelDistanceSensingRobotBehavior.prototype.setSpeed = function ( speed ) {
    this.speed = E.clip ( speed, 0.0, 1.0 );
    this.leftWheel.setSpeed(this.speed);
    this.rightWheel.setSpeed(this.speed);
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.decreaseSpeed = function ( ) {
    return this.setSpeed ( this.speed - 0.05 );
};

ThreeWheelDistanceSensingRobotBehavior.prototype.increaseSpeed = function ( ) {
    return this.setSpeed ( this.speed + 0.05 );
};

ThreeWheelDistanceSensingRobotBehavior.prototype.toggleLedBlinking = function ( led ) {
    var robot = this;
    if ( this.leds[led].interval === false ) {
        this.leds[led].interval = setInterval ( function() {
            robot.leds[led].toggle();
        }, this.leds[led].blinkingTime );
    }
    else {
        robot.leds[led].switchOff();
        this.leds[led].clearInterval();
    }
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.toggleLedBlinking1 = function ( ) {
    return this.toggleLedBlinking( '1' );
};

ThreeWheelDistanceSensingRobotBehavior.prototype.toggleLedBlinking2 = function ( ) {
    return this.toggleLedBlinking( '2' );
};

ThreeWheelDistanceSensingRobotBehavior.prototype.toggleLedBlinking3 = function ( ) {
    return this.toggleLedBlinking( '3' );
};

ThreeWheelDistanceSensingRobotBehavior.prototype.enableSonars = function ( ) {
    for ( var key in this.sonars ) {
        this.sonars[key].enable();
    }
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.beep = function ( ) {
    this.buzzer.beep();
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.play = function () {
    var self = this;
    this.inManeuver = false;
    if (!this.playing) {
        this.moveForward();
        this.playing = setInterval(function() {
            if ( self.sonars.front.distance < 20 && !self.inManeuver ) {
                self.backup();
            }
        }, 50);
    }
    return this;
};

ThreeWheelDistanceSensingRobotBehavior.prototype.pause = function () {
    this.stop();
    if ( this.playing ) {
        clearInterval( this.playing );
        this.playing = false;
    }
    return this;
};

module.exports = ThreeWheelDistanceSensingRobotBehavior;
<|endoftext|>


<commit_before>import React from 'react';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';

class Translation extends React.Component {
	render() {
		const { commentGroup } = this.props;
		console.log('commentGroup: ', commentGroup);
		return (

Hey now

		);
	}
}

export default createContainer(({ commentGroup }) => {
	let translationQuery = {};

	if (commentGroup) {
		translationQuery = {
			linesFrom: commentGroup.lineFrom,
			linesTo: commentGroup.lineTo,
			nLines: commentGroup.nLines,
			'subworkFrom.n': commentGroup.subwork.n,
			'work.slug': commentGroup.work.slug
		};

	}
	console.log('commentGroup: ', commentGroup);
	console.log('translationQuery: ', translationQuery);

	const handle = Meteor.subscribe('translations', translationQuery);
	const translation = Translations.find(translationQuery).fetch();
	const lines = [];

	// TODO: loop through lines in revisions and push to lines array

	return {
		lines,
		ready: handle.ready(),
	};
}, Translation);
<commit_msg>simplified translation record, updated subscription<commit_after>import React from 'react';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';

// api
import Translations from '/imports/api/collections/translations';

class Translation extends React.Component {
	render() {
		const { commentGroup } = this.props;
		console.log('commentGroup: ', commentGroup);
		return (

Hey now

		);
	}
}

export default createContainer(({ commentGroup }) => {
	let translationQuery = {};

	if (commentGroup) {
		translationQuery = {
			author: 'CHS',
			subworkFrom: commentGroup.subwork.title,
			work: commentGroup.work.slug
		};

	}
	console.log('commentGroup: ', commentGroup);
	console.log('translationQuery: ', translationQuery);

	const handle = Meteor.subscribe('translations', Session.get('tenantId'));

	const translation = Translations.find(translationQuery).fetch();

	console.log('found translation: ', translation);

	const lines = [];

	// TODO: loop through lines in revisions and push to lines array

	return {
		lines,
		ready: handle.ready(),
	};
}, Translation);
<|endoftext|>


<commit_before>// JavaScript Document

// Scripts written by __gulp_init__author_name @ __gulp_init__author_company

module.exports = {
    scripts(gulp, plugins, ran_tasks, on_error) {
        // task-specific plugins
        const ESLINT  = require("gulp-eslint");
        const WEBPACK = require("webpack-stream");

        // process scripts
        const PROCESS_SCRIPTS = (js_directory, destination_file_name = "modern.js", compare_file_name = "modern.js", source = [global.settings.paths.src + "/assets/scripts/*.js"]) => {
            return new Promise((resolve, reject) => {
                const WEBPACK_CONFIG = {
                    mode: "development",
                };

                // update webpack config for the current target destination and file name
                WEBPACK_CONFIG.mode   = plugins.argv.dist ? "production" : WEBPACK_CONFIG.mode;
                WEBPACK_CONFIG.output = {
                    filename: destination_file_name
                };

                const TASK = gulp.src(source)
                    // prevent breaking on error
                    .pipe(plugins.plumber({errorHandler: on_error}))
                    // check if source is newer than destination
                    .pipe(plugins.newer(js_directory + "/" + compare_file_name))
                    // lint all scripts
                    .pipe(ESLINT())
                    // print lint errors
                    .pipe(ESLINT.format())
                    // run webpack
                    .pipe(WEBPACK(WEBPACK_CONFIG))
                    // generate a hash and add it to the file name
                    .pipe(plugins.hash({template: "<%= name %>.<%= hash %><%= ext %>"}))
                    // output scripts to compiled directory
                    .pipe(gulp.dest(js_directory))
                    // generate a hash manfiest
                    .pipe(plugins.hash.manifest(".hashmanifest-scripts", {
                        deleteOld: true,
                        sourceDir: js_directory
                    }))
                    // output hash manifest in root
                    .pipe(gulp.dest("."))
                    // reject after errors
                    .on("error", () => {
                        reject(TASK);
                    })
                    // return the task after completion
                    .on("end", () => {
                        resolve(TASK);
                    });
            });
        };

        // scripts task, lints, concatenates, & compresses JS
        return new Promise ((resolve) => {
            // set JS directory
            const JS_DIRECTORY = plugins.argv.dist ? global.settings.paths.dist + "/assets/scripts" : global.settings.paths.dev + "/assets/scripts";

            // set the source directory
            const SOURCE_DIRECTORY = global.settings.paths.src + "/assets/scripts";

            // set up an empty merged stream
            const MERGED_STREAMS = plugins.merge();
            // get the script source folder list
            const SCRIPT_FOLDERS = plugins.fs.readdirSync(SOURCE_DIRECTORY);
            // get the script destination file list
            const SCRIPT_FILES   = plugins.fs.existsSync(JS_DIRECTORY) ? plugins.fs.readdirSync(JS_DIRECTORY) : false;

            // process all the script folders
            const PROCESS_SCRIPT_FOLDERS = () => {
                return new Promise((resolve) => {
                    const FOLDER_NAME = SCRIPT_FOLDERS.shift();
                    const FILE_NAME   = SCRIPT_FILES ? SCRIPT_FILES.find((name) => {
                        return name.match(new RegExp(FOLDER_NAME + ".[a-z0-9]{8}.js"));
                    }) : FOLDER_NAME + ".js";

                    // process all scripts, update the stream
                    PROCESS_SCRIPTS(JS_DIRECTORY, FOLDER_NAME + ".js", FILE_NAME, SOURCE_DIRECTORY + "/" + FOLDER_NAME + "/**/*").then((processed) => {
                        MERGED_STREAMS.add(processed);
                        resolve();
                    });
                }).then(() => SCRIPT_FOLDERS.length > 0 ? PROCESS_SCRIPT_FOLDERS() : resolve()); // loop again if foldres remain, otherwise resolve
            };

            return PROCESS_SCRIPT_FOLDERS().then(() => {
                // wrap up
                return MERGED_STREAMS
                    // prevent breaking on error
                    .pipe(plugins.plumber({
                        errorHandler: on_error,
                    }))
                    // notify that task is complete, if not part of default or watch
                    .pipe(plugins.gulpif(gulp.seq.indexOf("scripts") > gulp.seq.indexOf("default"), plugins.notify({
                        title:   "Success!",
                        message: "Scripts task complete!",
                        onLast:  true,
                    })))
                    // push task to ran_tasks array
                    .on("data", () => {
                        if (ran_tasks.indexOf("scripts") < 0) {
                            ran_tasks.push("scripts");
                        }
                    })
                    .on("end", () => {
                        return resolve();
                    });
            });

        });
    }
};
<commit_msg>Make sure everything gets returned<commit_after>// JavaScript Document

// Scripts written by __gulp_init__author_name @ __gulp_init__author_company

module.exports = {
    scripts(gulp, plugins, ran_tasks, on_error) {
        // task-specific plugins
        const ESLINT  = require("gulp-eslint");
        const WEBPACK = require("webpack-stream");

        // process scripts
        const PROCESS_SCRIPTS = (js_directory, destination_file_name = "modern.js", compare_file_name = "modern.js", source = [global.settings.paths.src + "/assets/scripts/*.js"]) => {
            return new Promise((resolve, reject) => {
                const WEBPACK_CONFIG = {
                    mode: "development",
                };

                // update webpack config for the current target destination and file name
                WEBPACK_CONFIG.mode   = plugins.argv.dist ? "production" : WEBPACK_CONFIG.mode;
                WEBPACK_CONFIG.output = {
                    filename: destination_file_name
                };

                const TASK = gulp.src(source)
                    // prevent breaking on error
                    .pipe(plugins.plumber({errorHandler: on_error}))
                    // check if source is newer than destination
                    .pipe(plugins.newer(js_directory + "/" + compare_file_name))
                    // lint all scripts
                    .pipe(ESLINT())
                    // print lint errors
                    .pipe(ESLINT.format())
                    // run webpack
                    .pipe(WEBPACK(WEBPACK_CONFIG))
                    // generate a hash and add it to the file name
                    .pipe(plugins.hash({template: "<%= name %>.<%= hash %><%= ext %>"}))
                    // output scripts to compiled directory
                    .pipe(gulp.dest(js_directory))
                    // generate a hash manfiest
                    .pipe(plugins.hash.manifest(".hashmanifest-scripts", {
                        deleteOld: true,
                        sourceDir: js_directory
                    }))
                    // output hash manifest in root
                    .pipe(gulp.dest("."))
                    // reject after errors
                    .on("error", () => {
                        return reject(TASK);
                    })
                    // return the task after completion
                    .on("end", () => {
                        return resolve(TASK);
                    });
            });
        };

        // scripts task, lints, concatenates, & compresses JS
        return new Promise ((resolve) => {
            // set JS directory
            const JS_DIRECTORY = plugins.argv.dist ? global.settings.paths.dist + "/assets/scripts" : global.settings.paths.dev + "/assets/scripts";

            // set the source directory
            const SOURCE_DIRECTORY = global.settings.paths.src + "/assets/scripts";

            // set up an empty merged stream
            const MERGED_STREAMS = plugins.merge();
            // get the script source folder list
            const SCRIPT_FOLDERS = plugins.fs.readdirSync(SOURCE_DIRECTORY);
            // get the script destination file list
            const SCRIPT_FILES   = plugins.fs.existsSync(JS_DIRECTORY) ? plugins.fs.readdirSync(JS_DIRECTORY) : false;

            // process all the script folders
            const PROCESS_SCRIPT_FOLDERS = () => {
                return new Promise((resolve) => {
                    const FOLDER_NAME = SCRIPT_FOLDERS.shift();
                    const FILE_NAME   = SCRIPT_FILES ? SCRIPT_FILES.find((name) => {
                        return name.match(new RegExp(FOLDER_NAME + ".[a-z0-9]{8}.js"));
                    }) : FOLDER_NAME + ".js";

                    // process all scripts, update the stream
                    return PROCESS_SCRIPTS(JS_DIRECTORY, FOLDER_NAME + ".js", FILE_NAME, SOURCE_DIRECTORY + "/" + FOLDER_NAME + "/**/*").then((processed) => {
                        MERGED_STREAMS.add(processed);
                        return resolve();
                    });
                }).then(() => SCRIPT_FOLDERS.length > 0 ? PROCESS_SCRIPT_FOLDERS() : resolve()); // loop again if foldres remain, otherwise resolve
            };

            return PROCESS_SCRIPT_FOLDERS().then(() => {
                // wrap up
                return MERGED_STREAMS
                    // prevent breaking on error
                    .pipe(plugins.plumber({
                        errorHandler: on_error,
                    }))
                    // notify that task is complete, if not part of default or watch
                    .pipe(plugins.gulpif(gulp.seq.indexOf("scripts") > gulp.seq.indexOf("default"), plugins.notify({
                        title:   "Success!",
                        message: "Scripts task complete!",
                        onLast:  true,
                    })))
                    // push task to ran_tasks array
                    .on("data", () => {
                        if (ran_tasks.indexOf("scripts") < 0) {
                            ran_tasks.push("scripts");
                        }
                    })
                    .on("end", () => {
                        return resolve();
                    });
            });

        });
    }
};
<|endoftext|>


<commit_before>var data = ["14/01/2016", "16/02/2016", "16/03/2016", "16/04/2016", "16/05/2016", "16/06/2016", "16/07/2016", "16/08/2016", "16/09/2016", "16/10/2016", "16/11/2016", "16/12/2016"],
    events = $(".events").find("ol"),
    eventsContent = $(".events-content").find("ol"),
    selectedClass = 'class="selected"';

var getTimelineData = function () { //input data will be passed as param
    $.each(data, function (index, event) {
        events.append('
' + event + '
');
        eventsContent.append('
Lorem ' + event + '
');
        selectedClass = "";
    });

    return $('#ttp-events');
};

var timelineNodeHandler = function (graph) {
  events.find("li").on("click", function (e) {
      $("#daily-graph").fadeOut().remove();
      $("#graph-wrapper").html('

');
      createGraph();
  });
};

var createGraph = function () {
    var cy = cytoscape({
        container: document.getElementById('daily-graph'),

        boxSelectionEnabled: false,
        autounselectify: true,

        style: cytoscape.stylesheet()
            .selector('node')
            .css({
                'content': 'data(id)'
            })
            .selector('edge')
            .css({
                'target-arrow-shape': 'triangle',
                'width': 4,
                'line-color': '#ddd',
                'target-arrow-color': '#ddd',
                'curve-style': 'bezier'
            })
            .selector('.highlighted')
            .css({
                'background-color': '#61bffc',
                'line-color': '#61bffc',
                'target-arrow-color': '#61bffc',
                'transition-property': 'background-color, line-color, target-arrow-color',
                'transition-duration': '0.5s'
            }),

        elements: {
            nodes: [
                { data: { id: 'a' } },
                { data: { id: 'b' } },
                { data: { id: 'c' } },
                { data: { id: 'd' } },
                { data: { id: 'e' } }
            ],

            edges: [
                { data: { id: 'a"e', weight: 1, source: 'a', target: 'e' } },
                { data: { id: 'ab', weight: 3, source: 'a', target: 'b' } },
                { data: { id: 'be', weight: 4, source: 'b', target: 'e' } },
                { data: { id: 'bc', weight: 5, source: 'b', target: 'c' } },
                { data: { id: 'ce', weight: 6, source: 'c', target: 'e' } },
                { data: { id: 'cd', weight: 2, source: 'c', target: 'd' } },
                { data: { id: 'de', weight: 7, source: 'd', target: 'e' } }
            ]
        },

        layout: {
            name: 'breadthfirst',
            directed: true,
            roots: '#a',
            padding: 10
        }
    });

    var bfs = cy.elements().bfs('#a', function(){}, true);

    var i = 0;
    var highlightNextEle = function(){
        if( i < bfs.path.length ){
            bfs.path[i].addClass('highlighted');

            i++;
            setTimeout(highlightNextEle, 1000);
        }
    };

// kick off first highlight
    highlightNextEle();

    return cy;
};

jQuery(document).ready(function ($) {
    getTimelineData().promise().done(function () {
        initTimeline($(this));

        var ttpGraph = createGraph();
        timelineNodeHandler(ttpGraph);
    });
});
<commit_msg>Made graph creation by a set of data<commit_after>var data = ["14/01/2016", "16/02/2016", "16/03/2016", "16/04/2016", "16/05/2016", "16/06/2016", "16/07/2016", "16/08/2016", "16/09/2016", "16/10/2016", "16/11/2016", "16/12/2016"],
    events = $(".events").find("ol"),
    eventsContent = $(".events-content").find("ol"),
    selectedClass = 'class="selected"';

var getTimelineData = function () { //input data will be passed as param
    $.each(data, function (index, event) {
        events.append('
' + event + '
');
        eventsContent.append('
Lorem ' + event + '
');
        selectedClass = "";
    });

    return $('#ttp-events');
};

var timelineNodeHandler = function (graph) {
  events.find("li").on("click", function (e) {
      $("#daily-graph").fadeOut().remove();
      $("#graph-wrapper").html('

');

      var graphData = {
          nodes: [
              { data: { id: 'a' } },
              { data: { id: 'b' } },
              { data: { id: 'c' } },
              { data: { id: 'd' } },
              { data: { id: 'e' } }
          ],

          edges: [
              { data: { id: 'a"e', weight: 1, source: 'a', target: 'e' } },
              { data: { id: 'ab', weight: 3, source: 'a', target: 'b' } },
              { data: { id: 'be', weight: 4, source: 'b', target: 'e' } },
              { data: { id: 'bc', weight: 5, source: 'e', target: 'c' } },
              { data: { id: 'ce', weight: 10, source: 'a', target: 'e' } },
              { data: { id: 'cd', weight: 2, source: 'c', target: 'd' } },
              { data: { id: 'de', weight: 7, source: 'd', target: 'b' } },
              { data: { id: 'de', weight: 7, source: 'b', target: 'bd' } }
          ]
      };
      createGraph(graphData);
  });
};

var createGraph = function (graphData) {
    var cy = cytoscape({
        container: document.getElementById('daily-graph'),

        boxSelectionEnabled: false,
        autounselectify: true,

        style: cytoscape.stylesheet()
            .selector('node')
            .css({
                'content': 'data(id)'
            })
            .selector('edge')
            .css({
                'target-arrow-shape': 'triangle',
                'width': 4,
                'line-color': '#ddd',
                'target-arrow-color': '#ddd',
                'curve-style': 'bezier'
            })
            .selector('.highlighted')
            .css({
                'background-color': '#61bffc',
                'line-color': '#61bffc',
                'target-arrow-color': '#61bffc',
                'transition-property': 'background-color, line-color, target-arrow-color',
                'transition-duration': '0.5s'
            }),

        elements: graphData,

        layout: {
            name: 'breadthfirst',
            directed: true,
            roots: '#a',
            padding: 10
        }
    });

    var bfs = cy.elements().bfs('#a', function(){}, true);

    var i = 0;
    var highlightNextEle = function(){
        if( i < bfs.path.length ){
            bfs.path[i].addClass('highlighted');

            i++;
            setTimeout(highlightNextEle, 1000);
        }
    };

// kick off first highlight
    highlightNextEle();

    return cy;
};

jQuery(document).ready(function ($) {
    getTimelineData().promise().done(function () {
        initTimeline($(this));
        var graphData = {
            nodes: [
                { data: { id: 'a' } },
                { data: { id: 'b' } },
                { data: { id: 'c' } },
                { data: { id: 'd' } },
                { data: { id: 'e' } }
            ],

            edges: [
                { data: { id: 'a"e', weight: 1, source: 'a', target: 'e' } },
                { data: { id: 'ab', weight: 3, source: 'a', target: 'b' } },
                { data: { id: 'be', weight: 4, source: 'b', target: 'e' } },
                { data: { id: 'bc', weight: 5, source: 'b', target: 'c' } },
                { data: { id: 'ce', weight: 6, source: 'c', target: 'e' } },
                { data: { id: 'cd', weight: 2, source: 'c', target: 'd' } },
                { data: { id: 'de', weight: 7, source: 'd', target: 'e' } }
            ]
        };
        var ttpGraph = createGraph(graphData);
        timelineNodeHandler(ttpGraph);
    });
});
<|endoftext|>


<commit_before>
function listThreads() {
  var names = []
  jQuery.each($('#thread_tabs>li>a'), function(ix,el) {
    names.push($(el).attr('href').replace('#thread_',''))
  })
  return names
}

function removeThread(thread_name) {
  var tid = 'thread_' + thread_name
  var cid = 'code_for_' + thread_name

  function rm(loc,nm) {
    $('#' + loc + '_tabs>li:has(a[href="#' + nm + '"])').remove()
    $('#' + loc + '_panes>#' + nm).remove()
    $('#' + loc + '_tabs').tabs()
  }

  rm('thread', 'thread_' + thread_name)
  rm('code','code_for_' + thread_name)
}

function drawNewThread(dbgState, thread) {

  var threadId = "thread_" + thread.name
  var codeID   = "code_for_" + thread.name

  function allocateNewParts() {
    var stack     = $('<ul/>').addClass('stack collection')
    var handlers  = $('<ul/>').addClass('handlers collection')
    var locals    = $('<ul/>').addClass('variables collection')
    var code = newCodeContainer(dbgState,'Thread ' + thread.name, codeID, null)

    var varSec =
      $('<li/>')
      .append([ $('<div/>')
                .addClass('collapsible-header active')
                .append([ $('<span/>')
                          .addClass('galua_section_label').text('Variable')
                        , $('<span/>').addClass('curFun')
                        ]
                       )
              , $('<div/>')
              .addClass('collapsible-body')
              .append(locals)
              ])

    function entry(name,active,thing) {
      return $('<li/>')
             .append([ $('<div/>')
                       .addClass('collapsible-header'+(active ? ' active' : ''))
                       .append($('<span/>')
                               .addClass('galua_section_label').text(name))
                     , $('<div/>')
                       .addClass('collapsible-body')
                       .append(thing) ])
    }

    var pane = $('<ul/>')
               .attr('id', threadId)
               .addClass('collapsible')
               .attr('data-collapsible','expandable')
               .append([ varSec // entry('Variables', true, locals)
                       , entry('Call Stack', false, stack)
                       , entry('Error Handlers', false, handlers)
                       ])
               .collapsible()

    var tabs = $('#thread_tabs')
    $('#thread_panes').append(pane)

    tabs.append($('<li/>')
                .addClass('tab')
                .append($('<a/>')
                        .attr('href', '#' + threadId)
                        .text('Thread ' + thread.name)))
    tabs.tabs()
    tabs.tabs('select_tab', threadId)
  }

  var me = $('#' + threadId)
  if (me.length === 0) {
    allocateNewParts()
    me = $('#' + threadId)
  }

  var out = $('#' + codeID)

  var threadParts = { stack:    me.find('.stack')
                    , handlers: me.find('.handlers')
                    , code:     out.find('.function')
                    , locals:   me.find('.variables')
                    , curFun:   me.find('.curFun')
                    }

  var env = thread.env

  fillInExecEnv(dbgState, threadParts, env)

  threadParts.stack.empty()
  jQuery.each(thread.stack, function(ix,f) {
    var fst = ix === 0
    threadParts.stack.append(drawStackFrame(dbgState, threadParts, ix, f, fst))
  })

  threadParts.handlers.empty()
  jQuery.each(thread.handlers, function(ix,h) {
    threadParts.handlers.append(drawHandler(dbgState, h))
  })

}

function fillInExecEnv(dbgState, threadParts, env) {

  threadParts.curFun.empty().append(drawFunName(env))

  threadParts.locals.empty()
                    .append([ drawValueList(dbgState, 'ups',  env.upvalues)
                            , drawValueList(dbgState, 'vas',  env.varargs)
                            , drawValueList(dbgState, 'regs', env.registers)
                            ])

  if (env.result) {
     var vals = $('<table/>').addClass('bordered')
     vals.append(
             [ $('<caption/>').text('Last C result'),
               $('<tr/>').append($('<td/>').append(drawPrimArg(env.result)))
             ])
     threadParts.locals.append(vals)
  }

  if (env.code) {
    var oldPC = dbgState.programCounter
    if (env.fid && env.pc !== undefined)
       dbgState.programCounter = { pc: env.pc, fid: env.fid }
    else {
       dbgState.programCounter = null
    }
    drawFunction(dbgState, threadParts.code, env.code)
    dbgState.programCounter = oldPC
  } else {
    var noCode = $('<div/>').text('No code available for this function')
    threadParts.code.empty().append(noCode)
               .data('galua-function',null)
  }

}

// The `threadParts` are passed in so that we can fill in the correct
// elements when the user asks for details of the stack frame.
function drawStackFrame(dbgState,threadParts,ix,f,focused) {
  var box = $('<li/>').addClass('collection-item')

  switch (f.tag) {
    case 'call':
      var ptr = $('<span/>')
                .addClass('secondary-content stack-ptr')
                .append($('<i/>').addClass('material-icons')
                                 .text('chevron_left'))
      var kbd = $('<i/>')
                .addClass('material-icons secondary-content stack-ptr')
                .text('keyboard')
                .click(function() {
                   editExpression('Evaluate Statment','',
                    function(txt) {
                      var args = { stat: txt, stackframe: f.ref }
                      jQuery.post('/exec', args, function() {}) // XXX: redraw
                    })
                 })
      if (!focused) { ptr.addClass('hide'); kbd.addClass('hide') }
      box.append([ptr,kbd])
      box.append(drawFunName(f))
      box.css('cursor','pointer')
      box.click(function() {

          dbgState.currentStackFrame = ix

          jQuery.post('/expand', { id: f.ref }, function(exp) {
            fillInExecEnv(dbgState,threadParts, exp)
            box.siblings().children()
                          .filter('.stack-ptr')
                          .addClass('hide')
            ptr.removeClass('hide')
            kbd.removeClass('hide')
          }).fail(disconnected)
      })
      break

    case 'throw_error':
      box.addClass('white-text red chip').text('Error')
  }
  return box
}

function drawHandler(dbgState, h) {
  var me = $('<li/>').addClass('collection-item')
  switch (h.tag) {
    case 'default':
      me.addClass('galua_remark').text('default handler')
      break
    case 'handler':
      me.append(drawValue(dbgState,h.value))
      break
    default:
      console.log('Unexpected handler', h)
  }
  return me
}

<commit_msg>Add a tooltip on statement evaluation icon<commit_after>
function listThreads() {
  var names = []
  jQuery.each($('#thread_tabs>li>a'), function(ix,el) {
    names.push($(el).attr('href').replace('#thread_',''))
  })
  return names
}

function removeThread(thread_name) {
  var tid = 'thread_' + thread_name
  var cid = 'code_for_' + thread_name

  function rm(loc,nm) {
    $('#' + loc + '_tabs>li:has(a[href="#' + nm + '"])').remove()
    $('#' + loc + '_panes>#' + nm).remove()
    $('#' + loc + '_tabs').tabs()
  }

  rm('thread', 'thread_' + thread_name)
  rm('code','code_for_' + thread_name)
}

function drawNewThread(dbgState, thread) {

  var threadId = "thread_" + thread.name
  var codeID   = "code_for_" + thread.name

  function allocateNewParts() {
    var stack     = $('<ul/>').addClass('stack collection')
    var handlers  = $('<ul/>').addClass('handlers collection')
    var locals    = $('<ul/>').addClass('variables collection')
    var code = newCodeContainer(dbgState,'Thread ' + thread.name, codeID, null)

    var varSec =
      $('<li/>')
      .append([ $('<div/>')
                .addClass('collapsible-header active')
                .append([ $('<span/>')
                          .addClass('galua_section_label').text('Variable')
                        , $('<span/>').addClass('curFun')
                        ]
                       )
              , $('<div/>')
              .addClass('collapsible-body')
              .append(locals)
              ])

    function entry(name,active,thing) {
      return $('<li/>')
             .append([ $('<div/>')
                       .addClass('collapsible-header'+(active ? ' active' : ''))
                       .append($('<span/>')
                               .addClass('galua_section_label').text(name))
                     , $('<div/>')
                       .addClass('collapsible-body')
                       .append(thing) ])
    }

    var pane = $('<ul/>')
               .attr('id', threadId)
               .addClass('collapsible')
               .attr('data-collapsible','expandable')
               .append([ varSec // entry('Variables', true, locals)
                       , entry('Call Stack', false, stack)
                       , entry('Error Handlers', false, handlers)
                       ])
               .collapsible()

    var tabs = $('#thread_tabs')
    $('#thread_panes').append(pane)

    tabs.append($('<li/>')
                .addClass('tab')
                .append($('<a/>')
                        .attr('href', '#' + threadId)
                        .text('Thread ' + thread.name)))
    tabs.tabs()
    tabs.tabs('select_tab', threadId)
  }

  var me = $('#' + threadId)
  if (me.length === 0) {
    allocateNewParts()
    me = $('#' + threadId)
  }

  var out = $('#' + codeID)

  var threadParts = { stack:    me.find('.stack')
                    , handlers: me.find('.handlers')
                    , code:     out.find('.function')
                    , locals:   me.find('.variables')
                    , curFun:   me.find('.curFun')
                    }

  var env = thread.env

  fillInExecEnv(dbgState, threadParts, env)

  threadParts.stack.empty()
  jQuery.each(thread.stack, function(ix,f) {
    var fst = ix === 0
    threadParts.stack.append(drawStackFrame(dbgState, threadParts, ix, f, fst))
  })

  threadParts.handlers.empty()
  jQuery.each(thread.handlers, function(ix,h) {
    threadParts.handlers.append(drawHandler(dbgState, h))
  })

}

function fillInExecEnv(dbgState, threadParts, env) {

  threadParts.curFun.empty().append(drawFunName(env))

  threadParts.locals.empty()
                    .append([ drawValueList(dbgState, 'ups',  env.upvalues)
                            , drawValueList(dbgState, 'vas',  env.varargs)
                            , drawValueList(dbgState, 'regs', env.registers)
                            ])

  if (env.result) {
     var vals = $('<table/>').addClass('bordered')
     vals.append(
             [ $('<caption/>').text('Last C result'),
               $('<tr/>').append($('<td/>').append(drawPrimArg(env.result)))
             ])
     threadParts.locals.append(vals)
  }

  if (env.code) {
    var oldPC = dbgState.programCounter
    if (env.fid && env.pc !== undefined)
       dbgState.programCounter = { pc: env.pc, fid: env.fid }
    else {
       dbgState.programCounter = null
    }
    drawFunction(dbgState, threadParts.code, env.code)
    dbgState.programCounter = oldPC
  } else {
    var noCode = $('<div/>').text('No code available for this function')
    threadParts.code.empty().append(noCode)
               .data('galua-function',null)
  }

}

// The `threadParts` are passed in so that we can fill in the correct
// elements when the user asks for details of the stack frame.
function drawStackFrame(dbgState,threadParts,ix,f,focused) {
  var box = $('<li/>').addClass('collection-item')

  switch (f.tag) {
    case 'call':
      var ptr = $('<span/>')
                .addClass('secondary-content stack-ptr')
                .append($('<i/>').addClass('material-icons')
                                 .text('chevron_left'))
      var kbd = $('<i/>')
                .addClass('material-icons secondary-content stack-ptr tooltipped')
                .attr('data-tooltip', 'Evaluate statement')
                .text('keyboard')
                .click(function() {
                   editExpression('Evaluate Statment','',
                    function(txt) {
                      var args = { stat: txt, stackframe: f.ref }
                      jQuery.post('/exec', args, function() {}) // XXX: redraw
                    })
                 })
                 .tooltip()
      if (!focused) { ptr.addClass('hide'); kbd.addClass('hide') }
      box.append([ptr,kbd])
      box.append(drawFunName(f))
      box.css('cursor','pointer')
      box.click(function() {

          dbgState.currentStackFrame = ix

          jQuery.post('/expand', { id: f.ref }, function(exp) {
            fillInExecEnv(dbgState,threadParts, exp)
            box.siblings().children()
                          .filter('.stack-ptr')
                          .addClass('hide')
            ptr.removeClass('hide')
            kbd.removeClass('hide')
          }).fail(disconnected)
      })
      break

    case 'throw_error':
      box.addClass('white-text red chip').text('Error')
  }
  return box
}

function drawHandler(dbgState, h) {
  var me = $('<li/>').addClass('collection-item')
  switch (h.tag) {
    case 'default':
      me.addClass('galua_remark').text('default handler')
      break
    case 'handler':
      me.append(drawValue(dbgState,h.value))
      break
    default:
      console.log('Unexpected handler', h)
  }
  return me
}

<|endoftext|>


<commit_before>const $ = window.jQuery

const text = require('../helpers').text
const createLink = require('../helpers').createLink

module.exports.process = function process () {
  $('.blob-code-inner').each((_, elem) => {
    let line = elem.innerText.trim()

    let match = line.match(/^import(?: +qualified)? +([^ ]+)/)
    if (!match) return

    let moduleName = match[1]
    text(`https://raw.githubusercontent.com/fiatjaf/module-linker/backends/data/hackage-modules/${moduleName}`)
      .then(packageName => {
        let info = {
          url: `https://hackage.haskell.org/package/${packageName}/docs/${moduleName.split('.').join('-')}.html`,
          kind: 'docs'
        }
        createLink(elem, moduleName, info)
      })
  })
}
<commit_msg>handle haskell module names followed by (<commit_after>const $ = window.jQuery

const text = require('../helpers').text
const createLink = require('../helpers').createLink

module.exports.process = function process () {
  $('.blob-code-inner').each((_, elem) => {
    let line = elem.innerText.trim()

    let match = line.match(/^import(?: +qualified)? +([\w.-_\d]+)/)
    if (!match) return

    let moduleName = match[1]
    text(`https://raw.githubusercontent.com/fiatjaf/module-linker/backends/data/hackage-modules/${moduleName}`)
      .then(packageName => {
        let info = {
          url: `https://hackage.haskell.org/package/${packageName}/docs/${moduleName.split('.').join('-')}.html`,
          kind: 'docs'
        }
        createLink(elem, moduleName, info)
      })
  })
}
<|endoftext|>


<commit_before>/**
 * Gulp tasks for managing an S3-based preview of the Pattern Library documentation.
 *
 * The tasks are as follows:
 *  - build-preview: builds a preview site and uploads it to S3
 *  - jekyll-build-preview: build the preview site
 *  - upload-preview: upload the preview site to S3
 *  - remove-preview: removes the preview site from S3
 *
 * Note: please set the environment variable S3_PREVIEW_DOMAIN to the domain
 * used to host your S3 preview.
 */
(function() {
    'use strict';

    var gulp = require('gulp'),
        runSequence = require('run-sequence'),
        childProcess = require('child_process'),
        gitUtils = require('../util/gitUtils'),
        previewConfigFile = '_tmp_preview_config.yml',
        previewSiteDir = '_preview_site',
        previewDomain = process.env.S3_PREVIEW_DOMAIN;

    gulp.task('build-preview', function(callback) {
        runSequence(
            'jekyll-build-preview',
            'upload-preview',
            callback);
    });

    gulp.task('jekyll-build-preview', function() {
        var branch = gitUtils.currentBranch(),
            previewBaseUrl = '/' + branch + '/';
        // Create a temporary Jekyll configuration file which specifies the base URL for the preview site
        childProcess.execSync(
            'echo \'baseurl: ' + previewBaseUrl + '\' > ' + previewConfigFile
        );

        // Generate the preview version of the site
        console.log('Generating preview for branch ' + branch);
        childProcess.execSync(
            'jekyll build --config _config.yml,' + previewConfigFile + ' --destination ' + previewSiteDir
        );

        // Invoke WebPack to rebuild the JavaScript in the preview site with the correct base URL
        childProcess.execSync(
            'OUTPUT_ROOT=' + previewSiteDir + '/ SITE_ROOT=' + previewBaseUrl + ' ./node_modules/.bin/webpack'
        );
    });

    gulp.task('upload-preview', function() {
        var branch = gitUtils.currentBranch();
        if (previewDomain) {
            childProcess.execSync(
                'aws s3 sync ' + previewSiteDir + ' s3://' + previewDomain + '/' + branch
            );
            console.log('Preview site ready at http://' + previewDomain + '/' + branch);
        } else {
            console.log(
                'No preview domain specified. Please export environment variable S3_PREVIEW_DOMAIN and try again.'
            );
        }
    });

    gulp.task('remove-preview', function() {
        var branch = gitUtils.currentBranch();
        childProcess.execSync(
            'aws s3 rm --recursive  s3://' + previewDomain + '/' + branch
        );
        console.log('Removed preview for branch ' + branch);
    });
}());
<commit_msg>Clean up the temporary config file<commit_after>/**
 * Gulp tasks for managing an S3-based preview of the Pattern Library documentation.
 *
 * The tasks are as follows:
 *  - build-preview: builds a preview site and uploads it to S3
 *  - jekyll-build-preview: build the preview site
 *  - upload-preview: upload the preview site to S3
 *  - remove-preview: removes the preview site from S3
 *
 * Note: please set the environment variable S3_PREVIEW_DOMAIN to the domain
 * used to host your S3 preview.
 */
(function() {
    'use strict';

    var gulp = require('gulp'),
        runSequence = require('run-sequence'),
        childProcess = require('child_process'),
        gitUtils = require('../util/gitUtils'),
        previewConfigFile = '_tmp_preview_config.yml',
        previewSiteDir = '_preview_site',
        previewDomain = process.env.S3_PREVIEW_DOMAIN;

    gulp.task('build-preview', function(callback) {
        runSequence(
            'jekyll-build-preview',
            'upload-preview',
            callback);
    });

    gulp.task('jekyll-build-preview', function() {
        var branch = gitUtils.currentBranch(),
            previewBaseUrl = '/' + branch + '/';
        // Create a temporary Jekyll configuration file which specifies the base URL for the preview site
        childProcess.execSync(
            'echo \'baseurl: ' + previewBaseUrl + '\' > ' + previewConfigFile
        );

        // Generate the preview version of the site
        console.log('Generating preview for branch ' + branch);
        childProcess.execSync(
            'jekyll build --config _config.yml,' + previewConfigFile + ' --destination ' + previewSiteDir
        );

        // Remove the configuration file since it is no longer needed
        childProcess.execSync('rm ' + previewConfigFile);

        // Invoke WebPack to rebuild the JavaScript in the preview site with the correct base URL
        childProcess.execSync(
            'OUTPUT_ROOT=' + previewSiteDir + '/ SITE_ROOT=' + previewBaseUrl + ' ./node_modules/.bin/webpack'
        );
    });

    gulp.task('upload-preview', function() {
        var branch = gitUtils.currentBranch();
        if (previewDomain) {
            childProcess.execSync(
                'aws s3 sync ' + previewSiteDir + ' s3://' + previewDomain + '/' + branch
            );
            console.log('Preview site ready at http://' + previewDomain + '/' + branch);
        } else {
            console.log(
                'No preview domain specified. Please export environment variable S3_PREVIEW_DOMAIN and try again.'
            );
        }
    });

    gulp.task('remove-preview', function() {
        var branch = gitUtils.currentBranch();
        childProcess.execSync(
            'aws s3 rm --recursive  s3://' + previewDomain + '/' + branch
        );
        console.log('Removed preview for branch ' + branch);
    });
}());
<|endoftext|>


<commit_before>'use strict';

/* browserify task
   ---------------
   Bundle javascripty things with browserify!
   This task is set up to generate multiple separate bundles, from
   different sources, and to use Watchify when run from the default task.
   See browserify.bundleConfigs in gulp/config.js
*/

var gulp = require( 'gulp' );
var browserify = require( 'browserify' );
var browserSync = require( 'browser-sync' );
var watchify = require( 'watchify' );
var mergeStream = require( 'merge-stream' );
var bundleLogger = require( '../utils/bundleLogger' );
var handleErrors = require( '../utils/handleErrors' );
var source = require( 'vinyl-source-stream' );
var config = require( '../config' ).scripts;
var _ = require( 'lodash' );

function browserifyTask( devMode ) {

  function browserifyThis( bundleConfig ) {
    if ( devMode ) {
      // Add watchify args and debug (sourcemaps) option
      _.extend( bundleConfig, watchify.args, { debug: true } );
      // A watchify require/external bug that prevents proper recompiling,
      // so (for now) we'll ignore these options during development. Running
      // `gulp browserify` directly will properly require and externalize.
      bundleConfig = _.omit( bundleConfig, [ 'external', 'require' ] );
    }

    var b = browserify( bundleConfig );

    function bundle() {
      // Log when bundling starts
      bundleLogger.start( bundleConfig.outputName );

      return b
        .bundle()
        // Report compile errors
        .on( 'error', handleErrors )
        // Use vinyl-source-stream to make thestream gulp compatible.
        // Specify the desired output filename here.
        .pipe( source( bundleConfig.outputName ) )
        // Specify the output destination
        .pipe( gulp.dest( bundleConfig.dest ) )
        .pipe( browserSync.reload( {
          stream: true
        } ) );
    }

    if ( devMode ) {
      // Wrap with watchify and rebundle on changes
      b = watchify( b );
      // Rebundle on update
      b.on( 'update', bundle );
      bundleLogger.watch( bundleConfig.outputName );
    } else {
      // Sort out shared dependencies.
      // b.require exposes modules externally
      if ( bundleConfig.require ) b.require( bundleConfig.require );
      // b.external excludes modules from the bundle, and expects
      // they'll be available externally
      if ( bundleConfig.external ) b.external( bundleConfig.external );
    }
    return bundle();
  }

  // Start bundling with Browserify for each bundleConfig specified
  return mergeStream.apply(
    gulp, _.map( config.bundleConfigs, browserifyThis )
  );
}

gulp.task( 'scripts', function() {
  return browserifyTask();
} );

// Exporting the task so we can call it directly in our watch task,
// with the 'devMode' option
module.exports = browserifyTask;
<commit_msg>Updates typo<commit_after>'use strict';

/* browserify task
   ---------------
   Bundle javascripty things with browserify!
   This task is set up to generate multiple separate bundles, from
   different sources, and to use Watchify when run from the default task.
   See browserify.bundleConfigs in gulp/config.js
*/

var gulp = require( 'gulp' );
var browserify = require( 'browserify' );
var browserSync = require( 'browser-sync' );
var watchify = require( 'watchify' );
var mergeStream = require( 'merge-stream' );
var bundleLogger = require( '../utils/bundleLogger' );
var handleErrors = require( '../utils/handleErrors' );
var source = require( 'vinyl-source-stream' );
var config = require( '../config' ).scripts;
var _ = require( 'lodash' );

function browserifyTask( devMode ) {

  function browserifyThis( bundleConfig ) {
    if ( devMode ) {
      // Add watchify args and debug (sourcemaps) option
      _.extend( bundleConfig, watchify.args, { debug: true } );
      // A watchify require/external bug that prevents proper recompiling,
      // so (for now) we'll ignore these options during development. Running
      // `gulp browserify` directly will properly require and externalize.
      bundleConfig = _.omit( bundleConfig, [ 'external', 'require' ] );
    }

    var b = browserify( bundleConfig );

    function bundle() {
      // Log when bundling starts
      bundleLogger.start( bundleConfig.outputName );

      return b
        .bundle()
        // Report compile errors
        .on( 'error', handleErrors )
        // Use vinyl-source-stream to make the stream gulp compatible.
        // Specify the desired output filename here.
        .pipe( source( bundleConfig.outputName ) )
        // Specify the output destination
        .pipe( gulp.dest( bundleConfig.dest ) )
        .pipe( browserSync.reload( {
          stream: true
        } ) );
    }

    if ( devMode ) {
      // Wrap with watchify and rebundle on changes
      b = watchify( b );
      // Rebundle on update
      b.on( 'update', bundle );
      bundleLogger.watch( bundleConfig.outputName );
    } else {
      // Sort out shared dependencies.
      // b.require exposes modules externally
      if ( bundleConfig.require ) b.require( bundleConfig.require );
      // b.external excludes modules from the bundle, and expects
      // they'll be available externally
      if ( bundleConfig.external ) b.external( bundleConfig.external );
    }
    return bundle();
  }

  // Start bundling with Browserify for each bundleConfig specified
  return mergeStream.apply(
    gulp, _.map( config.bundleConfigs, browserifyThis )
  );
}

gulp.task( 'scripts', function() {
  return browserifyTask();
} );

// Exporting the task so we can call it directly in our watch task,
// with the 'devMode' option
module.exports = browserifyTask;
<|endoftext|>


<commit_before>const gulp = require('gulp');
const gutil = require('gulp-util');
const path = require('path');

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const WebpackDevServer = require('webpack-dev-server');
const OptimizeCssPlugin = require('optimize-css-assets-webpack-plugin');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const CleanCss = require('clean-css');
const WriteFilePlugin = require('write-file-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const VueSSRServerPlugin = require('vue-server-renderer/server-plugin');
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const OfflinePlugin = require('offline-plugin');
const WebpackPwaManifest = require('webpack-pwa-manifest');

module.exports = function(config) {
	let base = path.resolve(config.projectBase);

	let noop = function() {};
	let devNoop = config.production ? undefined : noop;
	let prodNoop = !config.production ? undefined : noop;
	let browserNoop = config.server ? undefined : noop;
	let serverNoop = !config.server ? undefined : noop;

	const externalModules = ['client-voodoo'];
	if (!config.client) {
		externalModules.push('nw.gui');
	}

	let externals = {};
	for (let extern of externalModules) {
		externals[extern] = {
			commonjs: extern,
		};
	}

	if (config.server) {
		Object.assign(
			externals,
			nodeExternals({
				// do not externalize dependencies that need to be processed by webpack.
				// you can add more file types here e.g. raw *.vue files
				// you should also whitelist deps that modifies `global` (e.g. polyfills)
				whitelist: /\.css$/,
			})
		);
	}

	const cleanCssOptions = {
		level: 2,
	};

	let cleanCss = new CleanCss(cleanCssOptions);

	let webpackTarget = 'web';
	if (config.server) {
		webpackTarget = 'node';
	} else if (config.client) {
		webpackTarget = 'node-webkit';
	}

	let libraryTarget = 'var';
	if (config.server) {
		libraryTarget = 'commonjs2';
	}

	// Inline allows us to debug by setting breakpoints.
	// Eval may be faster, but it doesn't allow setting breakpoints.
	let devtool = 'source-map';
	if (!config.production) {
		devtool = !config.server ? 'cheap-module-inline-source-map' : 'source-map';
	}

	function stylesLoader(loaders, options) {
		if (config.production) {
			loaders.push({
				loader: 'clean-css-loader',
				options: cleanCssOptions,
			});

			return ExtractTextPlugin.extract({
				use: loaders,
				fallback: 'vue-style-loader',
			});
		}

		loaders.unshift('vue-style-loader');

		return loaders;
	}

	let webpackSectionConfigs = {};
	let webpackSectionTasks = [];
	config.sections.forEach(function(section) {
		let indexHtml = section === 'app' ? 'index.html' : section + '.html';
		let appEntries = [path.resolve(base, 'src/' + section + '/main.ts')];

		if (!config.production) {
			appEntries.push('webpack-dev-server/client?http://localhost:' + config.port + '/');
			appEntries.push('webpack/hot/dev-server');
		}

		let entry = {
			app: appEntries,
		};

		if (config.server) {
			entry = {
				server: [path.resolve(base, 'src/' + section + '/server.ts')],
			};
		}

		let webAppManifest = undefined;
		if (!config.server && config.webAppManifest && config.webAppManifest[section]) {
			webAppManifest = config.webAppManifest[section];

			for (const icon of webAppManifest.icons) {
				icon.src = path.resolve(base, 'src/app/img/touch/' + icon.src);
			}
		}

		let hasOfflineSupport =
			!config.server &&
			config.production &&
			config.offlineSupport &&
			config.offlineSupport.indexOf(section) !== -1;

		webpackSectionConfigs[section] = {
			entry,
			target: webpackTarget,
			devServer: {
				outputPath: path.resolve(base, config.buildDir),
			},
			output: {
				publicPath: (config.production ? config.staticCdn : '') + '/',
				path: path.resolve(base, config.buildDir),
				filename: config.production ? section + '.[name].[chunkhash:6].js' : section + '.[name].js',
				chunkFilename: config.production
					? section + '.[name].[chunkhash:6].js'
					: section + '.[name].js',
				sourceMapFilename: 'maps/[name].[chunkhash:6].map',
				libraryTarget: libraryTarget,
			},
			resolve: {
				extensions: ['.tsx', '.ts', '.js', '.styl'],
				modules: [path.resolve(base, 'src/vendor'), 'node_modules'],
				alias: {
					// Always "app" base img.
					img: path.resolve(base, 'src/app/img'),
					styles: path.resolve(base, 'src/' + section + '/styles'),
				},
			},
			externals: externals,
			resolveLoader: {
				alias: {
					view:
						'vue-template-loader?' +
						JSON.stringify({
							scoped: true,
							transformToRequire: {
								img: 'src',
							},
						}),
				},
			},
			module: {
				rules: [
					{
						test: /\.tsx?$/,
						use: [
							{
								loader: 'ts-loader',
								options: {
									transpileOnly: true,
								},
							},
						],
					},
					{
						enforce: 'pre',
						test: /\.styl$/,
						use: 'stylus-loader?paths[]=src/&resolve url&include css',
					},
					{
						enforce: 'post',
						test: /\.styl$/,
						use: stylesLoader([
							'css-loader?-minimize',
							{ loader: 'postcss-loader', options: { sourceMap: true } },
						]),
					},
					{
						test: /\.css$/,
						use: stylesLoader([
							'css-loader?-minimize',
							{ loader: 'postcss-loader', options: { sourceMap: true } },
						]),
					},
					{
						test: /\.md$/,
						use: ['html-loader', 'markdown-loader'],
					},
					{
						test: /\.(png|jpe?g|gif|svg|json|ogg|mp4)(\?.*)?$/,
						loader: 'file-loader?name=assets/[name].[hash:6].[ext]',
						exclude: /node_modules/,
					},
					{
						test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
						loader: 'file-loader?name=assets/[name].[hash:6].[ext]',
					},
				],
			},
			devtool,
			plugins: [
				// We use this in prod build too since gzip is able to zip up
				// path names better than hashed module IDs resulting in smaller
				// file sizes.
				new webpack.NamedModulesPlugin(),
				new webpack.NamedChunksPlugin(),
				// Hoists modules instead of using a function call when it can.
				devNoop || new webpack.optimize.ModuleConcatenationPlugin(),
				new webpack.DefinePlugin({
					GJ_ENVIRONMENT: JSON.stringify(!config.developmentEnv ? 'production' : 'development'),
					GJ_BUILD_TYPE: JSON.stringify(config.production ? 'production' : 'development'),
					GJ_IS_CLIENT: JSON.stringify(config.client),
					GJ_IS_SSR: JSON.stringify(config.server),
					GJ_VERSION: JSON.stringify(require(path.resolve(process.cwd(), 'package.json')).version),

					// This sets vue in production mode.
					'process.env': {
						NODE_ENV: JSON.stringify(config.production ? 'production' : 'development'),
					},
				}),
				new webpack.LoaderOptionsPlugin({
					options: {
						// Fix extract-loader: https://github.com/peerigon/extract-loader/issues/16
						output: {},
						htmlLoader: {
							minimize: config.production,
						},
						stylus: {
							use: [],
							preferPathResolver: 'webpack',
						},
					},
				}),
				// !config.client ? noop : new CopyWebpackPlugin([
				// 	{
				// 		from: path.resolve( base, 'client-package.json' ),
				// 		to: 'package.json',
				// 	},
				// ]),
				devNoop ||
					new webpack.optimize.UglifyJsPlugin({
						sourceMap: true,
						compress: {
							warnings: false,
							screw_ie8: true,
						},
					}),
				devNoop || new ImageminPlugin(),
				prodNoop || serverNoop || new webpack.HotModuleReplacementPlugin(),

				// Since form stuff is so large, we split it into an async chunk
				// that will get loaded alongside any chunks that need it.
				devNoop ||
					serverNoop ||
					new webpack.optimize.CommonsChunkPlugin({
						name: 'app',
						async: 'forms',
						minChunks: function(module) {
							return (
								module.context &&
								(module.context.indexOf('vee-validate') !== -1 ||
									module.context.indexOf('gj-lib-client/components/form') !== -1)
							);
						},
					}),

				// Pull out vendor code from the main entry point.
				devNoop ||
					serverNoop ||
					new webpack.optimize.CommonsChunkPlugin({
						name: 'vendor',
						minChunks: function(module) {
							return module.context && module.context.indexOf('node_modules') !== -1;
						},
					}),

				// This generates a manifest file that allows our vendor chunk
				// to be cached longer if it doesn't change.
				// More info: https://webpack.js.org/guides/code-splitting-libraries/#implicit-common-vendor-chunk
				devNoop ||
					serverNoop ||
					new webpack.optimize.CommonsChunkPlugin({
						name: 'manifest',
						minChunks: Infinity,
					}),

				devNoop || new ExtractTextPlugin('[name].[contenthash:6].css'),
				devNoop ||
					new OptimizeCssPlugin({
						cssProcessor: {
							process: function(css) {
								return new Promise(function(resolve, reject) {
									let output = cleanCss.minify(css);
									if (output.errors.length) {
										reject(output.errors);
									} else {
										resolve({
											css: output.styles,
										});
									}
								});
							},
						},
					}),
				serverNoop ||
					new HtmlWebpackPlugin({
						filename: indexHtml,
						template: '!!html-loader?interpolate=require!src/' + indexHtml,
						favicon: path.resolve(base, 'src/app/img/favicon.png'),
						inject: true,
						chunksSortMode: 'dependency',
					}),
				webAppManifest ? new WebpackPwaManifest(webAppManifest) : noop,
				prodNoop || new FriendlyErrorsWebpackPlugin(),
				serverNoop ||
					new VueSSRClientPlugin({
						filename: 'vue-ssr-client-manifest-' + section + '.json',
					}),
				browserNoop ||
					new VueSSRServerPlugin({
						filename: 'vue-ssr-server-bundle-' + section + '.json',
					}),
				hasOfflineSupport
					? new OfflinePlugin({
							excludes: ['vue-ssr-*'],
							ServiceWorker: {
								output: 'sjw.js',
								publicPath: 'https://gamejolt.com/sjw.js',
							},
						})
					: noop,
				config.write ? new WriteFilePlugin() : noop,
				config.analyze ? new BundleAnalyzerPlugin() : noop,
			],
		};

		gulp.task('compile:' + section, function(cb) {
			let compiler = webpack(webpackSectionConfigs[section]);
			compiler.run(function(err, stats) {
				if (err) {
					throw new gutil.PluginError('webpack:build', err);
				}

				gutil.log(
					'[webpack:build]',
					stats.toString({
						chunks: false,
						colors: true,
					})
				);

				cb();
			});
		});

		webpackSectionTasks.push('compile:' + section);
	});

	gulp.task(
		'watch',
		gulp.series('clean:pre', function(cb) {
			let compiler = webpack(webpackSectionConfigs[config.buildSection]);

			let server = new WebpackDevServer(compiler, {
				historyApiFallback: {
					rewrites: [
						{
							from: /./,
							to:
								config.buildSection === 'app' ? '/index.html' : '/' + config.buildSection + '.html',
						},
					],
				},
				quiet: true,
				hot: !config.server,
			});

			if (!config.server) {
				server.listen(config.port, 'localhost');
			}
		})
	);

	gulp.task('compile', gulp.series(webpackSectionTasks));
	gulp.task('default', gulp.series('clean:pre', 'translations:compile', 'compile'));
};
<commit_msg>Fix client + site watching<commit_after>const gulp = require('gulp');
const gutil = require('gulp-util');
const path = require('path');

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const WebpackDevServer = require('webpack-dev-server');
const OptimizeCssPlugin = require('optimize-css-assets-webpack-plugin');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const CleanCss = require('clean-css');
const WriteFilePlugin = require('write-file-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const VueSSRServerPlugin = require('vue-server-renderer/server-plugin');
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const OfflinePlugin = require('offline-plugin');
const WebpackPwaManifest = require('webpack-pwa-manifest');

module.exports = function(config) {
	let base = path.resolve(config.projectBase);

	let noop = function() {};
	let devNoop = config.production ? undefined : noop;
	let prodNoop = !config.production ? undefined : noop;
	let browserNoop = config.server ? undefined : noop;
	let serverNoop = !config.server ? undefined : noop;

	const externalModules = ['client-voodoo'];
	if (!config.client) {
		externalModules.push('nw.gui');
	}

	let externals = {};
<<<<<<< HEAD
	for (let extern of externalModules) {
=======
	let externalLibs = config.client ? ['client-voodoo'] : ['client-voodoo', 'nw.gui'];
	for (let extern of externalLibs) {
>>>>>>> a321937... Fix client + site watching
		externals[extern] = {
			commonjs: extern,
		};
	}

	if (config.server) {
		Object.assign(
			externals,
			nodeExternals({
				// do not externalize dependencies that need to be processed by webpack.
				// you can add more file types here e.g. raw *.vue files
				// you should also whitelist deps that modifies `global` (e.g. polyfills)
				whitelist: /\.css$/,
			})
		);
	}

	const cleanCssOptions = {
		level: 2,
	};

	let cleanCss = new CleanCss(cleanCssOptions);

	let webpackTarget = 'web';
	if (config.server) {
		webpackTarget = 'node';
	} else if (config.client) {
		webpackTarget = 'node-webkit';
	}

	let libraryTarget = 'var';
	if (config.server) {
		libraryTarget = 'commonjs2';
	}

	// Inline allows us to debug by setting breakpoints.
	// Eval may be faster, but it doesn't allow setting breakpoints.
	let devtool = 'source-map';
	if (!config.production) {
		if (config.server) {
			devTool = 'source-map';
		} else if (config.client) {
			// The old node-webkit versions of the client (currently 0.12.3) have trouble processing inline source maps in webpack 2.
			// They have an issue with the //# prefix. Using @ forces it back to webpack 1's //@ for inline sourcemaps.
			devTool = '@cheap-module-inline-source-map';
		} else {
			devTool = 'cheap-module-inline-source-map';
		}
	}

	function stylesLoader(loaders, options) {
		if (config.production) {
			loaders.push({
				loader: 'clean-css-loader',
				options: cleanCssOptions,
			});

			return ExtractTextPlugin.extract({
				use: loaders,
				fallback: 'vue-style-loader',
			});
		}

		loaders.unshift('vue-style-loader');

		return loaders;
	}

	let webpackSectionConfigs = {};
	let webpackSectionTasks = [];
	config.sections.forEach(function(section) {
		let indexHtml = section === 'app' ? 'index.html' : section + '.html';
		let appEntries = [path.resolve(base, 'src/' + section + '/main.ts')];

		if (!config.production) {
			appEntries.push('webpack-dev-server/client?http://localhost:' + config.port + '/');
			appEntries.push('webpack/hot/dev-server');
		}

		let entry = {
			app: appEntries,
		};

		if (config.server) {
			entry = {
				server: [path.resolve(base, 'src/' + section + '/server.ts')],
			};
		}

		let webAppManifest = undefined;
		if (!config.server && config.webAppManifest && config.webAppManifest[section]) {
			webAppManifest = config.webAppManifest[section];

			for (const icon of webAppManifest.icons) {
				icon.src = path.resolve(base, 'src/app/img/touch/' + icon.src);
			}
		}

		let hasOfflineSupport =
			!config.server &&
			config.production &&
			config.offlineSupport &&
			config.offlineSupport.indexOf(section) !== -1;

		webpackSectionConfigs[section] = {
			entry,
			target: webpackTarget,
			devServer: {
				outputPath: path.resolve(base, config.buildDir),
			},
			output: {
				publicPath: (config.production ? config.staticCdn : '') + '/',
				path: path.resolve(base, config.buildDir),
				filename: config.production ? section + '.[name].[chunkhash:6].js' : section + '.[name].js',
				chunkFilename: config.production
					? section + '.[name].[chunkhash:6].js'
					: section + '.[name].js',
				sourceMapFilename: 'maps/[name].[chunkhash:6].map',
				libraryTarget: libraryTarget,
			},
			resolve: {
				extensions: ['.tsx', '.ts', '.js', '.styl'],
				modules: [path.resolve(base, 'src/vendor'), 'node_modules'],
				alias: {
					// Always "app" base img.
					img: path.resolve(base, 'src/app/img'),
					styles: path.resolve(base, 'src/' + section + '/styles'),
				},
			},
			externals: externals,
			resolveLoader: {
				alias: {
					view:
						'vue-template-loader?' +
						JSON.stringify({
							scoped: true,
							transformToRequire: {
								img: 'src',
							},
						}),
				},
			},
			module: {
				rules: [
					{
						test: /\.tsx?$/,
						use: [
							{
								loader: 'ts-loader',
								options: {
									transpileOnly: true,
								},
							},
						],
					},
					{
						enforce: 'pre',
						test: /\.styl$/,
						use: 'stylus-loader?paths[]=src/&resolve url&include css',
					},
					{
						enforce: 'post',
						test: /\.styl$/,
						use: stylesLoader([
							'css-loader?-minimize',
							{ loader: 'postcss-loader', options: { sourceMap: true } },
						]),
					},
					{
						test: /\.css$/,
						use: stylesLoader([
							'css-loader?-minimize',
							{ loader: 'postcss-loader', options: { sourceMap: true } },
						]),
					},
					{
						test: /\.md$/,
						use: ['html-loader', 'markdown-loader'],
					},
					{
						test: /\.(png|jpe?g|gif|svg|json|ogg|mp4)(\?.*)?$/,
						loader: 'file-loader?name=assets/[name].[hash:6].[ext]',
						exclude: /node_modules/,
					},
					{
						test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
						loader: 'file-loader?name=assets/[name].[hash:6].[ext]',
					},
				],
			},
			devtool,
			plugins: [
				// We use this in prod build too since gzip is able to zip up
				// path names better than hashed module IDs resulting in smaller
				// file sizes.
				new webpack.NamedModulesPlugin(),
				new webpack.NamedChunksPlugin(),
				// Hoists modules instead of using a function call when it can.
				devNoop || new webpack.optimize.ModuleConcatenationPlugin(),
				new webpack.DefinePlugin({
					GJ_ENVIRONMENT: JSON.stringify(!config.developmentEnv ? 'production' : 'development'),
					GJ_BUILD_TYPE: JSON.stringify(config.production ? 'production' : 'development'),
					GJ_IS_CLIENT: JSON.stringify(config.client),
					GJ_IS_SSR: JSON.stringify(config.server),
					GJ_VERSION: JSON.stringify(require(path.resolve(process.cwd(), 'package.json')).version),

					// This sets vue in production mode.
					'process.env': {
						NODE_ENV: JSON.stringify(config.production ? 'production' : 'development'),
					},
				}),
				new webpack.LoaderOptionsPlugin({
					options: {
						// Fix extract-loader: https://github.com/peerigon/extract-loader/issues/16
						output: {},
						htmlLoader: {
							minimize: config.production,
						},
						stylus: {
							use: [],
							preferPathResolver: 'webpack',
						},
					},
				}),
				// !config.client ? noop : new CopyWebpackPlugin([
				// 	{
				// 		from: path.resolve( base, 'client-package.json' ),
				// 		to: 'package.json',
				// 	},
				// ]),
				devNoop ||
					new webpack.optimize.UglifyJsPlugin({
						sourceMap: true,
						compress: {
							warnings: false,
							screw_ie8: true,
						},
					}),
				devNoop || new ImageminPlugin(),
				prodNoop || serverNoop || new webpack.HotModuleReplacementPlugin(),

				// Since form stuff is so large, we split it into an async chunk
				// that will get loaded alongside any chunks that need it.
				devNoop ||
					serverNoop ||
					new webpack.optimize.CommonsChunkPlugin({
						name: 'app',
						async: 'forms',
						minChunks: function(module) {
							return (
								module.context &&
								(module.context.indexOf('vee-validate') !== -1 ||
									module.context.indexOf('gj-lib-client/components/form') !== -1)
							);
						},
					}),

				// Pull out vendor code from the main entry point.
				devNoop ||
					serverNoop ||
					new webpack.optimize.CommonsChunkPlugin({
						name: 'vendor',
						minChunks: function(module) {
							return module.context && module.context.indexOf('node_modules') !== -1;
						},
					}),

				// This generates a manifest file that allows our vendor chunk
				// to be cached longer if it doesn't change.
				// More info: https://webpack.js.org/guides/code-splitting-libraries/#implicit-common-vendor-chunk
				devNoop ||
					serverNoop ||
					new webpack.optimize.CommonsChunkPlugin({
						name: 'manifest',
						minChunks: Infinity,
					}),

				devNoop || new ExtractTextPlugin('[name].[contenthash:6].css'),
				devNoop ||
					new OptimizeCssPlugin({
						cssProcessor: {
							process: function(css) {
								return new Promise(function(resolve, reject) {
									let output = cleanCss.minify(css);
									if (output.errors.length) {
										reject(output.errors);
									} else {
										resolve({
											css: output.styles,
										});
									}
								});
							},
						},
					}),
				serverNoop ||
					new HtmlWebpackPlugin({
						filename: indexHtml,
						template: '!!html-loader?interpolate=require!src/' + indexHtml,
						favicon: path.resolve(base, 'src/app/img/favicon.png'),
						inject: true,
						chunksSortMode: 'dependency',
					}),
				webAppManifest ? new WebpackPwaManifest(webAppManifest) : noop,
				prodNoop || new FriendlyErrorsWebpackPlugin(),
				serverNoop ||
					new VueSSRClientPlugin({
						filename: 'vue-ssr-client-manifest-' + section + '.json',
					}),
				browserNoop ||
					new VueSSRServerPlugin({
						filename: 'vue-ssr-server-bundle-' + section + '.json',
					}),
				hasOfflineSupport
					? new OfflinePlugin({
							excludes: ['vue-ssr-*'],
							ServiceWorker: {
								output: 'sjw.js',
								publicPath: 'https://gamejolt.com/sjw.js',
							},
						})
					: noop,
				config.write ? new WriteFilePlugin() : noop,
				config.analyze ? new BundleAnalyzerPlugin() : noop,
			],
		};

		gulp.task('compile:' + section, function(cb) {
			let compiler = webpack(webpackSectionConfigs[section]);
			compiler.run(function(err, stats) {
				if (err) {
					throw new gutil.PluginError('webpack:build', err);
				}

				gutil.log(
					'[webpack:build]',
					stats.toString({
						chunks: false,
						colors: true,
					})
				);

				cb();
			});
		});

		webpackSectionTasks.push('compile:' + section);
	});

	gulp.task(
		'watch',
		gulp.series('clean:pre', function(cb) {
			let compiler = webpack(webpackSectionConfigs[config.buildSection]);

			let server = new WebpackDevServer(compiler, {
				historyApiFallback: {
					rewrites: [
						{
							from: /./,
							to:
								config.buildSection === 'app' ? '/index.html' : '/' + config.buildSection + '.html',
						},
					],
				},
				quiet: true,
				hot: !config.server,
			});

			if (!config.server) {
				server.listen(config.port, 'localhost');
			}
		})
	);

	gulp.task('compile', gulp.series(webpackSectionTasks));
	gulp.task('default', gulp.series('clean:pre', 'translations:compile', 'compile'));
};
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var gutil = require('gulp-util');
var log = gutil.log;
var colors = gutil.colors;
var Timer = require('./timer');
var inject = require('./injector');
var makeContainerTemplate = require('./makecontainertemplate');
var makeComponentTemplate = require('./makecomponenttemplate');

/*

Need to create:
  - actions file
  - data file
  - handler file
  - container file
  - component file

Need to inject:
  - constants
  - reducers import
  - reducers key/val
  - initialState key/val

*/

function makeConstantTemplate(capitalized, allCaps) {
  return '/**\n'
       + ' * Constants for ' + capitalize + '-related items\n'
       + ' */\n'
       + 'export const' + allCaps + ' = objectize([\n'
       + "  'FOO'\n"
       + ']);';
}

function makeReducerImportTemplate(reducers, reducersImport) {
  return 'import ' + reducers + " from '" + reducersImport + "';";
}

function makeReducerKeyVal(name, reducers) {
  return name + ': ' + reducers + ',';
}

function makeStateKeyVal(name) {
  return name + ': {},';
}

function makeActionsTemplate(constants) {
  return "import { " + constants + " } from '../lib/constants';\n"
       + "\n"
       + "export function foo() {\n"
       + "  return {\n"
       + "    type: " + constants + ".FOO\n"
       + "  }\n"
       + "}\n";
}

function makeDataTemplate(constants) {
  return "import axios from 'axios';\n"
       + "import brightsocket from 'brightsocket.io-client';\n"
       + "import { " + constants + " } from '../lib/constants';\n"
       + "\n"
       + "export function foo() {\n"
       + "\n"
       + "}\n";
}

function makeHandlerTemplate() {
  return "export function handleFoo(evt) {\n"
       + "  evt.preventDefault();\n"
       + "}\n";
}

function makeJs(names, callback) {
  var timer = new Timer();
  timer.start();
  log('Starting', colors.cyan('new JavaScript layer') + '...');

  var constantTemplate = makeConstantTemplate(names.component, names.constants);
  var reducerImportTemplate = makeReducerImportTemplate(names.reducers, names.reducersImport);
  var reducerKeyValTemplate = makeReducerKeyVal(names.state, names.reducers);
  var stateKeyValTemplate = makeStateKeyVal(names.state);
  var actionsTemplate = makeActionsTemplate(names.constants);
  var dataTemplate = makeDataTemplate(names.constants);
  var handlerTemplate = makeHandlerTemplate();
  var containerTemplate = makeConstantTemplate(names);
  var componentTemplate = makeComponentTemplate(names);

  log('Finished', colors.cyan('new JavaScript layer'), "after", colors.magenta(timer.end()));
  callback && callback();
}

module.exports = makeJs;
<commit_msg>get all pathnames<commit_after>var path = require('path');
var fs = require('fs');
var gutil = require('gulp-util');
var log = gutil.log;
var colors = gutil.colors;
var Timer = require('./timer');
var inject = require('./injector');
var makeContainerTemplate = require('./makecontainertemplate');
var makeComponentTemplate = require('./makecomponenttemplate');

/*

Need to create:
  - actions file
  - data file
  - handler file
  - container file
  - component file

Need to inject:
  - constants
  - reducers import
  - reducers key/val
  - initialState key/val

*/

function makeConstantTemplate(capitalized, allCaps) {
  return '/**\n'
       + ' * Constants for ' + capitalize + '-related items\n'
       + ' */\n'
       + 'export const' + allCaps + ' = objectize([\n'
       + "  'FOO'\n"
       + ']);';
}

function makeReducerImportTemplate(reducers, reducersImport) {
  return 'import ' + reducers + " from '" + reducersImport + "';";
}

function makeReducerKeyVal(name, reducers) {
  return name + ': ' + reducers + ',';
}

function makeStateKeyVal(name) {
  return name + ': {},';
}

function makeActionsTemplate(constants) {
  return "import { " + constants + " } from '../lib/constants';\n"
       + "\n"
       + "export function foo() {\n"
       + "  return {\n"
       + "    type: " + constants + ".FOO\n"
       + "  }\n"
       + "}\n";
}

function makeDataTemplate(constants) {
  return "import axios from 'axios';\n"
       + "import brightsocket from 'brightsocket.io-client';\n"
       + "import { " + constants + " } from '../lib/constants';\n"
       + "\n"
       + "export function foo() {\n"
       + "\n"
       + "}\n";
}

function makeHandlerTemplate() {
  return "export function handleFoo(evt) {\n"
       + "  evt.preventDefault();\n"
       + "}\n";
}

function makeJs(names, callback) {
  var timer = new Timer();
  timer.start();
  log('Starting', colors.cyan('new JavaScript layer') + '...');

  var constantTemplate = makeConstantTemplate(names.component, names.constants);
  var reducerImportTemplate = makeReducerImportTemplate(names.reducers, names.reducersImport);
  var reducerKeyValTemplate = makeReducerKeyVal(names.state, names.reducers);
  var stateKeyValTemplate = makeStateKeyVal(names.state);
  var actionsTemplate = makeActionsTemplate(names.constants);
  var dataTemplate = makeDataTemplate(names.constants);
  var handlerTemplate = makeHandlerTemplate();
  var containerTemplate = makeConstantTemplate(names);
  var componentTemplate = makeComponentTemplate(names);

  var actionsPath = path.resolve(__dirname, 'frontend', 'src', 'js', 'actions', names.actionsFile);
  var dataPath = path.resolve(__dirname, 'frontend', 'src', 'js', 'data', names.dataFile);
  var handlersPath = path.resolve(__dirname, 'frontend', 'src', 'js', 'handlers', names.handlersFile);
  var containerPath = path.resolve(__dirname, 'frontend', 'src', 'js', 'containers', names.containerFile);
  var componentPath = path.resolve(__dirname, 'frontend', 'src', 'js', 'components', names.componentFile);
  var constantsIndex = path.resolve(__dirname, 'frontend', 'src', 'js', 'lib', 'constants.js');
  var reducersPath = path.resolve(__dirname, 'frontend', 'src', 'js', 'reducers', names.reducersFile);
  var reducersIndex = path.resolve(__dirname, 'frontend', 'src', 'js', 'reducers', 'reducers.js');
  var stateIndex = path.resolve(__dirname, 'frontend', 'src', 'js', 'state', 'initialstate.js');

  log('Finished', colors.cyan('new JavaScript layer'), "after", colors.magenta(timer.end()));
  callback && callback();
}

module.exports = makeJs;
<|endoftext|>