<commit_before>'use strict';

var fs = require('fs');
var del = require('del');
var mkdirp = require('mkdirp');
var merge = require('merge2');
var assign = require('lodash.assign');
var series = require('stream-series');
var sequence = require('run-sequence');

var path = require("path");
var Builder = require('systemjs-builder');

var gulp = require('gulp');
var debug = require('gulp-debug');
var concat = require('gulp-concat');
var watch = require('gulp-watch');
var sourcemaps = require('gulp-sourcemaps');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var gutil = require('gulp-util');
var htmlmin = require('gulp-htmlmin');
var browsersync = require('browser-sync');
var cache = require('gulp-cached');
var addsrc = require('gulp-add-src');

var sass = require('gulp-sass');
var cssRebase = require('gulp-css-url-rebase');
var cssMin = require('gulp-minify-css');

var inject = require('gulp-inject');
var ts = require('gulp-typescript');
var tslint = require('gulp-tslint');
var source = require("vinyl-source-stream");
var buffer = require("vinyl-buffer");
var plumber = require('gulp-plumber');

var Config = require('./gulpfile.config');
var config = new Config();

var developmentMode = false;

var onError = function (err) {
    gutil.log(
        gutil.colors.red.bold('[ERROR:'+ err.plugin+']:'),
        gutil.colors.bgRed(err.message),
        gutil.colors.red.bold('in:'+err.fileName)
    );
    this.emit('end');
};

// ------------------------------------------------------------------
// clean
// ------------------------------------------------------------------
gulp.task('clean', function () {
    return del.sync([config.target]);
});

// ------------------------------------------------------------------
// Build Libraries
// ------------------------------------------------------------------

gulp.task('build:vendor', [], function () {
    var js = [];
    var css = [];
    config.vendor.forEach(function (elem) {
        if (elem.substr(-3) === ".js") {
            js.push(elem);
        } else if (elem.substr(-4) === ".css") {
            css.push(elem);
        } else {
            // TODO Warning 'unkown type'
        }
    });
    var streamJs = gulp.src(js)
        //.pipe(debug({title: "Including vendor JS:"}))
        .pipe(concat("vendor.js"))
        .pipe(gulp.dest(config.targetApp + "/vendor"));

    var streamCss = gulp.src(css)
        //.pipe(debug({title: "Including vendor CSS:"}))
        .pipe(concat("vendor.css"))
        .pipe(gulp.dest(config.targetApp + "/vendor"));

    var streamSystemJs = gulp.src(
        ["system-polyfills.js", "system.js"],
        {cwd: "node_modules/systemjs/dist"})
        .pipe(gulp.dest(config.targetApp + "/systemjs"));

    if (developmentMode) {
        var entryGenerated = "";
        entryGenerated += "if (!window.DISABLE_APP) {";
        entryGenerated += "System.config(";
        entryGenerated += JSON.stringify(config.systemJSConfig);
        entryGenerated += ");\n";
        entryGenerated += "System.import('" + config.systemImportMain + "');";
        entryGenerated += "}";
        mkdirp(config.targetApp + "/systemjs", function () {
            fs.writeFileSync(config.targetApp + "/systemjs/entry-generated.js", entryGenerated);
        });
    }

    return merge(streamJs, streamCss, streamSystemJs);
});

// ------------------------------------------------------------------
// Build HTML
// ------------------------------------------------------------------

gulp.task('build:html', [], function () {
    var s = gulp.src(config.htmlFiles, {cwd: "src"});
    s = s.pipe(cache("html"));
    //s = s.pipe(debug({title: "HTML:"}));
    s = s.pipe(gulp.dest(config.targetApp));
    s = s.pipe(inject(series(
        gulp.src(
            ["vendor/**/*.js", "vendor/**/*.css"],
            {read: false, cwd: config.targetApp}),

        gulp.src(
            ["systemjs/system.js", "systemjs/system-polyfills.js", "systemjs/entry-generated.js"],
            {read: false, cwd: config.targetApp}),

        gulp.src(
            ['**/*.css', "!vendor/**", "!systemjs/**"],
            {read: false, cwd: config.targetApp})
    ), {relative: true, quiet: true}));
    s = s.pipe(htmlmin({
        removeComments: true,
        collapseWhitespace: true,
        conservativeCollapse: true
    }));
    s = s.on('error', onError);
    s = s.pipe(gulp.dest(config.targetApp));
    s = s.pipe(browsersync.stream());

    return s;
});

// ------------------------------------------------------------------
// Build Copy files
// ------------------------------------------------------------------

gulp.task('build:copy', function () {
    var copyStreams = [];
    for (var i = 0; i < config.copyFiles.length; i++) {
        var source = config.copyFiles[i][0];
        var dest = config.copyFiles[i][1];
        copyStreams.push(
            gulp.src(source)
                .pipe(cache("copy" + i))
                .pipe(debug({title: "Copy:"}))
                .pipe(gulp.dest(config.targetApp + "/" + dest)));
    }
    return merge(copyStreams);
});

// ------------------------------------------------------------------
// Build CSS
// ------------------------------------------------------------------

function buildCss(useCache) {
    var scss = gulp.src(config.scssFiles, {nosort: true, cwd: "src"});
    scss = useCache ? scss.pipe(cache("scss")) : scss;
    scss = developmentMode ? scss.pipe(sourcemaps.init()) : scss;
    scss = scss.pipe(sass().on('error', sass.logError));
    scss = developmentMode ? scss.pipe(sourcemaps.write()) : scss;
    scss = developmentMode ? scss.pipe(gulp.dest(config.targetApp)) : scss;

    var css = gulp.src(config.cssFiles, {nosort: true, cwd: "src"});
    css = css.pipe(cache("css"));

    var both = merge(scss, css);
    both = both.pipe(debug({title: "CSS:"}));
    both = !developmentMode ? both.pipe(cssRebase()) : both;
    both = !developmentMode ? both.pipe(cssMin()) : both;
    both = !developmentMode ? both.pipe(concat("___.css")) : both;
    both = both.pipe(gulp.dest(config.targetApp));

    both = both.pipe(browsersync.stream());

    return both;
}

gulp.task('build:css', function () {
    return buildCss(true);
});

gulp.task('build:cssNoCache', function () {
    return buildCss(false);
});

// ------------------------------------------------------------------
// Build JavaScript
// ------------------------------------------------------------------

gulp.task('build:js', function () {
    var s = gulp.src(config.javaScriptFiles, {nosort: true, cwd: "src"});
    s = s.pipe(cache("js"));
    s = developmentMode ? s.pipe(sourcemaps.init()) : s;
    s = s.pipe(ngAnnotate());
    s = s.pipe(uglify());
    s = developmentMode ? s.pipe(sourcemaps.write()) : s;
    //s = s.pipe(debug({title: "JavaScript:"}));
    s = s.pipe(gulp.dest(config.targetJs));
    s = s.pipe(browsersync.stream());
    return s;
});

// ------------------------------------------------------------------
// Build TypeScript
// ------------------------------------------------------------------

var tsProject = ts.createProject('tsconfig.json');

gulp.task('build:ts', function () {
    if (developmentMode) {
        gulp.src(config.typeScriptLintFiles, {cwd: "src"})
            .pipe(cache("lint:ts"))
            .pipe(tslint()).pipe(tslint.report('prose', {emitError: false}));
    }

    var tsResult = gulp.src(config.typeScriptFiles, {cwd: "src"});

    tsResult = tsResult.pipe(addsrc(config.typeScriptDefinitions));
    tsResult = developmentMode ? tsResult.pipe(sourcemaps.init()) : tsResult;
    tsResult = tsResult.pipe(ts(tsProject, undefined, ts.reporter.longReporter()));

    var tsResultJs = tsResult.js;
    tsResultJs = tsResultJs.pipe(cache("ts"));
    tsResultJs = tsResultJs.pipe(debug({title: "TypeScript:"}));
    tsResultJs = tsResultJs.pipe(ngAnnotate());
    tsResultJs = tsResultJs.pipe(uglify());
    tsResultJs = tsResultJs.pipe(browsersync.stream());

    if (developmentMode) {
        tsResultJs = tsResultJs.pipe(sourcemaps.write());
    }

    return merge([
        tsResult.dts.pipe(gulp.dest(config.target + "/dts")),
        tsResultJs.pipe(gulp.dest(config.targetJs + "/"))
    ]);
});

// ------------------------------------------------------------------
// Build Bundle
// ------------------------------------------------------------------

gulp.task('bundle', [], function (done) {

    config.systemJSConfig.baseURL = config.targetJs + "/" + config.systemJSConfig.baseURL;

    new Builder(config.systemJSConfig)
        .buildSFX(config.systemImportMain, config.targetApp + "/systemjs/entry-generated.js", {minify: true})
        .then(function () {
            done();
        })
        .catch(function (err) {
            console.log('Build error');
            console.log(err);
        });
});

// ------------------------------------------------------------------
// BrowserSync
// ------------------------------------------------------------------

gulp.task('browsersync', ["dev"], function () {
    return browsersync(config.browserSyncOptions);
});

// ------------------------------------------------------------------
// Start Tasks
// ------------------------------------------------------------------

gulp.task('watch', ["browsersync"], function () {
    developmentMode = true;
    gulp.watch(config.typeScriptFiles, {cwd: "src"}, ["build:ts"]);
    gulp.watch(config.javaScriptFiles, {cwd: "src"}, ["build:js"]);
    gulp.watch(config.htmlFiles, {cwd: "src"}, ["build:html"]);
    gulp.watch(config.scssFiles, {cwd: "src"}, ["build:css"]);
    gulp.watch(config.scssRebuildAllFiles, {cwd: "src"}, ["build:cssNoCache"]);

    for (var i = 0; i < config.copyFiles.length; i++) {
        var source = config.copyFiles[i][0];
        gulp.watch(source, {cwd: "."}, ["build:copy"]);
    }
});

gulp.task('dev', function (callback) {

    config.targetJs = config.targetApp;

    developmentMode = true;
    sequence(
        "clean",
        ["build:vendor", "build:copy", "build:js", "build:ts", "build:css"],
        "build:html",
        callback);
});

gulp.task('dist', function (callback) {

    config.targetJs = config.target + "/tmpJs";

    sequence(
        "clean",
        ["build:vendor", "build:copy", "build:js", "build:ts", "build:css"],
        "bundle",
        "build:html",
        callback);
});

gulp.task('default', ["watch"]);
<commit_msg>small improvements<commit_after>'use strict';

var fs = require('fs');
var del = require('del');
var mkdirp = require('mkdirp');
var merge = require('merge2');
var assign = require('lodash.assign');
var series = require('stream-series');
var sequence = require('run-sequence');

var path = require("path");
var Builder = require('systemjs-builder');

var gulp = require('gulp');
var debug = require('gulp-debug');
var concat = require('gulp-concat');
var watch = require('gulp-watch');
var sourcemaps = require('gulp-sourcemaps');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var gutil = require('gulp-util');
var htmlmin = require('gulp-htmlmin');
var browsersync = require('browser-sync');
var cache = require('gulp-cached');
var addsrc = require('gulp-add-src');

var sass = require('gulp-sass');
var cssRebase = require('gulp-css-url-rebase');
var cssMin = require('gulp-minify-css');

var inject = require('gulp-inject');
var ts = require('gulp-typescript');
var tslint = require('gulp-tslint');
var source = require("vinyl-source-stream");
var buffer = require("vinyl-buffer");
var plumber = require('gulp-plumber');

var Config = require('./gulpfile.config');
var config = new Config();

var developmentMode = false;

var onError = function (err) {
    gutil.log(
        gutil.colors.red.bold('[ERROR:' + err.plugin + ']:'),
        gutil.colors.bgRed(err.message),
        gutil.colors.red.bold('in:' + err.fileName)
    );
    this.emit('end');
};

// ------------------------------------------------------------------
// clean
// ------------------------------------------------------------------
gulp.task('clean', function () {
    try {
        del.sync([config.target]);
    } catch (e) {
        if (developmentMode) {
            console.log(e);
        }
        else {
            throw e;
        }
    }
});

// ------------------------------------------------------------------
// Build Libraries
// ------------------------------------------------------------------

gulp.task('build:vendor', [], function () {
    var js = [];
    var css = [];
    config.vendor.forEach(function (elem) {
        if (elem.substr(-3) === ".js") {
            js.push(elem);
        } else if (elem.substr(-4) === ".css") {
            css.push(elem);
        } else {
            // TODO Warning 'unkown type'
        }
    });
    var streamJs = gulp.src(js)
        //.pipe(debug({title: "Including vendor JS:"}))
        .pipe(concat("vendor.js"))
        .pipe(gulp.dest(config.targetApp + "/vendor"));

    var streamCss = gulp.src(css)
        //.pipe(debug({title: "Including vendor CSS:"}))
        .pipe(concat("vendor.css"))
        .pipe(gulp.dest(config.targetApp + "/vendor"));

    var streamSystemJs = gulp.src(
        ["system-polyfills.js", "system.js"],
        {cwd: "node_modules/systemjs/dist"})
        .pipe(gulp.dest(config.targetApp + "/systemjs"));

    if (developmentMode) {
        var entryGenerated = "";
        entryGenerated += "if (!window.DISABLE_APP) {";
        entryGenerated += "System.config(";
        entryGenerated += JSON.stringify(config.systemJSConfig);
        entryGenerated += ");\n";
        entryGenerated += "System.import('" + config.systemImportMain + "');";
        entryGenerated += "}";
        mkdirp(config.targetApp + "/systemjs", function () {
            fs.writeFileSync(config.targetApp + "/systemjs/entry-generated.js", entryGenerated);
        });
    }

    return merge(streamJs, streamCss, streamSystemJs);
});

// ------------------------------------------------------------------
// Build HTML
// ------------------------------------------------------------------

gulp.task('build:html', [], function () {
    var s = gulp.src(config.htmlFiles, {cwd: "src"});
    s = s.pipe(cache("html"));
    //s = s.pipe(debug({title: "HTML:"}));
    s = s.pipe(gulp.dest(config.targetApp));
    s = s.pipe(inject(series(
        gulp.src(
            ["vendor/**/*.js", "vendor/**/*.css"],
            {read: false, cwd: config.targetApp}),

        gulp.src(
            ["systemjs/system.js", "systemjs/system-polyfills.js", "systemjs/entry-generated.js"],
            {read: false, cwd: config.targetApp}),

        gulp.src(
            ['**/*.css', "!vendor/**", "!systemjs/**"],
            {read: false, cwd: config.targetApp})
    ), {relative: true, quiet: true}));
    s = s.pipe(htmlmin({
        removeComments: true,
        collapseWhitespace: true,
        conservativeCollapse: true
    }));
    s = s.on('error', onError);
    s = s.pipe(gulp.dest(config.targetApp));
    s = s.pipe(browsersync.stream());

    return s;
});

// ------------------------------------------------------------------
// Build Copy files
// ------------------------------------------------------------------

gulp.task('build:copy', function () {
    var copyStreams = [];
    for (var i = 0; i < config.copyFiles.length; i++) {
        var source = config.copyFiles[i][0];
        var dest = config.copyFiles[i][1];
        copyStreams.push(
            gulp.src(source)
                .pipe(cache("copy" + i))
                //.pipe(debug({title: "Copy:"}))
                .pipe(gulp.dest(config.targetApp + "/" + dest)));
    }
    return merge(copyStreams);
});

// ------------------------------------------------------------------
// Build CSS
// ------------------------------------------------------------------

function buildCss(useCache) {
    var scss = gulp.src(config.scssFiles, {nosort: true, cwd: "src"});
    scss = useCache ? scss.pipe(cache("scss")) : scss;
    scss = scss.pipe(debug({title: "SCSS:"}));
    scss = developmentMode ? scss.pipe(sourcemaps.init()) : scss;
    scss = scss.pipe(sass().on('error', sass.logError));
    scss = developmentMode ? scss.pipe(sourcemaps.write()) : scss;
    scss = developmentMode ? scss.pipe(gulp.dest(config.targetApp)) : scss;

    var css = gulp.src(config.cssFiles, {nosort: true, cwd: "src"});
    css = css.pipe(debug({title: "CSS:"}));
    css = css.pipe(cache("css"));

    var both = merge(scss, css);
    both = !developmentMode ? both.pipe(cssRebase()) : both;
    both = !developmentMode ? both.pipe(cssMin()) : both;
    both = !developmentMode ? both.pipe(concat("___.css")) : both;
    both = both.pipe(gulp.dest(config.targetApp));

    both = both.pipe(browsersync.stream());

    return both;
}

gulp.task('build:css', function () {
    return buildCss(true);
});

gulp.task('build:cssNoCache', function () {
    return buildCss(false);
});

// ------------------------------------------------------------------
// Build JavaScript
// ------------------------------------------------------------------

gulp.task('build:js', function () {
    var s = gulp.src(config.javaScriptFiles, {nosort: true, cwd: "src"});
    s = s.pipe(cache("js"));
    s = developmentMode ? s.pipe(sourcemaps.init()) : s;
    s = s.pipe(ngAnnotate());
    s = s.pipe(uglify());
    s = developmentMode ? s.pipe(sourcemaps.write()) : s;
    //s = s.pipe(debug({title: "JavaScript:"}));
    s = s.pipe(gulp.dest(config.targetJs));
    s = s.pipe(browsersync.stream());
    return s;
});

// ------------------------------------------------------------------
// Build TypeScript
// ------------------------------------------------------------------

var tsProject = ts.createProject('tsconfig.json');

gulp.task('build:ts', function () {
    if (developmentMode) {
        gulp.src(config.typeScriptLintFiles, {cwd: "src"})
            .pipe(cache("lint:ts"))
            .pipe(tslint()).pipe(tslint.report('prose', {emitError: false}));
    }

    var tsResult = gulp.src(config.typeScriptFiles, {cwd: "src"});

    tsResult = tsResult.pipe(addsrc(config.typeScriptDefinitions));
    tsResult = developmentMode ? tsResult.pipe(sourcemaps.init()) : tsResult;
    tsResult = tsResult.pipe(ts(tsProject, undefined, ts.reporter.longReporter()));

    var tsResultJs = tsResult.js;
    tsResultJs = tsResultJs.pipe(cache("ts"));
    tsResultJs = tsResultJs.pipe(debug({title: "TypeScript:"}));
    tsResultJs = tsResultJs.pipe(ngAnnotate());
    tsResultJs = tsResultJs.pipe(uglify());
    tsResultJs = tsResultJs.pipe(browsersync.stream());

    if (developmentMode) {
        tsResultJs = tsResultJs.pipe(sourcemaps.write());
    }

    return merge([
        tsResult.dts.pipe(gulp.dest(config.target + "/dts")),
        tsResultJs.pipe(gulp.dest(config.targetJs + "/"))
    ]);
});

// ------------------------------------------------------------------
// Build Bundle
// ------------------------------------------------------------------

gulp.task('bundle', [], function (done) {

    config.systemJSConfig.baseURL = config.targetJs + "/" + config.systemJSConfig.baseURL;

    new Builder(config.systemJSConfig)
        .buildSFX(config.systemImportMain, config.targetApp + "/systemjs/entry-generated.js", {minify: true})
        .then(function () {
            done();
        })
        .catch(function (err) {
            console.log('Build error');
            console.log(err);
        });
});

// ------------------------------------------------------------------
// BrowserSync
// ------------------------------------------------------------------

gulp.task('browsersync', ["dev"], function () {
    return browsersync(config.browserSyncOptions);
});

// ------------------------------------------------------------------
// Start Tasks
// ------------------------------------------------------------------

gulp.task('watch', ["browsersync"], function () {
    developmentMode = true;
    gulp.watch(config.typeScriptFiles, {cwd: "src"}, ["build:ts"]);
    gulp.watch(config.javaScriptFiles, {cwd: "src"}, ["build:js"]);
    gulp.watch(config.htmlFiles, {cwd: "src"}, ["build:html"]);
    gulp.watch(config.scssFiles, {cwd: "src"}, ["build:css"]);
    gulp.watch(config.scssRebuildAllFiles, {cwd: "src"}, ["build:cssNoCache"]);

    for (var i = 0; i < config.copyFiles.length; i++) {
        var source = config.copyFiles[i][0];
        gulp.watch(source, {cwd: "."}, ["build:copy"]);
    }
});

gulp.task('dev', function (callback) {

    config.targetJs = config.targetApp;

    developmentMode = true;
    sequence(
        "clean",
        ["build:vendor", "build:copy", "build:js", "build:ts", "build:css"],
        "build:html",
        callback);
});

gulp.task('dist', function (callback) {

    config.targetJs = config.target + "/tmpJs";

    sequence(
        "clean",
        ["build:vendor", "build:copy", "build:js", "build:ts", "build:css"],
        "bundle",
        "build:html",
        callback);
});

gulp.task('default', ["watch"]);
<|endoftext|>


<commit_before>import _map from 'lodash/map';
import _find from 'lodash/find';
import _uniq from 'lodash/uniq';
import _filter from 'lodash/filter';
import _flatten from 'lodash/flatten';
import _cloneDeep from 'lodash/cloneDeep';
import _findIndex from 'lodash/findIndex';
import DataTableSource from './source/DataTableSource';
import { DataAnalytics, ModalChart } from '@entrylabs/tool';

class DataTable {
    #tables = [];
    #view;
    modal;
    selected;

    get tables() {
        return this.#tables;
    }

    get dataTables() {
        return _map(this.#tables, ({ id, fields, chart, name, origin, summary }) => ({
            id,
            name,
            summary,
            chart: _cloneDeep(chart),
            table: [[...fields], ..._cloneDeep(origin)],
        }));
    }

    constructor() {
        this.#generateView();
    }

    removeAllBlocks() {
        const { blocks } = EntryStatic.getAllBlocks().find(
            ({ category }) => category === 'analysis'
        );
        blocks.forEach((blockType) => {
            Entry.Utils.removeBlockByType(blockType);
        });
        this.banAllBlock();
        this.clear();
    }

    banAllBlock() {
        Entry.playground.blockMenu.banClass('analysis');
    }

    unbanBlock() {
        Entry.playground.blockMenu.unbanClass('analysis');
    }

    getTables(blockList = []) {
        return _uniq(
            _flatten(
                blockList
                    .filter((block) => {
                        const { _schema = {}, data = {} } = block || {};
                        if (!data.type) {
                            return false;
                        }
                        const { isFor, isNotFor = [] } = _schema;
                        const [key] = isNotFor;
                        return key && isFor && key === 'analysis';
                    })
                    .map((block) => {
                        const { params = [] } = block.data || {};
                        return params.filter((param) => {
                            if (typeof param !== 'string') {
                                return false;
                            }
                            return _find(this.#tables, { id: param });
                        });
                    })
            )
        ).map((tableId) => {
            const table = this.getSource(tableId);
            return table.toJSON();
        });
    }

    getSource(id) {
        if (!id) {
            console.warn('empty argument');
            return null;
        }
        return _find(this.#tables, { id });
    }

    getIndex({ id }) {
        if (!id) {
            console.warn('empty argument');
            return null;
        }
        return _findIndex(this.#tables, { id });
    }

    addSource(table) {
        let data = table || { name: Lang.Workspace.data_table };
        data.name = Entry.getOrderedName(data.name, this.#tables, 'name');

        this.#tables.push(table instanceof DataTableSource ? table : new DataTableSource(table));
        this.hide();
        this.show({ list: this.dataTables, selectedIndex: this.dataTables.length - 1 });
    }

    addSources(tables = []) {
        const dataTableSources = _map(tables, (table) =>
            table instanceof DataTableSource ? table : new DataTableSource(table)
        );
        this.#tables.push(...dataTableSources);
        this.hide();
        this.show({ list: this.dataTables, selectedIndex: this.dataTables.length - 1 });
    }

    changeItemPosition(start, end) {
        if (this.#tables.length) {
            this.#tables.splice(end, 0, this.#tables.splice(start, 1)[0]);
        }
    }

    setSource(selected) {
        const { chart, table, name, id } = selected;
        const source = this.getSource(id);
        if (source) {
            source.modal = null;
            source.setArray({
                name,
                chart,
                fields: table[0],
                data: table.slice(1),
            });
            source.updated = new Date();
        } else {
            const newSource = new DataTableSource({
                chart,
                data: table.slice(1),
                fields: table[0],
                name,
            });
            this.#tables.push(newSource);
            selected.id = newSource.id;
        }
    }

    saveTable = ({ selected }) => {
        this.setSource(selected);
        Entry.playground.reloadPlayground();
    };

    removeTable = (index) => {
        this.#tables = _filter(this.#tables, (__, tIndex) => index !== tIndex);
    };

    show(data) {
        if (!this.dataAnalytics) {
            this.#generateView();
        }
        this.dataAnalytics.show(
            data || { selectedIndex: this.#tables.legnth - 1, list: this.dataTables }
        );
    }

    hide() {
        this.dataAnalytics && this.dataAnalytics.hide();
        if (this.#tables.length) {
            this.unbanBlock();
        } else {
            this.banAllBlock();
        }
        Entry.playground.reloadPlayground();
        Entry.playground.refreshPlayground();
        Entry.dispatchEvent('dismissModal');
    }

    #generateView() {
        const view = document.createElement('div');
        view.className = 'table-modal';
        document.body.appendChild(view);
        this.dataAnalytics = new DataAnalytics({ container: view, data: {}, isShow: false })
            .on('submit', this.saveTable)
            .on('alert', ({ message, title = Lang.DataAnalytics.max_row_count_error_title }) =>
                entrylms.alert(message, title)
            )
            .on('toast', (message) => {
                const { title, content } = message;
                Entry.toast.alert(title, content);
            })
            .on('close', async () => {
                this.hide();
            })
            .on('addTable', () => {
                Entry.dispatchEvent('openTableManager');
            })
            .on('removeTable', this.removeTable);
    }

    getTableJSON() {
        return this.tables.filter(_.identity).map((v) => (v.toJSON ? v.toJSON() : v));
    }

    setTables(tables = []) {
        tables.forEach((table) => {
            let data = table || { name: Lang.Workspace.data_table };
            data.name = Entry.getOrderedName(data.name, this.#tables, 'name');
            const isDataTableSource = data instanceof DataTableSource;
            this.#tables.push(isDataTableSource ? data : new DataTableSource(data));
        });

        tables.length && this.refreshPlayground();
    }

    refreshPlayground() {
        const isWorkspace = Entry.type === 'workspace';
        if (isWorkspace) {
            this.unbanBlock();
            Entry.playground.reloadPlayground();
            Entry.playground.refreshPlayground();
        }
    }

    showChart(tableId, chartIndex = 0) {
        this.closeChart();
        const source = this.getSource(tableId);
        if (!source) {
            console.log(`not exist souce, table id: ${tableId}`);
            return;
        }
        if (!source.modal) {
            source.modal = this.createChart(source, chartIndex);
        }
        source.forceApply();
        source.modal.show({ chartIndex });
        this.modal = source.modal;
    }

    closeChart() {
        if (this.modal && this.modal.isShow) {
            this.modal.hide();
        }
    }

    createChart(source, chartIndex = 0) {
        const { chart = [], fields, rows } = source;
        const container = Entry.Dom('div', {
            class: 'entry-table-chart',
            parent: $('body'),
        })[0];
        return new ModalChart({
            data: {
                chartIndex,
                source: { fields, origin: rows, chart },
                togglePause: () => Entry.engine.togglePause(),
                stop: () => Entry.engine.toggleStop(),
                isIframe: self !== top,
            },
            container,
        });
    }

    clear() {
        this.#tables = [];
        this.modal = null;
    }
}

export default new DataTable();
<commit_msg>let to const<commit_after>import _map from 'lodash/map';
import _find from 'lodash/find';
import _uniq from 'lodash/uniq';
import _filter from 'lodash/filter';
import _flatten from 'lodash/flatten';
import _cloneDeep from 'lodash/cloneDeep';
import _findIndex from 'lodash/findIndex';
import DataTableSource from './source/DataTableSource';
import { DataAnalytics, ModalChart } from '@entrylabs/tool';

class DataTable {
    #tables = [];
    #view;
    modal;
    selected;

    get tables() {
        return this.#tables;
    }

    get dataTables() {
        return _map(this.#tables, ({ id, fields, chart, name, origin, summary }) => ({
            id,
            name,
            summary,
            chart: _cloneDeep(chart),
            table: [[...fields], ..._cloneDeep(origin)],
        }));
    }

    constructor() {
        this.#generateView();
    }

    removeAllBlocks() {
        const { blocks } = EntryStatic.getAllBlocks().find(
            ({ category }) => category === 'analysis'
        );
        blocks.forEach((blockType) => {
            Entry.Utils.removeBlockByType(blockType);
        });
        this.banAllBlock();
        this.clear();
    }

    banAllBlock() {
        Entry.playground.blockMenu.banClass('analysis');
    }

    unbanBlock() {
        Entry.playground.blockMenu.unbanClass('analysis');
    }

    getTables(blockList = []) {
        return _uniq(
            _flatten(
                blockList
                    .filter((block) => {
                        const { _schema = {}, data = {} } = block || {};
                        if (!data.type) {
                            return false;
                        }
                        const { isFor, isNotFor = [] } = _schema;
                        const [key] = isNotFor;
                        return key && isFor && key === 'analysis';
                    })
                    .map((block) => {
                        const { params = [] } = block.data || {};
                        return params.filter((param) => {
                            if (typeof param !== 'string') {
                                return false;
                            }
                            return _find(this.#tables, { id: param });
                        });
                    })
            )
        ).map((tableId) => {
            const table = this.getSource(tableId);
            return table.toJSON();
        });
    }

    getSource(id) {
        if (!id) {
            console.warn('empty argument');
            return null;
        }
        return _find(this.#tables, { id });
    }

    getIndex({ id }) {
        if (!id) {
            console.warn('empty argument');
            return null;
        }
        return _findIndex(this.#tables, { id });
    }

    addSource(table) {
        let data = table || { name: Lang.Workspace.data_table };
        data.name = Entry.getOrderedName(data.name, this.#tables, 'name');

        this.#tables.push(table instanceof DataTableSource ? table : new DataTableSource(table));
        this.hide();
        this.show({ list: this.dataTables, selectedIndex: this.dataTables.length - 1 });
    }

    addSources(tables = []) {
        const dataTableSources = _map(tables, (table) =>
            table instanceof DataTableSource ? table : new DataTableSource(table)
        );
        this.#tables.push(...dataTableSources);
        this.hide();
        this.show({ list: this.dataTables, selectedIndex: this.dataTables.length - 1 });
    }

    changeItemPosition(start, end) {
        if (this.#tables.length) {
            this.#tables.splice(end, 0, this.#tables.splice(start, 1)[0]);
        }
    }

    setSource(selected) {
        const { chart, table, name, id } = selected;
        const source = this.getSource(id);
        if (source) {
            source.modal = null;
            source.setArray({
                name,
                chart,
                fields: table[0],
                data: table.slice(1),
            });
            source.updated = new Date();
        } else {
            const newSource = new DataTableSource({
                chart,
                data: table.slice(1),
                fields: table[0],
                name,
            });
            this.#tables.push(newSource);
            selected.id = newSource.id;
        }
    }

    saveTable = ({ selected }) => {
        this.setSource(selected);
        Entry.playground.reloadPlayground();
    };

    removeTable = (index) => {
        this.#tables = _filter(this.#tables, (__, tIndex) => index !== tIndex);
    };

    show(data) {
        if (!this.dataAnalytics) {
            this.#generateView();
        }
        this.dataAnalytics.show(
            data || { selectedIndex: this.#tables.legnth - 1, list: this.dataTables }
        );
    }

    hide() {
        this.dataAnalytics && this.dataAnalytics.hide();
        if (this.#tables.length) {
            this.unbanBlock();
        } else {
            this.banAllBlock();
        }
        Entry.playground.reloadPlayground();
        Entry.playground.refreshPlayground();
        Entry.dispatchEvent('dismissModal');
    }

    #generateView() {
        const view = document.createElement('div');
        view.className = 'table-modal';
        document.body.appendChild(view);
        this.dataAnalytics = new DataAnalytics({ container: view, data: {}, isShow: false })
            .on('submit', this.saveTable)
            .on('alert', ({ message, title = Lang.DataAnalytics.max_row_count_error_title }) =>
                entrylms.alert(message, title)
            )
            .on('toast', (message) => {
                const { title, content } = message;
                Entry.toast.alert(title, content);
            })
            .on('close', async () => {
                this.hide();
            })
            .on('addTable', () => {
                Entry.dispatchEvent('openTableManager');
            })
            .on('removeTable', this.removeTable);
    }

    getTableJSON() {
        return this.tables.filter(_.identity).map((v) => (v.toJSON ? v.toJSON() : v));
    }

    setTables(tables = []) {
        tables.forEach((table) => {
            const data = table || { name: Lang.Workspace.data_table };
            data.name = Entry.getOrderedName(data.name, this.#tables, 'name');
            const isDataTableSource = data instanceof DataTableSource;
            this.#tables.push(isDataTableSource ? data : new DataTableSource(data));
        });

        tables.length && this.refreshPlayground();
    }

    refreshPlayground() {
        const isWorkspace = Entry.type === 'workspace';
        if (isWorkspace) {
            this.unbanBlock();
            Entry.playground.reloadPlayground();
            Entry.playground.refreshPlayground();
        }
    }

    showChart(tableId, chartIndex = 0) {
        this.closeChart();
        const source = this.getSource(tableId);
        if (!source) {
            console.log(`not exist souce, table id: ${tableId}`);
            return;
        }
        if (!source.modal) {
            source.modal = this.createChart(source, chartIndex);
        }
        source.forceApply();
        source.modal.show({ chartIndex });
        this.modal = source.modal;
    }

    closeChart() {
        if (this.modal && this.modal.isShow) {
            this.modal.hide();
        }
    }

    createChart(source, chartIndex = 0) {
        const { chart = [], fields, rows } = source;
        const container = Entry.Dom('div', {
            class: 'entry-table-chart',
            parent: $('body'),
        })[0];
        return new ModalChart({
            data: {
                chartIndex,
                source: { fields, origin: rows, chart },
                togglePause: () => Entry.engine.togglePause(),
                stop: () => Entry.engine.toggleStop(),
                isIframe: self !== top,
            },
            container,
        });
    }

    clear() {
        this.#tables = [];
        this.modal = null;
    }
}

export default new DataTable();
<|endoftext|>


<commit_before>var Poll = {
	reset: function (roomId) {
		Poll[roomId] = {
			question: undefined,
			optionList: [],
			options: {},
			display: '',
			topOption: ''
		};
	},

	splint: function (target) {
		var parts = target.split(',');
		var len = parts.length;
		while (len--) {
			parts[len] = parts[len].trim();
		}
		return parts;
	}
};

for (var id in Rooms.rooms) {
	if (Rooms.rooms[id].type === 'chat' && !Poll[id]) {
		Poll[id] = {};
		Poll.reset(id);
	}
}

exports.commands = {
	poll: function (target, room, user) {
		if (!this.can('broadcast', null, room)) return false;
		if (!Poll[room.id]) Poll.reset(room.id);
		if (Poll[room.id].question) return this.sendReply("There is currently a poll going on already.");
		if (!this.canTalk()) return;

		var options = Poll.splint(target);
		if (options.length < 3) return this.parse('/help poll');

		var question = options.shift();

		options = options.join(',').toLowerCase().split(',');

		Poll[room.id].question = question;
		Poll[room.id].optionList = options;

		var pollOptions = '';
		var start = 0;
		while (start < Poll[room.id].optionList.length) {
			pollOptions += '<button name="send" value="/vote ' + Tools.escapeHTML(Poll[room.id].optionList[start]) + '">' + Tools.escapeHTML(Poll[room.id].optionList[start]) + '</button> ';
			start++;
		}
		Poll[room.id].display = '
' + Tools.escapeHTML(Poll[room.id].question) + '  /vote OPTION
Poll started by ' + user.name + '

    ' + pollOptions;
		room.add('|raw|
' + Poll[room.id].display + '
');
	},

	pollhelp: ["/poll [question], [option 1], [option 2]... - Create a poll where users can vote on an option."],
	endpoll: function (target, room, user) {
		if (!this.can('broadcast', null, room)) return false;
		if (!Poll[room.id]) Poll.reset(room.id);
		if (!Poll[room.id].question) return this.sendReply("There is no poll to end in this room.");

		var votes = Object.keys(Poll[room.id].options).length;

		if (votes === 0) {
			Poll.reset(room.id);
			return room.add('|raw|
The poll was canceled because of lack of voters.
');
		}

		var options = {};

		for (var l in Poll[room.id].optionList) {
			options[Poll[room.id].optionList[l]] = 0;
		}

		for (var o in Poll[room.id].options) {
			options[Poll[room.id].options[o]]++;
		}

		var data = [];
		for (var i in options) {
			data.push([i, options[i]]);
		}
		data.sort(function (a, b) {
			return a[1] - b[1];
		});

		var results = '';
		var len = data.length;
		var topOption = data[len - 1][0];
		while (len--) {
			if (data[len][1] > 0) {
				results += '• ' + data[len][0] + ' - ' + Math.floor(data[len][1] / votes * 100) + '% (' + data[len][1] + ')
';
			}
		}
		room.add('|raw|

Results to "' + Poll[room.id].question + '"
Poll ended by ' + user.name + '

' + results + '
');
		Poll.reset(room.id);
		Poll[room.id].topOption = topOption;
	},

	elimtour: 'etour',
	etour: function (target, room, user) {
		if (!this.can('broadcast', null, room)) return;
		this.parse('/tour new ' + target + ', elimination');
	},

	roundrobintour: 'rtour',
	rtour: function (target, room, user) {
		if (!this.can('broadcast', null, room)) return;
		this.parse('/tour new ' + target + ', roundrobin');
	},

	pollr: 'pollremind',
	pollremind: function (target, room, user) {
		if (!Poll[room.id]) Poll.reset(room.id);
		if (!Poll[room.id].question) return this.sendReply("There is no poll currently going on in this room.");
		if (!this.canBroadcast()) return;
		this.sendReplyBox(Poll[room.id].display);
	},

	tournamentpoll: 'tourpoll',
	tourneypoll: 'tourpoll',
	tourpoll: function (target, room, user) {
		if (!this.can('poll', null, room)) return false;
		this.parse("/poll Tournament format?," + "OU, Ubers, UU, RU, NU, LC, VGC, Monotype, [Gen 4] OU, Random, 1v1 Random, Uber Random, High Tier Random, Low Tier Random, LC Random, Monotype Random, Generational Random, Inverse Random, Community Random, Spring Random, Orb Random, Hoenn Random, Hoenn Weather Random, Super Smash Bros. Random, Winter Wonderland, Furry Random, Metronome 3v3 Random, Metronome 6v6 Random, Doubles Random, Triples Random, Battle Factory, Hackmons Cup, [Seasonal] Random, [Gen 2] Random, [Gen 1] Random");
	},

	teampoll: function (target, room, user) {
		if (!this.can('poll', null, room)) return false;
		this.parse("/poll Tournament format?," + "OU, Ubers, UU, RU, NU, LC, VGC, Monotype, [Gen 4] OU");
	},

	randbatpoll: 'randompoll',
	randbatspoll: 'randompoll',
	randpoll: 'randompoll',
	randompoll: function (target, room, user) {
		if (!this.can('poll', null, room)) return false;
		this.parse("/poll Tournament format?," + "Random, 1v1 Random, Uber Random, High Tier Random, Low Tier Random, LC Random, Monotype Random, Generational Random, Inverse Random, Community Random, Spring Random, Orb Random, Hoenn Random, Hoenn Weather Random, Super Smash Bros. Random, Winter Wonderland, Furry Random, Metronome 3v3 Random, Metronome 6v6 Random, Doubles Random, Triples Random, Battle Factory, Hackmons Cup, [Seasonal] Random, [Gen 2] Random, [Gen 1] Random");
	},

	vote: function (target, room, user) {
		if (!Poll[room.id]) Poll.reset(room.id);
		if (!Poll[room.id].question) return this.sendReply("There is no poll currently going on in this room.");
		if (!target) return this.parse('/help vote');
		if (Poll[room.id].optionList.indexOf(target.toLowerCase()) === -1) return this.sendReply("'" + target + "' is not an option for the current poll.");

		var ips = JSON.stringify(user.ips);
		Poll[room.id].options[ips] = target.toLowerCase();

		return this.sendReply("You are now voting for " + target + ".");
	},
	votehelp: ["/vote [option] - Vote for an option in the poll."],

	votes: function (target, room, user) {
		if (!this.canBroadcast()) return;
		if (!Poll[room.id]) Poll.reset(room.id);
		if (!Poll[room.id].question) return this.sendReply("There is no poll currently going on in this room.");
		this.sendReply("NUMBER OF VOTES: " + Object.keys(Poll[room.id].options).length);
	}
};
<commit_msg>Update poll.js<commit_after>var Poll = {
	reset: function (roomId) {
		Poll[roomId] = {
			question: undefined,
			optionList: [],
			options: {},
			display: '',
			topOption: ''
		};
	},

	splint: function (target) {
		var parts = target.split(',');
		var len = parts.length;
		while (len--) {
			parts[len] = parts[len].trim();
		}
		return parts;
	}
};

for (var id in Rooms.rooms) {
	if (Rooms.rooms[id].type === 'chat' && !Poll[id]) {
		Poll[id] = {};
		Poll.reset(id);
	}
}

exports.commands = {
	poll: function (target, room, user) {
		if (!this.can('poll', null, room)) return false;
		if (!Poll[room.id]) Poll.reset(room.id);
		if (Poll[room.id].question) return this.sendReply("There is currently a poll going on already.");
		if (!this.canTalk()) return;

		var options = Poll.splint(target);
		if (options.length < 3) return this.parse('/help poll');

		var question = options.shift();

		options = options.join(',').toLowerCase().split(',');

		Poll[room.id].question = question;
		Poll[room.id].optionList = options;

		var pollOptions = '';
		var start = 0;
		while (start < Poll[room.id].optionList.length) {
			pollOptions += '<button name="send" value="/vote ' + Tools.escapeHTML(Poll[room.id].optionList[start]) + '">' + Tools.escapeHTML(Poll[room.id].optionList[start]) + '</button> ';
			start++;
		}
		Poll[room.id].display = '
' + Tools.escapeHTML(Poll[room.id].question) + '  /vote OPTION
Poll started by ' + user.name + '

    ' + pollOptions;
		room.add('|raw|
' + Poll[room.id].display + '
');
	},
	pollhelp: ["/poll [question], [option 1], [option 2]... - Create a poll where users can vote on an option."],

	endpoll: function (target, room, user) {
		if (!this.can('poll', null, room)) return false;
		if (!Poll[room.id]) Poll.reset(room.id);
		if (!Poll[room.id].question) return this.sendReply("There is no poll to end in this room.");

		var votes = Object.keys(Poll[room.id].options).length;

		if (votes === 0) {
			Poll.reset(room.id);
			return room.add('|raw|
The poll was canceled because of lack of voters.
');
		}

		var options = {};

		for (var l in Poll[room.id].optionList) {
			options[Poll[room.id].optionList[l]] = 0;
		}

		for (var o in Poll[room.id].options) {
			options[Poll[room.id].options[o]]++;
		}

		var data = [];
		for (var i in options) {
			data.push([i, options[i]]);
		}
		data.sort(function (a, b) {
			return a[1] - b[1];
		});

		var results = '';
		var len = data.length;
		var topOption = data[len - 1][0];
		while (len--) {
			if (data[len][1] > 0) {
				results += '• ' + data[len][0] + ' - ' + Math.floor(data[len][1] / votes * 100) + '% (' + data[len][1] + ')
';
			}
		}
		room.add('|raw|

Results to "' + Poll[room.id].question + '"
Poll ended by ' + user.name + '

' + results + '
');
		Poll.reset(room.id);
		Poll[room.id].topOption = topOption;
	},

	elimtour: 'etour',
	etour: function (target, room, user) {
		if (!this.can('voicetourmoderation')) return;
		this.parse('/tour new ' + target + ', elimination');
	},

	roundrobintour: 'rtour',
	rtour: function (target, room, user) {
		if (!this.can('voicetourmoderation')) return;
		this.parse('/tour new ' + target + ', roundrobin');
	},

	pollr: 'pollremind',
	pollremind: function (target, room, user) {
		if (!Poll[room.id]) Poll.reset(room.id);
		if (!Poll[room.id].question) return this.sendReply("There is no poll currently going on in this room.");
		if (!this.canBroadcast()) return;
		this.sendReplyBox(Poll[room.id].display);
	},

	tournamentpoll: 'tourpoll',
	tourneypoll: 'tourpoll',
	tourpoll: function (target, room, user) {
		if (!this.can('poll', null, room)) return false;
		this.parse("/poll Tournament format?," + "OU, Ubers, UU, RU, NU, LC, VGC, Monotype, [Gen 4] OU, Random, 1v1 Random, Uber Random, High Tier Random, Low Tier Random, LC Random, Monotype Random, Generational Random, Inverse Random, Community Random, Spring Random, Orb Random, Hoenn Random, Hoenn Weather Random, Super Smash Bros. Random, Winter Wonderland, Furry Random, Metronome 3v3 Random, Metronome 6v6 Random, Doubles Random, Triples Random, Battle Factory, Hackmons Cup, [Seasonal] Random, [Gen 2] Random, [Gen 1] Random");
	},

	teampoll: function (target, room, user) {
		if (!this.can('poll', null, room)) return false;
		this.parse("/poll Tournament format?," + "OU, Ubers, UU, RU, NU, LC, VGC, Monotype, [Gen 4] OU");
	},

	randbatpoll: 'randompoll',
	randbatspoll: 'randompoll',
	randpoll: 'randompoll',
	randompoll: function (target, room, user) {
		if (!this.can('poll', null, room)) return false;
		this.parse("/poll Tournament format?," + "Random, 1v1 Random, Uber Random, High Tier Random, Low Tier Random, LC Random, Monotype Random, Generational Random, Inverse Random, Community Random, Spring Random, Orb Random, Hoenn Random, Hoenn Weather Random, Super Smash Bros. Random, Winter Wonderland, Furry Random, Metronome 3v3 Random, Metronome 6v6 Random, Doubles Random, Triples Random, Battle Factory, Hackmons Cup, [Seasonal] Random, [Gen 2] Random, [Gen 1] Random");
	},

	vote: function (target, room, user) {
		if (!Poll[room.id]) Poll.reset(room.id);
		if (!Poll[room.id].question) return this.sendReply("There is no poll currently going on in this room.");
		if (!target) return this.parse('/help vote');
		if (Poll[room.id].optionList.indexOf(target.toLowerCase()) === -1) return this.sendReply("'" + target + "' is not an option for the current poll.");

		var ips = JSON.stringify(user.ips);
		Poll[room.id].options[ips] = target.toLowerCase();

		return this.sendReply("You are now voting for " + target + ".");
	},
	votehelp: ["/vote [option] - Vote for an option in the poll."],

	votes: function (target, room, user) {
		if (!this.canBroadcast()) return;
		if (!Poll[room.id]) Poll.reset(room.id);
		if (!Poll[room.id].question) return this.sendReply("There is no poll currently going on in this room.");
		this.sendReply("NUMBER OF VOTES: " + Object.keys(Poll[room.id].options).length);
	}
};
<|endoftext|>


<commit_before>"use strict";

var gulp = require("gulp"),
	lint = require("gulp-eslint"),
	mocha = require("gulp-mocha");

process.env.NODE_PATH = "./source:" + (process.env.NODE_PATH || "");

gulp.task("lint", function() {
	return gulp.src(["gulpfile.js", "source/**/*.js", "test/**/*.js"])
		.pipe(lint({
			globals: {
				suite: true,
				test: true
			},
			rules: {
				// Removing whitespace can be handled by a build tool
				"no-trailing-spaces": 0,
				// All functions that are being used before their definition are function statements,
				// not function expressions. As such hoisting isn't a problem and we can ignore this.
				"no-use-before-define": 0
			},
			envs: ["node"]
		}))
        .pipe(lint.format())
        .pipe(lint.failOnError());
});

gulp.task("test", function() {
	return gulp.src("./test/**/*.js")
		.pipe(mocha({
			ui: "tdd"
		}));
});

gulp.task("default", ["lint", "test"]);
<commit_msg>Fixed default task<commit_after>"use strict";

var gulp = require("gulp"),
	lint = require("gulp-eslint"),
	mocha = require("gulp-mocha");

gulp.task("lint", function() {
	return gulp.src(["gulpfile.js", "source/**/*.js", "test/**/*.js"])
		.pipe(lint({
			globals: {
				suite: true,
				test: true
			},
			rules: {
				// Removing whitespace can be handled by a build tool
				"no-trailing-spaces": 0,
				// All functions that are being used before their definition are function statements,
				// not function expressions. As such hoisting isn't a problem and we can ignore this.
				"no-use-before-define": 0
			},
			envs: ["node"]
		}))
        .pipe(lint.format())
        .pipe(lint.failOnError());
});

gulp.task("test", function() {
	return gulp.src("./test/**/*.js")
		.pipe(mocha({
			ui: "tdd"
		}));
});

/**
 * The default task runs the lint task then the test task.  This is done serially because otherwise it causes
 * an "Unexpected end of input" SyntaxError when parsing the linter's rules.
 */
gulp.task("default", ["lint"], function() {
	gulp.start("test");
});
<|endoftext|>


<commit_before>var gulp           = require('gulp'),
    connect        = require('gulp-connect'),
    csso           = require('gulp-csso'),
    sass           = require('gulp-sass'),
    rename         = require("gulp-rename"),
    deploy         = require("gulp-gh-pages");

// Styles.
gulp.task('styles', function() {
  return gulp.src('src/styles/*.scss')
    .pipe(
      sass( {
        includePaths: ['src/styles'],
        errLogToConsole: true
      }))
    .pipe(csso())
    .pipe(rename('styles/main.min.css'))
    .pipe(gulp.dest('./dist'))
    .pipe(connect.reload());
});

// Images
gulp.task('images', function() {
  return gulp.src('src/images/**/*')
    .pipe(gulp.dest('dist/images/'))
    .pipe(connect.reload());
});

// Templates
gulp.task('templates', function() {
  return gulp.src('src/**/*.html')
    .pipe(gulp.dest('dist/'))
    .pipe(connect.reload());
});

// Build
gulp.task('build', ['images','styles','templates']);

// Connect - let's get this party started!
gulp.task('connect', function() {
  connect.server({
    root: 'dist',
    port: 9000,
    livereload: true
  });
});

// Watch
gulp.task('watch', function() {
    gulp.watch('src/styles/**/*.scss', ['styles']);
    gulp.watch('src/images/**/*', ['images']);
    gulp.watch('src/**/*.html', ['templates']);
});

// Default task
gulp.task('default', function() {
    gulp.start('build', 'connect', 'watch');
});

// Deploy to gh-pages
gulp.task('deploy', function() {
  gulp.src("./dist/**/*")
    .pipe(deploy('git@github.com:amygori/etsy.git', 'origin'));
});<commit_msg>7th draft<commit_after>var gulp           = require('gulp'),
    connect        = require('gulp-connect'),
    csso           = require('gulp-csso'),
    sass           = require('gulp-sass'),
    rename         = require("gulp-rename"),
    deploy         = require("gulp-gh-pages");

// Styles.
gulp.task('styles', function() {
  return gulp.src('src/styles/*.scss')
    .pipe(
      sass( {
        includePaths: ['src/styles'],
        errLogToConsole: true
      }))
    .pipe(csso())
    .pipe(rename('styles/main.min.css'))
    .pipe(gulp.dest('./dist'))
    .pipe(connect.reload());
});

// Images
gulp.task('images', function() {
  return gulp.src('src/images/**/*')
    .pipe(gulp.dest('dist/images/'))
    .pipe(connect.reload());
});

// Templates
gulp.task('templates', function() {
  return gulp.src('src/**/*.html')
    .pipe(gulp.dest('dist/'))
    .pipe(connect.reload());
});

// Build
gulp.task('build', ['images','styles','templates']);

// Connect - let's get this party started!
gulp.task('connect', function() {
  connect.server({
    root: 'dist',
    port: 9000,
    livereload: true
  });
});

// Watch
gulp.task('watch', function() {
    gulp.watch('src/styles/**/*.scss', ['styles']);
    gulp.watch('src/images/**/*', ['images']);
    gulp.watch('src/**/*.html', ['templates']);
});

// Default task
gulp.task('default', function() {
    gulp.start('build', 'connect', 'watch');
});

// Deploy to gh-pages
gulp.task('deploy', function() {
  gulp.src("./dist/**/*")
    .pipe(deploy('<enter your repo git url here>', 'origin'));
});<|endoftext|>


<commit_before>
var gulp = require('gulp');
var concat = require('gulp-concat');
var watch = require('gulp-watch');
var watchify = require('watchify');
var babel = require('gulp-babel');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var uglify = require('gulp-uglify');
var compass = require('gulp-compass');
var minifyCss = require('gulp-minify-css');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var assign = require('lodash.assign');
var watch = require('gulp-watch');

gulp.task('styles', function() {

    gulp.src('./bower_components/bootstrap-sass/assets/{fonts,images}/**/*.*', {base: './bower_components/bootstrap-sass/assets'})
        .pipe(gulp.dest('./dist'));

    gulp.src('./src/_sass/default.scss')
        .pipe(compass({
            css: 'dist',
            sass: 'src/_sass',
            import_path: ['./bower_components/bootstrap-sass/assets/stylesheets']
        }))
        .pipe(minifyCss())
        .pipe(gulp.dest('dist'));

});

var scripts = [
    './node_modules/babel-core/browser-polyfill.js',
    './bower_components/jquery/dist/jquery.js',
    './bower_components/angular/angular.js',
    './bower_components/angular-bootstrap/ui-bootstrap.js',
    './bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
    './bower_components/angular-route/angular-route.js',
    './bower_components/angular-translate/angular-translate.js',
    './bower_components/angular-translate-loader-partial/angular-translate-loader-partial.js',
    './bower_components/angular-sanitize/angular-sanitize.js',
    './bower_components/autofill-event/src/autofill-event.js'
];

gulp.task('libraries', function() {

    gulp.src(scripts)
        .pipe(concat('libraries.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./dist'));
});

gulp.task('expose', function() {

    gulp.src('./assets/**/*.png', {base: './assets'})
        .pipe(watch('./assets/**/*.png', {base: './assets'}))
        .pipe(gulp.dest('./dist'));

    gulp.src('./src/**/*.{html,json}', {base: './src'})
        .pipe(watch('./src/**/*.{html,json}', {base: './src'}))
        .pipe(gulp.dest('./dist'));

    gulp.src('./LICENSE')
        .pipe(concat('LICENSE.txt'))
        .pipe(gulp.dest('./dist'));

});

gulp.task('watch', function() {

    gulp.watch(['./bower_components/bootstrap-sass/assets/stylesheets/**/*.scss', './src/_sass/**/*.scss'], ['styles']);

});

gulp.task('default', ['libraries', 'styles', 'expose', 'watch']);

<commit_msg>use angular-gettext<commit_after>
var gulp = require('gulp');
var concat = require('gulp-concat');
var watch = require('gulp-watch');
var watchify = require('watchify');
var babel = require('gulp-babel');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var uglify = require('gulp-uglify');
var compass = require('gulp-compass');
var minifyCss = require('gulp-minify-css');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var assign = require('lodash.assign');
var watch = require('gulp-watch');

gulp.task('styles', function() {

    gulp.src('./bower_components/bootstrap-sass/assets/{fonts,images}/**/*.*', {base: './bower_components/bootstrap-sass/assets'})
        .pipe(gulp.dest('./dist'));

    gulp.src('./src/_sass/default.scss')
        .pipe(compass({
            css: 'dist',
            sass: 'src/_sass',
            import_path: ['./bower_components/bootstrap-sass/assets/stylesheets']
        }))
        .pipe(minifyCss())
        .pipe(gulp.dest('dist'));

});

var scripts = [
    './node_modules/babel-core/browser-polyfill.js',
    './bower_components/jquery/dist/jquery.js',
    './bower_components/angular/angular.js',
    './bower_components/angular-bootstrap/ui-bootstrap.js',
    './bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
    './bower_components/angular-route/angular-route.js',
    './bower_components/angular-sanitize/angular-sanitize.js',
    './bower_components/autofill-event/src/autofill-event.js',
    './bower_components/angular-gettext/dist/angular-gettext.js'
];

gulp.task('libraries', function() {

    gulp.src(scripts)
        .pipe(concat('libraries.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./dist'));
});

gulp.task('expose', function() {

    gulp.src('./assets/**/*.png', {base: './assets'})
        .pipe(watch('./assets/**/*.png', {base: './assets'}))
        .pipe(gulp.dest('./dist'));

    gulp.src('./src/**/*.{html,json}', {base: './src'})
        .pipe(watch('./src/**/*.{html,json}', {base: './src'}))
        .pipe(gulp.dest('./dist'));

    gulp.src('./LICENSE')
        .pipe(concat('LICENSE.txt'))
        .pipe(gulp.dest('./dist'));

});

gulp.task('watch', function() {

    gulp.watch(['./bower_components/bootstrap-sass/assets/stylesheets/**/*.scss', './src/_sass/**/*.scss'], ['styles']);

});

gulp.task('default', ['libraries', 'styles', 'expose', 'watch']);

<|endoftext|>


<commit_before>/*
 * biojs-io-biom
 * https://github.com/molbiodiv/biojs-io-biom
 *
 * Copyright (c) 2015 Markus J. Ankenbrand
 * Licensed under the MIT license.
 */

// browserify build config
var buildDir = "build";
var outputFile = "biom";

// packages
var gulp   = require('gulp');

// es6 compilation
var babel = require('gulp-babel');
require('babel-core/register');

// browser builds
var browserify = require('browserify');
var watchify = require('watchify')
var uglify = require('gulp-uglify');

// testing
var mocha = require('gulp-mocha');
// coverage
var istanbul = require('gulp-istanbul');
var isparta = require('isparta');
var runSequence = require('run-sequence');
var coveralls = require('gulp-coveralls');

// code style
var jshint = require('gulp-jshint');

// gulp helper
var source = require('vinyl-source-stream'); // converts node streams into vinyl streams
var gzip = require('gulp-gzip');
var rename = require('gulp-rename');
var chmod = require('gulp-chmod');
var streamify = require('gulp-streamify'); // converts streams into buffers (legacy support for old plugins)

// path tools
var fs = require('fs');
var path = require('path');
var join = path.join;
var mkdirp = require('mkdirp');
var del = require('del');

// auto config
var outputFileMin = join(buildDir,outputFile + ".min.js");
var packageConfig = require('./package.json');

// a failing test breaks the whole build chain
gulp.task('build', ['babel', 'build-browser', 'build-browser-gzip']);
gulp.task('default', ['lint','test',  'build']);

gulp.task('lint', function() {
  return gulp.src('./src/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

gulp.task('coverage:instrument', function () {
  return gulp.src(['src/**/*.js'])
    // Covering files
    .pipe(istanbul({instrumenter: isparta.Instrumenter}))
    // Force `require` to return covered files
    .pipe(istanbul.hookRequire());
});

gulp.task('test-unit', function () {

    return gulp.src('./test/**/*.js', {read: false})

        .pipe(mocha({reporter: 'spec',
                    useColors: true}))
});

gulp.task('coverage:report', function(done) {
  return gulp.src(['src/**/*.js'], {read: false})
      .pipe(istanbul.writeReports({
        // Istanbul configuration (see https://github.com/SBoudrias/gulp-istanbul#istanbulwritereportsopt)
        // ...
      }));
});

gulp.task('test', function(done) {
  runSequence('coverage:instrument', 'test-unit', 'coverage:report', 'coveralls', done);
});

gulp.task('coveralls', function () {
  if (!process.env.CI) {
    return;
  }

  return gulp.src('./coverage/lcov.info')
      .pipe(coveralls());
});

gulp.task('test-watch', function() {
   gulp.watch(['./src/**/*.js','./lib/**/*.js', './test/**/*.js'], ['test']);
});

// will remove everything in build
gulp.task('clean', function(cb) {
  del([buildDir], cb);
});

// just makes sure that the build dir exists
gulp.task('init', ['clean'], function() {
  mkdirp(buildDir, function (err) {
    if (err) console.error(err)
  });
});

// browserify debug
gulp.task('build-browser',['init'], function() {
  var b = browserify({debug: true,hasExports: true});
  exposeBundles(b);
  return b.bundle()
    .pipe(source(outputFile + ".js"))
    .pipe(chmod(644))
    .pipe(gulp.dest(buildDir));
});

// browserify min
gulp.task('build-browser-min',['init'], function() {
  var b = browserify({hasExports: true, standalone: "biojs-io-biom"});
  exposeBundles(b);
  return b.bundle()
    .pipe(source(outputFile + ".min.js"))
    .pipe(chmod(644))
    .pipe(streamify(uglify()))
    .pipe(gulp.dest(buildDir));
});

gulp.task('build-browser-gzip', ['build-browser-min'], function() {
  return gulp.src(outputFileMin)
    .pipe(gzip({append: false, gzipOptions: { level: 9 }}))
    .pipe(rename(outputFile + ".min.gz.js"))
    .pipe(gulp.dest(buildDir));
});

// exposes the main package
// + checks the config whether it should expose other packages
function exposeBundles(b){
  b.add("./" + packageConfig.main, {expose: packageConfig.name });
  if(packageConfig.sniper !== undefined && packageConfig.sniper.exposed !== undefined){
    for(var i=0; i<packageConfig.sniper.exposed.length; i++){
      b.require(packageConfig.sniper.exposed[i]);
    }
  }
}

// watch task for browserify
// watchify has an internal cache -> subsequent builds are faster
gulp.task('watch', function() {
  var util = require('gulp-util')

  var b = browserify({debug: true,hasExports: true, cache: {}, packageCache: {} });
  b.add("./" + packageConfig.main, {expose: packageConfig.name});
  // expose other bundles
  exposeBundles(b);

  function rebundle(ids){
    b.bundle()
    .on("error", function(error) {
      util.log(util.colors.red("Error: "), error);
     })
    .pipe(source(outputFile + ".js"))
    .pipe(chmod(644))
    .pipe(gulp.dest(buildDir));
  }

  var watcher = watchify(b);
  watcher.on("update", rebundle)
   .on("log", function(message) {
      util.log("Refreshed:", message);
  });
  return rebundle();
});

gulp.task('babel', function () {
  return gulp.src("src/biojs-io-biom.js")
    .pipe(babel())
    .pipe(gulp.dest("lib"));
});
<commit_msg>Do not export biojs-io-biom as standalone in min version<commit_after>/*
 * biojs-io-biom
 * https://github.com/molbiodiv/biojs-io-biom
 *
 * Copyright (c) 2015 Markus J. Ankenbrand
 * Licensed under the MIT license.
 */

// browserify build config
var buildDir = "build";
var outputFile = "biom";

// packages
var gulp   = require('gulp');

// es6 compilation
var babel = require('gulp-babel');
require('babel-core/register');

// browser builds
var browserify = require('browserify');
var watchify = require('watchify')
var uglify = require('gulp-uglify');

// testing
var mocha = require('gulp-mocha');
// coverage
var istanbul = require('gulp-istanbul');
var isparta = require('isparta');
var runSequence = require('run-sequence');
var coveralls = require('gulp-coveralls');

// code style
var jshint = require('gulp-jshint');

// gulp helper
var source = require('vinyl-source-stream'); // converts node streams into vinyl streams
var gzip = require('gulp-gzip');
var rename = require('gulp-rename');
var chmod = require('gulp-chmod');
var streamify = require('gulp-streamify'); // converts streams into buffers (legacy support for old plugins)

// path tools
var fs = require('fs');
var path = require('path');
var join = path.join;
var mkdirp = require('mkdirp');
var del = require('del');

// auto config
var outputFileMin = join(buildDir,outputFile + ".min.js");
var packageConfig = require('./package.json');

// a failing test breaks the whole build chain
gulp.task('build', ['babel', 'build-browser', 'build-browser-gzip']);
gulp.task('default', ['lint','test',  'build']);

gulp.task('lint', function() {
  return gulp.src('./src/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

gulp.task('coverage:instrument', function () {
  return gulp.src(['src/**/*.js'])
    // Covering files
    .pipe(istanbul({instrumenter: isparta.Instrumenter}))
    // Force `require` to return covered files
    .pipe(istanbul.hookRequire());
});

gulp.task('test-unit', function () {

    return gulp.src('./test/**/*.js', {read: false})

        .pipe(mocha({reporter: 'spec',
                    useColors: true}))
});

gulp.task('coverage:report', function(done) {
  return gulp.src(['src/**/*.js'], {read: false})
      .pipe(istanbul.writeReports({
        // Istanbul configuration (see https://github.com/SBoudrias/gulp-istanbul#istanbulwritereportsopt)
        // ...
      }));
});

gulp.task('test', function(done) {
  runSequence('coverage:instrument', 'test-unit', 'coverage:report', 'coveralls', done);
});

gulp.task('coveralls', function () {
  if (!process.env.CI) {
    return;
  }

  return gulp.src('./coverage/lcov.info')
      .pipe(coveralls());
});

gulp.task('test-watch', function() {
   gulp.watch(['./src/**/*.js','./lib/**/*.js', './test/**/*.js'], ['test']);
});

// will remove everything in build
gulp.task('clean', function(cb) {
  del([buildDir], cb);
});

// just makes sure that the build dir exists
gulp.task('init', ['clean'], function() {
  mkdirp(buildDir, function (err) {
    if (err) console.error(err)
  });
});

// browserify debug
gulp.task('build-browser',['init'], function() {
  var b = browserify({debug: true,hasExports: true});
  exposeBundles(b);
  return b.bundle()
    .pipe(source(outputFile + ".js"))
    .pipe(chmod(644))
    .pipe(gulp.dest(buildDir));
});

// browserify min
gulp.task('build-browser-min',['init'], function() {
  var b = browserify({hasExports: true});
  exposeBundles(b);
  return b.bundle()
    .pipe(source(outputFile + ".min.js"))
    .pipe(chmod(644))
    .pipe(streamify(uglify()))
    .pipe(gulp.dest(buildDir));
});

gulp.task('build-browser-gzip', ['build-browser-min'], function() {
  return gulp.src(outputFileMin)
    .pipe(gzip({append: false, gzipOptions: { level: 9 }}))
    .pipe(rename(outputFile + ".min.gz.js"))
    .pipe(gulp.dest(buildDir));
});

// exposes the main package
// + checks the config whether it should expose other packages
function exposeBundles(b){
  b.add("./" + packageConfig.main, {expose: packageConfig.name });
  if(packageConfig.sniper !== undefined && packageConfig.sniper.exposed !== undefined){
    for(var i=0; i<packageConfig.sniper.exposed.length; i++){
      b.require(packageConfig.sniper.exposed[i]);
    }
  }
}

// watch task for browserify
// watchify has an internal cache -> subsequent builds are faster
gulp.task('watch', function() {
  var util = require('gulp-util')

  var b = browserify({debug: true,hasExports: true, cache: {}, packageCache: {} });
  b.add("./" + packageConfig.main, {expose: packageConfig.name});
  // expose other bundles
  exposeBundles(b);

  function rebundle(ids){
    b.bundle()
    .on("error", function(error) {
      util.log(util.colors.red("Error: "), error);
     })
    .pipe(source(outputFile + ".js"))
    .pipe(chmod(644))
    .pipe(gulp.dest(buildDir));
  }

  var watcher = watchify(b);
  watcher.on("update", rebundle)
   .on("log", function(message) {
      util.log("Refreshed:", message);
  });
  return rebundle();
});

gulp.task('babel', function () {
  return gulp.src("src/biojs-io-biom.js")
    .pipe(babel())
    .pipe(gulp.dest("lib"));
});
<|endoftext|>


<commit_before>// require ../support/jquery
// require esphinx_ui
// require esphinx/support/ajax
// require esphinx/support/function
// require esphinx/support/array
// require esphinx/observer

"use strict";

var
    jQuery,
    esPhinx,
    Singleton,
    Ajax,
    Constructor;

(function ($module) {

    $module.extend({

        windows: {

            modal: {

                // functions are objects in js
                new: function (contentSource, options) {

                    var
                        self = $module.windows.modal.new,
                        mainReference = this,
                        args = Array.from(arguments),

                        $ = esPhinx,
                        ajax = Ajax,
                        body = $("body"),
                        imagesLoaded = [],

                        modal,
                        mask,
                        main,
                        container,
                        btnClose,
                        btnHide,
                        headers,
                        params,
                        asynchronousAnswer,
                        imgControl,
                        singleton,

                        show = function () {
                            modal.css("z-index", 0);
                            restartTransition(mask);
                            if (options.fadeIn) {
                                mask.css("transition", "opacity "
                                + options.fadeIn);
                            }
                            mask.removeClass("transparent");
                            main.show();
                            // debugger
                        },

                        maskTransitionDuration = function (mask) {
                            return parseFloat(mask
                                .css("transition-duration")) * 1000;
                        },

                        restartTransition = function (mask) {
                            mask.css("transition", "opacity 0s");
                        },

                        resolveParams = function () {
                            options = options || {};

                            if (typeof options.windowController !== "boolean") {
                                options.windowController = true;
                            }

                            if (typeof options.remote !== "boolean") {
                                options.remote = true;
                            }
                        },

                        resolveHeaderActions = function (main, options) {
                            var
                                header,
                                actions;

                            if (options.windowController) {
                                header = $("");
                                actions = $("

").addClass("actions");
                                btnClose = $('')
                                    .addClass("btn-close");
                                btnHide = $('')
                                    .addClass("btn-hide");

                                header.append(actions);
                                actions.append(btnClose);
                                actions.append(btnHide);

                                main
                                    .prepend(header)
                                    .css({
                                        "max-height": $(document).height(),
                                        "max-width": $(document).width()
                                    });

                                bindHeaderEventListeners();
                            }
                        },

                        bindHeaderEventListeners = function () {
                            // $(document).off("keydown").on("keydown", function (e) {
                            //     if (e.keyCode === 27) {
                            //         self.hide();
                            //     }
                            // });

                            btnHide.on("click", function () {
                                mainReference.hide();
                            });

                            btnClose.on("click", function () {
                                mainReference.close();
                            });
                        },

                        observeContent = function (main, options) {
                            var
                                count = 0,
                                imgs;

                            main.observe(function (observer) {
                                // flowControl(observer);

                                imgs = main.find("img");
                                if (imgs.any()) {
                                    imgs.each(function (img) {
                                        $(img).on("load", function (e) {
                                            imagesLoaded.push(img);
                                            count += 1;
                                        });
                                    });

                                    FlowControl.new({
                                        condition: function () {
                                            if (count === imgs.length) {
                                                return true;
                                            }

                                            // when processing is synchronous
                                            if (!options.remote) {
                                                if (options.loading) {
                                                    options.loading(main);
                                                    main.centralizeAt(document);
                                                    mainReference.show();
                                                }
                                            }

                                            return false;
                                        },
                                        ready: function () {
                                            // agora já não há mais controle para exibir, estando tão somente na mão do usuário, portanto o método show deve ser melhorado

                                            if (!asynchronousAnswer) {
                                                container.html(contentSource);
                                                main.html(container);
                                            }

                                            main.centralizeAt(document);
                                            resolveHeaderActions(main, options);

                                            if (options.complete) {
                                                mainReference.hide(false);

                                                options.complete
                                                    .call(mainReference);
                                            }
                                        }
                                    });

                                } else {
                                    resolveHeaderActions(main, options);

                                    if (options.complete) {
                                        options.complete.call(mainReference);
                                    }
                                }

                                // talvez tenha que remanejar o disconnect
                                observer.disconnect();
                            });
                        },

                        create = function (remote) {
                            modal = $("

")
                                .addClass("esphinx ui modal");
                            main = $("")
                                .addClass("basicss hidden");
                            mask = $("

")
                                .addClass("basicss fixed transparent mask");
                            container = $("

").addClass("container");

                            modal
                                .append(mask)
                                .append(main);

                            body.append(modal);

                            observeContent(main, options);

                            if (options.remote) {
                                headers = options.header || options.headers
                                || null;
                                params = options.param || options.params
                                || null;
                                ajax.new(contentSource, {
                                    params: params,
                                    headers: headers,
                                    progress: function () {
                                        if (options.loading) {
                                            // callback
                                            options.loading(main);
                                            mainReference.show();
                                        }
                                    },
                                    success: function (a) {
                                        asynchronousAnswer = a;
                                        container.html(asynchronousAnswer);
                                        // because here the processing is asynchronous, it's not linear
                                        mainReference.hide(false);
                                        main.html(container);
                                    }
                                });
                            } else {
                                container.html(contentSource);
                                main.html(container);
                            }

                        };

                    resolveParams();
                    if (!(this instanceof self)) {
                        // debugger
                        // if (self.mainReference) {
                        //     self.mainReference.show();
                        // } else {
                        //     return self.singleton(arguments);
                        // }

                        singleton = Singleton
                            .exists(self, arguments);
                        // debugger
                        if (!singleton) {
                            return Singleton.new(self, arguments);
                        } else {
                            singleton.show();
                        }

                    // that "else" will should to exit for the "show" method can be used by who instanciates it
                    } else {
                        create();
                    }

                    // global scope (public)
                    this.close = function () {
                        main.hide();

                        restartTransition(mask);
                        if (options.fadeOut) {
                            mask.css("transition", "opacity "
                                + options.fadeOut);
                        }
                        mask.addClass("transparent");

                        setTimeout(function () {
                            modal.remove();
                        }, maskTransitionDuration(mask));

                        mainReference.deleteSingleton();

                        return mainReference;
                    };

                    // this.hide = function (animation) {
                    //     if (typeof animation !== "boolean") {animation = true;}
                    this.hide = function (animation = true) {
                        main.hide();

                        restartTransition(mask);

                        if (animation) {
                            if (options.fadeOut) {
                                mask.css("transition", "opacity "
                                + options.fadeOut);
                                setTimeout(function () {
                                    modal.css("z-index", -1);
                                }, maskTransitionDuration(mask));
                            }
                        }

                        mask.addClass("transparent");

                        return mainReference;
                    };

                    this.show = function () {
                        var
                            count = 0,
                            imgs;

                        imgs = main.find("img");
                        if (imgs.any()) {
                            imgs.each(function (img) {
                                if (!imagesLoaded.indexPerEquivalence(img)) {
                                    $(img).on("load", function (e) {
                                        count += 1;
                                    });
                                } else {
                                    count += 1;
                                }

                            });

                            FlowControl.new({
                                condition: function () {
                                    if (count === imgs.length) {
                                        return true;
                                    }

                                    return false;
                                },
                                ready: function () {
                                    main.centralizeAt(document);
                                    show();
                                }
                            });

                        } else {
                            show();
                        }

                        return mainReference;
                    };

                    return this;
                }

            }

        }

    });

}(esPhinx.ui));
<commit_msg>adequations<commit_after>// require ../support/jquery
// require esphinx_ui
// require esphinx/support/ajax
// require esphinx/support/function
// require esphinx/support/array
// require esphinx/observer

"use strict";

var
    jQuery,
    esPhinx,
    Singleton,
    Ajax,
    Constructor;

(function ($module) {

    $module.extend({

        windows: {

            modal: {

                // functions are objects in js
                new: function (contentSource, options) {

                    var
                        self = $module.windows.modal.new,
                        mainReference = this,
                        args = Array.from(arguments),

                        $ = esPhinx,
                        ajax = Ajax,
                        body = $("body"),
                        imagesLoaded = [],

                        modal,
                        mask,
                        main,
                        container,
                        btnClose,
                        btnHide,
                        headers,
                        params,
                        asynchronousAnswer,
                        imgControl,
                        singleton,

                        show = function () {
                            modal.css("z-index", 0);
                            restartTransition(mask);
                            if (options.fadeIn) {
                                mask.css("transition", "opacity "
                                + options.fadeIn);
                            }
                            mask.removeClass("transparent");
                            main.show();
                            // debugger
                        },

                        maskTransitionDuration = function (mask) {
                            return parseFloat(mask
                                .css("transition-duration")) * 1000;
                        },

                        restartTransition = function (mask) {
                            mask.css("transition", "opacity 0s");
                        },

                        resolveParams = function () {
                            options = options || {};

                            if (typeof options.windowController !== "boolean") {
                                options.windowController = true;
                            }

                            if (typeof options.remote !== "boolean") {
                                options.remote = true;
                            }
                        },

                        resolveHeaderActions = function (main, options) {
                            var
                                header,
                                actions;

                            if (options.windowController) {
                                header = $("");
                                actions = $("

").addClass("actions");
                                btnClose = $('')
                                    .addClass("btn-close");
                                btnHide = $('')
                                    .addClass("btn-hide");

                                header.append(actions);
                                actions.append(btnClose);
                                actions.append(btnHide);

                                main
                                    .prepend(header)
                                    .css({
                                        "max-height": $(document).height(),
                                        "max-width": $(document).width()
                                    });

                                bindHeaderEventListeners();
                            }
                        },

                        bindHeaderEventListeners = function () {
                            // $(document).off("keydown").on("keydown", function (e) {
                            //     if (e.keyCode === 27) {
                            //         self.hide();
                            //     }
                            // });

                            btnHide.on("click", function () {
                                mainReference.hide();
                            });

                            btnClose.on("click", function () {
                                mainReference.close();
                            });

                        },

                        observeContent = function (main, options) {
                            var
                                count = 0,
                                imgs;

                            main.observe(function (observer) {
                                // flowControl(observer);

                                imgs = main.find("img");
                                if (imgs.any()) {
                                    imgs.each(function (img) {
                                        $(img).on("load", function (e) {
                                            imagesLoaded.push(img);
                                            count += 1;
                                        });
                                    });

                                    FlowControl.new({
                                        condition: function () {
                                            if (count === imgs.length) {
                                                return true;
                                            }

                                            // when processing is synchronous
                                            if (!options.remote) {
                                                if (options.loading) {
                                                    options.loading(main);
                                                    main.centralizeAt(document);
                                                    mainReference.show();
                                                }
                                            }

                                            return false;
                                        },
                                        ready: function () {
                                            // agora já não há mais controle para exibir, estando tão somente na mão do usuário, portanto o método show deve ser melhorado

                                            if (!asynchronousAnswer) {
                                                container.html(contentSource);
                                                main.html(container);
                                            }

                                            main.centralizeAt(document);
                                            resolveHeaderActions(main, options);

                                            if (options.complete) {
                                                mainReference.hide(false);

                                                options.complete
                                                    .call(mainReference);
                                            }
                                        }
                                    });

                                } else {
                                    resolveHeaderActions(main, options);

                                    if (options.complete) {
                                        options.complete.call(mainReference);
                                    }
                                }

                                // talvez tenha que remanejar o disconnect
                                observer.disconnect();
                            });
                        },

                        create = function (remote) {
                            modal = $("

")
                                .addClass("esphinx ui modal");
                            main = $("")
                                .addClass("basicss hidden");
                            mask = $("

")
                                .addClass("basicss fixed transparent mask");
                            container = $("

").addClass("container");

                            modal
                                .append(mask)
                                .append(main);

                            body.append(modal);

                            observeContent(main, options);

                            if (options.remote) {
                                headers = options.header || options.headers
                                || null;
                                params = options.param || options.params
                                || null;
                                ajax.new(contentSource, {
                                    params: params,
                                    headers: headers,
                                    progress: function () {
                                        if (options.loading) {
                                            // callback
                                            options.loading(main);
                                            mainReference.show();
                                        }
                                    },
                                    success: function (a) {
                                        asynchronousAnswer = a;
                                        container.html(asynchronousAnswer);
                                        // because here the processing is asynchronous, it's not linear
                                        mainReference.hide(false);
                                        main.html(container);
                                    }
                                });
                            } else {
                                container.html(contentSource);
                                main.html(container);
                            }

                        };

                    resolveParams();
                    if (!(this instanceof self)) {
                        // debugger
                        // if (self.mainReference) {
                        //     self.mainReference.show();
                        // } else {
                        //     return self.singleton(arguments);
                        // }

                        singleton = Singleton
                            .exists(self, arguments);
                        // debugger
                        if (!singleton) {
                            return Singleton.new(self, arguments);
                        } else {
                            singleton.show();
                        }

                    // that "else" will should to exit for the "show" method can be used by who instanciates it
                    } else {
                        create();
                    }

                    // global scope (public)
                    this.close = function () {
                        main.hide();

                        restartTransition(mask);
                        if (options.fadeOut) {
                            mask.css("transition", "opacity "
                                + options.fadeOut);
                        }
                        mask.addClass("transparent");

                        modal.remove(maskTransitionDuration(mask));

                        mainReference.deleteSingleton();

                        return mainReference;
                    };

                    // this.hide = function (animation) {
                    //     if (typeof animation !== "boolean") {animation = true;}
                    this.hide = function (animation = true) {
                        main.hide();

                        restartTransition(mask);

                        if (animation) {
                            if (options.fadeOut) {
                                mask.css("transition", "opacity "
                                + options.fadeOut);

                                modal.css("z-index", -1,
                                    maskTransitionDuration(mask));
                            }
                        }

                        mask.addClass("transparent");

                        return mainReference;
                    };

                    this.show = function () {
                        var
                            count = 0,
                            imgs;

                        imgs = main.find("img");
                        if (imgs.any()) {
                            imgs.each(function (img) {
                                if (!imagesLoaded.indexPerEquivalence(img)) {
                                    $(img).on("load", function (e) {
                                        count += 1;
                                    });
                                } else {
                                    count += 1;
                                }

                            });

                            FlowControl.new({
                                condition: function () {
                                    if (count === imgs.length) {
                                        return true;
                                    }

                                    return false;
                                },
                                ready: function () {
                                    main.centralizeAt(document);
                                    show();
                                }
                            });

                        } else {
                            show();
                        }

                        return mainReference;
                    };

                    return this;
                }

            }

        }

    });

}(esPhinx.ui));
<|endoftext|>