<commit_before>'use strict';

WaveSurfer.Spectrogram = {

    /**
     * List of params:
     *   wavesurfer: wavesurfer object
     *   pixelRatio: to control the size of the spectrogram in relation with its canvas. 1=Draw on the whole canvas. 2 = draw on a quarter (1/2 the lenght and 1/2 the width)
     *   fftSamples: number of samples to fetch to FFT. Must be a pwer of 2. Default = 512
     *   windowFunc: the window function to be used. Default is 'hann'. Choose from the following:
     *               + 'bartlett'
     *               + 'bartlettHann'
     *               + 'blackman'
     *               + 'cosine'
     *               + 'gauss'
     *               + 'hamming'
     *               + 'hann'
     *               + 'lanczoz'
     *               + 'rectangular'
     *               + 'triangular'
     *   alpha: some window functions have this extra value (0<alpha<1);
     *   noverlap: size of the overlapping window. Must be < fftSamples. Auto deduced from canvas size by default.
     */
    init: function (params) {
        this.params = params;
        var wavesurfer = this.wavesurfer = params.wavesurfer;

        if (!this.wavesurfer) {
            throw Error('No WaveSurfer instance provided');
        }

        this.frequenciesDataUrl = params.frequenciesDataUrl;

        var drawer = this.drawer = this.wavesurfer.drawer;

        this.container = 'string' == typeof params.container ?
            document.querySelector(params.container) : params.container;

        if (!this.container) {
            throw Error('No container for WaveSurfer spectrogram');
        }

        this.width = drawer.width;
        this.pixelRatio = this.params.pixelRatio || wavesurfer.params.pixelRatio;
        this.fftSamples = this.params.fftSamples || wavesurfer.params.fftSamples || 512;
        this.height = this.fftSamples / 2;
        this.noverlap = params.noverlap;
        this.windowFunc = params.windowFunc;
        this.alpha = params.alpha;

        this.createWrapper();
        this.createCanvas();
        this.render();

        wavesurfer.drawer.wrapper.onscroll = this.updateScroll.bind(this);
        wavesurfer.on('redraw', this.render.bind(this));
        wavesurfer.on('destroy', this.destroy.bind(this));
    },

    destroy: function () {
        this.unAll();
        if (this.wrapper) {
            this.wrapper.parentNode.removeChild(this.wrapper);
            this.wrapper = null;
        }
    },

    createWrapper: function () {
        var prevSpectrogram = this.container.querySelector('spectrogram');
        if (prevSpectrogram) {
            this.container.removeChild(prevSpectrogram);
        }

        var wsParams = this.wavesurfer.params;

        this.wrapper = this.container.appendChild(
            document.createElement('spectrogram')
        );
        this.drawer.style(this.wrapper, {
            display: 'block',
            position: 'relative',
            userSelect: 'none',
            webkitUserSelect: 'none',
            height: this.height + 'px'
        });

        if (wsParams.fillParent || wsParams.scrollParent) {
            this.drawer.style(this.wrapper, {
                width: '100%',
                overflowX: 'hidden',
                overflowY: 'hidden'
            });
        }

        var my = this;
        this.wrapper.addEventListener('click', function (e) {
            e.preventDefault();
            var relX = 'offsetX' in e ? e.offsetX : e.layerX;
            my.fireEvent('click', (relX / my.scrollWidth) || 0);
        });
    },

    createCanvas: function () {
        var canvas = this.canvas = this.wrapper.appendChild(
          document.createElement('canvas')
        );

        this.spectrCc = canvas.getContext('2d');

        this.wavesurfer.drawer.style(canvas, {
            position: 'absolute',
            zIndex: 4
        });
    },

    render: function () {
        this.updateCanvasStyle();

        if (this.frequenciesDataUrl) {
            this.loadFrequenciesData(this.frequenciesDataUrl);
        }
        else {
            this.getFrequencies(this.drawSpectrogram);
        }
    },

    updateCanvasStyle: function () {
        var width = Math.round(this.width / this.pixelRatio) + 'px';
        this.canvas.width = this.width;
        this.canvas.height = this.height;
        this.canvas.style.width = width;
    },

    drawSpectrogram: function(frequenciesData, my) {
        var spectrCc = my.spectrCc;

        var length = my.wavesurfer.backend.getDuration();
        var height = my.height;

        var pixels = my.resample(frequenciesData);

        var heightFactor = my.buffer ? 2 / my.buffer.numberOfChannels : 1;

        for (var i = 0; i < pixels.length; i++) {
            for (var j = 0; j < pixels[i].length; j++) {
                var colorValue = 255 - pixels[i][j];
                my.spectrCc.fillStyle = 'rgb(' + colorValue + ', '  + colorValue + ', ' + colorValue + ')';
                my.spectrCc.fillRect(i, height - j * heightFactor, 1, heightFactor);
            }
        }
    },

    getFrequencies: function(callback) {
        var fftSamples = this.fftSamples;
        var buffer = this.buffer = this.wavesurfer.backend.buffer;
        var channelOne = Array.prototype.slice(buffer.getChannelData(0));
        var bufferLength = buffer.length;
        var sampleRate = buffer.sampleRate;
        var frequencies = [];

        if (! buffer) {
            this.fireEvent('error', 'Web Audio buffer is not available');
            return;
        }

        var noverlap = this.noverlap;
        if (! noverlap) {
            var uniqueSamplesPerPx = buffer.length / this.canvas.width;
            noverlap = Math.max(0, Math.round(fftSamples - uniqueSamplesPerPx));
        }

        var fft = new WaveSurfer.FFT(fftSamples, sampleRate, this.windowFunc, this.alpha);

        var maxSlicesCount = Math.floor(bufferLength/ (fftSamples - noverlap));

        var currentOffset = 0;

        while (currentOffset + fftSamples < channelOne.length) {
            var segment = channelOne.slice(currentOffset, currentOffset + fftSamples);
            var spectrum = fft.calculateSpectrum(segment);
            var array = new Uint8Array(fftSamples/2);
            for (var j = 0; j<fftSamples/2; j++) {
                array[j] = Math.max(-255, Math.log10(spectrum[j])*45);
            }
            frequencies.push(array);
            currentOffset += (fftSamples - noverlap);
        }
        callback(frequencies, this);
    },

    loadFrequenciesData: function (url) {
        var my = this;

        var ajax = WaveSurfer.util.ajax({ url: url });

        ajax.on('success', function(data) { my.drawSpectrogram(JSON.parse(data), my); });
        ajax.on('error', function (e) {
            my.fireEvent('error', 'XHR error: ' + e.target.statusText);
        });

        return ajax;
    },

    updateScroll: function(e) {
      this.wrapper.scrollLeft = e.target.scrollLeft;
    },

    resample: function(oldMatrix, columnsNumber) {
        var columnsNumber = this.width;
        var newMatrix = [];

        var oldPiece = 1 / oldMatrix.length;
        var newPiece = 1 / columnsNumber;

        for (var i = 0; i < columnsNumber; i++) {
            var column = new Array(oldMatrix[0].length);

            for (var j = 0; j < oldMatrix.length; j++) {
                var oldStart = j * oldPiece;
                var oldEnd = oldStart + oldPiece;
                var newStart = i * newPiece;
                var newEnd = newStart + newPiece;

                var overlap = (oldEnd <= newStart || newEnd <= oldStart) ?
                                0 :
                                Math.min(Math.max(oldEnd, newStart), Math.max(newEnd, oldStart)) -
                                Math.max(Math.min(oldEnd, newStart), Math.min(newEnd, oldStart));

                if (overlap > 0) {
                    for (var k = 0; k < oldMatrix[0].length; k++) {
                        if (column[k] == null) {
                            column[k] = 0;
                        }
                        column[k] += (overlap / newPiece) * oldMatrix[j][k];
                    }
                }
            }

            var intColumn = new Uint8Array(oldMatrix[0].length);

            for (var k = 0; k < oldMatrix[0].length; k++) {
                intColumn[k] = column[k];
            }

            newMatrix.push(intColumn);
        }

        return newMatrix;
    }

};

/**
 * Calculate FFT - Based on https://github.com/corbanbrook/dsp.js
 */
WaveSurfer.FFT = function(bufferSize, sampleRate, windowFunc, alpha) {
    this.bufferSize = bufferSize;
    this.sampleRate = sampleRate;
    this.bandwidth  = 2 / bufferSize * sampleRate / 2;

    this.sinTable = new Float32Array(bufferSize);
    this.cosTable = new Float32Array(bufferSize);
    this.windowValues = new Float32Array(bufferSize);
    this.reverseTable = new Uint32Array(bufferSize);

    this.peakBand   = 0;
    this.peak       = 0;

    switch (windowFunc) {
        case 'bartlett' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 2 / (bufferSize - 1) * ((bufferSize - 1) / 2 - Math.abs(i - (bufferSize - 1) / 2));
            }
            break;
        case 'bartlettHann' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 0.62 - 0.48 * Math.abs(i / (bufferSize - 1) - 0.5) - 0.38 * Math.cos(Math.PI * 2 * i / (bufferSize - 1));
            }
            break;
        case 'blackman' :
            alpha = alpha || 0.16;
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = (1 - alpha)/2 - 0.5 * Math.cos(Math.PI * 2 * i / (bufferSize - 1)) + alpha/2 * Math.cos(4 * Math.PI * i / (bufferSize - 1));
            }
            break;
        case 'cosine' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = Math.cos(Math.PI * i / (bufferSize - 1) - Math.PI / 2);
            }
            break;
        case 'gauss' :
            alpha = alpha || 0.25;
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = Math.pow(Math.E, -0.5 * Math.pow((i - (bufferSize - 1) / 2) / (alpha * (bufferSize - 1) / 2), 2));
            }
            break;
        case 'hamming' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 0.54 - 0.46 * Math.cos(Math.PI * 2 * i / (bufferSize - 1));
            }
            break;
        case 'hann' :
        case undefined :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 0.5 * (1 - Math.cos(Math.PI * 2 * i / (bufferSize - 1)));
            }
            break;
        case 'lanczoz' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = Math.sin(Math.PI * (2 * i / (bufferSize - 1) - 1)) / (Math.PI * (2 * i / (bufferSize - 1) - 1));
            }
            break;
        case 'rectangular' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 1;
            }
            break;
        case 'triangular' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 2 / bufferSize * (bufferSize / 2 - Math.abs(i - (bufferSize - 1) / 2));
            }
            break;
        default:
            throw Error('No such window function \'' + windowFunc + '\'');
    }

    var limit = 1;
    var bit = bufferSize >> 1;

    var i;

    while (limit < bufferSize) {
        for (i = 0; i < limit; i++) {
            this.reverseTable[i + limit] = this.reverseTable[i] + bit;
        }

        limit = limit << 1;
        bit = bit >> 1;
    }

    for (i = 0; i < bufferSize; i++) {
        this.sinTable[i] = Math.sin(-Math.PI/i);
        this.cosTable[i] = Math.cos(-Math.PI/i);
    }

    this.calculateSpectrum = function(buffer) {
        // Locally scope variables for speed up
        var bufferSize = this.bufferSize,
            cosTable = this.cosTable,
            sinTable = this.sinTable,
            reverseTable = this.reverseTable,
            real = new Float32Array(bufferSize),
            imag = new Float32Array(bufferSize),
            bSi = 2 / this.bufferSize,
            sqrt = Math.sqrt,
            rval,
            ival,
            mag,
            spectrum = new Float32Array(bufferSize / 2);

        var k = Math.floor(Math.log(bufferSize) / Math.LN2);

        if (Math.pow(2, k) !== bufferSize) {
            throw 'Invalid buffer size, must be a power of 2.';
        }
        if (bufferSize !== buffer.length) {
            throw 'Supplied buffer is not the same size as defined FFT. FFT Size: ' + bufferSize + ' Buffer Size: ' + buffer.length;
        }

        var halfSize = 1,
            phaseShiftStepReal,
            phaseShiftStepImag,
            currentPhaseShiftReal,
            currentPhaseShiftImag,
            off,
            tr,
            ti,
            tmpReal;

        for (var i = 0; i < bufferSize; i++) {
            real[i] = buffer[reverseTable[i]] * this.windowValues[reverseTable[i]];
            imag[i] = 0;
        }

        while (halfSize < bufferSize) {
            phaseShiftStepReal = cosTable[halfSize];
            phaseShiftStepImag = sinTable[halfSize];

            currentPhaseShiftReal = 1;
            currentPhaseShiftImag = 0;

            for (var fftStep = 0; fftStep < halfSize; fftStep++) {
                var i = fftStep;

                while (i < bufferSize) {
                    off = i + halfSize;
                    tr = (currentPhaseShiftReal * real[off]) - (currentPhaseShiftImag * imag[off]);
                    ti = (currentPhaseShiftReal * imag[off]) + (currentPhaseShiftImag * real[off]);

                    real[off] = real[i] - tr;
                    imag[off] = imag[i] - ti;
                    real[i] += tr;
                    imag[i] += ti;

                    i += halfSize << 1;
                }

                tmpReal = currentPhaseShiftReal;
                currentPhaseShiftReal = (tmpReal * phaseShiftStepReal) - (currentPhaseShiftImag * phaseShiftStepImag);
                currentPhaseShiftImag = (tmpReal * phaseShiftStepImag) + (currentPhaseShiftImag * phaseShiftStepReal);
            }

            halfSize = halfSize << 1;
        }

        for (var i = 0, N = bufferSize / 2; i < N; i++) {
            rval = real[i];
            ival = imag[i];
            mag = bSi * sqrt(rval * rval + ival * ival);

            if (mag > this.peak) {
                this.peakBand = i;
                this.peak = mag;
            }
            spectrum[i] = mag;
        }
        return spectrum;
    };
};

WaveSurfer.util.extend(WaveSurfer.Spectrogram, WaveSurfer.Observer, WaveSurfer.FFT);
<commit_msg>fix slice call<commit_after>'use strict';

WaveSurfer.Spectrogram = {

    /**
     * List of params:
     *   wavesurfer: wavesurfer object
     *   pixelRatio: to control the size of the spectrogram in relation with its canvas. 1=Draw on the whole canvas. 2 = draw on a quarter (1/2 the lenght and 1/2 the width)
     *   fftSamples: number of samples to fetch to FFT. Must be a pwer of 2. Default = 512
     *   windowFunc: the window function to be used. Default is 'hann'. Choose from the following:
     *               + 'bartlett'
     *               + 'bartlettHann'
     *               + 'blackman'
     *               + 'cosine'
     *               + 'gauss'
     *               + 'hamming'
     *               + 'hann'
     *               + 'lanczoz'
     *               + 'rectangular'
     *               + 'triangular'
     *   alpha: some window functions have this extra value (0<alpha<1);
     *   noverlap: size of the overlapping window. Must be < fftSamples. Auto deduced from canvas size by default.
     */
    init: function (params) {
        this.params = params;
        var wavesurfer = this.wavesurfer = params.wavesurfer;

        if (!this.wavesurfer) {
            throw Error('No WaveSurfer instance provided');
        }

        this.frequenciesDataUrl = params.frequenciesDataUrl;

        var drawer = this.drawer = this.wavesurfer.drawer;

        this.container = 'string' == typeof params.container ?
            document.querySelector(params.container) : params.container;

        if (!this.container) {
            throw Error('No container for WaveSurfer spectrogram');
        }

        this.width = drawer.width;
        this.pixelRatio = this.params.pixelRatio || wavesurfer.params.pixelRatio;
        this.fftSamples = this.params.fftSamples || wavesurfer.params.fftSamples || 512;
        this.height = this.fftSamples / 2;
        this.noverlap = params.noverlap;
        this.windowFunc = params.windowFunc;
        this.alpha = params.alpha;

        this.createWrapper();
        this.createCanvas();
        this.render();

        wavesurfer.drawer.wrapper.onscroll = this.updateScroll.bind(this);
        wavesurfer.on('redraw', this.render.bind(this));
        wavesurfer.on('destroy', this.destroy.bind(this));
    },

    destroy: function () {
        this.unAll();
        if (this.wrapper) {
            this.wrapper.parentNode.removeChild(this.wrapper);
            this.wrapper = null;
        }
    },

    createWrapper: function () {
        var prevSpectrogram = this.container.querySelector('spectrogram');
        if (prevSpectrogram) {
            this.container.removeChild(prevSpectrogram);
        }

        var wsParams = this.wavesurfer.params;

        this.wrapper = this.container.appendChild(
            document.createElement('spectrogram')
        );
        this.drawer.style(this.wrapper, {
            display: 'block',
            position: 'relative',
            userSelect: 'none',
            webkitUserSelect: 'none',
            height: this.height + 'px'
        });

        if (wsParams.fillParent || wsParams.scrollParent) {
            this.drawer.style(this.wrapper, {
                width: '100%',
                overflowX: 'hidden',
                overflowY: 'hidden'
            });
        }

        var my = this;
        this.wrapper.addEventListener('click', function (e) {
            e.preventDefault();
            var relX = 'offsetX' in e ? e.offsetX : e.layerX;
            my.fireEvent('click', (relX / my.scrollWidth) || 0);
        });
    },

    createCanvas: function () {
        var canvas = this.canvas = this.wrapper.appendChild(
          document.createElement('canvas')
        );

        this.spectrCc = canvas.getContext('2d');

        this.wavesurfer.drawer.style(canvas, {
            position: 'absolute',
            zIndex: 4
        });
    },

    render: function () {
        this.updateCanvasStyle();

        if (this.frequenciesDataUrl) {
            this.loadFrequenciesData(this.frequenciesDataUrl);
        }
        else {
            this.getFrequencies(this.drawSpectrogram);
        }
    },

    updateCanvasStyle: function () {
        var width = Math.round(this.width / this.pixelRatio) + 'px';
        this.canvas.width = this.width;
        this.canvas.height = this.height;
        this.canvas.style.width = width;
    },

    drawSpectrogram: function(frequenciesData, my) {
        var spectrCc = my.spectrCc;

        var length = my.wavesurfer.backend.getDuration();
        var height = my.height;

        var pixels = my.resample(frequenciesData);

        var heightFactor = my.buffer ? 2 / my.buffer.numberOfChannels : 1;

        for (var i = 0; i < pixels.length; i++) {
            for (var j = 0; j < pixels[i].length; j++) {
                var colorValue = 255 - pixels[i][j];
                my.spectrCc.fillStyle = 'rgb(' + colorValue + ', '  + colorValue + ', ' + colorValue + ')';
                my.spectrCc.fillRect(i, height - j * heightFactor, 1, heightFactor);
            }
        }
    },

    getFrequencies: function(callback) {
        var fftSamples = this.fftSamples;
        var buffer = this.buffer = this.wavesurfer.backend.buffer;
        var channelOne = Array.prototype.slice.call(buffer.getChannelData(0));
        var bufferLength = buffer.length;
        var sampleRate = buffer.sampleRate;
        var frequencies = [];

        if (! buffer) {
            this.fireEvent('error', 'Web Audio buffer is not available');
            return;
        }

        var noverlap = this.noverlap;
        if (! noverlap) {
            var uniqueSamplesPerPx = buffer.length / this.canvas.width;
            noverlap = Math.max(0, Math.round(fftSamples - uniqueSamplesPerPx));
        }

        var fft = new WaveSurfer.FFT(fftSamples, sampleRate, this.windowFunc, this.alpha);

        var maxSlicesCount = Math.floor(bufferLength/ (fftSamples - noverlap));

        var currentOffset = 0;

        while (currentOffset + fftSamples < channelOne.length) {
            var segment = channelOne.slice(currentOffset, currentOffset + fftSamples);
            var spectrum = fft.calculateSpectrum(segment);
            var array = new Uint8Array(fftSamples/2);
            for (var j = 0; j<fftSamples/2; j++) {
                array[j] = Math.max(-255, Math.log10(spectrum[j])*45);
            }
            frequencies.push(array);
            currentOffset += (fftSamples - noverlap);
        }
        callback(frequencies, this);
    },

    loadFrequenciesData: function (url) {
        var my = this;

        var ajax = WaveSurfer.util.ajax({ url: url });

        ajax.on('success', function(data) { my.drawSpectrogram(JSON.parse(data), my); });
        ajax.on('error', function (e) {
            my.fireEvent('error', 'XHR error: ' + e.target.statusText);
        });

        return ajax;
    },

    updateScroll: function(e) {
      this.wrapper.scrollLeft = e.target.scrollLeft;
    },

    resample: function(oldMatrix, columnsNumber) {
        var columnsNumber = this.width;
        var newMatrix = [];

        var oldPiece = 1 / oldMatrix.length;
        var newPiece = 1 / columnsNumber;

        for (var i = 0; i < columnsNumber; i++) {
            var column = new Array(oldMatrix[0].length);

            for (var j = 0; j < oldMatrix.length; j++) {
                var oldStart = j * oldPiece;
                var oldEnd = oldStart + oldPiece;
                var newStart = i * newPiece;
                var newEnd = newStart + newPiece;

                var overlap = (oldEnd <= newStart || newEnd <= oldStart) ?
                                0 :
                                Math.min(Math.max(oldEnd, newStart), Math.max(newEnd, oldStart)) -
                                Math.max(Math.min(oldEnd, newStart), Math.min(newEnd, oldStart));

                if (overlap > 0) {
                    for (var k = 0; k < oldMatrix[0].length; k++) {
                        if (column[k] == null) {
                            column[k] = 0;
                        }
                        column[k] += (overlap / newPiece) * oldMatrix[j][k];
                    }
                }
            }

            var intColumn = new Uint8Array(oldMatrix[0].length);

            for (var k = 0; k < oldMatrix[0].length; k++) {
                intColumn[k] = column[k];
            }

            newMatrix.push(intColumn);
        }

        return newMatrix;
    }

};

/**
 * Calculate FFT - Based on https://github.com/corbanbrook/dsp.js
 */
WaveSurfer.FFT = function(bufferSize, sampleRate, windowFunc, alpha) {
    this.bufferSize = bufferSize;
    this.sampleRate = sampleRate;
    this.bandwidth  = 2 / bufferSize * sampleRate / 2;

    this.sinTable = new Float32Array(bufferSize);
    this.cosTable = new Float32Array(bufferSize);
    this.windowValues = new Float32Array(bufferSize);
    this.reverseTable = new Uint32Array(bufferSize);

    this.peakBand   = 0;
    this.peak       = 0;

    switch (windowFunc) {
        case 'bartlett' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 2 / (bufferSize - 1) * ((bufferSize - 1) / 2 - Math.abs(i - (bufferSize - 1) / 2));
            }
            break;
        case 'bartlettHann' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 0.62 - 0.48 * Math.abs(i / (bufferSize - 1) - 0.5) - 0.38 * Math.cos(Math.PI * 2 * i / (bufferSize - 1));
            }
            break;
        case 'blackman' :
            alpha = alpha || 0.16;
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = (1 - alpha)/2 - 0.5 * Math.cos(Math.PI * 2 * i / (bufferSize - 1)) + alpha/2 * Math.cos(4 * Math.PI * i / (bufferSize - 1));
            }
            break;
        case 'cosine' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = Math.cos(Math.PI * i / (bufferSize - 1) - Math.PI / 2);
            }
            break;
        case 'gauss' :
            alpha = alpha || 0.25;
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = Math.pow(Math.E, -0.5 * Math.pow((i - (bufferSize - 1) / 2) / (alpha * (bufferSize - 1) / 2), 2));
            }
            break;
        case 'hamming' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 0.54 - 0.46 * Math.cos(Math.PI * 2 * i / (bufferSize - 1));
            }
            break;
        case 'hann' :
        case undefined :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 0.5 * (1 - Math.cos(Math.PI * 2 * i / (bufferSize - 1)));
            }
            break;
        case 'lanczoz' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = Math.sin(Math.PI * (2 * i / (bufferSize - 1) - 1)) / (Math.PI * (2 * i / (bufferSize - 1) - 1));
            }
            break;
        case 'rectangular' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 1;
            }
            break;
        case 'triangular' :
            for (var i = 0; i<bufferSize; i++) {
                this.windowValues[i] = 2 / bufferSize * (bufferSize / 2 - Math.abs(i - (bufferSize - 1) / 2));
            }
            break;
        default:
            throw Error('No such window function \'' + windowFunc + '\'');
    }

    var limit = 1;
    var bit = bufferSize >> 1;

    var i;

    while (limit < bufferSize) {
        for (i = 0; i < limit; i++) {
            this.reverseTable[i + limit] = this.reverseTable[i] + bit;
        }

        limit = limit << 1;
        bit = bit >> 1;
    }

    for (i = 0; i < bufferSize; i++) {
        this.sinTable[i] = Math.sin(-Math.PI/i);
        this.cosTable[i] = Math.cos(-Math.PI/i);
    }

    this.calculateSpectrum = function(buffer) {
        // Locally scope variables for speed up
        var bufferSize = this.bufferSize,
            cosTable = this.cosTable,
            sinTable = this.sinTable,
            reverseTable = this.reverseTable,
            real = new Float32Array(bufferSize),
            imag = new Float32Array(bufferSize),
            bSi = 2 / this.bufferSize,
            sqrt = Math.sqrt,
            rval,
            ival,
            mag,
            spectrum = new Float32Array(bufferSize / 2);

        var k = Math.floor(Math.log(bufferSize) / Math.LN2);

        if (Math.pow(2, k) !== bufferSize) {
            throw 'Invalid buffer size, must be a power of 2.';
        }
        if (bufferSize !== buffer.length) {
            throw 'Supplied buffer is not the same size as defined FFT. FFT Size: ' + bufferSize + ' Buffer Size: ' + buffer.length;
        }

        var halfSize = 1,
            phaseShiftStepReal,
            phaseShiftStepImag,
            currentPhaseShiftReal,
            currentPhaseShiftImag,
            off,
            tr,
            ti,
            tmpReal;

        for (var i = 0; i < bufferSize; i++) {
            real[i] = buffer[reverseTable[i]] * this.windowValues[reverseTable[i]];
            imag[i] = 0;
        }

        while (halfSize < bufferSize) {
            phaseShiftStepReal = cosTable[halfSize];
            phaseShiftStepImag = sinTable[halfSize];

            currentPhaseShiftReal = 1;
            currentPhaseShiftImag = 0;

            for (var fftStep = 0; fftStep < halfSize; fftStep++) {
                var i = fftStep;

                while (i < bufferSize) {
                    off = i + halfSize;
                    tr = (currentPhaseShiftReal * real[off]) - (currentPhaseShiftImag * imag[off]);
                    ti = (currentPhaseShiftReal * imag[off]) + (currentPhaseShiftImag * real[off]);

                    real[off] = real[i] - tr;
                    imag[off] = imag[i] - ti;
                    real[i] += tr;
                    imag[i] += ti;

                    i += halfSize << 1;
                }

                tmpReal = currentPhaseShiftReal;
                currentPhaseShiftReal = (tmpReal * phaseShiftStepReal) - (currentPhaseShiftImag * phaseShiftStepImag);
                currentPhaseShiftImag = (tmpReal * phaseShiftStepImag) + (currentPhaseShiftImag * phaseShiftStepReal);
            }

            halfSize = halfSize << 1;
        }

        for (var i = 0, N = bufferSize / 2; i < N; i++) {
            rval = real[i];
            ival = imag[i];
            mag = bSi * sqrt(rval * rval + ival * ival);

            if (mag > this.peak) {
                this.peakBand = i;
                this.peak = mag;
            }
            spectrum[i] = mag;
        }
        return spectrum;
    };
};

WaveSurfer.util.extend(WaveSurfer.Spectrogram, WaveSurfer.Observer, WaveSurfer.FFT);
<|endoftext|>


<commit_before>import Link from 'next/prefetch'

export default ({ pathname }) => (

    <Link href='/'>
      Home
    </Link>

    <Link href='/about'>
      About
    </Link>

)
<commit_msg>Use prefetch<commit_after>import Link from 'next/link'

export default ({ pathname }) => (

    <Link prefetch href='/'>
      Home
    </Link>

    <Link prefetch href='/about'>
      About
    </Link>

)
<|endoftext|>


<commit_before>// Rules which have been enforced in configuration upgrades and flag issues in existing code.
// We need to consider whether to disable those rules permanently, or fix the issues.
const legacyCode = {
  'class-methods-use-this': 'off',
  'constructor-super': 'off',
  'default-param-last': 'off',
  'import/first': 'off',
  'import/newline-after-import': 'off',
  'import/no-cycle': 'off',
  'import/no-extraneous-dependencies': 'off',
  'import/no-unresolved': ['error', { ignore: ['jquery'] }],
  'import/no-useless-path-segments': 'off',
  'import/order': 'off',
  'jsx-a11y/alt-text': 'off',
  'jsx-a11y/anchor-is-valid': 'off',
  'jsx-a11y/click-events-have-key-events': 'off',
  'jsx-a11y/interactive-supports-focus': 'off',
  'jsx-a11y/no-noninteractive-element-interactions': 'off',
  'jsx-a11y/role-supports-aria-props': 'off',
  'lines-between-class-members': 'off',
  'max-classes-per-file': 'off',
  'no-await-in-loop': 'off',
  'no-continue': 'off',
  'no-else-return': 'off',
  'no-extra-boolean-cast': 'off',
  'no-import-assign': 'off',
  'no-lonely-if': 'off',
  'no-plusplus': 'off',
  'no-prototype-builtins': 'off',
  'no-restricted-syntax': 'off',
  'no-this-before-super': 'off',
  'operator-assignment': 'off',
  'prefer-destructuring': 'off',
  'prefer-object-spread': 'off',
  'prefer-promise-reject-errors': 'off',
  'react-hooks/exhaustive-deps': 'off',
  'react-hooks/rules-of-hooks': 'off',
  'react/button-has-type': 'off',
  'react/destructuring-assignment': 'off',
  'react/forbid-prop-types': 'off',
  'react/function-component-definition': 'off',
  'react/jsx-curly-brace-presence': 'off',
  'react/jsx-filename-extension': 'off',
  'react/jsx-no-useless-fragment': 'off',
  'react/jsx-props-no-spreading': 'off',
  'react/no-danger': 'off',
  'react/no-deprecated': 'off',
  'react/require-default-props': 'off',
};

module.exports = {
  extends: [
    '@wagtail/eslint-config-wagtail',
    'plugin:@typescript-eslint/recommended',
  ],
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  env: {
    jest: true,
    browser: true,
  },
  rules: {
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-member-accessibility': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    '@typescript-eslint/no-use-before-define': ['error'],
    'import/extensions': [
      'error',
      'always',
      {
        ignorePackages: true,
        pattern: {
          js: 'never',
          jsx: 'never',
          ts: 'never',
          tsx: 'never',
        },
      },
    ],
    // does not align with the majority of legacy and newer code, some use named others use default exports
    'import/prefer-default-export': 'off',
    // note you must disable the base rule as it can report incorrect errors
    'no-use-before-define': 'off',
    'react/jsx-filename-extension': ['error', { extensions: ['.js', '.tsx'] }],
    'no-underscore-dangle': [
      'error',
      { allow: ['__REDUX_DEVTOOLS_EXTENSION__'] },
    ],
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.ts', '.tsx'],
      },
    },
  },
  overrides: [
    // Legacy Code - remove from `files` when adopting desired rules in new code progressively
    {
      files: [
        'client/src/components/**',
        'client/src/entrypoints/**',
        'client/src/utils/**',
        '**/documents/static_src/wagtaildocs/js/add-multiple.js',
        '**/images/static_src/wagtailimages/js/add-multiple.js',
        '**/images/static_src/wagtailimages/js/focal-point-chooser.js',
        '**/snippets/static_src/wagtailsnippets/js/snippet-multiple-select.js',
      ],
      rules: legacyCode,
    },
    {
      // Rules we don’t want to enforce for test and tooling code.
      files: [
        'client/extract-translatable-strings.js',
        'client/tests/**',
        'webpack.config.js',
        'tailwind.config.js',
        'storybook/**/*',
        '*.test.ts',
        '*.test.tsx',
        '*.test.js',
        '*.stories.js',
        '*.stories.tsx',
      ],
      rules: {
        '@typescript-eslint/no-empty-function': 'off',
        '@typescript-eslint/no-var-requires': 'off',
        'import/no-extraneous-dependencies': 'off',
        'react/function-component-definition': 'off',
        'react/jsx-props-no-spreading': 'off',
      },
    },
    {
      files: ['docs/_static/**'],
      globals: { $: 'readonly' },
    },
    {
      files: ['wagtail/**/**'],
      globals: {
        $: 'readonly',
        addMessage: 'readonly',
        buildExpandingFormset: 'readonly',
        cancelSpinner: 'readonly',
        escapeHtml: 'readonly',
        jQuery: 'readonly',
        jsonData: 'readonly',
        ModalWorkflow: 'readonly',
        DOCUMENT_CHOOSER_MODAL_ONLOAD_HANDLERS: 'writable',
        EMBED_CHOOSER_MODAL_ONLOAD_HANDLERS: 'writable',
        IMAGE_CHOOSER_MODAL_ONLOAD_HANDLERS: 'writable',
        QUERY_CHOOSER_MODAL_ONLOAD_HANDLERS: 'writable',
        SNIPPET_CHOOSER_MODAL_ONLOAD_HANDLERS: 'writable',
      },
      rules: {
        '@typescript-eslint/no-unused-vars': 'off',
        '@typescript-eslint/no-use-before-define': 'off',
        'camelcase': [
          'error',
          {
            allow: [
              '__unused_webpack_module',
              '__webpack_modules__',
              '__webpack_require__',
            ],
            properties: 'never',
          },
        ],
        'consistent-return': 'off',
        'func-names': 'off',
        'id-length': 'off',
        'indent': 'off',
        'key-spacing': 'off',
        'new-cap': 'off',
        'newline-per-chained-call': 'off',
        'no-param-reassign': 'off',
        'no-underscore-dangle': 'off',
        'object-shorthand': 'off',
        'prefer-arrow-callback': 'off',
        'quote-props': 'off',
        'space-before-function-paren': 'off',
        'vars-on-top': 'off',
      },
    },
  ],
};
<commit_msg>Fix ESLint issue with how jQuery is treated as a core module (#8591)<commit_after>// Rules which have been enforced in configuration upgrades and flag issues in existing code.
// We need to consider whether to disable those rules permanently, or fix the issues.
const legacyCode = {
  'class-methods-use-this': 'off',
  'constructor-super': 'off',
  'default-param-last': 'off',
  'import/first': 'off',
  'import/newline-after-import': 'off',
  'import/no-cycle': 'off',
  'import/no-extraneous-dependencies': 'off',
  'import/no-useless-path-segments': 'off',
  'import/order': 'off',
  'jsx-a11y/alt-text': 'off',
  'jsx-a11y/anchor-is-valid': 'off',
  'jsx-a11y/click-events-have-key-events': 'off',
  'jsx-a11y/interactive-supports-focus': 'off',
  'jsx-a11y/no-noninteractive-element-interactions': 'off',
  'jsx-a11y/role-supports-aria-props': 'off',
  'lines-between-class-members': 'off',
  'max-classes-per-file': 'off',
  'no-await-in-loop': 'off',
  'no-continue': 'off',
  'no-else-return': 'off',
  'no-extra-boolean-cast': 'off',
  'no-import-assign': 'off',
  'no-lonely-if': 'off',
  'no-plusplus': 'off',
  'no-prototype-builtins': 'off',
  'no-restricted-syntax': 'off',
  'no-this-before-super': 'off',
  'operator-assignment': 'off',
  'prefer-destructuring': 'off',
  'prefer-object-spread': 'off',
  'prefer-promise-reject-errors': 'off',
  'react-hooks/exhaustive-deps': 'off',
  'react-hooks/rules-of-hooks': 'off',
  'react/button-has-type': 'off',
  'react/destructuring-assignment': 'off',
  'react/forbid-prop-types': 'off',
  'react/function-component-definition': 'off',
  'react/jsx-curly-brace-presence': 'off',
  'react/jsx-filename-extension': 'off',
  'react/jsx-no-useless-fragment': 'off',
  'react/jsx-props-no-spreading': 'off',
  'react/no-danger': 'off',
  'react/no-deprecated': 'off',
  'react/require-default-props': 'off',
};

module.exports = {
  extends: [
    '@wagtail/eslint-config-wagtail',
    'plugin:@typescript-eslint/recommended',
  ],
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  env: {
    jest: true,
    browser: true,
  },
  rules: {
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-member-accessibility': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    '@typescript-eslint/no-use-before-define': ['error'],
    'import/extensions': [
      'error',
      'always',
      {
        ignorePackages: true,
        pattern: {
          js: 'never',
          jsx: 'never',
          ts: 'never',
          tsx: 'never',
        },
      },
    ],
    // does not align with the majority of legacy and newer code, some use named others use default exports
    'import/prefer-default-export': 'off',
    // note you must disable the base rule as it can report incorrect errors
    'no-use-before-define': 'off',
    'react/jsx-filename-extension': ['error', { extensions: ['.js', '.tsx'] }],
    'no-underscore-dangle': [
      'error',
      { allow: ['__REDUX_DEVTOOLS_EXTENSION__'] },
    ],
  },
  settings: {
    'import/core-modules': ['jquery'],
    'import/resolver': { node: { extensions: ['.js', '.ts', '.tsx'] } },
  },
  overrides: [
    // Legacy Code - remove from `files` when adopting desired rules in new code progressively
    {
      files: [
        'client/src/components/**',
        'client/src/entrypoints/**',
        'client/src/utils/**',
        '**/documents/static_src/wagtaildocs/js/add-multiple.js',
        '**/images/static_src/wagtailimages/js/add-multiple.js',
        '**/images/static_src/wagtailimages/js/focal-point-chooser.js',
        '**/snippets/static_src/wagtailsnippets/js/snippet-multiple-select.js',
      ],
      rules: legacyCode,
    },
    // Rules we don’t want to enforce for test and tooling code.
    {
      files: [
        'client/extract-translatable-strings.js',
        'client/tests/**',
        'webpack.config.js',
        'tailwind.config.js',
        'storybook/**/*',
        '*.test.ts',
        '*.test.tsx',
        '*.test.js',
        '*.stories.js',
        '*.stories.tsx',
      ],
      rules: {
        '@typescript-eslint/no-empty-function': 'off',
        '@typescript-eslint/no-var-requires': 'off',
        'import/no-extraneous-dependencies': 'off',
        'react/function-component-definition': 'off',
        'react/jsx-props-no-spreading': 'off',
      },
    },
    // Files that use jquery via a global
    {
      files: [
        'docs/_static/**',
        'wagtail/contrib/modeladmin/static_src/wagtailmodeladmin/js/prepopulate.js',
        'wagtail/contrib/settings/static_src/wagtailsettings/js/site-switcher.js',
        'wagtail/documents/static_src/wagtaildocs/js/add-multiple.js',
        'wagtail/embeds/static_src/wagtailembeds/js/embed-chooser-modal.js',
        'wagtail/images/static_src/wagtailimages/js/add-multiple.js',
        'wagtail/images/static_src/wagtailimages/js/focal-point-chooser.js',
        'wagtail/images/static_src/wagtailimages/js/image-url-generator.js',
        'wagtail/search/static_src/wagtailsearch/js/query-chooser-modal.js',
        'wagtail/search/templates/wagtailsearch/queries/chooser_field.js',
        'wagtail/snippets/static_src/wagtailsnippets/js/snippet-multiple-select.js',
        'wagtail/users/static_src/wagtailusers/js/group-form.js',
      ],
      globals: { $: 'readonly', jQuery: 'readonly' },
    },
    // Files that use other globals or legacy/vendor code that is unable to be easily linted
    {
      files: ['wagtail/**/**'],
      globals: {
        addMessage: 'readonly',
        buildExpandingFormset: 'readonly',
        cancelSpinner: 'readonly',
        escapeHtml: 'readonly',
        jsonData: 'readonly',
        ModalWorkflow: 'readonly',
        DOCUMENT_CHOOSER_MODAL_ONLOAD_HANDLERS: 'writable',
        EMBED_CHOOSER_MODAL_ONLOAD_HANDLERS: 'writable',
        IMAGE_CHOOSER_MODAL_ONLOAD_HANDLERS: 'writable',
        QUERY_CHOOSER_MODAL_ONLOAD_HANDLERS: 'writable',
        SNIPPET_CHOOSER_MODAL_ONLOAD_HANDLERS: 'writable',
      },
      rules: {
        '@typescript-eslint/no-unused-vars': 'off',
        '@typescript-eslint/no-use-before-define': 'off',
        'camelcase': [
          'error',
          {
            allow: [
              '__unused_webpack_module',
              '__webpack_modules__',
              '__webpack_require__',
            ],
            properties: 'never',
          },
        ],
        'consistent-return': 'off',
        'func-names': 'off',
        'id-length': 'off',
        'indent': 'off',
        'key-spacing': 'off',
        'new-cap': 'off',
        'newline-per-chained-call': 'off',
        'no-param-reassign': 'off',
        'no-underscore-dangle': 'off',
        'object-shorthand': 'off',
        'prefer-arrow-callback': 'off',
        'quote-props': 'off',
        'space-before-function-paren': 'off',
        'vars-on-top': 'off',
      },
    },
  ],
};
<|endoftext|>


<commit_before>const bankai = require('../')
const path = require('path')
const browserify = require('browserify')
const resolve = require('resolve')
const xtend = require('xtend')
const fs = require('fs')
const mkdirp = require('mkdirp')
const parallel = require('run-parallel')
const pump = require('pump')

module.exports = build

const defaults = {
  optimize: false,
  entry: '.',
  html: {},
  css: {},
  js: {}
}

const cwd = process.cwd()

// resolve a path according to require.resolve algorithm
// string -> string
function resolveEntryFile (relativePath) {
  const first = relativePath.charAt(0)
  const entry = ['.', '/'].includes(first) ? relativePath : './' + relativePath
  return resolve.sync(entry, {basedir: cwd})
}

function build (options, cb) {
  const assets = bankai({ optimize: true })

  const settings = xtend({}, defaults, options)
  const callback = cb || function () {}

  const entryFile = resolveEntryFile(settings.entry)
  const outputDir = settings.dir

  // Register css & html if specified. Register js no matter what
  const css = settings.css && assets.css(settings.css)
  const html = settings.html && assets.html(settings.html)
  const js = assets.js(browserify, entryFile, settings.js)

  mkdirp(outputDir, (err) => {
    if (err) return console.error(`Error creating directory ${outputDir}`, err)

    const operations = []

    if (js) {
      operations.push(function (done) {
        const jsPath = path.join(outputDir, settings.html.js || 'bundle.js')
        pump(js(), fs.createWriteStream(jsPath), done)
      })
    }

    if (css) {
      operations.push(function (done) {
        const cssPath = path.join(outputDir, settings.html.css || 'bundle.css')
        pump(css(), fs.createWriteStream(cssPath), done)
      })
    }

    if (html) {
      operations.push(function (done) {
        const htmlPath = path.join(outputDir, 'index.html')
        pump(html(), fs.createWriteStream(htmlPath), done)
      })
    }

    parallel(operations, callback)
  })
}
<commit_msg>build: add default path<commit_after>const bankai = require('../')
const path = require('path')
const browserify = require('browserify')
const resolve = require('resolve')
const xtend = require('xtend')
const fs = require('fs')
const mkdirp = require('mkdirp')
const parallel = require('run-parallel')
const pump = require('pump')

module.exports = build

const defaults = {
  optimize: false,
  dir: 'dist',
  entry: '.',
  html: {},
  css: {},
  js: {}
}

const cwd = process.cwd()

// resolve a path according to require.resolve algorithm
// string -> string
function resolveEntryFile (relativePath) {
  const first = relativePath.charAt(0)
  const entry = ['.', '/'].includes(first) ? relativePath : './' + relativePath
  return resolve.sync(entry, {basedir: cwd})
}

function build (options, cb) {
  const assets = bankai({ optimize: true })

  const settings = xtend({}, defaults, options)
  const callback = cb || function () {}

  const entryFile = resolveEntryFile(settings.entry)
  const outputDir = settings.dir

  // Register css & html if specified. Register js no matter what
  const css = settings.css && assets.css(settings.css)
  const html = settings.html && assets.html(settings.html)
  const js = assets.js(browserify, entryFile, settings.js)

  mkdirp(outputDir, (err) => {
    if (err) return console.error(`Error creating directory ${outputDir}`, err)

    const operations = []

    if (js) {
      operations.push(function (done) {
        const jsPath = path.join(outputDir, settings.html.js || 'bundle.js')
        pump(js(), fs.createWriteStream(jsPath), done)
      })
    }

    if (css) {
      operations.push(function (done) {
        const cssPath = path.join(outputDir, settings.html.css || 'bundle.css')
        pump(css(), fs.createWriteStream(cssPath), done)
      })
    }

    if (html) {
      operations.push(function (done) {
        const htmlPath = path.join(outputDir, 'index.html')
        pump(html(), fs.createWriteStream(htmlPath), done)
      })
    }

    parallel(operations, callback)
  })
}
<|endoftext|>


<commit_before>import resolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import commonjs from 'rollup-plugin-commonjs';
import svelte from 'rollup-plugin-svelte';
import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import copy from 'rollup-plugin-copy'
import config from 'sapper/config/rollup.js';
import pkg from './package.json';

const mode = process.env.NODE_ENV;
const dev = mode === 'development';
const legacy = !!process.env.SAPPER_LEGACY_BUILD;

const appsTargetFolder = 'Apps';
const appsOutputFolder = dev ? '__sapper__/dev/client' : '__sapper__/build/client';

export default {
	client: {
		input: config.client.input(),
		output: config.client.output(),
		plugins: [
			replace({
				'process.browser': true,
				'process.env.NODE_ENV': JSON.stringify(mode)
			}),
			svelte({
				dev,
				hydratable: true,
				emitCss: true
			}),
			resolve(),
			commonjs(),

			legacy && babel({
				extensions: ['.js', '.mjs', '.html', '.svelte'],
				runtimeHelpers: true,
				exclude: ['node_modules/@babel/**'],
				presets: [
					['@babel/preset-env', {
						targets: '> 0.25%, not dead'
					}]
				],
				plugins: [
					'@babel/plugin-syntax-dynamic-import',
					['@babel/plugin-transform-runtime', {
						useESModules: true
					}]
				]
			}),

			!dev && terser({
				module: true
			}),

			// https://github.com/vladshcherbin/rollup-plugin-copy
			copy({
				targets: appsTargetFolder,
				outputFolder: appsOutputFolder
			  })
		],
	},

	server: {
		input: config.server.input(),
		output: config.server.output(),
		plugins: [
			replace({
				'process.browser': false,
				'process.env.NODE_ENV': JSON.stringify(mode)
			}),
			svelte({
				generate: 'ssr',
				dev
			}),
			resolve(),
			commonjs()
		],
		external: Object.keys(pkg.dependencies).concat(
			require('module').builtinModules || Object.keys(process.binding('natives'))
		),
	},

	serviceworker: {
		input: config.serviceworker.input(),
		output: config.serviceworker.output(),
		plugins: [
			resolve(),
			replace({
				'process.browser': true,
				'process.env.NODE_ENV': JSON.stringify(mode)
			}),
			commonjs(),
			!dev && terser()
		]
	}
};
<commit_msg>Copy sample Apps at build time<commit_after>import resolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import commonjs from 'rollup-plugin-commonjs';
import svelte from 'rollup-plugin-svelte';
import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import copy from 'rollup-plugin-copy'
import config from 'sapper/config/rollup.js';
import pkg from './package.json';

const mode = process.env.NODE_ENV;
const dev = mode === 'development';
const legacy = !!process.env.SAPPER_LEGACY_BUILD;

export default {
	client: {
		input: config.client.input(),
		output: config.client.output(),
		plugins: [
			replace({
				'process.browser': true,
				'process.env.NODE_ENV': JSON.stringify(mode)
			}),
			svelte({
				dev,
				hydratable: true,
				emitCss: true
			}),
			resolve(),
			commonjs(),

			legacy && babel({
				extensions: ['.js', '.mjs', '.html', '.svelte'],
				runtimeHelpers: true,
				exclude: ['node_modules/@babel/**'],
				presets: [
					['@babel/preset-env', {
						targets: '> 0.25%, not dead'
					}]
				],
				plugins: [
					'@babel/plugin-syntax-dynamic-import',
					['@babel/plugin-transform-runtime', {
						useESModules: true
					}]
				]
			}),

			!dev && terser({
				module: true
			}),

			// https://github.com/vladshcherbin/rollup-plugin-copy
			copy({
				targets: ['Apps'],
				outputFolder: dev ? '__sapper__/dev/client' : '__sapper__/build/client',
				verbose: true
			})
		],
	},

	server: {
		input: config.server.input(),
		output: config.server.output(),
		plugins: [
			replace({
				'process.browser': false,
				'process.env.NODE_ENV': JSON.stringify(mode)
			}),
			svelte({
				generate: 'ssr',
				dev
			}),
			resolve(),
			commonjs()
		],
		external: Object.keys(pkg.dependencies).concat(
			require('module').builtinModules || Object.keys(process.binding('natives'))
		),
	},

	serviceworker: {
		input: config.serviceworker.input(),
		output: config.serviceworker.output(),
		plugins: [
			resolve(),
			replace({
				'process.browser': true,
				'process.env.NODE_ENV': JSON.stringify(mode)
			}),
			commonjs(),
			!dev && terser()
		]
	}
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { AppBar, Drawer, FlatButton, IconButton, IconMenu, MenuItem, Toggle } from 'material-ui';
import { deepOrangeA400, grey50, grey400 } from 'material-ui/styles/colors';
import MoreHorizIcon from 'material-ui/svg-icons/navigation/more-horiz';
import NavigationExpandMore from 'material-ui/svg-icons/navigation/expand-more';

import ModuleListContainer from '../containers/ModuleListContainer';

class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {logged: false, open: false};

    this.handleLogin = this.handleLogin.bind(this);
    this.handleToggle = this.handleToggle.bind(this);
  }

  handleLogin() {
    this.setState({logged: !this.state.logged});
  }

  handleToggle() {
    this.setState({open: !this.state.open});
  }

  render() {
    return (

        <AppBar
          title="NUS Workload Predictor"
          style={{position: 'fixed'}}
          onLeftIconButtonTouchTap={this.handleToggle}
          iconElementRight={<IconButton><NavigationExpandMore /></IconButton>}
          iconElementRight={this.state.logged
            ? <IconMenu iconButtonElement={
                <IconButton>
                  <MoreHorizIcon />
                </IconButton>
              }
              targetOrigin={{horizontal: 'right', vertical: 'top'}}
              anchorOrigin={{horizontal: 'right', vertical: 'top'}}
              style={{color: grey50}}>
                <MenuItem primaryText="Refresh" />
                <MenuItem primaryText="Help" />
                <MenuItem onTouchTap={this.handleLogin} primaryText="Sign out" />
              </IconMenu>
            : <FlatButton onTouchTap={this.handleLogin} style={{color: grey50}} label="Login" />
          }
        />
        <Drawer docked={false} width={200} open={this.state.open} onRequestChange={(open) => this.setState({open})} containerStyle={{height: '70%', top: 70}}>
          <ModuleListContainer />
        </Drawer>

    );
  }
}

Header.propTypes = {

};

export default Header;
<commit_msg>Change app name.<commit_after>import React, { Component, PropTypes } from 'react';
import { AppBar, Drawer, FlatButton, IconButton, IconMenu, MenuItem, Toggle } from 'material-ui';
import { deepOrangeA400, grey50, grey400 } from 'material-ui/styles/colors';
import MoreHorizIcon from 'material-ui/svg-icons/navigation/more-horiz';
import NavigationExpandMore from 'material-ui/svg-icons/navigation/expand-more';

import ModuleListContainer from '../containers/ModuleListContainer';

class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {logged: false, open: false};

    this.handleLogin = this.handleLogin.bind(this);
    this.handleToggle = this.handleToggle.bind(this);
  }

  handleLogin() {
    this.setState({logged: !this.state.logged});
  }

  handleToggle() {
    this.setState({open: !this.state.open});
  }

  render() {
    return (

        <AppBar
          title="NUSWorks"
          style={{position: 'fixed'}}
          onLeftIconButtonTouchTap={this.handleToggle}
          iconElementRight={<IconButton><NavigationExpandMore /></IconButton>}
          iconElementRight={this.state.logged
            ? <IconMenu iconButtonElement={
                <IconButton>
                  <MoreHorizIcon />
                </IconButton>
              }
              targetOrigin={{horizontal: 'right', vertical: 'top'}}
              anchorOrigin={{horizontal: 'right', vertical: 'top'}}
              style={{color: grey50}}>
                <MenuItem primaryText="Refresh" />
                <MenuItem primaryText="Help" />
                <MenuItem onTouchTap={this.handleLogin} primaryText="Sign out" />
              </IconMenu>
            : <FlatButton onTouchTap={this.handleLogin} style={{color: grey50}} label="Login" />
          }
        />
        <Drawer docked={false} width={200} open={this.state.open} onRequestChange={(open) => this.setState({open})} containerStyle={{height: '70%', top: 70}}>
          <ModuleListContainer />
        </Drawer>

    );
  }
}

Header.propTypes = {

};

export default Header;
<|endoftext|>


<commit_before>module.exports = {
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": 2018
    },
    "env": {
        "es6": true,
        "mocha": true,
        "node": true
    },
    "globals": {
        "after": true,
        "afterEach": true,
        "angular": true,
        "before": true,
        "beforeEach": true,
        "Buffer": true,
        "console": true,
        "clearInterval": true,
        "clearTimeout": true,
        "describe": true,
        "it": true,
        "jQuery": true,
        "Promise": true,
        "Map": true,
        "module": true,
        "os": true,
        "process": true,
        "require": true,
        "setImmediate": true,
        "setInterval": true,
        "setTimeout": true,
        "__dirname": true,
        "__filename": true
    },
    "rules": {
        "for-direction": "error",
        "getter-return": "error",
        "no-await-in-loop": "error",
        "no-compare-neg-zero": "error",
        "no-cond-assign": "error",
        "no-console": "error",
        "no-constant-condition": "error",
        "no-control-regex": "error",
        "no-debugger": "error",
        "no-dupe-args": "error",
        "no-dupe-else-if": "error",
        "no-dupe-keys": "error",
        "no-duplicate-case": "error",
        "no-empty": "error",
        "no-empty-character-class": "error",
        "no-ex-assign": "error",
        "no-extra-boolean-cast": "error",
        "no-extra-parens": "error",
        "no-extra-semi": "error",
        "no-func-assign": "error",
        "no-import-assign": "error",
        "no-inner-declarations": "error",
        "no-invalid-regexp": "error",
        "no-irregular-whitespace": "error",
        "no-obj-calls": "error",
        "no-prototype-builtins": "error",
        "no-regex-spaces": "error",
        "no-setter-return": "error",
        "no-sparse-arrays": "error",
        "no-template-curly-in-string": "error",
        "no-unexpected-multiline": "error",
        "no-unreachable": "error",
        "no-unsafe-finally": "error",
        "no-unsafe-negation": "error",
        "use-isnan": "error",
        "valid-jsdoc": "error",
        "valid-typeof": "error",

        "accessor-pairs": "error",
        "array-callback-return": "error",
        "block-scoped-var": "error",
        "class-methods-use-this": "error",
        "complexity": "error",
        "consistent-return": "error",
        "curly": "error",
        "default-case": "error",
        "dot-location": [ "error", "property" ],
        "dot-notation": "error",
        "eqeqeq": "error",
        "guard-for-in": 0,
        "no-alert": "error",
        "no-caller": "error",
        "no-case-declarations": "error",
        "no-div-regex": "error",
        "no-else-return": 0,
        "no-empty-function": "error",
        "no-empty-pattern": "error",
        "no-eq-null": "error",
        "no-eval": "error",
        "no-extend-native": "error",
        "no-extra-bind": "error",
        "no-extra-label": "error",
        "no-fallthrough": "error",
        "no-floating-decimal": "error",
        "no-global-assign": "error",
        "no-implicit-coercion": "error",
        "no-implicit-globals": "error",
        "no-implied-eval": "error",
        "no-invalid-this": "error",
        "no-iterator": "error",
        "no-labels": "error",
        "no-lone-blocks": "error",
        "no-loop-func": "error",
        "no-magic-numbers": 0,
        "no-multi-spaces": "error",
        "no-multi-str": "error",
        "no-new": "error",
        "no-new-func": "error",
        "no-new-wrappers": "error",
        "no-octal": "error",
        "no-octal-escape": "error",
        "no-param-reassign": "error",
        "no-proto": "error",
        "no-redeclare": "error",
        "no-restricted-properties": "error",
        "no-return-assign": "error",
        "no-return-await": "error",
        "no-script-url": "error",
        "no-self-assign": "error",
        "no-self-compare": "error",
        "no-sequences": "error",
        "no-throw-literal": "error",
        "no-unmodified-loop-condition": "error",
        "no-unused-expressions": "error",
        "no-unused-labels": "error",
        "no-useless-call": "error",
        "no-useless-concat": "error",
        "no-useless-escape": "error",
        "no-useless-return": "error",
        "no-void": "error",
        "no-warning-comments": "error",
        "no-with": "error",
        "prefer-promise-reject-errors": "error",
        "radix": "error",
        "require-await": "error",
        "vars-on-top": "error",
        "wrap-iife": "error",
        "yoda": [ "error", "always" ],

        "strict": [ "error", "global" ],

        "init-declarations": "error",
        "no-catch-shadow": "error",
        "no-delete-var": "error",
        "no-label-var": "error",
        "no-restricted-globals": "error",
        "no-shadow": "error",
        "no-shadow-restricted-names": "error",
        "no-undef": "error",
        "no-undef-init": "error",
        "no-undefined": "error",
        "no-unused-vars": "error",
        "no-use-before-define": "error",

        "callback-return": "error",
        "global-require": 0,
        "handle-callback-err": "error",
        "no-buffer-constructor": "error",
        "no-mixed-requires": "error",
        "no-new-require": "error",
        "no-path-concat": "error",
        "no-process-env": "error",
        "no-process-exit": "error",
        "no-restricted-modules": "error",
        "no-sync": "error",

        "array-bracket-newline": "error",
        "array-bracket-spacing": [ "error", "always" ],
        "array-element-newline": [ "error", "consistent" ],
        "block-spacing": "error",
        "brace-style": [ "error", "stroustrup" ],
        "camelcase": "error",
        "capitalized-comments": 0,
        "comma-dangle": [ "error", "never" ],
        "comma-spacing": [ "error", { "before": false, "after": true } ],
        "comma-style": [ "error", "last" ],
        "computed-property-spacing": [ "error", "never" ],
        "consistent-this": "error",
        "eol-last": "error",
        "func-call-spacing": "error",
        "func-name-matching": "error",
        "func-names": "error",
        "func-style": [ "error", "declaration" ],
        "id-blacklist": 0,
        "id-length": 0,
        "id-match": 0,
        "indent": 0,
        "jsx-quotes": [ "error", "prefer-double" ],
        "key-spacing": [ "error", { "beforeColon": false, "afterColon": true } ],
        "keyword-spacing": [ "error", { "after": true, "before": true } ],
        "line-comment-position": [ "error", { "position": "above" } ],
        "linebreak-style": 0,
        "lines-around-comment": "error",
        "max-depth": [ "error", 4 ],
        "max-len": [ "error", 150 ],
        "max-lines": [ "error", { "max": 500, "skipComments": true } ],
        "max-nested-callbacks": [ "error", 5 ],
        "max-params": [ "error", 4 ],
        "max-statements": [ "error", 25 ],
        "max-statements-per-line": [ "error", { "max": 2 } ],
        "multiline-ternary": 0,
        "new-cap": "error",
        "new-parens": "error",
        "newline-per-chained-call": 0,
        "no-array-constructor": "error",
        "no-bitwise": "error",
        "no-continue": "error",
        "no-inline-comments": "error",
        "no-lonely-if": "error",
        "no-mixed-operators": "error",
        "no-mixed-spaces-and-tabs": "error",
        "no-multi-assign": "error",
        "no-multiple-empty-lines": "error",
        "no-negated-condition": 0,
        "no-nested-ternary": "error",
        "no-new-object": "error",
        "no-plusplus": 0,
        "no-restricted-syntax": "error",
        "no-tabs": [ "error", { "allowIndentationTabs": true } ],
        "no-ternary": 0,
        "no-trailing-spaces": "error",
        "no-underscore-dangle": 0,
        "no-unneeded-ternary": "error",
        "no-whitespace-before-property": "error",
        "nonblock-statement-body-position": [ "error", "below" ],
        "object-curly-newline": [ "error", { "consistent": true } ],
        "object-curly-spacing": [ "error", "always" ],
        "object-property-newline": "error",
        "one-var": [ "error", "never" ],
        "one-var-declaration-per-line": "error",
        "operator-assignment": [ "error", "always" ],
        "operator-linebreak": [ "error", "after" ],
        "padded-blocks": ["error", { "classes": "always", "switches": "always" } ],
        "padding-line-between-statements": "error",
        "quote-props": [ "error", "always" ],
        "quotes": [ "error", "double" ],
        "require-jsdoc": "error",
        "semi": [ "error", "always" ],
        "semi-spacing": [ "error", { "before": false, "after": true } ],
        "semi-style": [ "error", "last" ],
        "sort-keys": 0,
        "sort-vars": "error",
        "space-before-blocks": [ "error", "always" ],
        "space-before-function-paren": [ "error", "always" ],
        "space-in-parens": [ "error", "never" ],
        "space-infix-ops": "error",
        "space-unary-ops": "error",
        "spaced-comment": [ "error", "always" ],
        "switch-colon-spacing": [ "error", { "after": true, "before": false } ],
        "template-tag-spacing": [ "error", "always" ],
        "unicode-bom": 0,
        "wrap-regex": "error",

        "arrow-body-style": [ "error", "always" ],
        "arrow-parens": [ "error", "always" ],
        "arrow-spacing": ["error", { "before": true, "after": true } ],
        "constructor-super": "error",
        "generator-star-spacing": [ "error", { "before": true, "after": false } ],
        "no-class-assign": "error",
        "no-confusing-arrow": "error",
        "no-const-assign": "error",
        "no-dupe-class-members": "error",
        "no-duplicate-imports": "error",
        "no-new-symbol": "error",
        "no-restricted-imports": 0,
        "no-this-before-super": "error",
        "no-useless-computed-key": "error",
        "no-useless-constructor": "error",
        "no-useless-rename": "error",
        "no-var": "error",
        "object-shorthand": "error",
        "prefer-arrow-callback": "error",
        "prefer-const": "error",
        "prefer-destructuring": "error",
        "prefer-numeric-literals": "error",
        "prefer-rest-params": "error",
        "prefer-spread": "error",
        "prefer-template": 0,
        "require-yield": "error",
        "rest-spread-spacing": [ "error", "never" ],
        "sort-imports": "error",
        "symbol-description": "error",
        "template-curly-spacing": "error",
        "yield-star-spacing": [ "error", { "before": true, "after": false } ]

    }
};
<commit_msg>eslint<commit_after>module.exports = {
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": 2018
    },
    "env": {
        "es6": true,
        "mocha": true,
        "node": true
    },
    "globals": {
        "after": true,
        "afterEach": true,
        "angular": true,
        "before": true,
        "beforeEach": true,
        "Buffer": true,
        "console": true,
        "clearInterval": true,
        "clearTimeout": true,
        "describe": true,
        "it": true,
        "jQuery": true,
        "Promise": true,
        "Map": true,
        "module": true,
        "os": true,
        "process": true,
        "require": true,
        "setImmediate": true,
        "setInterval": true,
        "setTimeout": true,
        "__dirname": true,
        "__filename": true
    },
    "rules": {
        "for-direction": "error",
        "getter-return": "error",
        "no-await-in-loop": "error",
        "no-compare-neg-zero": "error",
        "no-cond-assign": "error",
        "no-console": "error",
        "no-constant-condition": "error",
        "no-control-regex": "error",
        "no-debugger": "error",
        "no-dupe-args": "error",
        "no-dupe-else-if": "error",
        "no-dupe-keys": "error",
        "no-duplicate-case": "error",
        "no-empty": "error",
        "no-empty-character-class": "error",
        "no-ex-assign": "error",
        "no-extra-boolean-cast": "error",
        "no-extra-parens": "error",
        "no-extra-semi": "error",
        "no-func-assign": "error",
        "no-import-assign": "error",
        "no-inner-declarations": "error",
        "no-invalid-regexp": "error",
        "no-irregular-whitespace": "error",
        "no-obj-calls": "error",
        "no-prototype-builtins": "error",
        "no-regex-spaces": "error",
        "no-setter-return": "error",
        "no-sparse-arrays": "error",
        "no-template-curly-in-string": "error",
        "no-unexpected-multiline": "error",
        "no-unreachable": "error",
        "no-unsafe-finally": "error",
        "no-unsafe-negation": "error",
        "use-isnan": "error",
        "valid-jsdoc": "error",
        "valid-typeof": "error",

        "accessor-pairs": "error",
        "array-callback-return": "error",
        "block-scoped-var": "error",
        "class-methods-use-this": "error",
        "complexity": "error",
        "consistent-return": "error",
        "curly": "error",
        "default-case": "error",
        "dot-location": [ "error", "property" ],
        "dot-notation": "error",
        "eqeqeq": "error",
        "guard-for-in": 0,
        "no-alert": "error",
        "no-caller": "error",
        "no-case-declarations": "error",
        "no-div-regex": "error",
        "no-else-return": 0,
        "no-empty-function": "error",
        "no-empty-pattern": "error",
        "no-eq-null": "error",
        "no-eval": "error",
        "no-extend-native": "error",
        "no-extra-bind": "error",
        "no-extra-label": "error",
        "no-fallthrough": "error",
        "no-floating-decimal": "error",
        "no-global-assign": "error",
        "no-implicit-coercion": "error",
        "no-implicit-globals": "error",
        "no-implied-eval": "error",
        "no-invalid-this": "error",
        "no-iterator": "error",
        "no-labels": "error",
        "no-lone-blocks": "error",
        "no-loop-func": "error",
        "no-magic-numbers": 0,
        "no-multi-spaces": "error",
        "no-multi-str": "error",
        "no-new": "error",
        "no-new-func": "error",
        "no-new-wrappers": "error",
        "no-octal": "error",
        "no-octal-escape": "error",
        "no-param-reassign": "error",
        "no-proto": "error",
        "no-redeclare": "error",
        "no-restricted-properties": "error",
        "no-return-assign": "error",
        "no-return-await": "error",
        "no-script-url": "error",
        "no-self-assign": "error",
        "no-self-compare": "error",
        "no-sequences": "error",
        "no-throw-literal": "error",
        "no-unmodified-loop-condition": "error",
        "no-unused-expressions": "error",
        "no-unused-labels": "error",
        "no-useless-call": "error",
        "no-useless-concat": "error",
        "no-useless-escape": "error",
        "no-useless-return": "error",
        "no-void": "error",
        "no-warning-comments": "error",
        "no-with": "error",
        "prefer-promise-reject-errors": "error",
        "radix": "error",
        "require-await": "error",
        "vars-on-top": "error",
        "wrap-iife": "error",
        "yoda": [ "error", "always" ],

        "strict": [ "error", "global" ],

        "init-declarations": "error",
        "no-catch-shadow": "error",
        "no-delete-var": "error",
        "no-label-var": "error",
        "no-restricted-globals": "error",
        "no-shadow": "error",
        "no-shadow-restricted-names": "error",
        "no-undef": "error",
        "no-undef-init": "error",
        "no-undefined": "error",
        "no-unused-vars": "error",
        "no-use-before-define": "error",

        "callback-return": "error",
        "global-require": 0,
        "handle-callback-err": "error",
        "no-buffer-constructor": "error",
        "no-mixed-requires": "error",
        "no-new-require": "error",
        "no-path-concat": "error",
        "no-process-env": "error",
        "no-process-exit": "error",
        "no-restricted-modules": "error",
        "no-sync": "error",

        "array-bracket-newline": "error",
        "array-bracket-spacing": [ "error", "always" ],
        "array-element-newline": [ "error", "consistent" ],
        "block-spacing": "error",
        "brace-style": [ "error", "stroustrup" ],
        "camelcase": "error",
        "capitalized-comments": 0,
        "comma-dangle": [ "error", "never" ],
        "comma-spacing": [ "error", { "before": false, "after": true } ],
        "comma-style": [ "error", "last" ],
        "computed-property-spacing": [ "error", "never" ],
        "consistent-this": "error",
        "eol-last": "error",
        "func-call-spacing": "error",
        "func-name-matching": "error",
        "func-names": "error",
        "func-style": [ "error", "declaration" ],
        "id-blacklist": 0,
        "id-length": 0,
        "id-match": 0,
        "indent": 0,
        "jsx-quotes": [ "error", "prefer-double" ],
        "key-spacing": [ "error", { "beforeColon": false, "afterColon": true } ],
        "keyword-spacing": [ "error", { "after": true, "before": true } ],
        "line-comment-position": 0,
        "linebreak-style": 0,
        "lines-around-comment": "error",
        "max-depth": [ "error", 4 ],
        "max-len": [ "error", 150 ],
        "max-lines": [ "error", { "max": 500, "skipComments": true } ],
        "max-nested-callbacks": [ "error", 5 ],
        "max-params": [ "error", 4 ],
        "max-statements": [ "error", 25 ],
        "max-statements-per-line": [ "error", { "max": 2 } ],
        "multiline-ternary": 0,
        "new-cap": "error",
        "new-parens": "error",
        "newline-per-chained-call": 0,
        "no-array-constructor": "error",
        "no-bitwise": "error",
        "no-continue": "error",
        "no-inline-comments": 0,
        "no-lonely-if": "error",
        "no-mixed-operators": "error",
        "no-mixed-spaces-and-tabs": "error",
        "no-multi-assign": "error",
        "no-multiple-empty-lines": "error",
        "no-negated-condition": 0,
        "no-nested-ternary": "error",
        "no-new-object": "error",
        "no-plusplus": 0,
        "no-restricted-syntax": "error",
        "no-tabs": [ "error", { "allowIndentationTabs": true } ],
        "no-ternary": 0,
        "no-trailing-spaces": "error",
        "no-underscore-dangle": 0,
        "no-unneeded-ternary": "error",
        "no-whitespace-before-property": "error",
        "nonblock-statement-body-position": [ "error", "below" ],
        "object-curly-newline": [ "error", { "consistent": true } ],
        "object-curly-spacing": [ "error", "always" ],
        "object-property-newline": "error",
        "one-var": [ "error", "never" ],
        "one-var-declaration-per-line": "error",
        "operator-assignment": [ "error", "always" ],
        "operator-linebreak": [ "error", "after" ],
        "padded-blocks": ["error", { "classes": "always", "switches": "always" } ],
        "padding-line-between-statements": "error",
        "quote-props": [ "error", "always" ],
        "quotes": [ "error", "double" ],
        "require-jsdoc": "error",
        "semi": [ "error", "always" ],
        "semi-spacing": [ "error", { "before": false, "after": true } ],
        "semi-style": [ "error", "last" ],
        "sort-keys": 0,
        "sort-vars": "error",
        "space-before-blocks": [ "error", "always" ],
        "space-before-function-paren": [ "error", "always" ],
        "space-in-parens": [ "error", "never" ],
        "space-infix-ops": "error",
        "space-unary-ops": "error",
        "spaced-comment": [ "error", "always" ],
        "switch-colon-spacing": [ "error", { "after": true, "before": false } ],
        "template-tag-spacing": [ "error", "always" ],
        "unicode-bom": 0,
        "wrap-regex": "error",

        "arrow-body-style": [ "error", "always" ],
        "arrow-parens": [ "error", "always" ],
        "arrow-spacing": ["error", { "before": true, "after": true } ],
        "constructor-super": "error",
        "generator-star-spacing": [ "error", { "before": true, "after": false } ],
        "no-class-assign": "error",
        "no-confusing-arrow": "error",
        "no-const-assign": "error",
        "no-dupe-class-members": "error",
        "no-duplicate-imports": "error",
        "no-new-symbol": "error",
        "no-restricted-imports": 0,
        "no-this-before-super": "error",
        "no-useless-computed-key": "error",
        "no-useless-constructor": "error",
        "no-useless-rename": "error",
        "no-var": "error",
        "object-shorthand": "error",
        "prefer-arrow-callback": "error",
        "prefer-const": "error",
        "prefer-destructuring": "error",
        "prefer-numeric-literals": "error",
        "prefer-rest-params": "error",
        "prefer-spread": "error",
        "prefer-template": 0,
        "require-yield": "error",
        "rest-spread-spacing": [ "error", "never" ],
        "sort-imports": "error",
        "symbol-description": "error",
        "template-curly-spacing": "error",
        "yield-star-spacing": [ "error", { "before": true, "after": false } ]

    }
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
require('../server.babel'); // babel registration (runtime transpilation for node)

var webpack = require('webpack');
var webpackConfig = require('./merge-configs');
var fs = require('fs');
// var outputStatsPath = './webpack-stats.json';

console.log('\nBuilding webpack bundle...');
webpack(webpackConfig, function(err, stats) {
  if(err) {
    console.log('Webpack build had fatal error:', err);
    return;
  }

  var options = {
    hash: true,
    version: true,
    timings: true,
    assets: true,
    chunks: false,
    colors: true
  }

  console.log('Webpack compile was successful.');

  var jsonStats = stats.toJson();
  if(jsonStats.errors.length > 0) {
    console.log('Webpack had errors.');
    options.errors = true;
  }
  if(jsonStats.warnings.length > 0) {
    console.log('Webpack had warnings.');
    options.warnings = true;
  }

  console.log(stats.toString(options));

  if(outputStatsPath) {
    fs.writeFile(outputStatsPath, JSON.stringify(stats.toJson()), function(err) {
      if(err) {
        return console.log(err);
      }

      console.log('Webpack output stats were saved to', outputStatsPath);
    });
  }
});
<commit_msg>build if buildStats boolean is true<commit_after>#!/usr/bin/env node
require('../server.babel'); // babel registration (runtime transpilation for node)

var webpack = require('webpack');
var webpackConfig = require('./merge-configs');
var fs = require('fs');
var buildStats = false;

console.log('\nBuilding webpack bundle...');
webpack(webpackConfig, function(err, stats) {
  if(err) {
    console.log('Webpack build had fatal error:', err);
    return;
  }

  var options = {
    hash: true,
    version: true,
    timings: true,
    assets: true,
    chunks: false,
    colors: true
  }

  console.log('Webpack compile was successful.');

  var jsonStats = stats.toJson();
  if(jsonStats.errors.length > 0) {
    console.log('Webpack had errors.');
    options.errors = true;
  }
  if(jsonStats.warnings.length > 0) {
    console.log('Webpack had warnings.');
    options.warnings = true;
  }

  console.log(stats.toString(options));

  if(buildStats) {
    fs.writeFile('./webpack-stats.json', JSON.stringify(stats.toJson()), function(err) {
      if(err) {
        return console.log(err);
      }

      console.log('Webpack output stats were saved to', outputStatsPath);
    });
  }
});
<|endoftext|>


<commit_before>(function () {
  "use strict";

  var Database, ItemDataSource, GroupDataSource;

  // Alternative typeof implementation yielding more meaningful results,
  // see http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
  function type(obj) {
    var typeString;

    typeString = Object.prototype.toString.call(obj);
    return typeString.substring(8, typeString.length - 1).toLowerCase();
  }

  function toPropertySet(object) {
    var key, propertySet = new Windows.Foundation.Collections.PropertySet();

    for (key in object) {
      if (object.hasOwnProperty(key)) {
        propertySet.insert(key, object[key]);
      }
    }

    return propertySet;
  }

  function prepareArgs(args) {
    args = args || [];
    return (args instanceof Array) ? args : toPropertySet(args);
  }

  function wrapComException(comException) {
    var resultCode = comException.number & 0xffff;

    return WinJS.Promise.wrapError({
      message: 'SQLite Error (Result Code ' + resultCode + ')',
      resultCode: resultCode
    });
  }

  function wrapDatabase(connection) {
    function callNative(funcName, sql, args, callback) {
      var preparedArgs = prepareArgs(args);

      if (preparedArgs instanceof Windows.Foundation.Collections.PropertySet) {
        return connection[funcName + "Map"](sql, preparedArgs, callback);
      }

      return connection[funcName + "Vector"](sql, preparedArgs, callback);
    }

    var that = {
      runAsync: function (sql, args) {
        return callNative('runAsync', sql, args).then(function () {
          return that;
        }, wrapComException);
      },
      oneAsync: function (sql, args) {
        return callNative('oneAsync', sql, args).then(function (row) {
          return row;
        }, wrapComException);
      },
      allAsync: function (sql, args) {
        return callNative('allAsync', sql, args).then(function (rows) {
          return rows;
        }, wrapComException);
      },
      eachAsync: function (sql, args, callback) {
        if (!callback && typeof args === 'function') {
          callback = args;
          args = undefined;
        }

        return callNative('eachAsync', sql, args, callback).then(function () {
          return that;
        }, wrapComException);
      },
      mapAsync: function (sql, args, callback) {
        if (!callback && typeof args === 'function') {
          callback = args;
          args = undefined;
        }

        var results = [];

        return that.eachAsync(sql, args, function (row) {
          results.push(callback(row));
        }).then(function () {
          return results;
        });
      },
      getLastInsertRowId: function () {
        return connection.getLastInsertRowId();
      },
      itemDataSource: function (sql, args, keyColumnName, groupKeyColumnName) {
        if (typeof args === 'string') {
          groupKeyColumnName = keyColumnName;
          keyColumnName = args;
          args = undefined;
        }

        return new ItemDataSource(that, sql, args, keyColumnName, groupKeyColumnName);
      },
      groupDataSource: function (sql, args, keyColumnName, sizeColumnName) {
        if (typeof args === 'string') {
          sizeColumnName = keyColumnName;
          keyColumnName = args;
          args = undefined;
        }

        return new GroupDataSource(that, sql, args, keyColumnName, sizeColumnName);
      },
      close: function () {
        connection.close();
      }
    };

    return that;
  }

  ItemDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource,
    function (db, sql, args, keyColumnName, groupKeyColumnName) {
      var dataAdapter = {
        getCount: function () {
          return db.oneAsync('SELECT COUNT(*) AS cnt FROM (' + sql + ')', args)
            .then(function (row) { return row.cnt; });
        },
        itemsFromIndex: function (requestIndex, countBefore, countAfter) {
          var items,
              limit = countBefore + 1 + countAfter,
              offset = requestIndex - countBefore;

          return db.mapAsync(
            'SELECT * FROM (' + sql + ') LIMIT ' + limit + ' OFFSET ' + offset,
            function (row) {
              var item = {
                key: row[keyColumnName].toString(),
                data: row
              };
              if (groupKeyColumnName) {
                item.groupKey = row[groupKeyColumnName].toString();
              }
              return item;
            }).then(function (items) {
              return {
                items: items,
                offset: countBefore,
                atEnd: items.length < limit
              };
            });
        }
      };

      this._baseDataSourceConstructor(dataAdapter);
    }
  );

  GroupDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource,
    function (db, sql, args, keyColumnName, sizeColumnName) {
      var dataAdapter = {
        _keyIndexMap: {},
        _ensureGroupsAsync: function () {
          if (dataAdapter._groups) {
            return WinJS.Promise.wrap();
          }

          var groupIndex = 0,
              firstItemIndex = 0;
          return db.mapAsync(sql, args, function (row) {
            var item = {
              key: row[keyColumnName].toString(),
              groupSize: row[sizeColumnName],
              firstItemIndexHint: firstItemIndex,
              data: row
            };

            dataAdapter._keyIndexMap[item.key] = groupIndex;
            groupIndex += 1;
            firstItemIndex += item.groupSize;

            return item;
          }).then(function(groups) {
            dataAdapter._groups = groups;
          });
        },
        getCount: function () {
          return dataAdapter._ensureGroupsAsync().then(function() {
            return dataAdapter._groups.length;
          });
        },
        itemsFromIndex: function (requestIndex, countBefore, countAfter) {
          return dataAdapter._ensureGroupsAsync().then(function() {
            return {
              items: dataAdapter._groups.slice(),
              offset: requestIndex,
              absoluteIndex: requestIndex,
              atStart: true,
              atEnd: true
            };
          });
        },
        itemsFromKey: function (key, countBefore, countAfter) {
          return dataAdapter._ensureGroupsAsync().then(function () {
            return dataAdapter.itemsFromIndex(dataAdapter._keyIndexMap[key], countBefore, countAfter);
          });
        }
      };

      this._baseDataSourceConstructor(dataAdapter);
    }
  );

  function openAsync(dbPath) {
    return SQLite3.Database.openAsync(dbPath).then(function (connection) {
      return wrapDatabase(connection);
    }, wrapComException);
  }

  WinJS.Namespace.define('SQLite3JS', {
    openAsync: openAsync
  });

}());
<commit_msg>Return rows as JavaScript objects<commit_after>(function () {
  "use strict";

  var Database, ItemDataSource, GroupDataSource;

  // Alternative typeof implementation yielding more meaningful results,
  // see http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
  function type(obj) {
    var typeString;

    typeString = Object.prototype.toString.call(obj);
    return typeString.substring(8, typeString.length - 1).toLowerCase();
  }

  function toObject(propertySet) {
    function toObjectImpl(propertySet) {
      var key, object = {};

      for (key in propertySet) {
        if (propertySet.hasOwnProperty(key)) {
          object[key] = propertySet[key];
        }
      }

      return object;
    }

    return propertySet ? toObjectImpl(propertySet) : null;
  }

  function toPropertySet(object) {
    var key, propertySet = new Windows.Foundation.Collections.PropertySet();

    for (key in object) {
      if (object.hasOwnProperty(key)) {
        propertySet.insert(key, object[key]);
      }
    }

    return propertySet;
  }

  function prepareArgs(args) {
    args = args || [];
    return (args instanceof Array) ? args : toPropertySet(args);
  }

  function wrapComException(comException) {
    var resultCode = comException.number & 0xffff;

    return WinJS.Promise.wrapError({
      message: 'SQLite Error (Result Code ' + resultCode + ')',
      resultCode: resultCode
    });
  }

  function wrapDatabase(connection) {
    function callNative(funcName, sql, args, callback) {
      var preparedArgs = prepareArgs(args);

      if (preparedArgs instanceof Windows.Foundation.Collections.PropertySet) {
        return connection[funcName + "Map"](sql, preparedArgs, callback);
      }

      return connection[funcName + "Vector"](sql, preparedArgs, callback);
    }

    var that = {
      runAsync: function (sql, args) {
        return callNative('runAsync', sql, args).then(function () {
          return that;
        }, wrapComException);
      },
      oneAsync: function (sql, args) {
        return callNative('oneAsync', sql, args).then(function (row) {
          return toObject(row);
        }, wrapComException);
      },
      allAsync: function (sql, args) {
        return callNative('allAsync', sql, args).then(function (rows) {
          return rows.map(toObject);
        }, wrapComException);
      },
      eachAsync: function (sql, args, callback) {
        if (!callback && typeof args === 'function') {
          callback = args;
          args = undefined;
        }

        return callNative('eachAsync', sql, args, function (row) {
          callback(toObject(row));
        }).then(function () {
          return that;
        }, wrapComException);
      },
      mapAsync: function (sql, args, callback) {
        if (!callback && typeof args === 'function') {
          callback = args;
          args = undefined;
        }

        var results = [];

        return that.eachAsync(sql, args, function (row) {
          results.push(callback(row));
        }).then(function () {
          return results;
        });
      },
      getLastInsertRowId: function () {
        return connection.getLastInsertRowId();
      },
      itemDataSource: function (sql, args, keyColumnName, groupKeyColumnName) {
        if (typeof args === 'string') {
          groupKeyColumnName = keyColumnName;
          keyColumnName = args;
          args = undefined;
        }

        return new ItemDataSource(that, sql, args, keyColumnName, groupKeyColumnName);
      },
      groupDataSource: function (sql, args, keyColumnName, sizeColumnName) {
        if (typeof args === 'string') {
          sizeColumnName = keyColumnName;
          keyColumnName = args;
          args = undefined;
        }

        return new GroupDataSource(that, sql, args, keyColumnName, sizeColumnName);
      },
      close: function () {
        connection.close();
      }
    };

    return that;
  }

  ItemDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource,
    function (db, sql, args, keyColumnName, groupKeyColumnName) {
      var dataAdapter = {
        getCount: function () {
          return db.oneAsync('SELECT COUNT(*) AS cnt FROM (' + sql + ')', args)
            .then(function (row) { return row.cnt; });
        },
        itemsFromIndex: function (requestIndex, countBefore, countAfter) {
          var items,
              limit = countBefore + 1 + countAfter,
              offset = requestIndex - countBefore;

          return db.mapAsync(
            'SELECT * FROM (' + sql + ') LIMIT ' + limit + ' OFFSET ' + offset,
            function (row) {
              var item = {
                key: row[keyColumnName].toString(),
                data: row
              };
              if (groupKeyColumnName) {
                item.groupKey = row[groupKeyColumnName].toString();
              }
              return item;
            }).then(function (items) {
              return {
                items: items,
                offset: countBefore,
                atEnd: items.length < limit
              };
            });
        }
      };

      this._baseDataSourceConstructor(dataAdapter);
    }
  );

  GroupDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource,
    function (db, sql, args, keyColumnName, sizeColumnName) {
      var dataAdapter = {
        _keyIndexMap: {},
        _ensureGroupsAsync: function () {
          if (dataAdapter._groups) {
            return WinJS.Promise.wrap();
          }

          var groupIndex = 0,
              firstItemIndex = 0;
          return db.mapAsync(sql, args, function (row) {
            var item = {
              key: row[keyColumnName].toString(),
              groupSize: row[sizeColumnName],
              firstItemIndexHint: firstItemIndex,
              data: row
            };

            dataAdapter._keyIndexMap[item.key] = groupIndex;
            groupIndex += 1;
            firstItemIndex += item.groupSize;

            return item;
          }).then(function(groups) {
            dataAdapter._groups = groups;
          });
        },
        getCount: function () {
          return dataAdapter._ensureGroupsAsync().then(function() {
            return dataAdapter._groups.length;
          });
        },
        itemsFromIndex: function (requestIndex, countBefore, countAfter) {
          return dataAdapter._ensureGroupsAsync().then(function() {
            return {
              items: dataAdapter._groups.slice(),
              offset: requestIndex,
              absoluteIndex: requestIndex,
              atStart: true,
              atEnd: true
            };
          });
        },
        itemsFromKey: function (key, countBefore, countAfter) {
          return dataAdapter._ensureGroupsAsync().then(function () {
            return dataAdapter.itemsFromIndex(dataAdapter._keyIndexMap[key], countBefore, countAfter);
          });
        }
      };

      this._baseDataSourceConstructor(dataAdapter);
    }
  );

  function openAsync(dbPath) {
    return SQLite3.Database.openAsync(dbPath).then(function (connection) {
      return wrapDatabase(connection);
    }, wrapComException);
  }

  WinJS.Namespace.define('SQLite3JS', {
    openAsync: openAsync
  });

}());
<|endoftext|>