<commit_before>var gulp = require('gulp');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var ngAnnotate = require('gulp-ng-annotate');
var replace = require('gulp-replace');
var htmlreplace = require('gulp-html-replace');
var rename = require("gulp-rename");
var libs = [
    'lib/jquery/dist/jquery.min.js',
    'lib/jquery-ui/ui/minified/jquery-ui.min.js',
    'lib/bootstrap/dist/js/bootstrap.min.js',
    'lib/off-bower/pace.min.js',
    'lib/angular/angular.min.js',
    'lib/angular-route/angular-route.min.js',
    'lib/angular-resource/angular-resource.min.js',
    'lib/angular-bootstrap/ui-bootstrap.min.js',
    'lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
    'lib/es5-shim/es5-sham.min.js',
    'lib/angular-file-upload/angular-file-upload.min.js',
    'lib/angular-ui-utils/ui-utils.min.js',
    'lib/angular-animate/angular-animate.min.js',
    'lib/angularjs-toaster/toaster.min.js',
    'lib/angular-filter/dist/angular-filter.min.js',
    'lib/angularjs-dropdown-multiselect/dist/angularjs-dropdown-multiselect.min.js',
    'lib/ngInfiniteScroll/build/ng-infinite-scroll.min.js',
    'lib/angular-confirm-modal/angular-confirm.min.js',
    'lib/admin-lte/dist/js/app.min.js',
    'lib/angular-i18n/angular-locale_pt-br.js',
    'lib/modernizr/modernizr.js',
    'lib/checklist-model/checklist-model.js',
    'scripts/app.js',
    'scripts/offcanvas.js',
    'scripts/directives/datepicker.js',
    'scripts/directives/timepicker.js',
    'scripts/directives/datetimepicker.js',
    'scripts/filters/startFromFilter.js',
    'scripts/filters/genericSearchFilter.js',
    'scripts/filters/tagsFilter.js',
    'lib/ng-tags-input/ng-tags-input.min.js',
    'scripts/services/AgendaComissaoFactory.js',
    'scripts/controllers/gerenciarReuniaoController.js',
    'scripts/controllers/modalBuscarProposicaoController.js',
    'scripts/controllers/modalAddProposicaoController.js',
    'scripts/controllers/modalComentariosController.js',
    'scripts/controllers/modalEncaminhamentosController.js',
    'scripts/controllers/modalRelatorioReuniaoController.js',
    'scripts/controllers/modalRelatorioProposicaoController.js',
    'scripts/controllers/proposicaoController.js',
    'scripts/services/ComentarioFactory.js',
    'scripts/services/ComentarioService.js',
    'scripts/services/EncaminhamentoProposicaoFactory.js',
    'scripts/services/ComissaoFactory.js',
    'scripts/services/ProposicaoFactory.js',
    'scripts/services/ReuniaoFactory.js',
    'scripts/services/ElaboracaoNormativaFactory.js',
    'scripts/services/TarefaFactory.js',
    'scripts/services/NotificacaoFactory.js',
    'scripts/controllers/newPosicionamentoController.js',
    'scripts/controllers/searchPosicionamentoController.js',
    'scripts/controllers/editPosicionamentoController.js',
    'scripts/services/PosicionamentoFactory.js',
    'scripts/services/TipoEncaminhamentoFactory.js',
    'scripts/controllers/newTipoEncaminhamentoController.js',
    'scripts/controllers/searchTipoEncaminhamentoController.js',
    'scripts/controllers/editTipoEncaminhamentoController.js',
    'scripts/services/EquipeFactory.js',
    'scripts/controllers/searchEquipeController.js',
    'scripts/controllers/equipeController.js',
    'scripts/services/UsuarioFactory.js',
    'scripts/controllers/newUsuarioController.js',
    'scripts/controllers/searchUsuarioController.js',
    'scripts/controllers/editUsuarioController.js',
    'scripts/services/ReuniaoProposicaoFactory.js',
    'scripts/services/TagFactory.js',
    'scripts/controllers/searchElaboracaoNormativaController.js',
    'scripts/controllers/elaboracaoNormativaController.js',
    'scripts/controllers/searchStatusSidofController.js',
    'scripts/controllers/newStatusSidofController.js',
    'scripts/controllers/editStatusSidofController.js',
    'scripts/controllers/uploadController.js',
    'scripts/controllers/tarefaController.js',
    'scripts/controllers/notificacaoController.js',
    'scripts/services/OrigemElaboracaoNormativaFactory.js',
    'scripts/controllers/newOrigemElaboracaoNormativaController.js',
    'scripts/controllers/searchOrigemElaboracaoNormativaController.js',
    'scripts/services/AreaConsultadaFactory.js',
    'scripts/controllers/newAreaConsultadaController.js',
    'scripts/controllers/searchAreaConsultadaController.js',
    'scripts/controllers/editAreaConsultadaController.js',
    'scripts/services/OrgaoFactory.js',
    'scripts/controllers/newOrgaoController.js',
    'scripts/controllers/searchOrgaoController.js',
    'scripts/controllers/editOrgaoController.js',
    'scripts/controllers/SearchAgendaComissaoController.js',
    'scripts/services/ElaboracaoNormativaConsultaFactory.js',
    'scripts/services/StatusSidofFactory.js',
    'scripts/services/SituacaoLegislativaFactory.js',
    'scripts/controllers/SituacaoLegislativaController.js',
    'scripts/services/locationParser.js'

];

var compilacao = function() {
    console.info("Compilação executada");
    return gulp.src(libs)
        .pipe(ngAnnotate())
        .pipe(uglify())
        .pipe(concat('all.js'))
        .pipe(gulp.dest('./scripts'));
}
var generateHTMLs = function(){
	 console.info("Atualizando entradas do keycloak para apontar para: "+process.env.KEYCLOAK_SERVER);
	 if(!process.env.KEYCLOAK_SERVER){
		throw "Variável de ambiente KEYCLOAKSERVER não foi encontrada. Sete o valor de KEYCLOAKSERVER e tente novamente";
	 }
    console.info("Gerando index-dev.html");
	 var generateIndexDEVHtml = gulp.src(['template/index-source.html'])
	    .pipe(replace('KEYCLOAK_SERVER', process.env.KEYCLOAK_SERVER))
	    .pipe(rename("index-dev.html"))
	    .pipe(gulp.dest('./'));
     console.info("Gerando index.html");
     var generateIndexHTML = gulp.src('template/index-source.html')
	   .pipe(replace('KEYCLOAK_SERVER', process.env.KEYCLOAK_SERVER))
       .pipe(htmlreplace({
         		'js': 'js/all.js'
        	}))
       .pipe(rename("index.html"))
       .pipe(gulp.dest('./'));
      console.info("Gerando keycloak.json");
	 var generateFinalKeycloak = gulp.src(['template/keycloak.json'])
	    .pipe(replace('KEYCLOAK_SERVER', process.env.KEYCLOAKSERVER))
	    .pipe(gulp.dest('./'));

};
gulp.task('generateHTMLs',generateHTMLs);

gulp.task('compress', compilacao);

gulp.task('watch', function() {
    watch('scripts/**/*.js',compilacao);
    watch('template/*.*', generateHTMLs);
});

gulp.task('default', ['updatekeycloak', 'compress'], function() {
  // place code for your default task here
});
<commit_msg>Fix nome da task default<commit_after>var gulp = require('gulp');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var ngAnnotate = require('gulp-ng-annotate');
var replace = require('gulp-replace');
var htmlreplace = require('gulp-html-replace');
var rename = require("gulp-rename");
var libs = [
    'lib/jquery/dist/jquery.min.js',
    'lib/jquery-ui/ui/minified/jquery-ui.min.js',
    'lib/bootstrap/dist/js/bootstrap.min.js',
    'lib/off-bower/pace.min.js',
    'lib/angular/angular.min.js',
    'lib/angular-route/angular-route.min.js',
    'lib/angular-resource/angular-resource.min.js',
    'lib/angular-bootstrap/ui-bootstrap.min.js',
    'lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
    'lib/es5-shim/es5-sham.min.js',
    'lib/angular-file-upload/angular-file-upload.min.js',
    'lib/angular-ui-utils/ui-utils.min.js',
    'lib/angular-animate/angular-animate.min.js',
    'lib/angularjs-toaster/toaster.min.js',
    'lib/angular-filter/dist/angular-filter.min.js',
    'lib/angularjs-dropdown-multiselect/dist/angularjs-dropdown-multiselect.min.js',
    'lib/ngInfiniteScroll/build/ng-infinite-scroll.min.js',
    'lib/angular-confirm-modal/angular-confirm.min.js',
    'lib/admin-lte/dist/js/app.min.js',
    'lib/angular-i18n/angular-locale_pt-br.js',
    'lib/modernizr/modernizr.js',
    'lib/checklist-model/checklist-model.js',
    'scripts/app.js',
    'scripts/offcanvas.js',
    'scripts/directives/datepicker.js',
    'scripts/directives/timepicker.js',
    'scripts/directives/datetimepicker.js',
    'scripts/filters/startFromFilter.js',
    'scripts/filters/genericSearchFilter.js',
    'scripts/filters/tagsFilter.js',
    'lib/ng-tags-input/ng-tags-input.min.js',
    'scripts/services/AgendaComissaoFactory.js',
    'scripts/controllers/gerenciarReuniaoController.js',
    'scripts/controllers/modalBuscarProposicaoController.js',
    'scripts/controllers/modalAddProposicaoController.js',
    'scripts/controllers/modalComentariosController.js',
    'scripts/controllers/modalEncaminhamentosController.js',
    'scripts/controllers/modalRelatorioReuniaoController.js',
    'scripts/controllers/modalRelatorioProposicaoController.js',
    'scripts/controllers/proposicaoController.js',
    'scripts/services/ComentarioFactory.js',
    'scripts/services/ComentarioService.js',
    'scripts/services/EncaminhamentoProposicaoFactory.js',
    'scripts/services/ComissaoFactory.js',
    'scripts/services/ProposicaoFactory.js',
    'scripts/services/ReuniaoFactory.js',
    'scripts/services/ElaboracaoNormativaFactory.js',
    'scripts/services/TarefaFactory.js',
    'scripts/services/NotificacaoFactory.js',
    'scripts/controllers/newPosicionamentoController.js',
    'scripts/controllers/searchPosicionamentoController.js',
    'scripts/controllers/editPosicionamentoController.js',
    'scripts/services/PosicionamentoFactory.js',
    'scripts/services/TipoEncaminhamentoFactory.js',
    'scripts/controllers/newTipoEncaminhamentoController.js',
    'scripts/controllers/searchTipoEncaminhamentoController.js',
    'scripts/controllers/editTipoEncaminhamentoController.js',
    'scripts/services/EquipeFactory.js',
    'scripts/controllers/searchEquipeController.js',
    'scripts/controllers/equipeController.js',
    'scripts/services/UsuarioFactory.js',
    'scripts/controllers/newUsuarioController.js',
    'scripts/controllers/searchUsuarioController.js',
    'scripts/controllers/editUsuarioController.js',
    'scripts/services/ReuniaoProposicaoFactory.js',
    'scripts/services/TagFactory.js',
    'scripts/controllers/searchElaboracaoNormativaController.js',
    'scripts/controllers/elaboracaoNormativaController.js',
    'scripts/controllers/searchStatusSidofController.js',
    'scripts/controllers/newStatusSidofController.js',
    'scripts/controllers/editStatusSidofController.js',
    'scripts/controllers/uploadController.js',
    'scripts/controllers/tarefaController.js',
    'scripts/controllers/notificacaoController.js',
    'scripts/services/OrigemElaboracaoNormativaFactory.js',
    'scripts/controllers/newOrigemElaboracaoNormativaController.js',
    'scripts/controllers/searchOrigemElaboracaoNormativaController.js',
    'scripts/services/AreaConsultadaFactory.js',
    'scripts/controllers/newAreaConsultadaController.js',
    'scripts/controllers/searchAreaConsultadaController.js',
    'scripts/controllers/editAreaConsultadaController.js',
    'scripts/services/OrgaoFactory.js',
    'scripts/controllers/newOrgaoController.js',
    'scripts/controllers/searchOrgaoController.js',
    'scripts/controllers/editOrgaoController.js',
    'scripts/controllers/SearchAgendaComissaoController.js',
    'scripts/services/ElaboracaoNormativaConsultaFactory.js',
    'scripts/services/StatusSidofFactory.js',
    'scripts/services/SituacaoLegislativaFactory.js',
    'scripts/controllers/SituacaoLegislativaController.js',
    'scripts/services/locationParser.js'

];

var compilacao = function() {
    console.info("Compilação executada");
    return gulp.src(libs)
        .pipe(ngAnnotate())
        .pipe(uglify())
        .pipe(concat('all.js'))
        .pipe(gulp.dest('./scripts'));
}
var generateHTMLs = function(){
	 console.info("Atualizando entradas do keycloak para apontar para: "+process.env.KEYCLOAK_SERVER);
	 if(!process.env.KEYCLOAK_SERVER){
		throw "Variável de ambiente KEYCLOAKSERVER não foi encontrada. Sete o valor de KEYCLOAKSERVER e tente novamente";
	 }
    console.info("Gerando index-dev.html");
	 var generateIndexDEVHtml = gulp.src(['template/index-source.html'])
	    .pipe(replace('KEYCLOAK_SERVER', process.env.KEYCLOAK_SERVER))
	    .pipe(rename("index-dev.html"))
	    .pipe(gulp.dest('./'));
     console.info("Gerando index.html");
     var generateIndexHTML = gulp.src('template/index-source.html')
	   .pipe(replace('KEYCLOAK_SERVER', process.env.KEYCLOAK_SERVER))
       .pipe(htmlreplace({
         		'js': 'js/all.js'
        	}))
       .pipe(rename("index.html"))
       .pipe(gulp.dest('./'));
      console.info("Gerando keycloak.json");
	 var generateFinalKeycloak = gulp.src(['template/keycloak.json'])
	    .pipe(replace('KEYCLOAK_SERVER', process.env.KEYCLOAKSERVER))
	    .pipe(gulp.dest('./'));

};
gulp.task('generateHTMLs',generateHTMLs);

gulp.task('compress', compilacao);

gulp.task('watch', function() {
    watch('scripts/**/*.js',compilacao);
    watch('template/*.*', generateHTMLs);
});

gulp.task('default', ['generateHTMLs', 'compress'], function() {
  // place code for your default task here
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React from 'react'

import Icon from '../Icon'
import StyledButton from './StyledButton'
import {
  inkPropTypes,
  stylingAnimation,
  stylingInk,
  stylingLook,
  stylingPosition
} from '../utilStyles'

/**
 * Use <Button> to trigger any actions. Choose look and ink according Material Design.
 */
const Button = props => {
  return (

  )
}

Button.defaultProps = {
  iconPosition: stylingPosition.PREPEND,
  look: stylingLook.FLAT,
  type: 'button'
}

Button.propTypes = {
  /**
   * May be passed from <ButtonGroup> to use as default for ink. Do not set manually.
   */
  buttonGroupInk: inkPropTypes,
  /**
   * May be passed from <ButtonGroup> to morph buttons into a split button. Do not set manually.
   */
  buttonGroupMelt: PropTypes.bool,
  /**
   * If true, button occupies less space. It should only used for crowded areas like tables and only if necessary.
   */
  dense: PropTypes.bool,
  /**
   * If true, the button can not be triggered. Disable a button rather than hide it temporarily.
   */
  disabled: PropTypes.bool,
  /**
   * Display an icon alongside button label. It is possible to omit label text if a icon is chosen. Utilize
   * Glyphicon of Bootstrap 3.7 or Font Awesome 4.7 by setting specific classname (e.g. "bars")
   * https://getbootstrap.com/docs/3.3/components/#glyphicons or https://fontawesome.com/v4.7.0/icons/
   */
  icon: PropTypes.string,
  /**
   * Prepend icon or append icon to label. Use 'sole' if label text is omitted. Default value is 'prepend'.
   * Possible values: append|prepend|sole
   */
  iconPosition: PropTypes.oneOf([stylingPosition.APPEND, stylingPosition.PREPEND, stylingPosition.SOLE]),
  /**
   * Specify color palette. Default value is 'base'.
   */
  ink: inkPropTypes,
  /**
   * Describe button action concise. Default is ''.
   */
  label: PropTypes.node,
  /**
   * Look of button. Default value is 'flat'.
   */
  look: PropTypes.oneOf([stylingLook.FLAT, stylingLook.RAISED]),
  /**
   * Function that will be triggered on click event.
   */
  onClick: PropTypes.func,
  /**
   * Function that will be triggered on mouse enter event.
   */
  onMouseEnter: PropTypes.func,
  /**
   * Function that will be triggered on mouse leave event.
   */
  onMouseLeave: PropTypes.func,
  /**
   * Function that will be triggered on mouse down event.
   */
  onMouseDown: PropTypes.func,
  /**
  * If true, an animated spinner icon is prepended.
  */
  pending: PropTypes.bool,
  /**
   * Describe button action in detail to instruct users. It is shown as popover on mouse over.
   */
  title: PropTypes.string,
  /**
   * HTML Button type. Default is 'button'.
   */
  type: PropTypes.oneOf(['button', 'submit', 'reset'])
}

export default Button
<commit_msg>refactor(tocco-ui): remove unused events from Button<commit_after>import PropTypes from 'prop-types'
import React from 'react'

import Icon from '../Icon'
import StyledButton from './StyledButton'
import {
  inkPropTypes,
  stylingAnimation,
  stylingInk,
  stylingLook,
  stylingPosition
} from '../utilStyles'

/**
 * Use <Button> to trigger any actions. Choose look and ink according Material Design.
 */
const Button = props => {
  return (

  )
}

Button.defaultProps = {
  iconPosition: stylingPosition.PREPEND,
  look: stylingLook.FLAT,
  type: 'button'
}

Button.propTypes = {
  /**
   * May be passed from <ButtonGroup> to use as default for ink. Do not set manually.
   */
  buttonGroupInk: inkPropTypes,
  /**
   * May be passed from <ButtonGroup> to morph buttons into a split button. Do not set manually.
   */
  buttonGroupMelt: PropTypes.bool,
  /**
   * If true, button occupies less space. It should only used for crowded areas like tables and only if necessary.
   */
  dense: PropTypes.bool,
  /**
   * If true, the button can not be triggered. Disable a button rather than hide it temporarily.
   */
  disabled: PropTypes.bool,
  /**
   * Display an icon alongside button label. It is possible to omit label text if a icon is chosen. Utilize
   * Glyphicon of Bootstrap 3.7 or Font Awesome 4.7 by setting specific classname (e.g. "bars")
   * https://getbootstrap.com/docs/3.3/components/#glyphicons or https://fontawesome.com/v4.7.0/icons/
   */
  icon: PropTypes.string,
  /**
   * Prepend icon or append icon to label. Use 'sole' if label text is omitted. Default value is 'prepend'.
   * Possible values: append|prepend|sole
   */
  iconPosition: PropTypes.oneOf([stylingPosition.APPEND, stylingPosition.PREPEND, stylingPosition.SOLE]),
  /**
   * Specify color palette. Default value is 'base'.
   */
  ink: inkPropTypes,
  /**
   * Describe button action concise. Default is ''.
   */
  label: PropTypes.node,
  /**
   * Look of button. Default value is 'flat'.
   */
  look: PropTypes.oneOf([stylingLook.FLAT, stylingLook.RAISED]),
  /**
   * Function that will be triggered on click event.
   */
  onClick: PropTypes.func,
  /**
  * If true, an animated spinner icon is prepended.
  */
  pending: PropTypes.bool,
  /**
   * Describe button action in detail to instruct users. It is shown as popover on mouse over.
   */
  title: PropTypes.string,
  /**
   * HTML Button type. Default is 'button'.
   */
  type: PropTypes.oneOf(['button', 'submit', 'reset'])
}

export default Button
<|endoftext|>


<commit_before>'use strict';

var gulp     = require('gulp');
var gutil    = require('gulp-util');
var concat   = require('gulp-concat');
var gulpif   = require('gulp-if');
var cached   = require('gulp-cached');
var remember = require('gulp-remember');

var del      = require('del');
var minimist = require('minimist');

var sass       = require('gulp-sass');
var minifyCSS  = require('gulp-minify-css');
var sourcemaps = require('gulp-sourcemaps');

var minifyHTML  = require('gulp-minify-html');

var browserSync = require('browser-sync');
var reload      = browserSync.reload;

var ngAnnotate = require('gulp-ng-annotate');
var minifyJS   = require('gulp-uglify');

var knownOptions = {
    string: 'env',
    default: { env: process.env.NODE_ENV || 'development'}
};

var options = minimist(process.argv.slice(2), knownOptions);

gulp.task('build', ['scss', 'js', 'html', 'fonts', 'copy-res'], function() {
    gutil.log('Finished building app to folder www');
});

gulp.task('scss', function() {
   return gulp.src('app/scss/*.scss')
       .pipe(cached('scss'))
       .pipe(gulpif(options.env === 'development', sourcemaps.init()))
       .pipe(sass())
       .on('error', sass.logError)
       .pipe(gulpif(options.env !== 'development', minifyCSS()))
       .pipe(remember('scss'))
       .pipe(concat('app.css'))
       .pipe(gulpif(options.env === 'development', sourcemaps.write()))
       .pipe(gulp.dest('./www/css/'))
       .pipe(reload({stream: true}))
});

gulp.task('html', function() {
    return gulp.src(['./app/**/*.html', '!./app/vendor/**/*.html'])
       .pipe(cached('html'))
       .pipe(gulpif(options.env !== 'development', minifyHTML()))
       .pipe(gulp.dest('./www/'))
       .pipe(reload({stream: true}))
});

gulp.task('vendor-js', function() {
   return gulp.src(
       ['./app/vendor/ionic/js/ionic.bundle.min.js',
        './app/vendor/ngCordova/dist/*.js',
        './app/vendor/peerjs/peer.min.js',
        './app/vendor/lodash/lodash.min.js',
        './app/vendor/ngstorage/ngStorage.min.js',
        './app/vendor/angular-translate/angular-translate.min.js',
        './app/vendor/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js',
        './app/vendor/fabric.js/dist/fabric.js'],
       { base: './app' })
       .pipe(gulp.dest('./www/'))
});

gulp.task('copy-res', function() {
   return gulp.src(['./app/res/**/*'],
       { base: './app' })
       .pipe(gulp.dest('./www/'))
});

gulp.task('fonts', function() {
    return gulp.src(['./app/vendor/ionic/fonts/*'])
    .pipe(gulp.dest('./www/fonts'))
});

gulp.task('js', ['vendor-js'], function() {
    return gulp.src('./app/js/**/*')
        .pipe(ngAnnotate())
        .pipe(gulpif(options.env !== 'development', minifyJS()))
        .pipe(cached('js'))
        .pipe(gulp.dest('./www/js/'))
        .pipe(reload({stream: true}))
});

gulp.task('watch', ['build'], function() {
    browserSync({
        server: { baseDir: 'www/' },
        open:   false
    });

    var scss = gulp.watch('app/scss/*.scss', ['scss'], {cwd: 'www'}, reload);
    var html = gulp.watch(['./app/**/*.html', '!./app/vendor/**/*.html'], ['html'], {cwd: 'www'}, reload);
    var js   = gulp.watch('./app/js/**/*', ['js'], {cwd: 'www'}, reload);

    scss.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting scss: ' + event.path);
            delete cached.caches.scss[event.path];
            remember.forget('scss', event.path);
        }
    });

    html.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting html: ' + event.path);
            delete cached.caches.html[event.path];
        }
    });

    js.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting js: ' + event.path);
            delete cached.caches.js[event.path];
        }
    });
});

gulp.task('clean', function() {
    return del('www');
});
<commit_msg>Add reload to resource files<commit_after>'use strict';

var gulp     = require('gulp');
var gutil    = require('gulp-util');
var concat   = require('gulp-concat');
var gulpif   = require('gulp-if');
var cached   = require('gulp-cached');
var remember = require('gulp-remember');

var del      = require('del');
var minimist = require('minimist');

var sass       = require('gulp-sass');
var minifyCSS  = require('gulp-minify-css');
var sourcemaps = require('gulp-sourcemaps');

var minifyHTML  = require('gulp-minify-html');

var browserSync = require('browser-sync');
var reload      = browserSync.reload;

var ngAnnotate = require('gulp-ng-annotate');
var minifyJS   = require('gulp-uglify');

var knownOptions = {
    string: 'env',
    default: { env: process.env.NODE_ENV || 'development'}
};

var options = minimist(process.argv.slice(2), knownOptions);

gulp.task('build', ['scss', 'js', 'html', 'fonts', 'copy-res'], function() {
    gutil.log('Finished building app to folder www');
});

gulp.task('scss', function() {
   return gulp.src('app/scss/*.scss')
       .pipe(cached('scss'))
       .pipe(gulpif(options.env === 'development', sourcemaps.init()))
       .pipe(sass())
       .on('error', sass.logError)
       .pipe(gulpif(options.env !== 'development', minifyCSS()))
       .pipe(remember('scss'))
       .pipe(concat('app.css'))
       .pipe(gulpif(options.env === 'development', sourcemaps.write()))
       .pipe(gulp.dest('./www/css/'))
       .pipe(reload({stream: true}))
});

gulp.task('html', function() {
    return gulp.src(['./app/**/*.html', '!./app/vendor/**/*.html'])
       .pipe(cached('html'))
       .pipe(gulpif(options.env !== 'development', minifyHTML()))
       .pipe(gulp.dest('./www/'))
       .pipe(reload({stream: true}))
});

gulp.task('vendor-js', function() {
   return gulp.src(
       ['./app/vendor/ionic/js/ionic.bundle.min.js',
        './app/vendor/ngCordova/dist/*.js',
        './app/vendor/peerjs/peer.min.js',
        './app/vendor/lodash/lodash.min.js',
        './app/vendor/ngstorage/ngStorage.min.js',
        './app/vendor/angular-translate/angular-translate.min.js',
        './app/vendor/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js',
        './app/vendor/fabric.js/dist/fabric.js'],
       { base: './app' })
       .pipe(gulp.dest('./www/'))
});

gulp.task('copy-res', function() {
   return gulp.src(['./app/res/**/*'],
       { base: './app' })
       .pipe(cached('res'))
       .pipe(gulp.dest('./www/'))
       .pipe(reload({stream: true}))
});

gulp.task('fonts', function() {
    return gulp.src(['./app/vendor/ionic/fonts/*'])
    .pipe(gulp.dest('./www/fonts'))
});

gulp.task('js', ['vendor-js'], function() {
    return gulp.src('./app/js/**/*')
        .pipe(ngAnnotate())
        .pipe(gulpif(options.env !== 'development', minifyJS()))
        .pipe(cached('js'))
        .pipe(gulp.dest('./www/js/'))
        .pipe(reload({stream: true}))
});

gulp.task('watch', ['build'], function() {
    browserSync({
        server: { baseDir: 'www/' },
        open:   false
    });

    var scss = gulp.watch('./app/scss/*.scss', ['scss'], {cwd: 'www'}, reload);
    var html = gulp.watch(['./app/**/*.html', '!./app/vendor/**/*.html'], ['html'], {cwd: 'www'}, reload);
    var js   = gulp.watch('./app/js/**/*', ['js'], {cwd: 'www'}, reload);
    var res  = gulp.watch('./app/res/**/*', ['copy-res'],  {cwd: 'www'}, reload);

    scss.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting scss: ' + event.path);
            delete cached.caches.scss[event.path];
            remember.forget('scss', event.path);
        }
    });

    html.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting html: ' + event.path);
            delete cached.caches.html[event.path];
        }
    });

    js.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting js: ' + event.path);
            delete cached.caches.js[event.path];
        }
    });

    res.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting res: ' + event.path);
            delete cached.caches.res[event.path];
        }
    });
});

gulp.task('clean', function() {
    return del('www');
});
<|endoftext|>


<commit_before>/*=====================================
=        Default Configuration        =
=====================================*/

// Please use config.js to override these selectively:

var config = {
  dest: 'www',
  cordova: true,
  minify_images: true,

  vendor: {
    js: [
      './bower_components/angular/angular.js',
      './bower_components/angular-route/angular-route.js',
      './bower_components/angular-touch/angular-touch.js',
      './bower_components/mobile-angular-ui/dist/js/mobile-angular-ui.js'
    ],

    fonts: [
      './bower_components/font-awesome/fonts/fontawesome-webfont.*'
    ]
  },

  server: {
    host: '0.0.0.0',
    port: '8000'
  },

  weinre: {
    httpPort:     8001,
    boundHost:    'localhost',
    verbose:      false,
    debug:        false,
    readTimeout:  5,
    deathTimeout: 15
  }
};

if (require('fs').existsSync('./config.js')) {
  var configFn = require('./config');
  configFn(config);
};

/*-----  End of Configuration  ------*/

/*========================================
=            Requiring stuffs            =
========================================*/

var gulp           = require('gulp'),
    seq            = require('run-sequence'),
    connect        = require('gulp-connect'),
    less           = require('gulp-less'),
    uglify         = require('gulp-uglify'),
    sourcemaps     = require('gulp-sourcemaps'),
    cssmin         = require('gulp-cssmin'),
    order          = require('gulp-order'),
    concat         = require('gulp-concat'),
    ignore         = require('gulp-ignore'),
    rimraf         = require('gulp-rimraf'),
    imagemin       = require('gulp-imagemin'),
    pngcrush       = require('imagemin-pngcrush'),
    templateCache  = require('gulp-angular-templatecache'),
    mobilizer      = require('gulp-mobilizer'),
    ngAnnotate     = require('gulp-ng-annotate'),
    replace        = require('gulp-replace'),
    ngFilesort     = require('gulp-angular-filesort'),
    streamqueue    = require('streamqueue'),
    rename         = require('gulp-rename'),
    path           = require('path');

/*================================================
=            Report Errors to Console            =
================================================*/

gulp.on('err', function(e) {
  console.log(e.err.stack);
});

/*=========================================
=            Clean dest folder            =
=========================================*/

gulp.task('clean', function (cb) {
  return gulp.src([
        path.join(config.dest, 'index.html'),
        path.join(config.dest, 'images'),
        path.join(config.dest, 'css'),
        path.join(config.dest, 'js'),
        path.join(config.dest, 'fonts')
      ], { read: false })
     .pipe(rimraf());
});

/*==========================================
=            Start a web server            =
==========================================*/

gulp.task('connect', function() {
  if (typeof config.server === 'object') {
    connect.server({
      root: config.dest,
      host: config.server.host,
      port: config.server.port,
      livereload: true
    });
  } else {
    throw new Error('Connect is not configured');
  }
});

/*==============================================================
=            Setup live reloading on source changes            =
==============================================================*/

gulp.task('livereload', function () {
  gulp.src(path.join(config.dest, '*.html'))
    .pipe(connect.reload());
});

/*=====================================
=            Minify images            =
=====================================*/

gulp.task('images', function () {
  var stream = gulp.src('src/images/**/*')

  if (config.minify_images) {
    stream = stream.pipe(imagemin({
        progressive: true,
        svgoPlugins: [{removeViewBox: false}],
        use: [pngcrush()]
    }))
  };

  return stream.pipe(gulp.dest(path.join(config.dest, 'images')));
});

/*==================================
=            Copy fonts            =
==================================*/

gulp.task('fonts', function() {
  return gulp.src(config.vendor.fonts)
  .pipe(gulp.dest(path.join(config.dest, 'fonts')));
});

/*=================================================
=            Copy html files to dest              =
=================================================*/

gulp.task('html', function() {
  var inject = [];
  if (typeof config.weinre === 'object') {
    inject.push('<script src="http://'+config.weinre.boundHost+':'+config.weinre.httpPort+'/target/target-script-min.js"></script>');
  }
  if (config.cordova) {
    inject.push('<script src="cordova.js"></script>');
  }
  gulp.src(['src/html/**/*.html'])
  .pipe(replace('<!-- inject:js -->', inject.join('\n    ')))
  .pipe(gulp.dest(config.dest));
});

/*======================================================================
=            Compile, minify, mobilize less                            =
======================================================================*/

gulp.task('less', function () {
  gulp.src(['./src/less/app.less', './src/less/responsive.less'])
    .pipe(less({
      paths: [ path.resolve(__dirname, 'src/less'), path.resolve(__dirname, 'bower_components') ]
    }))
    .pipe(mobilizer('app.css', {
      'app.css': {
        hover: 'exclude',
        screens: ['0px']
      },
      'hover.css': {
        hover: 'only',
        screens: ['0px']
      }
    }))
    .pipe(cssmin())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest(path.join(config.dest, 'css')));
});

/*====================================================================
=            Compile and minify js generating source maps            =
====================================================================*/
// - Orders ng deps automatically
// - Precompile templates to ng templateCache

gulp.task('js', function() {
    streamqueue({ objectMode: true },
      gulp.src(config.vendor.js),
      gulp.src('./src/js/**/*.js').pipe(ngFilesort()),
      gulp.src(['src/templates/**/*.html']).pipe(templateCache({ module: 'Catleya' }))
    )
    .pipe(sourcemaps.init())
    .pipe(concat('app.js'))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(sourcemaps.write('.'))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest(path.join(config.dest, 'js')));
});

/*===================================================================
=            Watch for source changes and rebuild/reload            =
===================================================================*/

gulp.task('watch', function () {
  if (typeof config.server === 'object') {
    gulp.watch([config.dest + '/**/*'], ['livereload']);
  };
  gulp.watch(['./src/html/**/*'], ['html']);
  gulp.watch(['./src/less/**/*'], ['less']);
  gulp.watch(['./src/js/**/*', './src/templates/**/*', config.vendor.js], ['js']);
  gulp.watch(['./src/images/**/*'], ['images']);
});

/*===================================================
=            Starts a Weinre Server                 =
===================================================*/

gulp.task('weinre', function() {
  if (typeof config.weinre === 'object') {
    require('./node_modules/weinre/node_modules/coffee-script');
    var weinre = require('./node_modules/weinre/lib/weinre');
    weinre.run(config.weinre);
  } else {
    throw new Error('Weinre is not configured');
  }
});

/*======================================
=            Build Sequence            =
======================================*/

gulp.task('build', function(done) {
  var tasks = ['html', 'fonts', 'images', 'less', 'js'];
  seq('clean', tasks, done);
});

/*====================================
=            Default Task            =
====================================*/

gulp.task('default', function(done){
  var tasks = [];

  if (typeof config.weinre === 'object') {
    tasks.push('weinre');
  };

  if (typeof config.server === 'object') {
    tasks.push('connect');
  };

  tasks.push('watch');

  seq('build', tasks, done);
});<commit_msg>Deal with strange bug in gulpfile<commit_after>/*=====================================
=        Default Configuration        =
=====================================*/

// Please use config.js to override these selectively:

var config = {
  dest: 'www',
  cordova: true,
  minify_images: true,

  vendor: {
    js: [
      './bower_components/angular/angular.js',
      './bower_components/angular-route/angular-route.js',
      './bower_components/angular-touch/angular-touch.js',
      './bower_components/mobile-angular-ui/dist/js/mobile-angular-ui.js'
    ],

    fonts: [
      './bower_components/font-awesome/fonts/fontawesome-webfont.*'
    ]
  },

  server: {
    host: '0.0.0.0',
    port: '8000'
  },

  weinre: {
    httpPort:     8001,
    boundHost:    'localhost',
    verbose:      false,
    debug:        false,
    readTimeout:  5,
    deathTimeout: 15
  }
};

if (require('fs').existsSync('./config.js')) {
  var configFn = require('./config');
  configFn(config);
};

/*-----  End of Configuration  ------*/

/*========================================
=            Requiring stuffs            =
========================================*/

var gulp           = require('gulp'),
    seq            = require('run-sequence'),
    connect        = require('gulp-connect'),
    less           = require('gulp-less'),
    uglify         = require('gulp-uglify'),
    sourcemaps     = require('gulp-sourcemaps'),
    cssmin         = require('gulp-cssmin'),
    order          = require('gulp-order'),
    concat         = require('gulp-concat'),
    ignore         = require('gulp-ignore'),
    rimraf         = require('gulp-rimraf'),
    imagemin       = require('gulp-imagemin'),
    pngcrush       = require('imagemin-pngcrush'),
    templateCache  = require('gulp-angular-templatecache'),
    mobilizer      = require('gulp-mobilizer'),
    ngAnnotate     = require('gulp-ng-annotate'),
    replace        = require('gulp-replace'),
    ngFilesort     = require('gulp-angular-filesort'),
    streamqueue    = require('streamqueue'),
    rename         = require('gulp-rename'),
    path           = require('path');

/*================================================
=            Report Errors to Console            =
================================================*/

gulp.on('err', function(e) {
  console.log(e.err.stack);
});

/*=========================================
=            Clean dest folder            =
=========================================*/

gulp.task('clean', function (cb) {
  return gulp.src([
        path.join(config.dest, 'index.html'),
        path.join(config.dest, 'images'),
        path.join(config.dest, 'css'),
        path.join(config.dest, 'js'),
        path.join(config.dest, 'fonts')
      ], { read: false })
     .pipe(rimraf());
});

/*==========================================
=            Start a web server            =
==========================================*/

gulp.task('connect', function() {
  if (typeof config.server === 'object') {
    connect.server({
      root: config.dest,
      host: config.server.host,
      port: config.server.port,
      livereload: true
    });
  } else {
    throw new Error('Connect is not configured');
  }
});

/*==============================================================
=            Setup live reloading on source changes            =
==============================================================*/

gulp.task('livereload', function () {
  gulp.src(path.join(config.dest, '*.html'))
    .pipe(connect.reload());
});

/*=====================================
=            Minify images            =
=====================================*/

gulp.task('images', function () {
  var stream = gulp.src('src/images/**/*')

  if (config.minify_images) {
    stream = stream.pipe(imagemin({
        progressive: true,
        svgoPlugins: [{removeViewBox: false}],
        use: [pngcrush()]
    }))
  };

  return stream.pipe(gulp.dest(path.join(config.dest, 'images')));
});

/*==================================
=            Copy fonts            =
==================================*/

gulp.task('fonts', function() {
  return gulp.src(config.vendor.fonts)
  .pipe(gulp.dest(path.join(config.dest, 'fonts')));
});

/*=================================================
=            Copy html files to dest              =
=================================================*/

gulp.task('html', function() {
  var inject = [];
  if (typeof config.weinre === 'object') {
    inject.push('<script src="http://'+config.weinre.boundHost+':'+config.weinre.httpPort+'/target/target-script-min.js"></script>');
  }
  if (config.cordova) {
    inject.push('<script src="cordova.js"></script>');
  }
  gulp.src(['src/html/**/*.html'])
  .pipe(replace('<!-- inject:js -->', inject.join('\n    ')))
  .pipe(gulp.dest(config.dest));
});

/*======================================================================
=            Compile, minify, mobilize less                            =
======================================================================*/

gulp.task('less', function () {
  gulp.src(['./src/less/app.less', './src/less/responsive.less'])
    .pipe(less({
      paths: [ path.resolve(__dirname, 'src/less'), path.resolve(__dirname, 'bower_components') ]
    }))
    .pipe(mobilizer('app.css', {
      'app.css': {
        hover: 'exclude',
        screens: ['0px']
      },
      'hover.css': {
        hover: 'only',
        screens: ['0px']
      }
    }))
    .pipe(cssmin())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest(path.join(config.dest, 'css')));
});

/*====================================================================
=            Compile and minify js generating source maps            =
====================================================================*/
// - Orders ng deps automatically
// - Precompile templates to ng templateCache

gulp.task('js', function() {
    streamqueue({ objectMode: true },
      gulp.src(config.vendor.js),
      gulp.src('./src/js/**/*.js').pipe(ngFilesort()),
      gulp.src(['src/templates/**/*.html']).pipe(templateCache({ module: 'Catleya' }))
    )
    .pipe(sourcemaps.init())
    .pipe(concat('app.js'))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(sourcemaps.write('.'))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest(path.join(config.dest, 'js')));
});

/*===================================================================
=            Watch for source changes and rebuild/reload            =
===================================================================*/

gulp.task('watch', function () {
  if (typeof config.server === 'object') {
    gulp.watch([config.dest + '/**/*'], ['livereload']);
  };
  gulp.watch(['./src/html/**/*'], ['html']);
  gulp.watch(['./src/less/**/*'], ['less']);
  gulp.watch(['./src/js/**/*', './src/templates/**/*', config.vendor.js], ['js']);
  gulp.watch(['./src/images/**/*'], ['images']);
});

/*===================================================
=            Starts a Weinre Server                 =
===================================================*/

gulp.task('weinre', function() {
  if (typeof config.weinre === 'object') {
    config.weinre.verbose =      false;
    config.weinre.debug =        false;
    config.weinre.readTimeout =  5;
    config.weinre.deathTimeout = 15;
    require('./node_modules/weinre/node_modules/coffee-script');
    var weinre = require('./node_modules/weinre/lib/weinre');
    weinre.run(config.weinre);
  } else {
    throw new Error('Weinre is not configured');
  }
});

/*======================================
=            Build Sequence            =
======================================*/

gulp.task('build', function(done) {
  var tasks = ['html', 'fonts', 'images', 'less', 'js'];
  seq('clean', tasks, done);
});

/*====================================
=            Default Task            =
====================================*/

gulp.task('default', function(done){
  var tasks = [];

  if (typeof config.weinre === 'object') {
    tasks.push('weinre');
  };

  if (typeof config.server === 'object') {
    tasks.push('connect');
  };

  tasks.push('watch');

  seq('build', tasks, done);
});<|endoftext|>


<commit_before>/**
 * @author Andreas Bresser
 */
/**
 * Scale 9 Container.
 * e.g. useful for scalable buttons.
 *
 * @class ScaleContainer
 * @constructor
 */

PIXI_UI.ScaleContainer = function(texture, rect) {
    PIXI.DisplayObjectContainer.call( this );

    this.rect = rect;
    this.baseTexture = texture.baseTexture;
    this.frame = texture.frame;

    this._width = this.frame.width;
    this._height = this.frame.height;

    // left / middle / right width
    var lw = rect.x;
    var mw = rect.width;
    var rw = this.frame.width - (mw + lw);

    // top / center / bottom height
    var th = rect.y;
    var ch = rect.height;
    var bh = this.frame.height - (ch + th);

    // top
    this.tl = this._getTexture(0, 0, lw, th);
    this.tm = this._getTexture(lw, 0, mw, th);
    this.tr = this._getTexture(lw+mw, 0, rw, th);

    // center
    this.cl = this._getTexture(0, th, lw, ch);
    this.cm = this._getTexture(lw, th, mw, ch);
    this.cr = this._getTexture(lw+mw, th, rw, ch);

    // bottom
    this.bl = this._getTexture(0, th+ch, lw, bh);
    this.bm = this._getTexture(lw, th+ch, mw, bh);
    this.br = this._getTexture(lw+mw, th+ch, rw, bh);

    this.cl.y = this.cm.y = this.cr.y = th;
    this.tm.x = this.cm.x = this.bm.x = lw;

    this.addChild(this.tl);
    this.addChild(this.tm);
    this.addChild(this.tr);

    this.addChild(this.cl);
    this.addChild(this.cm);
    this.addChild(this.cr);

    this.addChild(this.bl);
    this.addChild(this.bm);
    this.addChild(this.br);
};

// constructor
PIXI_UI.ScaleContainer.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
PIXI_UI.ScaleContainer.prototype.constructor = PIXI_UI.ScaleContainer;

/**
 * create a new texture from a base-texture by given dimensions
 *
 * @method _getTexture
 * @private
 */
PIXI_UI.ScaleContainer.prototype._getTexture = function(x, y, w, h) {
    var frame = new PIXI.Rectangle(this.frame.x+x, this.frame.y+y, w, h);
    var t = new PIXI.Texture(this.baseTexture, frame, frame.clone(), null);
    return new PIXI.Sprite(t);
};

/**
 * The width of the container, setting this will redraw the component.
 *
 * @property width
 * @type Number
 */
Object.defineProperty(PIXI_UI.ScaleContainer.prototype, 'width', {
    get: function() {
        return this._width;
    },
    set: function(value) {
        if (this._width !== value) {
            this._width = value;
            this.invalid = true;
        }
    }
});

/**
 * The height of the container, setting this will redraw the component.
 *
 * @property height
 * @type Number
 */
Object.defineProperty(PIXI_UI.ScaleContainer.prototype, 'height', {
    get: function() {
        return this._height;
    },
    set: function(value) {
        if (this._height !== value) {
            this._height = value;
            this.invalid = true;
        }
    }
});

/**
 * update before draw call (reposition textures)
 *
 * @method redraw
 */
PIXI_UI.ScaleContainer.prototype.redraw = function() {
    if (this.invalid) {
        this._positionTilable();
        this.invalid = false;
    }
};

/**
 * recalculate the position of the tiles (every time width/height changes)
 *
 * @method _positionTilable
 * @private
 */
PIXI_UI.ScaleContainer.prototype._positionTilable = function() {
    // left / middle / right width
    var lw = this.rect.x;
    var mw = this.rect.width;
    var rw = this.frame.width - (mw + lw);

    // top / center / bottom height
    var th = this.rect.y;
    var ch = this.rect.height;
    var bh = this.frame.height - (ch + th);

    this.cr.x = this.br.x = this.tr.x = this._width - rw;
    this.cm.width = this.bm.width = this.tm.width = this._width - (lw + rw);

    this.cl.height = this.cm.height = this.cr.height = this._height - (th + bh);
    this.br.y = this.bm.y = this.bl.y = this._height - bh;
};

/**
 *
 * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
 * The frame ids are created when a Texture packer file has been loaded
 *
 * @method fromFrame
 * @static
 * @param frameId {String} The frame Id of the texture in the cache
 * @param rect {Rectangle} defines tilable area
 * @return {ScaleTexture} A new Scalable Texture (e.g. a button) using a texture from the texture cache matching the frameId
 */
PIXI_UI.ScaleContainer.fromFrame = function(frameId, rect) {
    var texture = PIXI.TextureCache[frameId];
    if(!texture) {
        throw new Error('The frameId "' + frameId + '" does not exist ' +
                        'in the texture cache');
    }
    return new PIXI_UI.ScaleContainer(texture, rect);
};

/**
 * Renders the object using the WebGL renderer
 *
 * @method _renderWebGL
 * @param renderSession {RenderSession}
 * @private
 */
/* istanbul ignore next */
PIXI_UI.ScaleContainer.prototype._renderWebGL = function(renderSession) {
    this.redraw();
    return PIXI.DisplayObjectContainer.prototype._renderWebGL.call(this, renderSession);
};

/**
 * Renders the object using the Canvas renderer
 *
 * @method _renderWebGL
 * @param renderSession {RenderSession}
 * @private
 */
/* istanbul ignore next */
PIXI_UI.ScaleContainer.prototype._renderCanvas = function(renderSession) {
    this.redraw();
    return PIXI.DisplayObjectContainer.prototype._renderCanvas.call(this, renderSession);
};<commit_msg>do not create tiles with 0 px width/height<commit_after>/**
 * @author Andreas Bresser
 */
/**
 * Scale 9 Container.
 * e.g. useful for scalable buttons.
 *
 * @class ScaleContainer
 * @constructor
 */

PIXI_UI.ScaleContainer = function(texture, rect) {
    PIXI.DisplayObjectContainer.call( this );

    this.rect = rect;
    this.baseTexture = texture.baseTexture;
    this.frame = texture.frame;

    this._width = this.frame.width;
    this._height = this.frame.height;

    // left / middle / right width
    var lw = rect.x;
    var mw = rect.width;
    var rw = this.frame.width - (mw + lw);

    // top / center / bottom height
    var th = rect.y;
    var ch = rect.height;
    var bh = this.frame.height - (ch + th);

    // top
    if (lw > 0 && th > 0) {
        this.tl = this._getTexture(0, 0, lw, th);
        this.addChild(this.tl);
    }
    if (mw > 0 && th > 0) {
        this.tm = this._getTexture(lw, 0, mw, th);
        this.addChild(this.tm);
        this.tm.x = lw;
    }
    if (rw > 0 && th > 0) {
        this.tr = this._getTexture(lw + mw, 0, rw, th);
        this.addChild(this.tr);
    }

    // center
    if (lw > 0 && ch > 0) {
        this.cl = this._getTexture(0, th, lw, ch);
        this.addChild(this.cl);
        this.cl.y = th;
    }
    if (mw > 0 && ch > 0) {
        this.cm = this._getTexture(lw, th, mw, ch);
        this.addChild(this.cm);
        this.cm.y = th;
        this.cm.x = lw;
    }
    if (rw > 0 && ch > 0) {
        this.cr = this._getTexture(lw + mw, th, rw, ch);
        this.addChild(this.cr);
        this.cr.y = th;
    }

    // bottom
    if (lw > 0 && bh > 0) {
        this.bl = this._getTexture(0, th + ch, lw, bh);
        this.addChild(this.bl);
    }
    if (mw > 0 && bh > 0) {
        this.bm = this._getTexture(lw, th + ch, mw, bh);
        this.addChild(this.bm);
        this.bm.x = lw;
    }
    if (rw > 0 && bh > 0) {
        this.br = this._getTexture(lw + mw, th + ch, rw, bh);
        this.addChild(this.br);
    }
};

// constructor
PIXI_UI.ScaleContainer.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
PIXI_UI.ScaleContainer.prototype.constructor = PIXI_UI.ScaleContainer;

/**
 * create a new texture from a base-texture by given dimensions
 *
 * @method _getTexture
 * @private
 */
PIXI_UI.ScaleContainer.prototype._getTexture = function(x, y, w, h) {
    var frame = new PIXI.Rectangle(this.frame.x+x, this.frame.y+y, w, h);
    var t = new PIXI.Texture(this.baseTexture, frame, frame.clone(), null);
    return new PIXI.Sprite(t);
};

/**
 * The width of the container, setting this will redraw the component.
 *
 * @property width
 * @type Number
 */
Object.defineProperty(PIXI_UI.ScaleContainer.prototype, 'width', {
    get: function() {
        return this._width;
    },
    set: function(value) {
        if (this._width !== value) {
            this._width = value;
            this.invalid = true;
        }
    }
});

/**
 * The height of the container, setting this will redraw the component.
 *
 * @property height
 * @type Number
 */
Object.defineProperty(PIXI_UI.ScaleContainer.prototype, 'height', {
    get: function() {
        return this._height;
    },
    set: function(value) {
        if (this._height !== value) {
            this._height = value;
            this.invalid = true;
        }
    }
});

/**
 * update before draw call (reposition textures)
 *
 * @method redraw
 */
PIXI_UI.ScaleContainer.prototype.redraw = function() {
    if (this.invalid) {
        this._positionTilable();
        this.invalid = false;
    }
};

/**
 * recalculate the position of the tiles (every time width/height changes)
 *
 * @method _positionTilable
 * @private
 */
PIXI_UI.ScaleContainer.prototype._positionTilable = function() {
    // left / middle / right width
    var lw = this.rect.x;
    var mw = this.rect.width;
    var rw = this.frame.width - (mw + lw);

    // top / center / bottom height
    var th = this.rect.y;
    var ch = this.rect.height;
    var bh = this.frame.height - (ch + th);

    var rightX = this._width - rw;
    var bottomY = this._height - bh;
    if (this.cr) {
        this.cr.x = rightX;
    }
    if (this.br) {
        this.br.x = rightX;
        this.br.y = bottomY;
    }
    if (this.tr) {
        this.tr.x = rightX;
    }

    var middleWidth = this._width - (lw + rw);
    var centerHeight = this._height - (th + bh);
    if (this.cm) {
        this.cm.width = middleWidth;
        this.cm.height = centerHeight;
    }
    if (this.bm) {
        this.bm.width = middleWidth;
        this.bm.y = bottomY;
    }
    if (this.tm) {
        this.tm.width = middleWidth;
    }
    if (this.cl) {
        this.cl.height = centerHeight;
    }
    if (this.cr) {
        this.cr.height = centerHeight;
    }

    if (this.bl) {
        this.bl.y = bottomY;
    }
};

/**
 *
 * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
 * The frame ids are created when a Texture packer file has been loaded
 *
 * @method fromFrame
 * @static
 * @param frameId {String} The frame Id of the texture in the cache
 * @param rect {Rectangle} defines tilable area
 * @return {ScaleTexture} A new Scalable Texture (e.g. a button) using a texture from the texture cache matching the frameId
 */
PIXI_UI.ScaleContainer.fromFrame = function(frameId, rect) {
    var texture = PIXI.TextureCache[frameId];
    if(!texture) {
        throw new Error('The frameId "' + frameId + '" does not exist ' +
                        'in the texture cache');
    }
    return new PIXI_UI.ScaleContainer(texture, rect);
};

/**
 * Renders the object using the WebGL renderer
 *
 * @method _renderWebGL
 * @param renderSession {RenderSession}
 * @private
 */
/* istanbul ignore next */
PIXI_UI.ScaleContainer.prototype._renderWebGL = function(renderSession) {
    this.redraw();
    return PIXI.DisplayObjectContainer.prototype._renderWebGL.call(this, renderSession);
};

/**
 * Renders the object using the Canvas renderer
 *
 * @method _renderWebGL
 * @param renderSession {RenderSession}
 * @private
 */
/* istanbul ignore next */
PIXI_UI.ScaleContainer.prototype._renderCanvas = function(renderSession) {
    this.redraw();
    return PIXI.DisplayObjectContainer.prototype._renderCanvas.call(this, renderSession);
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var config = {
    directory: "./",
    js: "./js/app.js",
    css: "./css/app.css",
    icons: "node_modules/geomicons-open/icons/*.svg"
};

function pages() {

    var nunjucks = require('static-engine-renderer-nunjucks');
    var render = require('static-engine-render');
    var one = require('static-engine-one');
    var engine = require('static-engine');
    var page;

    nunjucks.configure('./templates/', {
        autoescape: true
    });

    render.configure('./');

    return engine(one, render('index.html', nunjucks('index.html')));
}

function css(){

    var autoprefixer = require('gulp-autoprefixer');
    var uncss = require('gulp-uncss');
    var minifycss = require('gulp-minify-css');
    var glob = require('glob');
    var rework = require('gulp-rework');
    var concat = require('gulp-concat');
    var calc = require('rework-calc');
    var media = require('rework-custom-media');
    var npm = require('rework-npm');
    var vars = require('rework-vars');
    var colors = require('rework-plugin-colors');
    var cheerio = require('gulp-cheerio');

    return gulp.src(config.css)
        .pipe(rework(
            npm(),
            vars(),
            media(),
            calc,
            colors()
        ))
        .pipe(autoprefixer('> 1%', 'last 2 versions'))
        .pipe(concat("index.css"))
        .pipe(uncss({
            html: glob.sync('index.html')
        }))
        .pipe(minifycss())
        .pipe(gulp.dest(config.directory));
}

function js() {

    var concat = require('gulp-concat');
    var uglify = require('gulp-uglify');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');
    var browserify = require('browserify');
    var source = require('vinyl-source-stream');
    var buffer = require('vinyl-buffer');
    var collapse = require('bundle-collapser/plugin');
    var bundler = browserify({
        entries: config.js,
        debug: false
    });

    return bundler
        .plugin(collapse)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(uglify({
            preserveComments: 'some'
        }))
        .pipe(tap(function(file){

            return gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('body').append('<script>'+file.contents+'</script>');
                }))
                .pipe(gulp.dest(config.directory));
        }));
}

function optimize(){

    var htmlmin = require('gulp-htmlmin');

    return gulp.src('index.html')
        .pipe(htmlmin({
            collapseWhitespace: true
        }))
        .pipe(gulp.dest(config.directory));
}

function icons() {

    var cheerio = require('gulp-cheerio');
    var concat = require('gulp-concat');
    var tap = require('gulp-tap');

    return gulp.src(config.icons)
    .pipe(concat('icons.svg'))
    .pipe(tap(function(file){

        return gulp.src('index.html')
        .pipe(cheerio(function($){

            var defs = $('<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"><defs>'+file.contents+'</defs></svg>');

            $('body').append(defs);

            $('use').each(function(){

                $(this).replaceWith($('svg' + $(this).attr('xlink:href') + ' path').clone());
            });

            defs.remove();
        }))
        .pipe(gulp.dest(config.directory));
    }));
}

function selectors() {

    var gs = require('gulp-selectors');

    return gulp.src(['index.css', 'index.html'])
        .pipe(gs.run())
        .pipe(gulp.dest(config.directory));
}

function combine() {

    var path = require('path');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');

    return gulp.src('index.css')
        .pipe(tap(function(file){

            gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('head').append('<style type="text/css">'+file.contents+'</style>');

                }))
                .pipe(gulp.dest(config.directory));
        }));
}

function serve(done){

    var express = require('express');
    var static = require('express-static');
    var logger = require('express-log');

    var app = express();

    app.use(logger());

    app.use(static(config.directory));

    app.use(function(req, res, next){

        res.redirect('/');
    });

    var server = app.listen(8088, function(){
        console.log('server is running at %s', server.address().port);
    });

    done();
}

function watch() {

    gulp.watch(['css/**/*.css', 'js/**/*.js', 'templates/**/*.html'], 'default');
}

gulp.task('default', gulp.series( pages, optimize, icons, js, css, selectors, combine) );

gulp.task('dev', gulp.parallel('default', watch, serve));
<commit_msg>Add a space<commit_after>var gulp = require('gulp');
var config = {
    directory: "./",
    js: "./js/app.js",
    css: "./css/app.css",
    icons: "node_modules/geomicons-open/icons/*.svg"
};

function pages() {

    var nunjucks = require('static-engine-renderer-nunjucks');
    var render = require('static-engine-render');
    var one = require('static-engine-one');
    var engine = require('static-engine');
    var page;

    nunjucks.configure('./templates/', {
        autoescape: true
    });

    render.configure('./');

    return engine(one, render('index.html', nunjucks('index.html')));
}

function css(){

    var autoprefixer = require('gulp-autoprefixer');
    var uncss = require('gulp-uncss');
    var minifycss = require('gulp-minify-css');
    var glob = require('glob');
    var rework = require('gulp-rework');
    var concat = require('gulp-concat');
    var calc = require('rework-calc');
    var media = require('rework-custom-media');
    var npm = require('rework-npm');
    var vars = require('rework-vars');
    var colors = require('rework-plugin-colors');
    var cheerio = require('gulp-cheerio');

    return gulp.src(config.css)
        .pipe(rework(
            npm(),
            vars(),
            media(),
            calc,
            colors()
        ))
        .pipe(autoprefixer('> 1%', 'last 2 versions'))
        .pipe(concat("index.css"))
        .pipe(uncss({
            html: glob.sync('index.html')
        }))
        .pipe(minifycss())
        .pipe(gulp.dest(config.directory));
}

function js() {

    var concat = require('gulp-concat');
    var uglify = require('gulp-uglify');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');
    var browserify = require('browserify');
    var source = require('vinyl-source-stream');
    var buffer = require('vinyl-buffer');
    var collapse = require('bundle-collapser/plugin');
    var bundler = browserify({
        entries: config.js,
        debug: false
    });

    return bundler
        .plugin(collapse)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(uglify({
            preserveComments: 'some'
        }))
        .pipe(tap(function(file){

            return gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('body').append('<script>'+file.contents+'</script>');
                }))
                .pipe(gulp.dest(config.directory));
        }));
}

function optimize(){

    var htmlmin = require('gulp-htmlmin');

    return gulp.src('index.html')
        .pipe(htmlmin({
            collapseWhitespace: true
        }))
        .pipe(gulp.dest(config.directory));
}

function icons() {

    var cheerio = require('gulp-cheerio');
    var concat = require('gulp-concat');
    var tap = require('gulp-tap');

    return gulp.src(config.icons)
    .pipe(concat('icons.svg'))
    .pipe(tap(function(file){

        return gulp.src('index.html')
        .pipe(cheerio(function($){

            var defs = $('<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"><defs>'+file.contents+'</defs></svg>');

            $('body').append(defs);

            $('use').each(function(){

                $(this).replaceWith($('svg' + $(this).attr('xlink:href') + ' path').clone());
            });

            defs.remove();
        }))
        .pipe(gulp.dest(config.directory));
    }));
}

function selectors() {

    var gs = require('gulp-selectors');

    return gulp.src(['index.css', 'index.html'])
        .pipe(gs.run())
        .pipe(gulp.dest(config.directory));
}

function combine() {

    var path = require('path');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');

    return gulp.src('index.css')
        .pipe(tap(function(file){

            gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('head').append('<style type="text/css">'+file.contents+'</style>');

                }))
                .pipe(gulp.dest(config.directory));
        }));
}

function serve(done){

    var express = require('express');
    var static = require('express-static');
    var logger = require('express-log');

    var app = express();

    app.use(logger());

    app.use(static(config.directory));

    app.use(function(req, res, next){

        res.redirect('/');
    });

    var server = app.listen(8088, function(){
        console.log('server is running at %s', server.address().port);
    });

    done();
}

function watch() {

    gulp.watch(['css/**/*.css', 'js/**/*.js', 'templates/**/*.html'], 'default');
}

gulp.task('default', gulp.series( pages, optimize, icons, js, css, selectors, combine ) );

gulp.task('dev', gulp.parallel('default', watch, serve));
<|endoftext|>


<commit_before>var	name    = require('./package.json').moduleName,
    fs      = require('fs'),
    gulp    = require('gulp'),
    plugins = require('gulp-load-plugins')()

var head = fs.readFileSync('./node_modules/@electerious/modulizer/head.js', { encoding: 'utf8' }),
    foot = fs.readFileSync('./node_modules/@electerious/modulizer/foot.js', { encoding: 'utf8' })

var catchError = function(err) {

	console.log(err.toString())
	this.emit('end')

}

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

	gulp.src('./src/styles/main.scss')
	    .pipe(plugins.sass())
	    .on('error', catchError)
	    .pipe(plugins.concat(name + '.min.css', { newLine: "\n" }))
	    .pipe(plugins.autoprefixer('last 2 version', '> 1%'))
	    .pipe(plugins.minifyCss())
	    .pipe(gulp.dest('./dist'))

})

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

	gulp.src('./src/scripts/*.js')
	    .pipe(plugins.header(head, { name: name }))
	    .pipe(plugins.footer(foot))
	    .pipe(plugins.babel())
	    .pipe(plugins.concat(name + '.min.js', { newLine: "\n" }))
	    .pipe(plugins.uglify())
	    .on('error', catchError)
	    .pipe(gulp.dest('./dist'))

})

gulp.task('default', ['styles', 'scripts'])

gulp.task('watch', ['styles', 'scripts'], function() {

	gulp.watch('./src/styles/**/*.scss', ['styles'])
	gulp.watch('./src/scripts/**/*.js', ['scripts'])

})<commit_msg>Catch babel errors<commit_after>var	name    = require('./package.json').moduleName,
    fs      = require('fs'),
    gulp    = require('gulp'),
    plugins = require('gulp-load-plugins')()

var head = fs.readFileSync('./node_modules/@electerious/modulizer/head.js', { encoding: 'utf8' }),
    foot = fs.readFileSync('./node_modules/@electerious/modulizer/foot.js', { encoding: 'utf8' })

var catchError = function(err) {

	console.log(err.toString())
	this.emit('end')

}

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

	gulp.src('./src/styles/main.scss')
	    .pipe(plugins.sass())
	    .on('error', catchError)
	    .pipe(plugins.concat(name + '.min.css', { newLine: "\n" }))
	    .pipe(plugins.autoprefixer('last 2 version', '> 1%'))
	    .pipe(plugins.minifyCss())
	    .pipe(gulp.dest('./dist'))

})

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

	gulp.src('./src/scripts/*.js')
	    .pipe(plugins.header(head, { name: name }))
	    .pipe(plugins.footer(foot))
	    .pipe(plugins.babel())
	    .on('error', catchError)
	    .pipe(plugins.concat(name + '.min.js', { newLine: "\n" }))
	    .pipe(plugins.uglify())
	    .on('error', catchError)
	    .pipe(gulp.dest('./dist'))

})

gulp.task('default', ['styles', 'scripts'])

gulp.task('watch', ['styles', 'scripts'], function() {

	gulp.watch('./src/styles/**/*.scss', ['styles'])
	gulp.watch('./src/scripts/**/*.js', ['scripts'])

})<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
  gulp = require('gulp'),
  gutil = require('gulp-util'),
  buffer = require('vinyl-buffer'),
  source = require('vinyl-source-stream'),
  watchify = require('watchify'),
  browserify = require('browserify'),
  sourcemaps = require('gulp-sourcemaps'),
  browserSync = require('browser-sync'),
  reload = browserSync.reload,
  jshint = require('gulp-jshint'),
  uglify = require('gulp-uglify'),
  ngAnnotate = require('gulp-ng-annotate'),
  sass = require('gulp-sass'),
  postcss = require('gulp-postcss'),
  autoprefixer = require('autoprefixer-core'),
  csswring = require('csswring'),
  svgSprite = require('gulp-svg-sprite'),
  replace = require('gulp-replace'),
  ghPages = require('gulp-gh-pages');

function browserifiedSrc(src) {
  var b = browserify(src);
  b.on('log', gutil.log);
  return b.bundle()
    .pipe(source(path.basename(src)))
    .pipe(buffer());
}

function watchifiedSrc(src, pipelineFn) {
  var b = watchify(browserify(src, {cache: {}, packageCache: {}, fullPaths: true, debug: true}));

  function doBundle() {
    return pipelineFn(
      b.bundle()
        .pipe(source(path.basename(src)))
        .pipe(buffer())
    );
  }

  b.on('log', gutil.log);
  b.on('update', doBundle);

  return doBundle();
}

// do the work on svg assets, just need to be piped out
function doSvg() {
  return gulp.src([
    'node_modules/Ionicons/src/ios-search.svg',
    'node_modules/Ionicons/src/ios-close.svg',
    'node_modules/Ionicons/src/ios-close-empty.svg',
    'node_modules/Ionicons/src/ios-videocam.svg',
    'app/images/mt-plus-corner.svg',
    'app/images/mt-play-circle.svg',
    'app/images/mt-pause-circle.svg'
  ])
    .pipe(svgSprite({
      dest: 'build/images',
      svg: {
        dest: '.',
        xmlDeclaration: false,
        doctypeDeclaration: false
      },
      mode: {
        symbol: {
          dest: '.',
          sprite: 'sprite.svg'
        }
      }
    }));
}

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

gulp.task('svg:dev', function() {
  doSvg()
    .pipe(gulp.dest('build/images'));
});

gulp.task('css:dev', function() {
  return gulp.src('app/styles/css/main.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({
      errLogToConsole: true
    }))
    .pipe(postcss([
      autoprefixer({browsers: ['last 1 version']})
    ]))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('build/styles'))
    .pipe(reload({stream: true}));
});

gulp.task('js:dev', function() {
  // generates the bundle and watches changes
  return watchifiedSrc('./app/scripts/app.js', function(pipeline) {
    return pipeline
      .pipe(ngAnnotate())
      .pipe(gulp.dest('build/scripts'));
  });
});

gulp.task('serve', ['jshint', 'css:dev', 'js:dev', 'svg:dev'], function() {

  gulp.watch('app/scripts/**/*.js', ['jshint']);
  gulp.watch('app/styles/**/*.scss', ['css:dev']);

  browserSync({
    open: false,
    notify: false,
    server: ['build', 'app'],
    https: true
  });
});

gulp.task('copy:dist', function() {
  return gulp.src('app/index.html', {base: 'app'})
    .pipe(gulp.dest('dist'));
});

gulp.task('svg:dist', function() {
  doSvg()
    .pipe(gulp.dest('dist/images'));
});

gulp.task('css:dist', function() {
  return gulp.src('app/styles/css/main.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({
      errLogToConsole: true
    }))
    .pipe(postcss([
      autoprefixer({browsers: ['last 1 version']}),
      csswring
    ]))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('dist/styles'));
});

gulp.task('js:dist', function() {
  return browserifiedSrc('./app/scripts/app.js')
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('dist/scripts'));
});

gulp.task('dist', ['js:dist', 'css:dist', 'copy:dist', 'svg:dist']);

gulp.task('serve:dist', ['dist'], function() {
  browserSync({
    open: false,
    notify: false,
    server: 'dist',
    https: true
  });
});

gulp.task('dist:gh', ['js:dist', 'css:dist', 'copy:dist', 'svg:dist'], function() {
  return gulp.src('dist/index.html')
    .pipe(replace('<base href="/">', '<base href="/mixtube/">'))
    .pipe(gulp.dest('dist'));
});

gulp.task('deploy:gh', ['dist:gh'], function() {
  return gulp.src('dist/**/*')
    .pipe(ghPages());
});<commit_msg>fixed sourcemap in dev mode<commit_after>'use strict';

var path = require('path'),
  gulp = require('gulp'),
  gutil = require('gulp-util'),
  buffer = require('vinyl-buffer'),
  source = require('vinyl-source-stream'),
  watchify = require('watchify'),
  browserify = require('browserify'),
  sourcemaps = require('gulp-sourcemaps'),
  browserSync = require('browser-sync'),
  reload = browserSync.reload,
  jshint = require('gulp-jshint'),
  uglify = require('gulp-uglify'),
  ngAnnotate = require('gulp-ng-annotate'),
  sass = require('gulp-sass'),
  postcss = require('gulp-postcss'),
  autoprefixer = require('autoprefixer-core'),
  csswring = require('csswring'),
  svgSprite = require('gulp-svg-sprite'),
  replace = require('gulp-replace'),
  ghPages = require('gulp-gh-pages');

function browserifiedSrc(src) {
  var b = browserify(src);
  b.on('log', gutil.log);
  return b.bundle()
    .pipe(source(path.basename(src)))
    .pipe(buffer());
}

function watchifiedSrc(src, pipelineFn) {
  var b = watchify(browserify(src, {cache: {}, packageCache: {}, fullPaths: true, debug: true}));

  function doBundle() {
    return pipelineFn(
      b.bundle()
        .pipe(source(path.basename(src)))
        .pipe(buffer())
    );
  }

  b.on('log', gutil.log);
  b.on('update', doBundle);

  return doBundle();
}

// do the work on svg assets, just need to be piped out
function doSvg() {
  return gulp.src([
    'node_modules/Ionicons/src/ios-search.svg',
    'node_modules/Ionicons/src/ios-close.svg',
    'node_modules/Ionicons/src/ios-close-empty.svg',
    'node_modules/Ionicons/src/ios-videocam.svg',
    'app/images/mt-plus-corner.svg',
    'app/images/mt-play-circle.svg',
    'app/images/mt-pause-circle.svg'
  ])
    .pipe(svgSprite({
      dest: 'build/images',
      svg: {
        dest: '.',
        xmlDeclaration: false,
        doctypeDeclaration: false
      },
      mode: {
        symbol: {
          dest: '.',
          sprite: 'sprite.svg'
        }
      }
    }));
}

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

gulp.task('svg:dev', function() {
  doSvg()
    .pipe(gulp.dest('build/images'));
});

gulp.task('css:dev', function() {
  return gulp.src('app/styles/css/main.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({
      errLogToConsole: true
    }))
    .pipe(postcss([
      autoprefixer({browsers: ['last 1 version']})
    ]))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('build/styles'))
    .pipe(reload({stream: true}));
});

gulp.task('js:dev', function() {
  // generates the bundle and watches changes
  return watchifiedSrc('./app/scripts/app.js', function(pipeline) {
    return pipeline
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(ngAnnotate())
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('build/scripts'));
  });
});

gulp.task('serve', ['jshint', 'css:dev', 'js:dev', 'svg:dev'], function() {

  gulp.watch('app/scripts/**/*.js', ['jshint']);
  gulp.watch('app/styles/**/*.scss', ['css:dev']);

  browserSync({
    open: false,
    notify: false,
    server: ['build', 'app'],
    https: true
  });
});

gulp.task('copy:dist', function() {
  return gulp.src('app/index.html', {base: 'app'})
    .pipe(gulp.dest('dist'));
});

gulp.task('svg:dist', function() {
  doSvg()
    .pipe(gulp.dest('dist/images'));
});

gulp.task('css:dist', function() {
  return gulp.src('app/styles/css/main.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({
      errLogToConsole: true
    }))
    .pipe(postcss([
      autoprefixer({browsers: ['last 1 version']}),
      csswring
    ]))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('dist/styles'));
});

gulp.task('js:dist', function() {
  return browserifiedSrc('./app/scripts/app.js')
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('dist/scripts'));
});

gulp.task('dist', ['js:dist', 'css:dist', 'copy:dist', 'svg:dist']);

gulp.task('serve:dist', ['dist'], function() {
  browserSync({
    open: false,
    notify: false,
    server: 'dist',
    https: true
  });
});

gulp.task('dist:gh', ['js:dist', 'css:dist', 'copy:dist', 'svg:dist'], function() {
  return gulp.src('dist/index.html')
    .pipe(replace('<base href="/">', '<base href="/mixtube/">'))
    .pipe(gulp.dest('dist'));
});

gulp.task('deploy:gh', ['dist:gh'], function() {
  return gulp.src('dist/**/*')
    .pipe(ghPages());
});<|endoftext|>


<commit_before>var gulp = require("gulp"),
    sass = require("gulp-sass"),
    htmlmin = require("gulp-htmlmin"),
    watch = require("gulp-watch"),
    uglify = require("gulp-uglify"),
    concat = require("gulp-concat"),
    bower = require("gulp-bower"),
    minifyCss = require("gulp-minify-css"),
    sourcemaps = require("gulp-sourcemaps"),
    uncss = require("gulp-uncss"),
    rename = require("gulp-rename");

var paths = {
  unCSS: {
    ignore: [],
    src: {
      html: "./src/*.html",
      css: "./www/css/style.css"
    },
    dest: "./www/css/"
  },
  moveAssets: {
    src: "./assets/**/*",
    dest: "www"
  },
  sassToCSS: {
    src: "./src/scss/style.scss",
    dest: "./www/css"
  },
  minifyCSS: {
    src: "./www/css/style.css",
    new: "script.min.css"
  },
  concatJS: {
    concat: "script.js"
  },
  uglifyJS: {
    src: "./www/js/script.js",
    new: "script.min.js"
  },
  bower: {
    dest: "src/lib"
  },
  html: {
    src: "./src/*.html",
    dest: "www"
  },
  scss: {
    src: "./src/scss/style.scss",
    dest: "./www/css",
    watch: [
      "./src/scss/*.scss",
      "./src/scss/_*.scss"
    ]
  },
  js: {
    src: [
      "./src/lib/jquery/dist/jquery.js",
      "./src/js/**/*.js"
    ],
    dest: "./www/js/"
  }
};

// move contents of assets folder to www
gulp.task("moveAssets", function(){
  return gulp.src(paths.moveAssets.src)
    .pipe(gulp.dest(paths.moveAssets.dest));
});

// move html to www folder (not minified)
gulp.task("moveHTML", function(){
  return gulp.src(paths.html.src)
    .pipe(gulp.dest(paths.html.dest));
});

// put bower components in lib folder
gulp.task("bower", function() {
  return bower()
    .pipe(gulp.dest(paths.bower.dest));
});

// minify html
gulp.task("minifyHTML", function() {
  return gulp.src(paths.html.src)
    .pipe(htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest(paths.html.dest));
});

// sass => css
gulp.task("sassToCSS", function() {
  return gulp.src(paths.sassToCSS.src)
    .pipe(sourcemaps.init())
    .pipe(sass().on("error", sass.logError))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.sassToCSS.dest));
});

// removed unused css rules
gulp.task("unCSS", ["sassToCSS"], function() {
  return gulp.src(paths.unCSS.src.css)
    .pipe(uncss({html:paths.unCSS.src.html,ignore:paths.unCSS.ignore}))
    .pipe(gulp.dest(paths.scss.dest));
});

// minify css
gulp.task("minifyCSS", ["sassToCSS", "unCSS"], function() {
  return gulp.src(paths.minifyCSS.src)
    .pipe(minifyCss())
    .pipe(rename(paths.minifyCSS.new))
    .pipe(gulp.dest(paths.scss.dest));
});

// concat javascript
gulp.task("concatJS", function() {
  return gulp.src(paths.js.src)
    .pipe(sourcemaps.init())
    .pipe(concat(paths.concatJS.concat))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.js.dest));
});

// uglify javascript and rename
gulp.task("uglifyJS", ["concatJS"], function() {
  return gulp.src(paths.uglifyJS.src)
    .pipe(uglify())
    .pipe(rename(paths.uglifyJS.new))
    .pipe(gulp.dest(paths.js.dest));
});

// watch for changes
gulp.task("watch", function() {
  gulp.watch(paths.moveAssets.src, ["moveAssets"]);
  gulp.watch(paths.html.src, ["minifyHTML"]);
  gulp.watch(paths.scss.watch, ["minifyCSS"]);
  gulp.watch(paths.js.src, ["concatJS"]);
});

// The default task (called when you run `gulp` from cli)
gulp.task("build", ["moveAssets", "bower", "minifyHTML", "sassToCSS", "unCSS", "minifyCSS", "concatJS", "uglifyJS"]); /*compresses html, css, js*/
gulp.task("default", ["moveAssets", "bower", "moveHTML", "sassToCSS", "unCSS", "concatJS", "watch"]);
<commit_msg>update gulpfile.js<commit_after>var gulp = require("gulp"),
    sass = require("gulp-sass"),
    htmlmin = require("gulp-htmlmin"),
    watch = require("gulp-watch"),
    uglify = require("gulp-uglify"),
    concat = require("gulp-concat"),
    bower = require("gulp-bower"),
    minifyCss = require("gulp-minify-css"),
    uncss = require("gulp-uncss"),
    rename = require("gulp-rename");

var paths = {
  moveAssets: {
    src: "./assets/**/*",
    dest: "www"
  },
  sassToCSS: {
    src: "./src/scss/style.scss",
    dest: "./www/css"
  },
  // don't include './' in front in unCSSTask
  unCSSTask: {
    src: "www/css/style.css",
    html: "src/*.html",
    dest: "www/css"
  },
  minifyCSS: {
    src: "./www/css/style.css",
    newName: "style.min.css",
    dest: "./www/css"
  },
  concatJS: {
    concat: "script.js"
  },
  uglifyJS: {
    src: "./www/js/script.js",
    newName: "script.min.js"
  },
  bower: {
    dest: "src/lib"
  },
  html: {
    src: "./src/*.html",
    dest: "www"
  },
  scss: {
    src: "./src/scss/style.scss",
    dest: "./www/css",
    watch: [
      "./src/scss/*.scss",
      "./src/scss/_*.scss"
    ]
  },
  js: {
    src: [],
    dest: "./www/js/"
  }
};

// move contents of assets folder to www
gulp.task("moveAssets", function(){
  return gulp.src(paths.moveAssets.src)
    .pipe(gulp.dest(paths.moveAssets.dest));
});

// move html to www folder (not minified)
gulp.task("moveHTML", function(){
  return gulp.src(paths.html.src)
    .pipe(gulp.dest(paths.html.dest));
});

// put bower components in lib folder
gulp.task("bower", function() {
  return bower()
    .pipe(gulp.dest(paths.bower.dest));
});

// minifies html
gulp.task("minifyHTML", function() {
  return gulp.src(paths.html.src)
    .pipe(htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest(paths.html.dest));
});

// compiles sass to css
gulp.task("sassToCSS", function() {
  return gulp.src(paths.sassToCSS.src)
    .pipe(sass().on("error", sass.logError))
    .pipe(gulp.dest(paths.sassToCSS.dest));
});

// removes unused css rules
gulp.task("unCSS", ["sassToCSS"], function() {
  return gulp.src(paths.unCSSTask.src)
    .pipe(uncss({
      html: paths.unCSSTask.html
    }))
    .pipe(gulp.dest(paths.unCSSTask));
});

// minifies css
gulp.task("minifyCSS", function() {
  return gulp.src(paths.minifyCSS.src)
    .pipe(minifyCss())
    .pipe(rename(paths.minifyCss.newName))
    .pipe(gulp.dest(paths.minifyCss.dest));
});

// concat javascript
gulp.task("concatJS", function() {
  return gulp.src(paths.js.src)
    .pipe(concat(paths.concatJS.concat))
    .pipe(gulp.dest(paths.js.dest));
});

// uglify javascript and rename
gulp.task("uglifyJS", ["concatJS"], function() {
  return gulp.src(paths.uglifyJS.src)
    .pipe(uglify())
    .pipe(rename(paths.uglifyJS.newName))
    .pipe(gulp.dest(paths.js.dest));
});

// watch for changes
gulp.task("watch", function() {
  gulp.watch(paths.moveAssets.src, ["moveAssets"]);
  gulp.watch(paths.html.src, ["minifyHTML"]);
  gulp.watch(paths.scss.watch, ["sassToCSS"]);
  gulp.watch(paths.js.src, ["concatJS"]);
});

// The default task (called when you run `gulp` from cli)
gulp.task("build", ["moveAssets", "bower", "minifyHTML", "sassToCSS", "unCSS", "minifyCSS", "concatJS", "uglifyJS"]); /*compresses html, css, js*/
gulp.task("default", ["moveAssets", "bower", "moveHTML", "sassToCSS", "unCSS", "concatJS", "watch"]);
<|endoftext|>


<commit_before> /*
 * sublimetext-gulpfile.js
 * https://github.com/idleberg/sublimetext-gulpfile.js
 *
 * Copyright (c) 2014-2018 Jan T. Sott
 * Licensed under the MIT license.
 */

// Dependencies
const gulp = require('gulp'),
  debug = require('gulp-debug'),
  jsonLint = require('gulp-jsonlint');
  ymlVal = require('gulp-yaml-validate');
  xmlVal = require('gulp-xml-validator');

// Supported files
const jsonFiles = [
  '**/*.JSON-sublime-syntax',
  '**/*.JSON-tmLanguage',
  '**/*.JSON-tmTheme',
  '**/*.sublime-build',
  '**/*.sublime-commands',
  '**/*.sublime-completions',
  '**/*.sublime-keymap',
  '**/*.sublime-macro',
  '**/*.sublime-menu',
  '**/*.sublime-settings',
  '**/*.sublime-theme',
  'messages.json',
  '!node_modules/**/*'
];

const xmlFiles = [
  '**/*.plist',
  '**/*.PLIST-sublime-syntax',
  '**/*.PLIST-tmLanguage',
  '**/*.PLIST-tmTheme',
  '**/*.sublime-snippet',
  '**/*.tmCommand',
  '**/*.tmLanguage',
  '**/*.tmPreferences',
  '**/*.tmSnippet',
  '**/*.tmTheme',
  '**/*.xml',
  '!node_modules/**/*'
];

var ymlFiles = [
  '**/*.sublime-syntax',
  '**/*.YAML-tmLanguage',
  '**/*.YAML-tmTheme',
  '!node_modules/**/*'
];

// Lint JSON
gulp.task('lint:json', (done) => {
  gulp.src(jsonFiles)
    .pipe(debug({title: 'lint:json'}))
    .pipe(jsonLint())
    .pipe(jsonLint.failAfterError())
    .pipe(jsonLint.reporter());

  done();
});

// Validate XML
gulp.task('lint:xml', (done) => {
  gulp.src(xmlFiles)
    .pipe(debug({title: 'lint:xml'}))
    .pipe(xmlVal());

  done();
});

// Validate YAML
gulp.task('lint:yml', (done) => {
  gulp.src(ymlFiles)
    .pipe(debug({title: 'lint:yml'}))
    .pipe(ymlVal({ safe: true }));

  done();
});

// Available tasks
gulp.task('lint', gulp.parallel('lint:json', 'lint:xml', 'lint:yml', (done) => {
  done();
}));
<commit_msg>delete gulpfile<commit_after><|endoftext|>


<commit_before>import Vue from 'vue';
import VueRouter from 'vue-router';
import VueForm from 'vue-form';
import { sync } from 'vuex-router-sync';

import store from './vuex/store.js';
import * as actions from './vuex/actions.js';

import App from './app.vue';
import FeatureList from './components/featurelist.vue';
import FeatureForm from './components/featureform.vue';

Vue.use(VueRouter);
Vue.use(VueForm);

let router = new VueRouter({
    linkActiveClass: 'active'
});

/* sync route info to store */
sync(store, router);

router.map({
    '/list': {
        name: 'home'
    },
    '/list/:page': {
        component: FeatureList,
        name: 'list-all'
    },
    '/new': {
        component: FeatureForm,
        name: 'new-feature'
    }
});

/* Bootstrap the application */
router.start({
    template: '
<app></app>
',
    store,
    components: { App },
    vuex: {
        actions
    },
    compiled() {
        this.fetchFeatures();
        this.fetchClients();
        this.fetchProductAreas();
    }
}, '#app');

router.redirect({
    '*': '/list/1'
});

router.alias({
    '/list': '/list/1'
});
<commit_msg>Set redirect and alias config before starting app<commit_after>import Vue from 'vue';
import VueRouter from 'vue-router';
import VueForm from 'vue-form';
import { sync } from 'vuex-router-sync';

import store from './vuex/store.js';
import * as actions from './vuex/actions.js';

import App from './app.vue';
import FeatureList from './components/featurelist.vue';
import FeatureForm from './components/featureform.vue';

Vue.use(VueRouter);
Vue.use(VueForm);

let router = new VueRouter({
    linkActiveClass: 'active'
});

/* sync route info to store */
sync(store, router);

router.map({
    '/list': {
        name: 'home'
    },
    '/list/:page': {
        component: FeatureList,
        name: 'list-all'
    },
    '/new': {
        component: FeatureForm,
        name: 'new-feature'
    }
});

router.redirect({
    '*': '/list/1'
});

router.alias({
    '/list': '/list/1'
});

/* Bootstrap the application */
router.start({
    template: '
<app></app>
',
    store,
    components: { App },
    vuex: {
        actions
    },
    compiled() {
        this.fetchFeatures();
        this.fetchClients();
        this.fetchProductAreas();
    }
}, '#app');
<|endoftext|>


<commit_before>/**
 * Main JS file for Casper behaviours
 */

/*globals jQuery, document */
(function ($) {
    "use strict";

    $(document).ready(function(){

        $(".post-content").fitVids();

        function casperFullImg() {
            $("img").each( function() {
                var contentWidth = $(".post-content").outerWidth(); // Width of the content
                var imageWidth = $(this)[0].naturalWidth; // Original image resolution

                if (imageWidth >= contentWidth) {
                    $(this).addClass('full-img');
                } else {
                    $(this).removeClass('full-img');
                }
            });
        };

        casperFullImg();
        $(window).smartresize(casperFullImg);

        // Setup post images
        $(".post-preview").find(".post-image").each(function() {
          if($(this).find("img").length != 0){
            var postImage = $(this).find("img").attr("src");
            $(this).html("");
            $(this).css("background-image","url('"+postImage+"')")
          } else {
            $(this).remove();
          }
        });

        // single post header image
        if($(".single-post .post-content p:first img").length != 0){
            var postImage = $(".single-post .post-content p:first img").attr("src");
            $(".single-post .post-content p:first").remove();
            $(".post-image").css("background-image","url('"+postImage+"')");
        } else {
          $(".single-post .post-image").remove();
        }

    });

}(jQuery));

(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
  // smartresize
  jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');<commit_msg>Removed unneeded JS<commit_after>/**
 * Main JS file for Casper behaviours
 */

/*globals jQuery, document */
(function ($) {
    "use strict";

    $(document).ready(function(){

        $(".post-content").fitVids();

        function casperFullImg() {
            $("img").each( function() {
                var contentWidth = $(".post-content").outerWidth(); // Width of the content
                var imageWidth = $(this)[0].naturalWidth; // Original image resolution

                if (imageWidth >= contentWidth) {
                    $(this).addClass('full-img');
                } else {
                    $(this).removeClass('full-img');
                }
            });
        };

        casperFullImg();
        $(window).smartresize(casperFullImg);

    });

}(jQuery));

(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
  // smartresize
  jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');<|endoftext|>


<commit_before>var fs = require("fs");
var url = require("url");
var ejs = require("ejs");
var utils = require("./utils.js");

var controllers = {};

exports.Handler = function () {
  var routes = {
    HEAD: {},
    GET: {},
    POST: {},
    PUT: {},
    PATCH: {},
    DELETE: {},
    OPTIONS: {}
  };

  if (fs.existsSync("app/routes.json")) {
    var rawRoutes = JSON.parse(fs.readFileSync("app/routes.json"));
    for (var i = 0; i < rawRoutes.length; i++) {
      if (utils.objValidate(rawRoutes[i], {required: ['type', 'url', 'to']})) {
        var action = rawRoutes[i].to;
        var actionSplat = action.split(".");
        var controller = actionSplat[0];
        var method = actionSplat[actionSplat.length - 1];
        var controllerFile = "./app/controllers/" + controller + ".js";

        if (controllers[controller]) {
          routes[rawRoutes[i].type][rawRoutes[i].url] = {
            method: controllers[controller][method],
            view: exports.getView(action)
          };
        }
        if (fs.existsSync(controllerFile)) {
          var loaded = require(controllerFile);
          controllers[controller] = loaded;
          routes[rawRoutes[i].type][rawRoutes[i].url] = {
            method: controllers[controller][method],
            view: exports.getView(action)
          };
        }
        else {
          console.log("WARNING: Route " + rawRoutes[i] + ": Controller doesn't exist - ignoring.");
        }
      }
      else {
        console.log("WARNING: Found route" + rawRoutes[i] + ": missing required key(s): type, url, to - ignoring.");
      }
    }
  }
  else {
    throw new ReferenceError("Tried to load the routing file, but it doesn't exist!");
  }

  this.routes = routes;

  this.getHandler = req => {
    var uri = url.parse(req.url, true);
    if (routes[req.method].hasOwnProperty(uri.pathname)) {
      return routes[req.method][uri.pathname].method;
    }
    return null;
  };
};

exports.getStaticContent = name => {
  if (fs.existsSync("app/static/" + name)) {
    return fs.readFileSync("app/static/" + name);
  }
  return null;
};

exports.getView = route => {
  var action = route.split(".");
  var controller = action[0];
  var method = action[action.length - 1];
  if (fs.existsSync("app/views/" + controller + "/" + method + ".ejs")) {
    return ejs.compile(fs.readFileSync("app/views/" + controller + "/" + method + ".ejs").toString());
  }
  return null;
};

exports.renderer = (req, res, opts) => {
  if (!utils.objValidate(opts, {required: ['routes']})) {
    res.writeHead(500, 'Internal Server Error');
    res.end();
    console.error("ERROR: handlers.renderer: expected opts.routes, got " + opts['routes']);
    return;
  }

  if (opts.text) {
    opts.content = opts.text;
    delete opts['text'];
    exports.renderer(req, res, Object.assign(opts, {headers: {'content-type': 'text/plain'}}));
    return;
  }
  else if (opts.json) {
    opts.content = JSON.stringify(opts.json);
    delete opts['json'];
    exports.renderer(req, res, Object.assign(opts, {headers: {'content-type': 'application/json'}}));
    return;
  }

  opts.headers = opts.headers || {'content-type': 'text/html'};
  var headerNames = Object.keys(opts.headers);
  for (var i = 0; i < headerNames.length; i++) {
    res.setHeader(headerNames[i], opts.headers[headerNames[i]]);
  }

  opts.status = opts.status || 200;
  res.statusCode = opts.status;

  if (opts.view) {
    var view = opts.routes[req.method][url.parse(req.url, true).pathname].view;
    if (view) {
      opts.locals = opts.locals || {};
      res.write(view(opts.locals));
      res.end();
    }
    else {
      console.log("WARNING: handlers.renderer: render specified view: true, but no view present.");
      res.statusCode = 204;
      res.end();
    }
  }
  else if (opts.content) {
    res.write(opts.content);
    res.end();
  }
  else {
    res.statusCode = 204;
    res.end();
  }
};
<commit_msg>Enable view inclusion<commit_after>var fs = require("fs");
var url = require("url");
var ejs = require("ejs");
var utils = require("./utils.js");

var controllers = {};

exports.Handler = function () {
  var routes = {
    HEAD: {},
    GET: {},
    POST: {},
    PUT: {},
    PATCH: {},
    DELETE: {},
    OPTIONS: {}
  };

  if (fs.existsSync("app/routes.json")) {
    var rawRoutes = JSON.parse(fs.readFileSync("app/routes.json"));
    for (var i = 0; i < rawRoutes.length; i++) {
      if (utils.objValidate(rawRoutes[i], {required: ['type', 'url', 'to']})) {
        var action = rawRoutes[i].to;
        var actionSplat = action.split(".");
        var controller = actionSplat[0];
        var method = actionSplat[actionSplat.length - 1];
        var controllerFile = "./app/controllers/" + controller + ".js";

        if (controllers[controller]) {
          routes[rawRoutes[i].type][rawRoutes[i].url] = {
            method: controllers[controller][method],
            view: exports.getView(action)
          };
        }
        if (fs.existsSync(controllerFile)) {
          var loaded = require(controllerFile);
          controllers[controller] = loaded;
          routes[rawRoutes[i].type][rawRoutes[i].url] = {
            method: controllers[controller][method],
            view: exports.getView(action)
          };
        }
        else {
          console.log("WARNING: Route " + rawRoutes[i] + ": Controller doesn't exist - ignoring.");
        }
      }
      else {
        console.log("WARNING: Found route" + rawRoutes[i] + ": missing required key(s): type, url, to - ignoring.");
      }
    }
  }
  else {
    throw new ReferenceError("Tried to load the routing file, but it doesn't exist!");
  }

  this.routes = routes;

  this.getHandler = req => {
    var uri = url.parse(req.url, true);
    if (routes[req.method].hasOwnProperty(uri.pathname)) {
      return routes[req.method][uri.pathname].method;
    }
    return null;
  };
};

exports.getStaticContent = name => {
  if (fs.existsSync("app/static/" + name)) {
    return fs.readFileSync("app/static/" + name);
  }
  return null;
};

exports.getView = route => {
  var action = route.split(".");
  var controller = action[0];
  var method = action[action.length - 1];
  if (fs.existsSync("app/views/" + controller + "/" + method + ".ejs")) {
    return ejs.compile(fs.readFileSync("app/views/" + controller + "/" + method + ".ejs").toString(), {
      filename: "app/views/" + controller + "/" + method + ".ejs"
    });
  }
  return null;
};

exports.renderer = (req, res, opts) => {
  if (!utils.objValidate(opts, {required: ['routes']})) {
    res.writeHead(500, 'Internal Server Error');
    res.end();
    console.error("ERROR: handlers.renderer: expected opts.routes, got " + opts['routes']);
    return;
  }

  if (opts.text) {
    opts.content = opts.text;
    delete opts['text'];
    exports.renderer(req, res, Object.assign(opts, {headers: {'content-type': 'text/plain'}}));
    return;
  }
  else if (opts.json) {
    opts.content = JSON.stringify(opts.json);
    delete opts['json'];
    exports.renderer(req, res, Object.assign(opts, {headers: {'content-type': 'application/json'}}));
    return;
  }

  opts.headers = opts.headers || {'content-type': 'text/html'};
  var headerNames = Object.keys(opts.headers);
  for (var i = 0; i < headerNames.length; i++) {
    res.setHeader(headerNames[i], opts.headers[headerNames[i]]);
  }

  opts.status = opts.status || 200;
  res.statusCode = opts.status;

  if (opts.view) {
    var view = opts.routes[req.method][url.parse(req.url, true).pathname].view;
    if (view) {
      opts.locals = opts.locals || {};
      res.write(view(opts.locals));
      res.end();
    }
    else {
      console.log("WARNING: handlers.renderer: render specified view: true, but no view present.");
      res.statusCode = 204;
      res.end();
    }
  }
  else if (opts.content) {
    res.write(opts.content);
    res.end();
  }
  else {
    res.statusCode = 204;
    res.end();
  }
};
<|endoftext|>