<commit_before>var fs = require('fs'),
    gulp = require('gulp'),
    plumber = require('gulp-plumber'),
    jade = require('gulp-jade'),
    less = require('gulp-less'),
    csso = require('gulp-csso'),
    newer = require('gulp-newer'),
    concat = require('gulp-concat'),
    base64 = require('gulp-base64'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify'),
    requirejs = require('requirejs'),
    imagemin = require('gulp-imagemin'),
    connect = require('gulp-connect'),
    pleeease = require('gulp-pleeease'),
    sourcemap = require('gulp-sourcemaps'),
    nunjucks = require('gulp-nunjucks-render'),

    src = {
        js: 'layout/js/*.js',
        jade: 'layout/jade/**/*.jade',
        less: 'layout/less/style.less',
        less_all: 'layout/less/**/*.less',
        images: 'layout/img/*',
        bower: {
            js: [
                'bower_components/jquery/jquery.js',
                'bower_components/requirejs/require.js'<% if (backbone) { %>,
                'bower_components/backbone/backbone.js'<% } if (bootstrap) { %>,
                'bower_components/bootstrap/dist/js/bootstrap.js'<% } if (lightbox) { %>,
                'bower_components/lightbox2/js/lightbox.js'<% } if (lodash) { %>,
                'bower_components/lodash/lodash.js'<% } %>
            ],
            css: [
                'bower_components/normalize-css/normalize.css'<% if (bootstrap) { %>,
                'bower_components/bootstrap/dist/css/bootstrap.css'<% } if (font_awesome) { %>,
                'bower_components/components-font-awesome/css/font-awesome.css'<% } if (lightbox) { %>,
                'bower_components/lightbox2/css/lightbox.css'<% } %>
            ],
            img: [<% if (lightbox) { %>
                'bower_components/lightbox2/img/*'<% } %>
            ],
            fonts: [<% if (bootstrap) { %>
                'bower_components/bootstrap/dist/fonts/*'<% } if (font_awesome) { %>
                'bower_components/components-font-awesome/fonts/*'<% } %>
            ]
        }
    },
    dst = '<%= _.slugify(projectName) %>',
    imageminrc = {
        progressive: true,
        svgoPlugins: [{removeViewBox: false}]
    },
    jaderc = {
        pretty: true,
        data: {
            min: false
        }
    },
    requirerc = {
        baseUrl: dst + '/static/js',
        name: 'script',
        out: dst + '/static/js/script.min.js',
        mainConfigFile: dst + '/static/js/script.js',
        paths: {
            jquery: 'empty:',
            backbone: 'empty:',
            bootstrap: 'empty:',
            underscore: 'empty:',
            lightbox: 'empty:'
        }
    },
    lessrc = {
        'strictUnits': true
    },
    pleeeaserc = {
        autoprefixer: {
            browsers: ['> 5%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'],
            cascade: true
        },
        import: {
            path: dst + '/static/css'
        },
        filters: true,
        rem: true,
        opacity: true,
        mqpacker: true,
        minifier: false
    },
    cssorc = {},
    base64rc = {
        extensions: ['svg', 'png', 'gif']
    };

gulp.task('set-min', function(cb) {
    jaderc.data.min = true;
    cb();
});

gulp.task('copy-vendor-js', function() {
    return gulp.src(src.bower.js)
        .pipe(plumber())
        .pipe(rename(function(path) {
            path.basename += '.min'
        }))
        .pipe(newer(dst + '/static/js'))
        .pipe(uglify())
        .pipe(gulp.dest(dst + '/static/js'));
});

gulp.task('copy-vendor-img', function() {
    return !src.bower.img.length || gulp.src(src.bower.img)
        .pipe(plumber())
        .pipe(newer(dst + '/static/img'))
        .pipe(gulp.dest(dst + '/static/img'));
});

gulp.task('copy-vendor-fonts', function() {
    return !src.bower.fonts.length || gulp.src(src.bower.fonts)
        .pipe(plumber())
        .pipe(newer(dst + '/static/fonts'))
        .pipe(gulp.dest(dst + '/static/fonts'));
});

gulp.task('copy-vendor-css', ['copy-vendor-img', 'copy-vendor-fonts'], function() {
    return !src.bower.css.length || gulp.src(src.bower.css)
        .pipe(plumber())
        .pipe(newer(dst + '/static/css'))
        .pipe(gulp.dest(dst + '/static/css'));
});

gulp.task('copy-images', ['copy-vendor-img'], function() {
    return gulp.src(src.images)
        .pipe(plumber())
        .pipe(newer(dst + '/static/img'))
        .pipe(imagemin(imageminrc))
        .pipe(gulp.dest(dst + '/static/img'));
});

gulp.task('js', ['copy-vendor-js'], function() {
    return gulp.src(src.js)
        .pipe(plumber())
        .pipe(sourcemap.init())
        .pipe(newer(dst + '/static/js'))
        .pipe(sourcemap.write())
        .pipe(gulp.dest(dst + '/static/js'))
        .pipe(connect.reload());
});

gulp.task('rjs', ['js'], function(cb) {
    requirejs.optimize(requirerc);
    cb();
});

gulp.task('jade', function() {
    return gulp.src(src.jade)
        .pipe(plumber())
        .pipe(jade(jaderc))
        .pipe(rename(function(path) {
            path.extname = '.j2html';
        }))
        .pipe(gulp.dest(dst + '/templates'))
});

gulp.task('nunjucks', ['jade'], function() {
    nunjucks.nunjucks.configure([dst + '/templates'])
    return gulp.src(dst + '/templates/*.j2html')
        .pipe(plumber())
        .pipe(nunjucks(
            JSON.parse(
                fs.readFileSync('./layout/content.json', 'utf8')
            )
        ))
        .pipe(rename(function(path) {
            path.extname = '.html';
        }))
        .pipe(gulp.dest(dst))
        .pipe(connect.reload());
});

gulp.task('less', ['copy-vendor-css', 'copy-images'], function() {
    return gulp.src(src.less)
        .pipe(plumber())
        .pipe(less(lessrc))
        .pipe(pleeease(pleeeaserc))
        .pipe(gulp.dest(dst + '/static/css'))
        .pipe(connect.reload());
});

gulp.task('css-min', ['less'], function() {
    return gulp.src(dst + '/static/css/style.css')
        .pipe(plumber())
        .pipe(csso(cssorc))
        .pipe(base64(base64rc))
        .pipe(rename('style.min.css'))
        .pipe(gulp.dest(dst + '/static/css'))
        .pipe(connect.reload());
});

gulp.task('server', function() {
    connect.server({
        root: dst,
        port: 3000,
        livereload: true
    });
});

gulp.task('watch', ['server'], function() {
    gulp.watch(src.js, ['js']);
    gulp.watch(src.jade, ['nunjucks']);
    gulp.watch(src.less_all, ['less']);
});

gulp.task('devel', ['js', 'nunjucks', 'less']);
gulp.task('build', ['set-min', 'rjs', 'nunjucks', 'css-min']);

gulp.task('default', ['devel', 'watch']);
<commit_msg>watch to content.json<commit_after>var fs = require('fs'),
    gulp = require('gulp'),
    plumber = require('gulp-plumber'),
    jade = require('gulp-jade'),
    less = require('gulp-less'),
    csso = require('gulp-csso'),
    newer = require('gulp-newer'),
    concat = require('gulp-concat'),
    base64 = require('gulp-base64'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify'),
    requirejs = require('requirejs'),
    imagemin = require('gulp-imagemin'),
    connect = require('gulp-connect'),
    pleeease = require('gulp-pleeease'),
    sourcemap = require('gulp-sourcemaps'),
    nunjucks = require('gulp-nunjucks-render'),

    src = {
        js: 'layout/js/*.js',
        jade: 'layout/jade/**/*.jade',
        less: 'layout/less/style.less',
        less_all: 'layout/less/**/*.less',
        images: 'layout/img/*',
        bower: {
            js: [
                'bower_components/jquery/jquery.js',
                'bower_components/requirejs/require.js'<% if (backbone) { %>,
                'bower_components/backbone/backbone.js'<% } if (bootstrap) { %>,
                'bower_components/bootstrap/dist/js/bootstrap.js'<% } if (lightbox) { %>,
                'bower_components/lightbox2/js/lightbox.js'<% } if (lodash) { %>,
                'bower_components/lodash/lodash.js'<% } %>
            ],
            css: [
                'bower_components/normalize-css/normalize.css'<% if (bootstrap) { %>,
                'bower_components/bootstrap/dist/css/bootstrap.css'<% } if (font_awesome) { %>,
                'bower_components/components-font-awesome/css/font-awesome.css'<% } if (lightbox) { %>,
                'bower_components/lightbox2/css/lightbox.css'<% } %>
            ],
            img: [<% if (lightbox) { %>
                'bower_components/lightbox2/img/*'<% } %>
            ],
            fonts: [<% if (bootstrap) { %>
                'bower_components/bootstrap/dist/fonts/*'<% } if (font_awesome) { %>
                'bower_components/components-font-awesome/fonts/*'<% } %>
            ]
        }
    },
    dst = '<%= _.slugify(projectName) %>',
    imageminrc = {
        progressive: true,
        svgoPlugins: [{removeViewBox: false}]
    },
    jaderc = {
        pretty: true,
        data: {
            min: false
        }
    },
    requirerc = {
        baseUrl: dst + '/static/js',
        name: 'script',
        out: dst + '/static/js/script.min.js',
        mainConfigFile: dst + '/static/js/script.js',
        paths: {
            jquery: 'empty:',
            backbone: 'empty:',
            bootstrap: 'empty:',
            underscore: 'empty:',
            lightbox: 'empty:'
        }
    },
    lessrc = {
        'strictUnits': true
    },
    pleeeaserc = {
        autoprefixer: {
            browsers: ['> 5%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'],
            cascade: true
        },
        import: {
            path: dst + '/static/css'
        },
        filters: true,
        rem: true,
        opacity: true,
        mqpacker: true,
        minifier: false
    },
    cssorc = {},
    base64rc = {
        extensions: ['svg', 'png', 'gif']
    };

gulp.task('set-min', function(cb) {
    jaderc.data.min = true;
    cb();
});

gulp.task('copy-vendor-js', function() {
    return gulp.src(src.bower.js)
        .pipe(plumber())
        .pipe(rename(function(path) {
            path.basename += '.min'
        }))
        .pipe(newer(dst + '/static/js'))
        .pipe(uglify())
        .pipe(gulp.dest(dst + '/static/js'));
});

gulp.task('copy-vendor-img', function() {
    return !src.bower.img.length || gulp.src(src.bower.img)
        .pipe(plumber())
        .pipe(newer(dst + '/static/img'))
        .pipe(gulp.dest(dst + '/static/img'));
});

gulp.task('copy-vendor-fonts', function() {
    return !src.bower.fonts.length || gulp.src(src.bower.fonts)
        .pipe(plumber())
        .pipe(newer(dst + '/static/fonts'))
        .pipe(gulp.dest(dst + '/static/fonts'));
});

gulp.task('copy-vendor-css', ['copy-vendor-img', 'copy-vendor-fonts'], function() {
    return !src.bower.css.length || gulp.src(src.bower.css)
        .pipe(plumber())
        .pipe(newer(dst + '/static/css'))
        .pipe(gulp.dest(dst + '/static/css'));
});

gulp.task('copy-images', ['copy-vendor-img'], function() {
    return gulp.src(src.images)
        .pipe(plumber())
        .pipe(newer(dst + '/static/img'))
        .pipe(imagemin(imageminrc))
        .pipe(gulp.dest(dst + '/static/img'));
});

gulp.task('js', ['copy-vendor-js'], function() {
    return gulp.src(src.js)
        .pipe(plumber())
        .pipe(sourcemap.init())
        .pipe(newer(dst + '/static/js'))
        .pipe(sourcemap.write())
        .pipe(gulp.dest(dst + '/static/js'))
        .pipe(connect.reload());
});

gulp.task('rjs', ['js'], function(cb) {
    requirejs.optimize(requirerc);
    cb();
});

gulp.task('jade', function() {
    return gulp.src(src.jade)
        .pipe(plumber())
        .pipe(jade(jaderc))
        .pipe(rename(function(path) {
            path.extname = '.j2html';
        }))
        .pipe(gulp.dest(dst + '/templates'))
});

gulp.task('nunjucks', ['jade'], function() {
    nunjucks.nunjucks.configure([dst + '/templates'])
    return gulp.src(dst + '/templates/*.j2html')
        .pipe(plumber())
        .pipe(nunjucks(
            JSON.parse(
                fs.readFileSync('./layout/content.json', 'utf8')
            )
        ))
        .pipe(rename(function(path) {
            path.extname = '.html';
        }))
        .pipe(gulp.dest(dst))
        .pipe(connect.reload());
});

gulp.task('less', ['copy-vendor-css', 'copy-images'], function() {
    return gulp.src(src.less)
        .pipe(plumber())
        .pipe(less(lessrc))
        .pipe(pleeease(pleeeaserc))
        .pipe(gulp.dest(dst + '/static/css'))
        .pipe(connect.reload());
});

gulp.task('css-min', ['less'], function() {
    return gulp.src(dst + '/static/css/style.css')
        .pipe(plumber())
        .pipe(csso(cssorc))
        .pipe(base64(base64rc))
        .pipe(rename('style.min.css'))
        .pipe(gulp.dest(dst + '/static/css'))
        .pipe(connect.reload());
});

gulp.task('server', function() {
    connect.server({
        root: dst,
        port: 3000,
        livereload: true
    });
});

gulp.task('watch', ['server'], function() {
    gulp.watch(src.js, ['js']);
    gulp.watch(src.jade, ['nunjucks']);
    gulp.watch('./layout/content.json', ['nunjucks']);
    gulp.watch(src.less_all, ['less']);
});

gulp.task('devel', ['js', 'nunjucks', 'less']);
gulp.task('build', ['set-min', 'rjs', 'nunjucks', 'css-min']);

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


<commit_before>/*
 * common part for `nw` && `connectjs` front ends
 */

var app// FIXME: check if this can be just `App`, one global var is needed

(function gc_wrapper(con){
    app = {
        config: null,
        btn: null,// quick launch buttons to access when error
        extjs_load: extjs_load_gc_wrapped
    }
    return

/* init stuff must be garbage collected */

function extjs_load_gc_wrapped(doc ,w){
var path, extjs

    if(app.config.extjs.load.css.length){
        for(path in app.config.extjs.load.css){
            css_load(app.config.extjs.load.css[path], app.config.backend.url)
        }
    }
    path = app.config.extjs.path
    css_load(path + 'resources/css/ext-all.css')
    extjs = doc.createElement('script')
    extjs.setAttribute('type', 'application/javascript')
    extjs.setAttribute('charset', 'utf-8')
    extjs.setAttribute('src', path + 'ext-all-nw.js')//`loadScriptFile()` fixed
    doc.head.appendChild(extjs)

    extjs = setInterval(function waiting_extjs(){
        if(!w.Ext) return// waiting if xhr HEAD check is done

        clearInterval(extjs)
        app.extjs_load = null//mark for GC
        path = Ext.Loader.getPath('Ext')//ExtJS 5: config is OK, remove this
        extjs = path + '/../locale/ext-lang-' + l10n.lang + '.js'
        Ext.Loader.loadScript({
            url: extjs,
            onError: function fail_load_locale(){
                throw new Error('Error loading locale file:\n' + extjs)
            }
        })
        con.log(
            'ExtJS version: ' + Ext.getVersion('extjs') + '\n ' +
            'ExtJS locale: ' + l10n.lang + '\n ' +
            'ExtJS is at <' + path + '>'
        )
        Ext.Loader.setPath('Ext.ux', path + '/../examples/ux')
        Ext.Loader.setPath('Ext.uxo', app.config.extjs.appFolder + '/uxo')

        if(app.config.backend.url){// `nw` context`
            app.config.extjs.appFolder = app.config.backend.url
           /*
            * patch ExtJS Loader to work from "file://" in `node-webkit`
            * also `debugSourceURL` removed in `ext-all-debug.js#loadScriptFile()`
            * it crushes `eval` there
            **/
            Ext.Loader._getPath = Ext.Loader.getPath
            Ext.Loader.getPath = function getPath(className){
                return '/' == className[0] ?
                    app.config.backend.url + className + '.js' :
                    Ext.Loader._getPath(className)
            }
        }

        app.config.extjs.launch = extjs_launch
        app.config.extjs.controllers.push('Main')
        Ext.application(app.config.extjs)

        return
    }, 1024)
    con.log('extjs_load: done, waiting for ExtJS')

    return

    function css_load(url, backend){
        var el = doc.createElement('link')
        el.setAttribute('rel', 'stylesheet')
        el.setAttribute('href', (backend || '') + url)
        doc.head.appendChild(el)
    }
}

function extjs_launch(){
    delete app.config.extjs.launch
    app.config.createViewport = true
    delete app.extjs_load

    // global `App` object is available now
    if(app.backend_check){
        App.doCheckBackend = app.backend_check
        App.doRestartBackend = app.backend_restart
        App.doTerminateBackend = app.backend_terminate

        delete app.backend_check
        delete app.backend_restart
        delete app.backend_terminate
    }
    App.cfg = app.config
    App.backendURL = App.cfg.backend.url || ''
    App.create = sub_app_create
    App.reload = sub_app_reload_devel_view
    App.getHelpAbstract = get_help_abstract

   /*
    * l10n: Access existing data via e.g.:
    * > l10n.docOpenAll
    * When developing to have some placeholders and viewable content without
    * need to fill of the `l10n` files use call:
    * > l10n('create_season')
    * The namespace of a module can be selected by:
    * > l10n._ns = 'so'; 'code with l10n("stuff")' ; l10n._ns = ''
    * > l10n.so.stuff
    **/
    var t = l10n
    l10n = l10n_provider
    l10n._ns = ''
    Ext.apply(l10n, t)

    // NOTE: Ext JSON decoding is useful for JS-as-JSON with `l10n` as values
    con.log('ExtJS Ext.encode: always native `JSON.stringify()`')
    Ext.encode = JSON.stringify

    Ext.state.Manager.setProvider(new Ext.state.LocalStorageProvider)
    Ext.Error.handle = Ext_Error_handle// by Ext.Error.raise()
    // Start loading The Application
    Ext.syncRequire('App.backend.Connection')// `req`<->`res` with backend
    Ext.syncRequire('App.model.Base') // loading Models manually, then [M]VC
    Ext.syncRequire('App.store.CRUD') // our CRUD for `Ext.data.*`
    Ext.syncRequire('App.view.Window')// provide core View Class(es)

    t = App.cfg.extjs.load.requireLaunch.length
    if(t){// load stuff required by backend
    var j, i = 0, l = Ext.fly('startup').dom.lastChild

        do {
            l.innerHTML += '
' + (j = App.cfg.extjs.load.requireLaunch[i])
            Ext.syncRequire(j)
        } while(++i < t)
    }

    if(App.cfg.createViewport){// if no app module (e.g. userman auth) does that
        Ext.globalEvents.fireEvent('createViewport')
    }

    con.log('ExtJS + App launch: OK')
}

function l10n_provider(msg){
var me, m, idx, tail

    me = (me = l10n._ns) ? l10n[me] : l10n

    idx = msg.indexOf(':')

    if(idx > 0){
        tail = msg.slice(idx + 1)
        msg = msg.slice(0, idx)

        return me && (m = me[msg]) ?
               m + '

' + tail + '
' :
               msg
    }

    return me && (m = me[msg]) ? m : msg
}

function sub_app_create(ns, btn, cfg){
/*
 * There are classes with run time development reloading for
 * - controllers (e.g. 'App.userman.Chat'),
 * - slow view:
 *     Ext.define('App.view.Chat',...)
 * - and fast view definitions (config only):
 *     App.cfg['App.view.Userman'] = { ... }
 **/
    btn && (app.btn = btn).setLoading(true)

    if(!(~ns.indexOf('.app.'))){
        ns = 'App.' + ns// if class name from "App" (this) namespace

        if(btn){// normal load && launch via button (not dev reload)
            if(Ext.ClassManager.classes[ns]){
                run_module()
                return
            }
            Ext.syncRequire(ns)
        }
    }

    if(~ns.indexOf('.controller.')){
        App.getApplication().getController(ns)
        btn && btn.setLoading(false)
        return
    }

    // define a Class *only* once
    // use `override` to redefine it (e.g. when developing) in run time
    if(App.cfg[ns]){
        btn || (App.cfg[ns].override = ns)// no button -- development reload
        Ext.define(ns, App.cfg[ns], run_module)
        App.cfg[ns] = null// GC
        return
        /* Noticed: multiple `Ext.define('some.view')` is fine from (re)loaded JS file */
    }

    Ext.Msg.show({
       title: l10n.errun_title,
       buttons: Ext.Msg.OK,
       icon: Ext.Msg.ERROR,
       msg:
"Can't do `App.create('" + ns + "')`!

" +
"`App.create()` is only used with `App.cfg['Class.name']` definitions
" +
"in app modules for fast initial App loading."
    })
    btn && btn.setLoading(false)
    return

    function run_module(){
        if(~ns.indexOf('.app.')){
            Ext.application(ns)
        } else if(~ns.indexOf('.controller.')){
            App.getApplication().getController(ns)
        } else {// usually plain views
            Ext.create(ns, cfg)
        }
        btn && btn.setLoading(false)
    }
}

function sub_app_reload_devel_view(panel, tool, event){
var url, url_l10n

    if(!panel.wmId){
        console.warn("window doesn't support development mode")
        return
    }

    panel.destroy()// models, stores and backend can be reloaded there

    url_l10n = App.backendURL + '/l10n/' + panel.wmId
              .replace(/([^.]+)[.].*$/, l10n.lang + '_$1.js')
    Ext.Loader.loadScript({
        url: url_l10n
       ,onLoad: function l10n_reloaded(){
            Ext.Loader.removeScriptElement(url_l10n)
            url = App.backendURL + '/' +
                    panel.wmId.replace(/[.]/g, '/') + '.js'
            Ext.Loader.loadScript({
                url: url
               ,onLoad: view_loaded
            })
        }
    })

    return

    function view_loaded(){
        Ext.Loader.removeScriptElement(url)
        Ext.Loader.loadScript({
            url: url = url.replace(/[/]view[/]/, '/controller/')
           ,onLoad: function ctl_loaded(){
                Ext.Loader.removeScriptElement(url)
                App.create(panel.wmId.replace(/view[.]/, 'controller.'))
            }
           ,onError: function ctl_not_loaded(){
                Ext.Loader.removeScriptElement(url)
                App.create(panel.wmId, null,{
                    constrainTo: Ext.getCmp('desk').getEl()
                })
            }
        })
    }
}

function get_help_abstract(panel, tool, event){
    console.warn('abstract method')
}

function Ext_Error_handle(err){
    Ext.Msg.show({
        title: l10n.errun_title,
        buttons: Ext.Msg.OK,
        icon: Ext.Msg.ERROR,
        msg: '' +
err.msg.slice(0, 177) + '...

sourceClass: ' +
err.sourceClass + '
sourceMethod: ' +
err.sourceMethod + ''
    })
    return !con.warn(err)
}

})(window.console)
<commit_msg>createViewport: fix check<commit_after>/*
 * common part for `nw` && `connectjs` front ends
 */

var app// FIXME: check if this can be just `App`, one global var is needed

(function gc_wrapper(con){
    app = {
        config: null,
        btn: null,// quick launch buttons to access when error
        extjs_load: extjs_load_gc_wrapped
    }
    return

/* init stuff must be garbage collected */

function extjs_load_gc_wrapped(doc ,w){
var path, extjs

    if(app.config.extjs.load.css.length){
        for(path in app.config.extjs.load.css){
            css_load(app.config.extjs.load.css[path], app.config.backend.url)
        }
    }
    path = app.config.extjs.path
    css_load(path + 'resources/css/ext-all.css')
    extjs = doc.createElement('script')
    extjs.setAttribute('type', 'application/javascript')
    extjs.setAttribute('charset', 'utf-8')
    extjs.setAttribute('src', path + 'ext-all-nw.js')//`loadScriptFile()` fixed
    doc.head.appendChild(extjs)

    extjs = setInterval(function waiting_extjs(){
        if(!w.Ext) return// waiting if xhr HEAD check is done

        clearInterval(extjs)
        app.extjs_load = null//mark for GC
        path = Ext.Loader.getPath('Ext')//ExtJS 5: config is OK, remove this
        extjs = path + '/../locale/ext-lang-' + l10n.lang + '.js'
        Ext.Loader.loadScript({
            url: extjs,
            onError: function fail_load_locale(){
                throw new Error('Error loading locale file:\n' + extjs)
            }
        })
        con.log(
            'ExtJS version: ' + Ext.getVersion('extjs') + '\n ' +
            'ExtJS locale: ' + l10n.lang + '\n ' +
            'ExtJS is at <' + path + '>'
        )
        Ext.Loader.setPath('Ext.ux', path + '/../examples/ux')
        Ext.Loader.setPath('Ext.uxo', app.config.extjs.appFolder + '/uxo')

        if(app.config.backend.url){// `nw` context`
            app.config.extjs.appFolder = app.config.backend.url
           /*
            * patch ExtJS Loader to work from "file://" in `node-webkit`
            * also `debugSourceURL` removed in `ext-all-debug.js#loadScriptFile()`
            * it crushes `eval` there
            **/
            Ext.Loader._getPath = Ext.Loader.getPath
            Ext.Loader.getPath = function getPath(className){
                return '/' == className[0] ?
                    app.config.backend.url + className + '.js' :
                    Ext.Loader._getPath(className)
            }
        }

        app.config.extjs.launch = extjs_launch
        app.config.extjs.controllers.push('Main')
        Ext.application(app.config.extjs)

        return
    }, 1024)
    con.log('extjs_load: done, waiting for ExtJS')

    return

    function css_load(url, backend){
        var el = doc.createElement('link')
        el.setAttribute('rel', 'stylesheet')
        el.setAttribute('href', (backend || '') + url)
        doc.head.appendChild(el)
    }
}

function extjs_launch(){
    delete app.config.extjs.launch
    delete app.extjs_load

    // global `App` object is available now
    if(app.backend_check){
        App.doCheckBackend = app.backend_check
        App.doRestartBackend = app.backend_restart
        App.doTerminateBackend = app.backend_terminate

        delete app.backend_check
        delete app.backend_restart
        delete app.backend_terminate
    }
    App.cfg = app.config
    App.backendURL = App.cfg.backend.url || ''
    App.create = sub_app_create
    App.reload = sub_app_reload_devel_view
    App.getHelpAbstract = get_help_abstract

   /*
    * l10n: Access existing data via e.g.:
    * > l10n.docOpenAll
    * When developing to have some placeholders and viewable content without
    * need to fill of the `l10n` files use call:
    * > l10n('create_season')
    * The namespace of a module can be selected by:
    * > l10n._ns = 'so'; 'code with l10n("stuff")' ; l10n._ns = ''
    * > l10n.so.stuff
    **/
    var t = l10n
    l10n = l10n_provider
    l10n._ns = ''
    Ext.apply(l10n, t)

    // NOTE: Ext JSON decoding is useful for JS-as-JSON with `l10n` as values
    con.log('ExtJS Ext.encode: always native `JSON.stringify()`')
    Ext.encode = JSON.stringify

    Ext.state.Manager.setProvider(new Ext.state.LocalStorageProvider)
    Ext.Error.handle = Ext_Error_handle// by Ext.Error.raise()
    // Start loading The Application
    Ext.syncRequire('App.backend.Connection')// `req`<->`res` with backend
    Ext.syncRequire('App.model.Base') // loading Models manually, then [M]VC
    Ext.syncRequire('App.store.CRUD') // our CRUD for `Ext.data.*`
    Ext.syncRequire('App.view.Window')// provide core View Class(es)

    t = App.cfg.extjs.load.requireLaunch.length
    if(t){// load stuff required by backend
    var j, i = 0, l = Ext.fly('startup').dom.lastChild

        do {
            l.innerHTML += '
' + (j = App.cfg.extjs.load.requireLaunch[i])
            Ext.syncRequire(j)
        } while(++i < t)
    }

    if(false !== App.cfg.createViewport){// if no app module (e.g. userman auth) does that
        Ext.globalEvents.fireEvent('createViewport')
    }

    con.log('ExtJS + App launch: OK')
}

function l10n_provider(msg){
var me, m, idx, tail

    me = (me = l10n._ns) ? l10n[me] : l10n

    idx = msg.indexOf(':')

    if(idx > 0){
        tail = msg.slice(idx + 1)
        msg = msg.slice(0, idx)

        return me && (m = me[msg]) ?
               m + '

' + tail + '
' :
               msg
    }

    return me && (m = me[msg]) ? m : msg
}

function sub_app_create(ns, btn, cfg){
/*
 * There are classes with run time development reloading for
 * - controllers (e.g. 'App.userman.Chat'),
 * - slow view:
 *     Ext.define('App.view.Chat',...)
 * - and fast view definitions (config only):
 *     App.cfg['App.view.Userman'] = { ... }
 **/
    btn && (app.btn = btn).setLoading(true)

    if(!(~ns.indexOf('.app.'))){
        ns = 'App.' + ns// if class name from "App" (this) namespace

        if(btn){// normal load && launch via button (not dev reload)
            if(Ext.ClassManager.classes[ns]){
                run_module()
                return
            }
            Ext.syncRequire(ns)
        }
    }

    if(~ns.indexOf('.controller.')){
        App.getApplication().getController(ns)
        btn && btn.setLoading(false)
        return
    }

    // define a Class *only* once
    // use `override` to redefine it (e.g. when developing) in run time
    if(App.cfg[ns]){
        btn || (App.cfg[ns].override = ns)// no button -- development reload
        Ext.define(ns, App.cfg[ns], run_module)
        App.cfg[ns] = null// GC
        return
        /* Noticed: multiple `Ext.define('some.view')` is fine from (re)loaded JS file */
    }

    Ext.Msg.show({
       title: l10n.errun_title,
       buttons: Ext.Msg.OK,
       icon: Ext.Msg.ERROR,
       msg:
"Can't do `App.create('" + ns + "')`!

" +
"`App.create()` is only used with `App.cfg['Class.name']` definitions
" +
"in app modules for fast initial App loading."
    })
    btn && btn.setLoading(false)
    return

    function run_module(){
        if(~ns.indexOf('.app.')){
            Ext.application(ns)
        } else if(~ns.indexOf('.controller.')){
            App.getApplication().getController(ns)
        } else {// usually plain views
            Ext.create(ns, cfg)
        }
        btn && btn.setLoading(false)
    }
}

function sub_app_reload_devel_view(panel, tool, event){
var url, url_l10n

    if(!panel.wmId){
        con.warn("window doesn't support development mode")
        return
    }

    panel.destroy()// models, stores and backend can be reloaded there

    url_l10n = App.backendURL + '/l10n/' + panel.wmId
              .replace(/([^.]+)[.].*$/, l10n.lang + '_$1.js')
    Ext.Loader.loadScript({
        url: url_l10n
       ,onLoad: function l10n_reloaded(){
            Ext.Loader.removeScriptElement(url_l10n)
            url = App.backendURL + '/' +
                    panel.wmId.replace(/[.]/g, '/') + '.js'
            Ext.Loader.loadScript({
                url: url
               ,onLoad: view_loaded
            })
        }
    })

    return

    function view_loaded(){
        Ext.Loader.removeScriptElement(url)
        Ext.Loader.loadScript({
            url: url = url.replace(/[/]view[/]/, '/controller/')
           ,onLoad: function ctl_loaded(){
                Ext.Loader.removeScriptElement(url)
                App.create(panel.wmId.replace(/view[.]/, 'controller.'))
            }
           ,onError: function ctl_not_loaded(){
                Ext.Loader.removeScriptElement(url)
                App.create(panel.wmId, null,{
                    constrainTo: Ext.getCmp('desk').getEl()
                })
            }
        })
    }
}

function get_help_abstract(panel, tool, event){
    con.warn('abstract method')
}

function Ext_Error_handle(err){
    Ext.Msg.show({
        title: l10n.errun_title,
        buttons: Ext.Msg.OK,
        icon: Ext.Msg.ERROR,
        msg: '' +
err.msg.slice(0, 177) + '...

sourceClass: ' +
err.sourceClass + '
sourceMethod: ' +
err.sourceMethod + ''
    })
    return !con.warn(err)
}

})(window.console)
<|endoftext|>


<commit_before>'use strict';
// generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {<% if (includeSass) { %>
  return gulp.src('app/styles/main.scss')
    .pipe($.plumber())
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10
    }))<% } else { %>
  return gulp.src('app/styles/main.css')<% } %>
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('.tmp/styles'));
});

gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
});

gulp.task('html', ['styles'], function () {<% if (includeBootstrap && includeSass) { %>
  var lazypipe = require('lazypipe');
  var cssChannel = lazypipe()
    .pipe($.csso)
    .pipe($.replace, 'bower_components/bootstrap-sass-official/vendor/assets/fonts/bootstrap','fonts');<% } %>
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/*.html')
    .pipe(assets)
    .pipe($.if('*.js', $.uglify()))<% if (includeBootstrap && includeSass) { %>
    .pipe($.if('*.css', cssChannel()))<% } else { %>
    .pipe($.if('*.css', $.csso()))<% } %>
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest('dist'));
});

gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', function () {
  return gulp.src(require('main-bower-files')().concat('app/fonts/**/*'))
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('extras', function () {
  return gulp.src([
    'app/*.*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

gulp.task('clean', require('del').bind(null, ['.tmp', 'dist']));

gulp.task('connect', function () {
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')()
    .use(require('connect-livereload')({port: 35729}))
    .use(serveStatic('app'))
    .use(serveStatic('.tmp'))
    // paths to bower_components should be relative to the current file
    // e.g. in app/index.html you should use ../bower_components
    .use('/bower_components', serveStatic('bower_components'))
    .use(serveIndex('app'));

  require('http').createServer(app)
    .listen(9000)
    .on('listening', function () {
      console.log('Started connect web server on http://localhost:9000');
    });
});

gulp.task('serve', ['connect'<% if (includeSass) { %>, 'styles'<% } %>], function () {
  require('opn')('http://localhost:9000');
});

// inject bower components
gulp.task('wiredep', function () {
  var wiredep = require('wiredep').stream;
<% if (includeSass) { %>
  gulp.src('app/styles/*.scss')
    .pipe(wiredep({directory: 'bower_components'}))
    .pipe(gulp.dest('app/styles'));
<% } %>
  gulp.src('app/*.html')
    .pipe(wiredep({
      directory: 'bower_components'<% if (includeSass && includeBootstrap) { %>,
      exclude: ['bootstrap-sass-official']<% } %>
    }))
    .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect', 'serve'], function () {
  $.livereload.listen();

  // watch for changes
  gulp.watch([
    'app/*.html',
    '.tmp/styles/**/*.css',
    'app/scripts/**/*.js',
    'app/images/**/*'
  ]).on('change', $.livereload.changed);

  gulp.watch('app/styles/**/*.<%= includeSass ? 'scss' : 'css' %>', ['styles']);
  gulp.watch('bower.json', ['wiredep']);
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});
<commit_msg>Fix Bootstrap replaced font path when building<commit_after>'use strict';
// generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {<% if (includeSass) { %>
  return gulp.src('app/styles/main.scss')
    .pipe($.plumber())
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10
    }))<% } else { %>
  return gulp.src('app/styles/main.css')<% } %>
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('.tmp/styles'));
});

gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
});

gulp.task('html', ['styles'], function () {<% if (includeBootstrap && includeSass) { %>
  var lazypipe = require('lazypipe');
  var cssChannel = lazypipe()
    .pipe($.csso)
    .pipe($.replace, 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap','fonts');<% } %>
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/*.html')
    .pipe(assets)
    .pipe($.if('*.js', $.uglify()))<% if (includeBootstrap && includeSass) { %>
    .pipe($.if('*.css', cssChannel()))<% } else { %>
    .pipe($.if('*.css', $.csso()))<% } %>
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest('dist'));
});

gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', function () {
  return gulp.src(require('main-bower-files')().concat('app/fonts/**/*'))
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('extras', function () {
  return gulp.src([
    'app/*.*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

gulp.task('clean', require('del').bind(null, ['.tmp', 'dist']));

gulp.task('connect', function () {
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')()
    .use(require('connect-livereload')({port: 35729}))
    .use(serveStatic('app'))
    .use(serveStatic('.tmp'))
    // paths to bower_components should be relative to the current file
    // e.g. in app/index.html you should use ../bower_components
    .use('/bower_components', serveStatic('bower_components'))
    .use(serveIndex('app'));

  require('http').createServer(app)
    .listen(9000)
    .on('listening', function () {
      console.log('Started connect web server on http://localhost:9000');
    });
});

gulp.task('serve', ['connect'<% if (includeSass) { %>, 'styles'<% } %>], function () {
  require('opn')('http://localhost:9000');
});

// inject bower components
gulp.task('wiredep', function () {
  var wiredep = require('wiredep').stream;
<% if (includeSass) { %>
  gulp.src('app/styles/*.scss')
    .pipe(wiredep({directory: 'bower_components'}))
    .pipe(gulp.dest('app/styles'));
<% } %>
  gulp.src('app/*.html')
    .pipe(wiredep({
      directory: 'bower_components'<% if (includeSass && includeBootstrap) { %>,
      exclude: ['bootstrap-sass-official']<% } %>
    }))
    .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect', 'serve'], function () {
  $.livereload.listen();

  // watch for changes
  gulp.watch([
    'app/*.html',
    '.tmp/styles/**/*.css',
    'app/scripts/**/*.js',
    'app/images/**/*'
  ]).on('change', $.livereload.changed);

  gulp.watch('app/styles/**/*.<%= includeSass ? 'scss' : 'css' %>', ['styles']);
  gulp.watch('bower.json', ['wiredep']);
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});
<|endoftext|>


<commit_before>/*global define */

(function () {
    "use strict";

    console.log('DestWndSetupCtrl setup');
    var areWeInitialized = false;
    define([
        'angular'
    ], function (angular) {
        console.log('DestWndSetupCtrl define');

        var selfdict = {},
            scopeDict = {};
        selfdict.isInitialized = areWeInitialized = false;

        function DestWndSetupCtrl($scope, $modal, $rootScope) {
            console.log("in DestWndSetupCtrl");
            selfdict.scope = $scope;
            selfdict.isInitialized = areWeInitialized = false;
            scopeDict.rootScope = $rootScope;

            // selfdict.callbackFunction = null;
            $scope.showDestDialog = false;
            $scope.choiceCallback = null;
            $scope.destSelections = ["Same Window", "New Tab", "New Pop-up Window"];
            $scope.data = {
                dstSel : $scope.destSelections[0].slice(0),
                prevDstSel : $scope.destSelections[0].slice(0),
                whichDismiss : "Cancel",
                dlg2show : "SelectWndDlg",
                title : 'do we have a title?',
                icon : null,
                snippet : 'nothing in snippet',
                showDetail : '+'
            };

            $scope.preserveState = function () {
                console.log("preserveState");
                // $scope.data.whichDismiss = 'Cancel';
                $scope.data.prevDstSel = $scope.data.dstSel.slice(0);
                console.log("preserve " + $scope.data.prevDstSel + " from " + $scope.data.dstSel);
            };

            $scope.restoreState = function () {
                console.log("restoreState");
                // $scope.data.whichDismiss = 'Accept';
                console.log("restore " + $scope.data.dstSel + " from " + $scope.data.prevDstSel);
                $scope.data.dstSel = $scope.data.prevDstSel.slice(0);
            };

            $scope.showDialog = function (choiceCallback, args) {
                $scope.choiceCallback = choiceCallback;
                var title = args.title,
                    icon = args.thumbnail,
                    snippet = args.snippet;
                $scope.data.title = title;
                $scope.data.icon = icon;
                $scope.data.snippet = snippet;
                $scope.showDestDialog = true;
            };

            $scope.onAcceptDestination = function () {
                console.log("onAcceptDestination " + $scope.data.dstSel);
                var callback = $scope.choiceCallback;
                if ($scope.choiceCallback) {
                    $scope.choiceCallback = null;
                    callback($scope.data.dstSel);
                } else {
                    scopeDict.rootScope.$broadcast('DestinationSelectorEvent', { destWnd: $scope.data.dstSel });
                }
            };

            $scope.hitEnter = function (evt) {
                if (angular.equals(evt.keyCode, 13) && !(angular.equals($scope.name, null) || angular.equals($scope.name, ''))) {
                    $scope.save();
                }
            }; // end hitEnter

            $scope.safeApply = function (fn) {
                var phase = this.$root.$$phase;
                if (phase === '$apply' || phase === '$digest') {
                    if (fn && (typeof fn === 'function')) {
                        fn();
                    }
                } else {
                    this.$apply(fn);
                }
            };
        }

        DestWndSetupCtrl.prototype.isInitialized = function () {
            return areWeInitialized;
        };

        DestWndSetupCtrl.prototype.showDialog = function (choiceCallback) {
            $scope.$scope.choiceCallback = choiceCallback;
            $scope.showDialog($scope.choiceCallback);
        };

        function init(App) {
            console.log('DestWndSetupCtrl init');

            selfdict.isInitialized = areWeInitialized = true;
            App.controller('DestWndSetupCtrl',  ['$scope', '$modal', '$rootScope', DestWndSetupCtrl]);

            App.directive("modalShowDest", function () {
                console.log("setting up directive modalShowDest");
                return {
                    restrict: "A",   /* why doesn't "E" work? */
                     /*
                    It will check the cache for inlined templates and if one is not found
                    it will make an xhr to the url to fetch the template.
                    The url with "/" prefix is relative to the domain, without the "/" prefix
                    it will be relative to the main ("index.html") page or
                    base url (if you use location in the html5 mode).
                    */

                    templateUrl : '/templates/DestSelectDlgGen',   // .jade will be appended
                    // template : '<ng-include src="getContentUrl()"/>',
                    replace : true,
                    transclude: true,
                    scope: {
                        modalVisible: "=",
                        modalMdata: "="
                    },

                    controller: function ($scope) {
                        console.log("setting up directive modalShowDest controller");
                        $scope.getContentUrl = function () {
                            console.log("find file modalShowDest html");
                            return '/templates/DestSelectDlgGen.html';
                        };

                        $scope.status = {
                            'detailsOpen' : false,
                            'destChoicesOpen' : false
                        };
                        /*
                        $scope.onShowDetailsClick = function () {
                            $scope.status.detailsOpen = !$scope.status.detailsOpen;
                            if ($scope.status.detailsOpen && $scope.status.destChoicesOpen) {
                                $scope.status.destChoicesOpen = false;
                            }
                            // $scope.status.destChoicesOpen = !$scope.status.destChoicesOpen;
                        }

                        $scope.onDestChoiceClick = function () {
                            $scope.status.destChoicesOpen = !$scope.status.destChoicesOpen;
                            if ($scope.status.destChoicesOpen && $scope.status.detailsOpen) {
                                $scope.status.detailsOpen = false;
                            }
                            // $scope.status.detailsOpen = !$scope.status.detailsOpen;
                        }
                        */
                    },

                    link: function (scope, element, attrs) {
                        var localScope = scope;
                        //Hide or show the modal
                        scope.showModal = function (visible, elem) {
                            if (!elem) {
                                elem = element;
                            }
                            scope.status.detailsOpen = scope.status.destChoicesOpen = false;
                            scope.$parent.safeApply(function () {
                                scope.status.detailsOpen = scope.status.destChoicesOpen = false;
                            });
                            if (visible) {
                                $(elem).modal311("show");
                            } else {
                                $(elem).modal311("hide");
                            }
                        };

                        scope.$on('ShowWindowSelectorModalEvent', function (event, args) {
                            var title = args.title,
                                icon = args.thumbnail,
                                snippet = args.snippet;
                            localScope.$parent.data.title = title;
                            localScope.$parent.data.icon = icon;
                            localScope.$parent.data.snippet = snippet;
                            localScope.$parent.safeApply(function () {
                                localScope.status.detailsOpen = localScope.status.destChoicesOpen = false;
                            });
                            // localScope.status.detailsOpen = localScope.status.destChoicesOpen = false;
                            console.log('local scope.$on received title : ' + title);

                            localScope.$parent.safeApply(function () {
                                localScope.$parent.showDestDialog = true;
                            });
                        });

                        //Check to see if the modal-visible attribute exists
                        if (!attrs.modalVisible) {
                            //The attribute isn't defined, show the modal by default
                            scope.showModal(true);
                        } else {
                            //Watch for changes to the modal-visible attribute
                            scope.$watch("modalVisible", function (newValue, oldValue) {
                                scope.showModal(newValue);
                                console.log("watch modalVisible  : ");
                                console.debug(scope.$parent.data);
                                // scope.$parent.preserveState();
                            });
                            //Watch for changes to the modal-mdata attribute
                            scope.$watch("modalMdata", function (newValue, oldValue) {
                                if (!angular.isUndefinedOrNull(newValue)) {
                                    localScope.$parent.data = newValue;
                                }
                                console.log("watch modalMdata scope.$parent data  : ");
                                console.debug(localScope.$parent.data);
                            });
                            //Watch for changes to the modal-mdata attribute
                            scope.$watch("data.dstSel", function (newValue, oldValue) {
                                if (!angular.isUndefinedOrNull(newValue)) {
                                    localScope.$parent.data.dstSel = newValue;
                                }
                                console.log("watch modalMdata scope.$parent data  : ");
                                console.debug(localScope.$parent.data);
                            });

                            scope.$watch('scope.$parent.showDestDialog', function (newValue, oldValue) {
                                console.log("scope.$watch newValue : " + newValue);
                                console.log("scope.$watch 'scope.$parent.showDestDialog' : " + scope.$parent.showDestDialog);
                                scope.showModal(newValue);
                                //attrs.modalVisible = false;
                            });

                        }
                        //Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
                        $(element).on('hidden.bs.modal', function () {
                            scope.modalVisible = localScope.$parent.showDestDialog = localScope.showDestDialog =false;
                            scope.status.detailsOpen = scope.status.destChoicesOpen = false;
                            scope.$parent.data.title = '';
                            scope.$parent.data.icon = null;
                            scope.$parent.data.snippet = '';
                            console.log("hide event called");
                            if (!scope.$$phase && !scope.$root.$$phase) {
                                scope.$apply();
                            }
                            scope.$apply();
                            console.log("hidden modalMdata : ");
                            console.debug(scope.$parent.data);
                            console.log("whichDismiss : " + scope.$parent.data.whichDismiss);
                            if (scope.$parent.data.whichDismiss === "Accept") {
                                scope.$parent.onAcceptDestination();
                            }
                        });
                    }

                };
            });

            return DestWndSetupCtrl;
        }

        return {
            start: init,
            showDialog : DestWndSetupCtrl.prototype.showDialog,
            isInitialized : DestWndSetupCtrl.prototype.isInitialized
        };

    });
}());
<commit_msg>Added jslint global in prototype function to stop complaint about  undefined<commit_after>/*global define */

(function () {
    "use strict";

    console.log('DestWndSetupCtrl setup');
    var areWeInitialized = false;
    define([
        'angular'
    ], function (angular) {
        console.log('DestWndSetupCtrl define');

        var selfdict = {},
            scopeDict = {};
        selfdict.isInitialized = areWeInitialized = false;

        function DestWndSetupCtrl($scope, $modal, $rootScope) {
            console.log("in DestWndSetupCtrl");
            selfdict.scope = $scope;
            selfdict.isInitialized = areWeInitialized = false;
            scopeDict.rootScope = $rootScope;

            // selfdict.callbackFunction = null;
            $scope.showDestDialog = false;
            $scope.choiceCallback = null;
            $scope.destSelections = ["Same Window", "New Tab", "New Pop-up Window"];
            $scope.data = {
                dstSel : $scope.destSelections[0].slice(0),
                prevDstSel : $scope.destSelections[0].slice(0),
                whichDismiss : "Cancel",
                dlg2show : "SelectWndDlg",
                title : 'do we have a title?',
                icon : null,
                snippet : 'nothing in snippet',
                showDetail : '+'
            };

            $scope.preserveState = function () {
                console.log("preserveState");
                // $scope.data.whichDismiss = 'Cancel';
                $scope.data.prevDstSel = $scope.data.dstSel.slice(0);
                console.log("preserve " + $scope.data.prevDstSel + " from " + $scope.data.dstSel);
            };

            $scope.restoreState = function () {
                console.log("restoreState");
                // $scope.data.whichDismiss = 'Accept';
                console.log("restore " + $scope.data.dstSel + " from " + $scope.data.prevDstSel);
                $scope.data.dstSel = $scope.data.prevDstSel.slice(0);
            };

            $scope.showDialog = function (choiceCallback, args) {
                $scope.choiceCallback = choiceCallback;
                var title = args.title,
                    icon = args.thumbnail,
                    snippet = args.snippet;
                $scope.data.title = title;
                $scope.data.icon = icon;
                $scope.data.snippet = snippet;
                $scope.showDestDialog = true;
            };

            $scope.onAcceptDestination = function () {
                console.log("onAcceptDestination " + $scope.data.dstSel);
                var callback = $scope.choiceCallback;
                if ($scope.choiceCallback) {
                    $scope.choiceCallback = null;
                    callback($scope.data.dstSel);
                } else {
                    scopeDict.rootScope.$broadcast('DestinationSelectorEvent', { destWnd: $scope.data.dstSel });
                }
            };

            $scope.hitEnter = function (evt) {
                if (angular.equals(evt.keyCode, 13) && !(angular.equals($scope.name, null) || angular.equals($scope.name, ''))) {
                    $scope.save();
                }
            }; // end hitEnter

            $scope.safeApply = function (fn) {
                var phase = this.$root.$$phase;
                if (phase === '$apply' || phase === '$digest') {
                    if (fn && (typeof fn === 'function')) {
                        fn();
                    }
                } else {
                    this.$apply(fn);
                }
            };
        }

        DestWndSetupCtrl.prototype.isInitialized = function () {
            return areWeInitialized;
        };

        DestWndSetupCtrl.prototype.showDialog = function (choiceCallback) {

            /*global $scope */
            $scope.$scope.choiceCallback = choiceCallback;
            $scope.showDialog($scope.choiceCallback);
        };

        function init(App) {
            console.log('DestWndSetupCtrl init');

            selfdict.isInitialized = areWeInitialized = true;
            App.controller('DestWndSetupCtrl',  ['$scope', '$modal', '$rootScope', DestWndSetupCtrl]);

            App.directive("modalShowDest", function () {
                console.log("setting up directive modalShowDest");
                return {
                    restrict: "A",   /* why doesn't "E" work? */
                     /*
                    It will check the cache for inlined templates and if one is not found
                    it will make an xhr to the url to fetch the template.
                    The url with "/" prefix is relative to the domain, without the "/" prefix
                    it will be relative to the main ("index.html") page or
                    base url (if you use location in the html5 mode).
                    */

                    templateUrl : '/templates/DestSelectDlgGen',   // .jade will be appended
                    // template : '<ng-include src="getContentUrl()"/>',
                    replace : true,
                    transclude: true,
                    scope: {
                        modalVisible: "=",
                        modalMdata: "="
                    },

                    controller: function ($scope) {
                        console.log("setting up directive modalShowDest controller");
                        $scope.getContentUrl = function () {
                            console.log("find file modalShowDest html");
                            return '/templates/DestSelectDlgGen.html';
                        };

                        $scope.status = {
                            'detailsOpen' : false,
                            'destChoicesOpen' : false
                        };
                        /*
                        $scope.onShowDetailsClick = function () {
                            $scope.status.detailsOpen = !$scope.status.detailsOpen;
                            if ($scope.status.detailsOpen && $scope.status.destChoicesOpen) {
                                $scope.status.destChoicesOpen = false;
                            }
                            // $scope.status.destChoicesOpen = !$scope.status.destChoicesOpen;
                        }

                        $scope.onDestChoiceClick = function () {
                            $scope.status.destChoicesOpen = !$scope.status.destChoicesOpen;
                            if ($scope.status.destChoicesOpen && $scope.status.detailsOpen) {
                                $scope.status.detailsOpen = false;
                            }
                            // $scope.status.detailsOpen = !$scope.status.detailsOpen;
                        }
                        */
                    },

                    link: function (scope, element, attrs) {
                        var localScope = scope;
                        //Hide or show the modal
                        scope.showModal = function (visible, elem) {
                            if (!elem) {
                                elem = element;
                            }
                            scope.status.detailsOpen = scope.status.destChoicesOpen = false;
                            scope.$parent.safeApply(function () {
                                scope.status.detailsOpen = scope.status.destChoicesOpen = false;
                            });
                            if (visible) {
                                $(elem).modal311("show");
                            } else {
                                $(elem).modal311("hide");
                            }
                        };

                        scope.$on('ShowWindowSelectorModalEvent', function (event, args) {
                            var title = args.title,
                                icon = args.thumbnail,
                                snippet = args.snippet;
                            localScope.$parent.data.title = title;
                            localScope.$parent.data.icon = icon;
                            localScope.$parent.data.snippet = snippet;
                            localScope.$parent.safeApply(function () {
                                localScope.status.detailsOpen = localScope.status.destChoicesOpen = false;
                            });
                            // localScope.status.detailsOpen = localScope.status.destChoicesOpen = false;
                            console.log('local scope.$on received title : ' + title);

                            localScope.$parent.safeApply(function () {
                                localScope.$parent.showDestDialog = true;
                            });
                        });

                        //Check to see if the modal-visible attribute exists
                        if (!attrs.modalVisible) {
                            //The attribute isn't defined, show the modal by default
                            scope.showModal(true);
                        } else {
                            //Watch for changes to the modal-visible attribute
                            scope.$watch("modalVisible", function (newValue, oldValue) {
                                scope.showModal(newValue);
                                console.log("watch modalVisible  : ");
                                console.debug(scope.$parent.data);
                                // scope.$parent.preserveState();
                            });
                            //Watch for changes to the modal-mdata attribute
                            scope.$watch("modalMdata", function (newValue, oldValue) {
                                if (!angular.isUndefinedOrNull(newValue)) {
                                    localScope.$parent.data = newValue;
                                }
                                console.log("watch modalMdata scope.$parent data  : ");
                                console.debug(localScope.$parent.data);
                            });
                            //Watch for changes to the modal-mdata attribute
                            scope.$watch("data.dstSel", function (newValue, oldValue) {
                                if (!angular.isUndefinedOrNull(newValue)) {
                                    localScope.$parent.data.dstSel = newValue;
                                }
                                console.log("watch modalMdata scope.$parent data  : ");
                                console.debug(localScope.$parent.data);
                            });

                            scope.$watch('scope.$parent.showDestDialog', function (newValue, oldValue) {
                                console.log("scope.$watch newValue : " + newValue);
                                console.log("scope.$watch 'scope.$parent.showDestDialog' : " + scope.$parent.showDestDialog);
                                scope.showModal(newValue);
                                //attrs.modalVisible = false;
                            });

                        }
                        //Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
                        $(element).on('hidden.bs.modal', function () {
                            scope.modalVisible = localScope.$parent.showDestDialog = localScope.showDestDialog =false;
                            scope.status.detailsOpen = scope.status.destChoicesOpen = false;
                            scope.$parent.data.title = '';
                            scope.$parent.data.icon = null;
                            scope.$parent.data.snippet = '';
                            console.log("hide event called");
                            if (!scope.$$phase && !scope.$root.$$phase) {
                                scope.$apply();
                            }
                            scope.$apply();
                            console.log("hidden modalMdata : ");
                            console.debug(scope.$parent.data);
                            console.log("whichDismiss : " + scope.$parent.data.whichDismiss);
                            if (scope.$parent.data.whichDismiss === "Accept") {
                                scope.$parent.onAcceptDestination();
                            }
                        });
                    }

                };
            });

            return DestWndSetupCtrl;
        }

        return {
            start: init,
            showDialog : DestWndSetupCtrl.prototype.showDialog,
            isInitialized : DestWndSetupCtrl.prototype.isInitialized
        };

    });
}());
<|endoftext|>


<commit_before>'use strict';
// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>

var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync'),
    runSequence = require('run-sequence'),
    del = require('del'),
    neat = require('node-neat').includePaths;

var production = false,
    paths = {
      app:     'app',
      html:    'app/**/*.html',
      styles:  'app/styles/**/*.scss',<% if (jsPre === 'coffeescript') { %>
      scripts: 'app/scripts/**/*.coffee',<% } else { %>
      scripts: 'app/scripts/**/*.js',<% } %>
      images:  'app/images/**/*.{png,gif,jpg,jpeg,svg}',
      fonts:   'app/fonts/**/*.{eot*,otf,svg,ttf,woff}',
      vendor:  'vendor'
    };

gulp.task('html', function (cb) {
  var config = (production) ? '_config.yml,_config.build.yml' : '_config.yml',
      dest   = (production) ? 'dist' : '.tmp',
      spawn  = require('child_process').spawn,
      jekyll = spawn('jekyll', ['build', '-q', '--config', config, '-s', paths.app, '-d', dest], { stdio: 'inherit' });

  jekyll.on('exit', function (code) {
    cb(code === 0 ? null : 'ERROR: Jekyll process exited with code: ' + code);
    browserSync.reload();
  });
});

gulp.task('styles', function () {<% if (sassComp === 'libsass') { %>
  return gulp.src(paths.styles)
    .pipe($.sass({
      style: 'nested',
      includePaths: [paths.styles].concat(neat),
      onError: console.error.bind(console, 'Sass error:')
    }))<% } else { %>
  return $.rubySass('app/styles/', {
      style: 'nested',
      loadPath: [paths.styles].concat(neat),
      onError: console.error.bind(console, 'Sass error:')
    })<% } %>
    .pipe($.autoprefixer('last 2 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('scripts', function () {
  return gulp.src(paths.scripts)<% if (jsPre === 'coffeescript') { %>
    .pipe($.coffee()).on('error', function(err) {})<% } %>
    .pipe($.jshint('.jshintrc'))
    .pipe($.jshint.reporter('default'))
    .pipe(gulp.dest('.tmp/scripts'))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('images', function () {
  return gulp.src(paths.images)
    .pipe($.imagemin({
      progressive: true,
      svgoPlugins: [{ removeViewBox: false }],
      use: []
    }))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', function () {
  return gulp.src(paths.fonts)
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('clean', function (cb) {
  del(['.tmp', 'dist'], cb);
});

gulp.task('optimize', ['html', 'styles', 'scripts', 'images', 'fonts'], function () {
  var assets = $.useref.assets({ searchPath: ['.tmp', 'dist', '.'] });

  return gulp.src('dist/**/*.html')
    .pipe(assets)
    .pipe($.if('*.css', $.minifyCss()))
    .pipe($.if('*.js', $.uglify()))
    .pipe($.rev())
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe($.revReplace())
    .pipe($.if('*.html', $.htmlmin({collapseWhitespace: true})))
    .pipe(gulp.dest('dist'));
});<% if (ghPages && ghPagesType === 'project') { %>

// Update absolute asset paths for GitHub Pages subdirectory
gulp.task('replace', ['optimize'], function () {
  var ghPages = '$1http://<%= ghOwner %>.github.io/<%= ghRepo %>';

  return gulp.src('dist/**/*.html')
    .pipe($.replace(/("|'?)\/?styles\//g,  ghPages + '/styles/'))
    .pipe($.replace(/("|'?)\/?scripts\//g, ghPages + '/scripts/'))
    .pipe(gulp.dest('dist'));
});<% } %>

gulp.task('build', ['replace'], function () {
  return gulp.src('dist/**/*')
    .pipe($.size({
      title: 'build',
      gzip: true
    }));
});<% if (ghPages) { %>

gulp.task('gh-pages', function () {
  return gulp.src('dist/**/*')
    .pipe($.ghPages(<% if (ghPagesType === 'user_organization') { %>{
      branch: 'master'
    }<% } %>))
});<% } %>

gulp.task('watch', function () {
  gulp.watch(paths.html,    ['html']);
  gulp.watch(paths.styles,  ['styles']);
  gulp.watch(paths.scripts, ['scripts']);
  gulp.watch(paths.images,  ['images']);
  gulp.watch(paths.fonts,   ['fonts']);
});

gulp.task('browser-sync', ['html', 'styles', 'scripts'], function () {
  browserSync({
    notify: false,
    port: 9000,
    server: {
      baseDir: ['.tmp', paths.app],
      routes: {
        '/vendor': 'vendor'
      }
    }
  });
});

gulp.task('serve', function () {
  runSequence('clean', ['browser-sync', 'watch']);
});<% if (ghPages) { %>

gulp.task('deploy', function () {
  production = true;
  runSequence('clean', 'build', 'gh-pages');
});<% } %>

gulp.task('default', function () {
  production = true;
  runSequence('clean', 'build');
});
<commit_msg>Revert script variable declaration for sake of clarity<commit_after>'use strict';
// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>

var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync'),
    runSequence = require('run-sequence'),
    del = require('del'),
    neat = require('node-neat').includePaths;

var production = false,
    paths = {
      app:     'app',
      html:    'app/**/*.html',
      styles:  'app/styles/**/*.scss',<% if (jsPre === 'coffeescript') { %>
      scripts: 'app/scripts/**/*.coffee',<% } else { %>
      scripts: 'app/scripts/**/*.js',<% } %>
      images:  'app/images/**/*.{png,gif,jpg,jpeg,svg}',
      fonts:   'app/fonts/**/*.{eot*,otf,svg,ttf,woff}',
      vendor:  'vendor'
    };

gulp.task('html', function (cb) {
  var config = (production) ? '_config.yml,_config.build.yml' : '_config.yml',
      dest   = (production) ? 'dist' : '.tmp';

  var spawn  = require('child_process').spawn,
      jekyll = spawn('jekyll', ['build', '-q', '--config', config, '-s', paths.app, '-d', dest], { stdio: 'inherit' });

  jekyll.on('exit', function (code) {
    cb(code === 0 ? null : 'ERROR: Jekyll process exited with code: ' + code);
    browserSync.reload();
  });
});

gulp.task('styles', function () {<% if (sassComp === 'libsass') { %>
  return gulp.src(paths.styles)
    .pipe($.sass({
      style: 'nested',
      includePaths: [paths.styles].concat(neat),
      onError: console.error.bind(console, 'Sass error:')
    }))<% } else { %>
  return $.rubySass('app/styles/', {
      style: 'nested',
      loadPath: [paths.styles].concat(neat),
      onError: console.error.bind(console, 'Sass error:')
    })<% } %>
    .pipe($.autoprefixer('last 2 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('scripts', function () {
  return gulp.src(paths.scripts)<% if (jsPre === 'coffeescript') { %>
    .pipe($.coffee()).on('error', function(err) {})<% } %>
    .pipe($.jshint('.jshintrc'))
    .pipe($.jshint.reporter('default'))
    .pipe(gulp.dest('.tmp/scripts'))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('images', function () {
  return gulp.src(paths.images)
    .pipe($.imagemin({
      progressive: true,
      svgoPlugins: [{ removeViewBox: false }],
      use: []
    }))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', function () {
  return gulp.src(paths.fonts)
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('clean', function (cb) {
  del(['.tmp', 'dist'], cb);
});

gulp.task('optimize', ['html', 'styles', 'scripts', 'images', 'fonts'], function () {
  var assets = $.useref.assets({ searchPath: ['.tmp', 'dist', '.'] });

  return gulp.src('dist/**/*.html')
    .pipe(assets)
    .pipe($.if('*.css', $.minifyCss()))
    .pipe($.if('*.js', $.uglify()))
    .pipe($.rev())
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe($.revReplace())
    .pipe($.if('*.html', $.htmlmin({collapseWhitespace: true})))
    .pipe(gulp.dest('dist'));
});<% if (ghPages && ghPagesType === 'project') { %>

// Update absolute asset paths for GitHub Pages subdirectory
gulp.task('replace', ['optimize'], function () {
  var ghPages = '$1http://<%= ghOwner %>.github.io/<%= ghRepo %>';

  return gulp.src('dist/**/*.html')
    .pipe($.replace(/("|'?)\/?styles\//g,  ghPages + '/styles/'))
    .pipe($.replace(/("|'?)\/?scripts\//g, ghPages + '/scripts/'))
    .pipe(gulp.dest('dist'));
});<% } %>

gulp.task('build', ['replace'], function () {
  return gulp.src('dist/**/*')
    .pipe($.size({
      title: 'build',
      gzip: true
    }));
});<% if (ghPages) { %>

gulp.task('gh-pages', function () {
  return gulp.src('dist/**/*')
    .pipe($.ghPages(<% if (ghPagesType === 'user_organization') { %>{
      branch: 'master'
    }<% } %>))
});<% } %>

gulp.task('watch', function () {
  gulp.watch(paths.html,    ['html']);
  gulp.watch(paths.styles,  ['styles']);
  gulp.watch(paths.scripts, ['scripts']);
  gulp.watch(paths.images,  ['images']);
  gulp.watch(paths.fonts,   ['fonts']);
});

gulp.task('browser-sync', ['html', 'styles', 'scripts'], function () {
  browserSync({
    notify: false,
    port: 9000,
    server: {
      baseDir: ['.tmp', paths.app],
      routes: {
        '/vendor': 'vendor'
      }
    }
  });
});

gulp.task('serve', function () {
  runSequence('clean', ['browser-sync', 'watch']);
});<% if (ghPages) { %>

gulp.task('deploy', function () {
  production = true;
  runSequence('clean', 'build', 'gh-pages');
});<% } %>

gulp.task('default', function () {
  production = true;
  runSequence('clean', 'build');
});
<|endoftext|>


<commit_before>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
'use strict';

var gulp = require('gulp'),
  prefix = require('gulp-autoprefixer'),
  cache = require('gulp-cache'),
  csso = require('gulp-csso'),
  clean = require('del'),
  filter = require('gulp-filter'),
  imagemin = require('gulp-imagemin'),
  jshint = require('gulp-jshint'),
  rubySass = require('gulp-ruby-sass'),
  shell = require('gulp-shell'),
  size = require('gulp-size'),
  uglify = require('gulp-uglify'),
  useref = require('gulp-useref');

var paths = {
  styles: 'app/styles/**/*.scss',
  scripts: 'app/scripts/**/*.js',
  images: 'app/images/**/*.{gif,jpg,png,svg,webp}',
  extras: 'app/*.*',
  html: ['app/**/*.html'],
  index: 'app/templates/_layout.html',
  clean: ['.tmp/*', 'public/**/*',
      '!public/assets', '!public/assets/**/*',
      '!public/index.php', '!public/.htaccess']
};

/**
 * `gulp deploy-init`
 * 1. Add dokku remote to git repository.
 * 2. Push to dokku to intialize app container.
 * 3. Set a custom PHP buildpack
 * 4. Create mariadb container.
 * 5. Link app container with mariadb container.
 */
gulp.task('deploy-init', shell.task([
  'git remote add dokku dokku@staging.francisbond.com:<%= _.slugify(slug) %>', /*[1]*/
  'git push dokku master', /*[2]*/
  'ssh dokku@staging.francisbond.com config:set <%= _.slugify(slug) %> BUILDPACK_URL=https://github.com/CHH/heroku-buildpack-php', /*[3]*/
  'ssh dokku@staging.francisbond.com mariadb:create <%= _.slugify(slug) %>', /*[4]*/
  'ssh dokku@staging.francisbond.com mariadb:link <%= _.slugify(slug) %> <%= _.slugify(slug) %>' /*[5]*/
]));

gulp.task('deploy', shell.task([
  'git push dokku master'
]));

/**
 * `gulp db-dump-local`
 * 1. Check if .tmp exists, create it if it doesn't.
 * 2. Dump the local database to .tmp/local.sql.
 */
gulp.task('db-dump-local', ['build'], shell.task([
  '[ -d ".tmp" ] || mkdir .tmp', /*[1]*/
  'vagrant ssh --command "mysqldump -uroot -proot <%= _.slugify(slug) %> > /vagrant/.tmp/local.sql"' /*[2]*/
]));

/**
 * `gulp db-dump-remote`
 * 1. Check if .tmp exists, create it if it doesn't.
 * 2. Dump the remote database to .tmp/remote.sql.
 */
gulp.task('db-dump-remote', ['build'], shell.task([
  '[ -d ".tmp" ] || mkdir .tmp', /*[1]*/
  'ssh dokku@staging.francisbond.com mariadb:dumpraw <%= _.slugify(slug) %> | tee .tmp/remote.sql > /dev/null' /*[2]*/
]));

gulp.task('db-push', ['db-dump-local'], shell.task([
  'ssh dokku@staging.francisbond.com mariadb:console <%= _.slugify(slug) %> < .tmp/local.sql'
]));

gulp.task('db-pull', ['db-dump-remote'], shell.task([
  'vagrant ssh --command "mysql -uroot -proot <%= _.slugify(slug) %> < /vagrant/.tmp/remote.sql"'
]));

gulp.task('db-dump', ['clean', 'db-dump-local', 'db-dump-remote'], function() {
  return gulp.src(['.tmp/local.sql', '.tmp/remote.sql'])
    .pipe(gulp.dest('databases'));
});

gulp.task('styles', function() {
  return gulp.src([paths.styles, 'bower_components/**/*.scss'])
    .pipe(rubySass({
      style: 'expanded'
    }))
    .pipe(prefix('last 1 version'))
    .pipe(gulp.dest('public/styles'))
    .pipe(size());
});

gulp.task('scripts', function() {
  return gulp.src(paths.scripts)
    .pipe(jshint())
    .pipe(jshint.reporter(require('jshint-stylish')))
    .pipe(gulp.dest('public/scripts'))
    .pipe(size());
});

gulp.task('images', function() {
  return gulp.src(paths.images)
    .pipe(cache(imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('public/images'))
    .pipe(size());
});

gulp.task('extras', function() {
  return gulp.src(paths.extras, { dot: true })
    .pipe(gulp.dest('public'));
});

gulp.task('clean', function(cb) {
  clean(paths.clean, cb);
});

gulp.task('build', ['clean'], function() {
  gulp.start('build-useref');
});

gulp.task('build-useref', ['images', 'styles', 'extras'], function() {
  var jsFilter = filter('**/*.js');
  var cssFilter = filter('**/*.css');

  return gulp.src(paths.html)
    .pipe(useref.assets({searchPath: '{public,app}'}))
    .pipe(jsFilter)
    .pipe(uglify())
    .pipe(jsFilter.restore())
    .pipe(cssFilter)
    .pipe(csso())
    .pipe(cssFilter.restore())
    .pipe(useref.restore())
    .pipe(useref())
    .pipe(gulp.dest('public'))
    .pipe(size());
});

gulp.task('watch', function() {
  gulp.start('extras')
    .start('scripts')
    .start('images')
    .start('build-useref');

  gulp.watch(paths.extras, ['extras']);
  gulp.watch(paths.html, ['build-useref']);
  gulp.watch(paths.scripts, ['scripts', 'build-useref']);
  gulp.watch(paths.styles, ['build-useref']);
  gulp.watch(paths.images, ['images']);
});

gulp.task('default', ['build']);<commit_msg>livereload<commit_after>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
'use strict';

var gulp = require('gulp'),
    $ = require('gulp-load-plugins')();

var paths = {
  styles: 'app/styles/**/*.scss',
  scripts: 'app/scripts/**/*.js',
  images: 'app/images/**/*.{gif,jpg,png,svg,webp}',
  extras: 'app/*.*',
  html: ['app/**/*.html'],
  index: 'app/templates/_layout.html',
  clean: ['.tmp/*', 'public/**/*',
      '!public/assets', '!public/assets/**/*',
      '!public/index.php', '!public/.htaccess']
};

/**
 * `gulp deploy-init`
 * 1. Add dokku remote to git repository.
 * 2. Push to dokku to intialize app container.
 * 3. Set a custom PHP buildpack
 * 4. Create mariadb container.
 * 5. Link app container with mariadb container.
 */
gulp.task('deploy-init', shell.task([
  'git remote add dokku dokku@staging.francisbond.com:<%= _.slugify(slug) %>', /*[1]*/
  'git push dokku master', /*[2]*/
  'ssh dokku@staging.francisbond.com config:set <%= _.slugify(slug) %> BUILDPACK_URL=https://github.com/CHH/heroku-buildpack-php', /*[3]*/
  'ssh dokku@staging.francisbond.com mariadb:create <%= _.slugify(slug) %>', /*[4]*/
  'ssh dokku@staging.francisbond.com mariadb:link <%= _.slugify(slug) %> <%= _.slugify(slug) %>' /*[5]*/
]));

gulp.task('deploy', shell.task([
  'git push dokku master'
]));

/**
 * `gulp db-dump-local`
 * 1. Check if .tmp exists, create it if it doesn't.
 * 2. Dump the local database to .tmp/local.sql.
 */
gulp.task('db-dump-local', ['build'], shell.task([
  '[ -d ".tmp" ] || mkdir .tmp', /*[1]*/
  'vagrant ssh --command "mysqldump -uroot -proot <%= _.slugify(slug) %> > /vagrant/.tmp/local.sql"' /*[2]*/
]));

/**
 * `gulp db-dump-remote`
 * 1. Check if .tmp exists, create it if it doesn't.
 * 2. Dump the remote database to .tmp/remote.sql.
 */
gulp.task('db-dump-remote', ['build'], shell.task([
  '[ -d ".tmp" ] || mkdir .tmp', /*[1]*/
  'ssh dokku@staging.francisbond.com mariadb:dumpraw <%= _.slugify(slug) %> | tee .tmp/remote.sql > /dev/null' /*[2]*/
]));

gulp.task('db-push', ['db-dump-local'], shell.task([
  'ssh dokku@staging.francisbond.com mariadb:console <%= _.slugify(slug) %> < .tmp/local.sql'
]));

gulp.task('db-pull', ['db-dump-remote'], shell.task([
  'vagrant ssh --command "mysql -uroot -proot <%= _.slugify(slug) %> < /vagrant/.tmp/remote.sql"'
]));

gulp.task('db-dump', ['clean', 'db-dump-local', 'db-dump-remote'], function() {
  return gulp.src(['.tmp/local.sql', '.tmp/remote.sql'])
    .pipe(gulp.dest('databases'));
});

gulp.task('styles', function() {
  return gulp.src([paths.styles, 'bower_components/**/*.scss'])
    .pipe($.plumber())
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10
    }))
    .pipe($.autoprefixer('last 1 version'))
    .pipe(prefix('last 1 version'))
    .pipe(gulp.dest('public/styles'))
});

gulp.task('scripts', function() {
  return gulp.src(paths.scripts)
    .pipe(jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'))
    .pipe(gulp.dest('public/scripts'));
});

gulp.task('images', function() {
  return gulp.src(paths.images)
    .pipe(cache(imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('public/images'))
    .pipe(size());
});

gulp.task('extras', function() {
  return gulp.src(paths.extras, { dot: true })
    .pipe(gulp.dest('public'));
});

gulp.task('clean', function(cb) {
  require('del').bind(null, paths.clean)
});

gulp.task('build', ['clean'], function() {
  gulp.start('build-useref');
});

gulp.task('build-useref', ['images', 'styles', 'extras'], function() {
  var jsFilter = filter('**/*.js');
  var cssFilter = filter('**/*.css');

  return gulp.src(paths.html)
    .pipe(useref.assets({searchPath: '{public,app}'}))
    .pipe(jsFilter)
    .pipe(uglify())
    .pipe(jsFilter.restore())
    .pipe(cssFilter)
    .pipe(csso())
    .pipe(cssFilter.restore())
    .pipe(useref.restore())
    .pipe(useref())
    .pipe(gulp.dest('public'))
    .pipe(size());
});

gulp.task('watch', function() {
  gulp.src(paths.index($.inject('http://localhost:35729/livereload.js')));

  gulp.start('extras')
    .start('scripts')
    .start('images')
    .start('build-useref');

  livereload.listen();
  gulp.watch('public/**/*')
    .on('change', livereload.changed);

  gulp.watch(paths.extras, ['extras']);
  gulp.watch(paths.html, ['build-useref']);
  gulp.watch(paths.scripts, ['scripts', 'build-useref']);
  gulp.watch(paths.styles, ['build-useref']);
  gulp.watch(paths.images, ['images']);
});

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


<commit_before><commit_msg>Fix comments and indentation<commit_after><|endoftext|>


<commit_before>'use strict';

const communityController = {};

$('#community-div #post-exp-button').on('click', e => {
  e.preventDefault();
  page('/experiences');
});

$('#community-div #edit-exp-button').on('click', e => {
  e.preventDefault();
  page('/experiences');

$('#back-button').on('click', e => {
  e.preventDefault();
  let storedId = localStorage.getItem('communityId');
  page('/community/' + storedId);
});

communityController.render = function(ctx, next) {
  communityController.fetchExp(ctx.params.id);
  next();
};

communityController.fetchExp = function(commId) {
  superagent
    .get('/lunch/community/' + commId)
    .set('authorization', localStorage.getItem('token'))
    .end((err, res) => {
      if (err) throw err;
      $('#current-community').text(res.body[0].communityId.name);
      experienceView.populateHandlebars(res.body);
    });
};<commit_msg>Fix goober<commit_after>'use strict';

const communityController = {};

$('#community-div #post-exp-button').on('click', e => {
  e.preventDefault();
  page('/experiences');
});

$('#community-div #edit-exp-button').on('click', e => {
  e.preventDefault();
  page('/experiences');
});

$('#back-button').on('click', e => {
  e.preventDefault();
  let storedId = localStorage.getItem('communityId');
  page('/community/' + storedId);
});

communityController.render = function(ctx, next) {
  communityController.fetchExp(ctx.params.id);
  next();
};

communityController.fetchExp = function(commId) {
  superagent
    .get('/lunch/community/' + commId)
    .set('authorization', localStorage.getItem('token'))
    .end((err, res) => {
      if (err) throw err;
      $('#current-community').text(res.body[0].communityId.name);
      experienceView.populateHandlebars(res.body);
    });
};<|endoftext|>


<commit_before>'use strict';
// generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {<% if (includeSass) { %>
  return gulp.src('app/styles/main.scss')
    .pipe($.plumber())
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10
    }))<% } else { %>
  return gulp.src('app/styles/main.css')<% } %>
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('.tmp/styles'));
});

gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
});

gulp.task('html', ['styles'], function () {<% if (includeBootstrap && includeSass) { %>
  var lazypipe = require('lazypipe');
  var cssChannel = lazypipe()
    .pipe($.csso)
    .pipe($.replace, 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap','fonts');<% } %>
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/*.html')
    .pipe(assets)
    .pipe($.if('*.js', $.uglify()))<% if (includeBootstrap && includeSass) { %>
    .pipe($.if('*.css', cssChannel()))<% } else { %>
    .pipe($.if('*.css', $.csso()))<% } %>
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest('dist'));
});

gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', function () {
  return gulp.src(require('main-bower-files')().concat('app/fonts/**/*'))
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('extras', function () {
  return gulp.src([
    'app/*.*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

gulp.task('clean', require('del').bind(null, ['.tmp', 'dist']));

gulp.task('connect', function () {
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')()
    .use(require('connect-livereload')({port: 35729}))
    .use(serveStatic('app'))
    .use(serveStatic('.tmp'))
    // paths to bower_components should be relative to the current file
    // e.g. in app/index.html you should use ../bower_components
    .use('/bower_components', serveStatic('bower_components'))
    .use(serveIndex('app'));

  require('http').createServer(app)
    .listen(9000)
    .on('listening', function () {
      console.log('Started connect web server on http://localhost:9000');
    });
});

gulp.task('serve', ['connect'<% if (includeSass) { %>, 'styles'<% } %>], function () {
  require('opn')('http://localhost:9000');
});

// inject bower components
gulp.task('wiredep', function () {
  var wiredep = require('wiredep').stream;
<% if (includeSass) { %>
  gulp.src('app/styles/*.scss')
    .pipe(wiredep())
    .pipe(gulp.dest('app/styles'));
<% } %>
  gulp.src('app/*.html')
    .pipe(wiredep(<% if (includeSass && includeBootstrap) { %>{exclude: ['bootstrap-sass-official']}<% } %>))
    .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect', 'serve'], function () {
  $.livereload.listen();

  // watch for changes
  gulp.watch([
    'app/*.html',
    '.tmp/styles/**/*.css',
    'app/scripts/**/*.js',
    'app/images/**/*'
  ]).on('change', $.livereload.changed);

  gulp.watch('app/styles/**/*.<%= includeSass ? 'scss' : 'css' %>', ['styles']);
  gulp.watch('bower.json', ['wiredep']);
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});
<commit_msg>Make gulp serve depend on gulp watch<commit_after>'use strict';
// generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {<% if (includeSass) { %>
  return gulp.src('app/styles/main.scss')
    .pipe($.plumber())
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10
    }))<% } else { %>
  return gulp.src('app/styles/main.css')<% } %>
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('.tmp/styles'));
});

gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
});

gulp.task('html', ['styles'], function () {<% if (includeBootstrap && includeSass) { %>
  var lazypipe = require('lazypipe');
  var cssChannel = lazypipe()
    .pipe($.csso)
    .pipe($.replace, 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap','fonts');<% } %>
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/*.html')
    .pipe(assets)
    .pipe($.if('*.js', $.uglify()))<% if (includeBootstrap && includeSass) { %>
    .pipe($.if('*.css', cssChannel()))<% } else { %>
    .pipe($.if('*.css', $.csso()))<% } %>
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest('dist'));
});

gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', function () {
  return gulp.src(require('main-bower-files')().concat('app/fonts/**/*'))
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('extras', function () {
  return gulp.src([
    'app/*.*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

gulp.task('clean', require('del').bind(null, ['.tmp', 'dist']));

gulp.task('connect',<% if (includeSass) { %> ['styles'],<% } %> function () {
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')()
    .use(require('connect-livereload')({port: 35729}))
    .use(serveStatic('app'))
    .use(serveStatic('.tmp'))
    // paths to bower_components should be relative to the current file
    // e.g. in app/index.html you should use ../bower_components
    .use('/bower_components', serveStatic('bower_components'))
    .use(serveIndex('app'));

  require('http').createServer(app)
    .listen(9000)
    .on('listening', function () {
      console.log('Started connect web server on http://localhost:9000');
    });
});

gulp.task('serve', ['connect', 'watch'], function () {
  require('opn')('http://localhost:9000');
});

// inject bower components
gulp.task('wiredep', function () {
  var wiredep = require('wiredep').stream;
<% if (includeSass) { %>
  gulp.src('app/styles/*.scss')
    .pipe(wiredep())
    .pipe(gulp.dest('app/styles'));
<% } %>
  gulp.src('app/*.html')
    .pipe(wiredep(<% if (includeSass && includeBootstrap) { %>{exclude: ['bootstrap-sass-official']}<% } %>))
    .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect'], function () {
  $.livereload.listen();

  // watch for changes
  gulp.watch([
    'app/*.html',
    '.tmp/styles/**/*.css',
    'app/scripts/**/*.js',
    'app/images/**/*'
  ]).on('change', $.livereload.changed);

  gulp.watch('app/styles/**/*.<%= includeSass ? 'scss' : 'css' %>', ['styles']);
  gulp.watch('bower.json', ['wiredep']);
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});
<|endoftext|>


<commit_before>var core                    = require('../core').core;
var numeric                 = require('numeric');
var _                       = require('underscore');

/**
  Returns the model grid geometry as a MultiPoint GeoJSON response.
 */
function geometry(req, res){

  if (!req.params.scenario) return res.send(400, 'Bad Request');

  if (!(req.params.scenario in core.INDEX) || core.INDEX[req.params.scenario] === undefined) {
      return res.send(404, 'Not Found');
  }

  var idx = core.INDEX[req.params.scenario];
  var body = {
    type: "MultiPoint",
    coordinates: []
  }

  for (var i = 0; i < idx.length; i+=1) {
    body.coordinates.push(idx[i])
  };

  return res.send(body);

}

/**
  Returns the model grid geometry as a GeometryCollection GeoJSON response.
 */
function geometryCollection(req, res){

  if(!req.params.scenario) return res.send(400, 'Bad Request');

  if (!(req.params.scenario in core.INDEX) || core.INDEX[req.params.scenario] === undefined) {
      return res.send(404, 'Not Found');
  }

  var idx = core.INDEX[req.params.scenario];
  var body = {type: "GeometryCollection", geometries:[]}
  for (var i = 0; i < idx.length; i++) {
    body.geometries.push({type:"Point", coordinates:idx[i]})
  };

  return res.send(body);

}

exports.geometry = geometry;
<commit_msg>Added _id field to geometry.json responses<commit_after>var core                    = require('../core').core;
var numeric                 = require('numeric');
var _                       = require('underscore');

/**
  Returns the model grid geometry as a MultiPoint GeoJSON response.
 */
function geometry(req, res){

  if (!req.params.scenario) return res.send(400, 'Bad Request');

  if (!(req.params.scenario in core.INDEX) || core.INDEX[req.params.scenario] === undefined) {
      return res.send(404, 'Not Found');
  }

  var idx = core.INDEX[req.params.scenario];
  var body = {
    type: "MultiPoint",
    _id: req.params.scenario,
    coordinates: []
  }

  for (var i = 0; i < idx.length; i+=1) {
    body.coordinates.push(idx[i])
  };

  return res.send(body);

}

/**
  Returns the model grid geometry as a GeometryCollection GeoJSON response.
 */
function geometryCollection(req, res){

  if(!req.params.scenario) return res.send(400, 'Bad Request');

  if (!(req.params.scenario in core.INDEX) || core.INDEX[req.params.scenario] === undefined) {
      return res.send(404, 'Not Found');
  }

  var idx = core.INDEX[req.params.scenario];
  var body = {
    type: "GeometryCollection",
    _id: req.params.scenario,
    geometries: []
  }
  for (var i = 0; i < idx.length; i++) {
    body.geometries.push({type:"Point", coordinates:idx[i]})
  };

  return res.send(body);

}

exports.geometry = geometry;
<|endoftext|>