<commit_before>/**
 * Module dependencies.
 */

var _ = require('lodash');
var sailsUtil = require('sails-util');

/**
 * @param  {SailsApp} sails  [Sails app]
 * @return {Function}
 */
module.exports = function to(sails) {

  /**
   * `interpretRouteSyntax()`
   *
   * "Teach" router to understand references to controllers.
   * This is the event handler for the 'route:typeUnknown' emitted on `sails`.
   *
   * @param  {Dictionary} route
   *         @property {String} verb
   *         @property {String} path
   *         @property {Dictionary} target
   *         @property {Dictionary} options
   *
   * @api private
   */
  return function interpretRouteSyntax (route) {
    var target = route.target;
    var path = route.path;
    var verb = route.verb;
    var options = route.options;

    // Support various dictionary target notations, e.g.:
    // `{ controller: 'UserController' }`
    if (_.isObject(target) && !_.isFunction(target) && !_.isArray(target)) {

      // Merge target into `options` to get hold of relevant route options:
      options = _.merge(options, target);
      // Note: this (^) could be moved up into lib/router/bind.js, since its
      // only pertinent for core options such as `skipAssets`.  There would need
      // to be changes in other hooks as well.

      // Support { controller: 'FooController' } notation (with or without `action`)
      if ( !_.isUndefined(target.controller) ) {
        return bindController(path, target, verb, options);
      }

      // Support resourceful sub-mappings for verbless routes
      // e.g. '/someRoute': { post: 'FooController.bar', get: '...', /* ... */ }
      // If verb was manually specified in route address (e.g. `get /someRoute`), ignore the sub-mappings.
      //
      ////////////////////////////////////////////////////////////////////////////////////
      // Support for this routing syntax will be deprecated in Sails v1.0.
      ////////////////////////////////////////////////////////////////////////////////////
      if ( !options.detectedVerb ) {
        if ( target.get ) { sails.router.bind (path, target['get'],'get', options); }
        if ( target.post ) { sails.router.bind (path, target['post'],'post', options); }
        if ( target.put ) { sails.router.bind (path, target['put'],'put', options); }
        if ( target['delete'] ) { sails.router.bind (path, target['delete'],'delete', options); }
        // If there is a legitimate use case for it, add other HTTP verbs here for completeness.
      }

      // Lone action syntax, e.g.:
      // '/someRoute': { action: 'find', model: 'foo' }
      //
      // (useful for explicitly routing a URL to a blueprint action)
      //
      ////////////////////////////////////////////////////////////////////////////////////
      // Support for this routing syntax will be deprecated in Sails v1.0.
      ////////////////////////////////////////////////////////////////////////////////////
      else if ( !_.isUndefined(target.action) ) {

        // Merge target def. into route options:
        options.action = target.action;

        return bindBlueprintAction(path, target.action, verb, options);
      }
    }

    // Support string ('FooController.bar') notation
    else if (_.isString(target)) {

      // Handle dot notation
      var parsedTarget = target.match(/^([^.]+)\.?([^.]*)?$/);

      // If target matches a controller (or, if views hook enabled, a view)
      // go ahead and assume that this is a dot notation route
      var controllerId = sailsUtil.normalizeControllerId(parsedTarget[1]);
      var actionId = _.isString(parsedTarget[2]) ? parsedTarget[2].toLowerCase() : 'index';

      // If this is a known controller, bind it
      if ( controllerId && (
        sails.middleware.controllers[controllerId] ||
        (sails.config.hooks.views.blueprints && sails.middleware.views[controllerId])
        )
      ) {
        return bindController (path, {
          controller: controllerId,
          action: actionId
        }, verb, options);
      }
    }

    // Ignore unknown route syntax
    // If it needs to be understood by another hook, the hook would have also received
    // the typeUnknown event, so we're done.
    return;
  };

  /**
   * Bind route to a controller/action.
   *
   * @param  {[type]} path   [description]
   * @param  {[type]} target [description]
   * @param  {[type]} verb   [description]
   * @param  {[type]} options[description]
   * @return {[type]}        [description]
   * @api private
   */
  function bindController ( path, target, verb, options ) {

    // Normalize controller and action ids
    var controllerId = sailsUtil.normalizeControllerId(target.controller);
    var actionId = _.isString(target.action) ? target.action.toLowerCase() : null;

    // Look up appropriate controller/action and make sure it exists
    var controller = sails.middleware.controllers[controllerId];

    // Fall back to matching view
    if (!controller) {
      controller = sails.middleware.views[controllerId];
    }

    // If a controller and/or action was specified,
    // but it's not a match, warn the user
    if ( ! ( controller && _.isObject(controller) )) {
      sails.after('lifted', function () {
        sails.log.error(
          'Ignored attempt to bind route (' + path + ') to unknown controller ::',
          controllerId+'.'
        );
      });
      return;
    }
    if ( actionId && !controller[actionId] ) {
      sails.after('lifted', function () {
        sails.log.error(
          'Ignored attempt to bind route (' + path + ') to unknown controller.action ::',
          controllerId + '.' + (actionId || 'index')
        );
      });
      return;
    }

    // (if unspecified, default actionId to 'index'
    actionId = actionId || 'index';

    // Merge the target controller/action into our route options:
    options.controller = controllerId;
    options.action = actionId;

    // Determine the model connected to this controller either by:
    // -> on the routes config
    // -> on the controller
    //
    ////////////////////////////////////////////////////////////////////////////////////
    // Support for specifying `model` on the route target will be deprecated in Sails v1.0.
    // (instead you will be able to override the action directly)
    ////////////////////////////////////////////////////////////////////////////////////
    var modelId = options.model || controllerId;

    // If the orm hook is enabled, it has already been loaded by this time,
    // so just double-check to see if the attached model exists in `sails.models`.
    //
    ////////////////////////////////////////////////////////////////////////////////////
    // In Sails v1.0, this logic will be implemented by the blueprints hook rather than here.
    ////////////////////////////////////////////////////////////////////////////////////
    if (sails.hooks.orm && sails.models && sails.models[modelId]) {

      // If a model with matching identity exists,
      // extend route options with the id of the model.
      options.model = modelId;

      var Model = sails.models[modelId];

      // Mix in the known associations for this model to the route options.
      options = _.merge({ associations: _.cloneDeep(Model.associations) }, options);

      // Mix in the relevant blueprint config
      options = _.defaults(options, {
        populate: sails.config.blueprints.populate,
        defaultLimit: sails.config.blueprints.defaultLimit
      });

    }

    // Now bind the specified action-- our "subTarget"
    var subTarget = controller[actionId];
    //
    // But first, if this is not an array, then wrap it in one (non-destructive)
    if ( !_.isArray(subTarget) ) {
      subTarget = [ subTarget ];
    }
    //
    // Now we have an array of functions, so bind each one to the route address in order.
    _.each(subTarget, function bindEachMiddlewareInSubTarget (fn) {
      sails.router.bind(path, controllerHandler(fn), verb, options);
    });

    // Wrap up the controller middleware to supply access to
    // the original target when requests comes in
    function controllerHandler (originalFn) {

      if ( !_.isFunction(originalFn) ) {
        sails.after('lifted', function () {
          sails.log.error(
            'In '+controllerId + '.' + actionId+', ignored invalid attempt to bind route to a non-function controller:',
            originalFn, 'for path: ', path, verb ? ('and verb: ' + verb) : '');
        });
        return;
      }

      // Bind intercepted middleware function to route
      return originalFn;
    }

    return;
  }

  /**
   * Bind specified blueprint action to the specified route.
   *
   * @param  {[type]} path              [description]
   * @param  {[type]} blueprintActionID [description]
   * @param  {[type]} verb              [description]
   * @param  {[type]} options           [description]
   * @return {[type]}                   [description]
   */
  function bindBlueprintAction (path, blueprintActionID, verb, options){

    // Look up appropriate blueprint action and make sure it exists
    var blueprint = sails.middleware.blueprints[blueprintActionID];

    // If a 'blueprint' was specified, but it doesn't exist, warn the user and ignore it.
    if ( ! ( blueprint && _.isFunction(blueprint) )) {
      sails.after('lifted', function () {
        sails.log.error(
          'Ignored attempt to bind route (' + path + ') to unknown blueprint action (`'+blueprintActionID+'`).'
        );
      });
      return;
    }

    sails.router.bind(path, blueprint, verb, options);
  }

};

<commit_msg>Remove support for action/model syntax for routes<commit_after>/**
 * Module dependencies.
 */

var _ = require('lodash');
var sailsUtil = require('sails-util');

/**
 * @param  {SailsApp} sails  [Sails app]
 * @return {Function}
 */
module.exports = function to(sails) {

  /**
   * `interpretRouteSyntax()`
   *
   * "Teach" router to understand references to controllers.
   * This is the event handler for the 'route:typeUnknown' emitted on `sails`.
   *
   * @param  {Dictionary} route
   *         @property {String} verb
   *         @property {String} path
   *         @property {Dictionary} target
   *         @property {Dictionary} options
   *
   * @api private
   */
  return function interpretRouteSyntax (route) {
    var target = route.target;
    var path = route.path;
    var verb = route.verb;
    var options = route.options;

    // Support various dictionary target notations, e.g.:
    // `{ controller: 'UserController' }`
    if (_.isObject(target) && !_.isFunction(target) && !_.isArray(target)) {

      // Merge target into `options` to get hold of relevant route options:
      options = _.merge(options, target);
      // Note: this (^) could be moved up into lib/router/bind.js, since its
      // only pertinent for core options such as `skipAssets`.  There would need
      // to be changes in other hooks as well.

      // Support { controller: 'FooController' } notation (with or without `action`)
      if ( !_.isUndefined(target.controller) ) {
        return bindController(path, target, verb, options);
      }

      // Support resourceful sub-mappings for verbless routes
      // e.g. '/someRoute': { post: 'FooController.bar', get: '...', /* ... */ }
      // If verb was manually specified in route address (e.g. `get /someRoute`), ignore the sub-mappings.
      //
      ////////////////////////////////////////////////////////////////////////////////////
      // Support for this routing syntax will be deprecated in Sails v1.0.
      ////////////////////////////////////////////////////////////////////////////////////
      if ( !options.detectedVerb ) {
        if ( target.get ) { sails.router.bind (path, target['get'],'get', options); }
        if ( target.post ) { sails.router.bind (path, target['post'],'post', options); }
        if ( target.put ) { sails.router.bind (path, target['put'],'put', options); }
        if ( target['delete'] ) { sails.router.bind (path, target['delete'],'delete', options); }
        // If there is a legitimate use case for it, add other HTTP verbs here for completeness.
      }

    }

    // Support string ('FooController.bar') notation
    else if (_.isString(target)) {

      // Handle dot notation
      var parsedTarget = target.match(/^([^.]+)\.?([^.]*)?$/);

      // If target matches a controller (or, if views hook enabled, a view)
      // go ahead and assume that this is a dot notation route
      var controllerId = sailsUtil.normalizeControllerId(parsedTarget[1]);
      var actionId = _.isString(parsedTarget[2]) ? parsedTarget[2].toLowerCase() : 'index';

      // If this is a known controller, bind it
      if ( controllerId && (
        sails.middleware.controllers[controllerId] ||
        (sails.config.hooks.views.blueprints && sails.middleware.views[controllerId])
        )
      ) {
        return bindController (path, {
          controller: controllerId,
          action: actionId
        }, verb, options);
      }
    }

    // Ignore unknown route syntax
    // If it needs to be understood by another hook, the hook would have also received
    // the typeUnknown event, so we're done.
    return;
  };

  /**
   * Bind route to a controller/action.
   *
   * @param  {[type]} path   [description]
   * @param  {[type]} target [description]
   * @param  {[type]} verb   [description]
   * @param  {[type]} options[description]
   * @return {[type]}        [description]
   * @api private
   */
  function bindController ( path, target, verb, options ) {

    // Normalize controller and action ids
    var controllerId = sailsUtil.normalizeControllerId(target.controller);
    var actionId = _.isString(target.action) ? target.action.toLowerCase() : null;

    // Look up appropriate controller/action and make sure it exists
    var controller = sails.middleware.controllers[controllerId];

    // Fall back to matching view
    if (!controller) {
      controller = sails.middleware.views[controllerId];
    }

    // If a controller and/or action was specified,
    // but it's not a match, warn the user
    if ( ! ( controller && _.isObject(controller) )) {
      sails.after('lifted', function () {
        sails.log.error(
          'Ignored attempt to bind route (' + path + ') to unknown controller ::',
          controllerId+'.'
        );
      });
      return;
    }
    if ( actionId && !controller[actionId] ) {
      sails.after('lifted', function () {
        sails.log.error(
          'Ignored attempt to bind route (' + path + ') to unknown controller.action ::',
          controllerId + '.' + (actionId || 'index')
        );
      });
      return;
    }

    // (if unspecified, default actionId to 'index'
    actionId = actionId || 'index';

    // Merge the target controller/action into our route options:
    options.controller = controllerId;
    options.action = actionId;

    // Determine the model connected to this controller either by:
    // -> on the routes config
    // -> on the controller
    //
    ////////////////////////////////////////////////////////////////////////////////////
    // Support for specifying `model` on the route target will be deprecated in Sails v1.0.
    // (instead you will be able to override the action directly)
    ////////////////////////////////////////////////////////////////////////////////////
    var modelId = options.model || controllerId;

    // If the orm hook is enabled, it has already been loaded by this time,
    // so just double-check to see if the attached model exists in `sails.models`.
    //
    ////////////////////////////////////////////////////////////////////////////////////
    // In Sails v1.0, this logic will be implemented by the blueprints hook rather than here.
    ////////////////////////////////////////////////////////////////////////////////////
    if (sails.hooks.orm && sails.models && sails.models[modelId]) {

      // If a model with matching identity exists,
      // extend route options with the id of the model.
      options.model = modelId;

      var Model = sails.models[modelId];

      // Mix in the known associations for this model to the route options.
      options = _.merge({ associations: _.cloneDeep(Model.associations) }, options);

      // Mix in the relevant blueprint config
      options = _.defaults(options, {
        populate: sails.config.blueprints.populate,
        defaultLimit: sails.config.blueprints.defaultLimit
      });

    }

    // Now bind the specified action-- our "subTarget"
    var subTarget = controller[actionId];
    //
    // But first, if this is not an array, then wrap it in one (non-destructive)
    if ( !_.isArray(subTarget) ) {
      subTarget = [ subTarget ];
    }
    //
    // Now we have an array of functions, so bind each one to the route address in order.
    _.each(subTarget, function bindEachMiddlewareInSubTarget (fn) {
      sails.router.bind(path, controllerHandler(fn), verb, options);
    });

    // Wrap up the controller middleware to supply access to
    // the original target when requests comes in
    function controllerHandler (originalFn) {

      if ( !_.isFunction(originalFn) ) {
        sails.after('lifted', function () {
          sails.log.error(
            'In '+controllerId + '.' + actionId+', ignored invalid attempt to bind route to a non-function controller:',
            originalFn, 'for path: ', path, verb ? ('and verb: ' + verb) : '');
        });
        return;
      }

      // Bind intercepted middleware function to route
      return originalFn;
    }

    return;
  }

  /**
   * Bind specified blueprint action to the specified route.
   *
   * @param  {[type]} path              [description]
   * @param  {[type]} blueprintActionID [description]
   * @param  {[type]} verb              [description]
   * @param  {[type]} options           [description]
   * @return {[type]}                   [description]
   */
  function bindBlueprintAction (path, blueprintActionID, verb, options){

    // Look up appropriate blueprint action and make sure it exists
    var blueprint = sails.middleware.blueprints[blueprintActionID];

    // If a 'blueprint' was specified, but it doesn't exist, warn the user and ignore it.
    if ( ! ( blueprint && _.isFunction(blueprint) )) {
      sails.after('lifted', function () {
        sails.log.error(
          'Ignored attempt to bind route (' + path + ') to unknown blueprint action (`'+blueprintActionID+'`).'
        );
      });
      return;
    }

    sails.router.bind(path, blueprint, verb, options);
  }

};

<|endoftext|>


<commit_before>var gulp            = require('gulp'),
    // Sass for writing and pre-processing CSS
    sass            = require('gulp-sass'),
    // Nano for optimising and post-processing CSS
    nano            = require('gulp-cssnano'),
    // Join JS file into a single file
    concat          = require('gulp-concat'),
    // Minify that single JS file
    uglify          = require('gulp-uglify'),
    // Minify and clean up HTML files
    htmlmin         = require('gulp-htmlmin'),
    // Data storage for Twig templates
    data            = require('gulp-data'),
    // Templating
    twig            = require('gulp-twig'),
    // Report file sizes in the CLI
    size            = require('gulp-size'),
    // Stops stream from ending on error
    plumber         = require('gulp-plumber'),
    // Send noficitations to the system and CLI
    notify          = require('gulp-notify'),
    // Sync changes to the Browser
    browserSync     = require('browser-sync')
    reload          = browserSync.reload;

///
/// Setup an error notification for gulp-plumber to handle
///
var hasError = notify.onError({
  title: 'Error',
  message: '<%= error.message %>',
  sound: "Basso"
});

gulp.task('sync', function() {
  browserSync({
    startPath: '/demo/',
    open: 'external',
    host: 'basekit.dev',
    proxy: 'basekit.dev',
    reloadDelay: 0,
    notify: false,
    scrollRestoreTechnique: "cookie",
    logLevel: "silent",
  });
});

///
/// Compile Sass (with Nano and Autoprefixer)
///
gulp.task('scss', function() {
  gulp.src('css/basekit.scss')
    .pipe(plumber({errorHandler: hasError}))
    .pipe(sass().on('error', sass.logError))
    .pipe(nano({
      // http://cssnano.co/optimisations/minifySelectors/
      // This was interfering with the global selector so I've disabled it
      minifySelectors: false,
      // Enable adding prefixes
      autoprefixer: {
        add: true,
        // Browser support level
        // Must be over 0.5% usage, going back 2 versions, but IE is from 9 to 11
        browsers: [ '> 0.5%', 'last 2 versions', 'ie >= 9' ]
      }
    }))
    //
    .pipe(gulp.dest('css'))
    // Reload and inject
    .pipe(reload({ stream: true }))
    // Show file size before gzip
    .pipe(size({ showFiles: true }))
    // Show file size after gzip
    .pipe(size({ gzip: true, showFiles: true }));
});

///
/// Minify and combine javascript files for production, unless they start with an _
/// gulp.src('js/[^_]*.js')
///
gulp.task('js', function() {
  gulp.src('js/*.js')
    .pipe(plumber({errorHandler: hasError}))
    // Combine all (none _) js files into this file
    .pipe(concat('basekit.js'))
    // Minify the file
    .pipe(uglify())
    // Output it here
    .pipe(gulp.dest('js/min'))
    // Report the gzipped file size
    .pipe(size({
      gzip: true,
      showFiles: true
    })
  );
});

///
/// Minify, clean and output HTML files
/// NOTE: I'm likely to deprecate this soon in favour of using Twig
///
// gulp.task('html', function() {
//   gulp.src('./html/*.html')
//     .pipe(plumber({errorHandler: hasError}))
//     .pipe(htmlmin({
//       collapseWhitespace: true,
//       removeComments: true,
//       removeAttributeQuotes: true,
//       // removeRedundantAttributes: true,
//       removeEmptyAttributes: true,
//       removeScriptTypeAttributes: true,
//       removeStyleLinkTypeAttributes: true,
//       collapseBooleanAttributes: true,
//       quoteCharacter: '\'',
//       minifyJS: true,
//       minifyCSS: true
//     }))
//     .pipe(gulp.dest('./'))
//     .pipe(notify({
//       title: 'Created',
//       message: '<%= file.relative %>'
//     }));
// });

///
/// Compile Twig templates to an HTML frontend
/// NOTE: At the time of writing March 2017 we use Craft CMS. Writing frontend templates in Twig makes sense since Craft uses twig, these files are also output as HTML for demonstration and testing.
///
gulp.task('twig', function() {
  // De-caching so that the data.json file can be watched correctly
  // See this https://github.com/colynb/gulp-data/issues/17
  function requireUncached( $module ) {
    delete require.cache[require.resolve( $module )];
    return require( $module );
  }

  // run the Twig template parser on .twig files that don't start with an _
  return gulp.src('./templates/**/[^_]*.twig')
  .pipe(plumber({errorHandler: hasError}))
  // Uncached data for populating Twig files
  .pipe( data(function(file){ return requireUncached('./templates/data.json'); }))
  // Let gulp-twig know where the base template directory is
  .pipe(twig({ base: 'templates' }))
  // Minify the files for development use
  .pipe(htmlmin({
    collapseWhitespace: true,
    removeComments: true,
    removeAttributeQuotes: true,
    removeEmptyAttributes: true,
    removeScriptTypeAttributes: true,
    removeStyleLinkTypeAttributes: true,
    collapseBooleanAttributes: true,
    quoteCharacter: '\'',
    minifyJS: true,
    minifyCSS: true
  }))
  // Return default behaviour
  .pipe(plumber.stop())
  // Output minified file
  .pipe(gulp.dest('demo'))
});

// Combine various functions into watch
gulp.task('watch', function() {
  gulp.watch('css/**/*.scss', { interval: 500 }, ['scss']);
  gulp.watch('js/*.js', ['js']);
  gulp.watch(['templates/**/*.twig', 'templates/**/*.json'], { interval: 500 }, ['twig']);
  gulp.watch('demo/**/*.html').on('change', reload);
});

gulp.task('default', ['watch', 'sync']);<commit_msg>Improved settings<commit_after>var gulp            = require('gulp'),
    // Sass for writing and pre-processing CSS
    sass            = require('gulp-sass'),
    // Nano for optimising and post-processing CSS
    nano            = require('gulp-cssnano'),
    // Join JS file into a single file
    concat          = require('gulp-concat'),
    // Minify that single JS file
    uglify          = require('gulp-uglify'),
    // Minify and clean up HTML files
    htmlmin         = require('gulp-htmlmin'),
    // Data storage for Twig templates
    data            = require('gulp-data'),
    // Templating
    twig            = require('gulp-twig'),
    // Report file sizes in the CLI
    size            = require('gulp-size'),
    // Stops stream from ending on error
    plumber         = require('gulp-plumber'),
    // Send noficitations to the system and CLI
    notify          = require('gulp-notify'),
    // Sync changes to the Browser
    browserSync     = require('browser-sync')
    reload          = browserSync.reload;

///
/// Setup an error notification for gulp-plumber to handle
///
var hasError = notify.onError({
  title: 'Error',
  message: '<%= error.message %>',
  sound: "Basso"
});

gulp.task('sync', function() {
  browserSync({
    startPath: '/demo/',
    open: false, // or 'external'
    host: 'basekit.dev',
    proxy: 'basekit.dev',
    // notify: false,
    scrollRestoreTechnique: "cookie",
    logLevel: "silent",
    reloadDelay: 2500
  });
});

///
/// Compile Sass (with Nano and Autoprefixer)
///
gulp.task('scss', function() {
  gulp.src('css/basekit.scss')
    .pipe(plumber({errorHandler: hasError}))
    .pipe(sass().on('error', sass.logError))
    .pipe(nano({
      // http://cssnano.co/optimisations/minifySelectors/
      // This was interfering with the global selector so I've disabled it
      minifySelectors: false,
      // Enable adding prefixes
      autoprefixer: {
        add: true,
        // Browser support level
        // Must be over 0.5% usage, going back 2 versions, but IE is from 9 to 11
        browsers: [ '> 0.5%', 'last 2 versions', 'ie >= 9' ]
      }
    }))
    //
    .pipe(gulp.dest('css'))
    // Reload and inject
    .pipe(reload({ stream: true }))
    // Show file size before gzip
    .pipe(size({ showFiles: true }))
    // Show file size after gzip
    .pipe(size({ gzip: true, showFiles: true }));
});

///
/// Minify and combine javascript files for production, unless they start with an _
/// gulp.src('js/[^_]*.js')
///
gulp.task('js', function() {
  gulp.src('js/*.js')
    .pipe(plumber({errorHandler: hasError}))
    // Combine all (none _) js files into this file
    .pipe(concat('basekit.js'))
    // Minify the file
    .pipe(uglify())
    // Output it here
    .pipe(gulp.dest('js/min'))
    // Report the gzipped file size
    .pipe(size({
      gzip: true,
      showFiles: true
    })
  );
});

///
/// Minify, clean and output HTML files
/// NOTE: I'm likely to deprecate this soon in favour of using Twig
///
// gulp.task('html', function() {
//   gulp.src('./html/*.html')
//     .pipe(plumber({errorHandler: hasError}))
//     .pipe(htmlmin({
//       collapseWhitespace: true,
//       removeComments: true,
//       removeAttributeQuotes: true,
//       // removeRedundantAttributes: true,
//       removeEmptyAttributes: true,
//       removeScriptTypeAttributes: true,
//       removeStyleLinkTypeAttributes: true,
//       collapseBooleanAttributes: true,
//       quoteCharacter: '\'',
//       minifyJS: true,
//       minifyCSS: true
//     }))
//     .pipe(gulp.dest('./'))
//     .pipe(notify({
//       title: 'Created',
//       message: '<%= file.relative %>'
//     }));
// });

///
/// Compile Twig templates to an HTML frontend
/// NOTE: At the time of writing March 2017 we use Craft CMS. Writing frontend templates in Twig makes sense since Craft uses twig, these files are also output as HTML for demonstration and testing.
///
gulp.task('twig', function() {
  // De-caching so that the data.json file can be watched correctly
  // See this https://github.com/colynb/gulp-data/issues/17
  function requireUncached( $module ) {
    delete require.cache[require.resolve( $module )];
    return require( $module );
  }

  // run the Twig template parser on .twig files that don't start with an _
  return gulp.src('./templates/**/[^_]*.twig')
  .pipe(plumber({errorHandler: hasError}))
  // Uncached data for populating Twig files
  .pipe( data(function(file){ return requireUncached('./templates/data.json'); }))
  // Let gulp-twig know where the base template directory is
  .pipe(twig({ base: 'templates' }))
  // Minify the files for development use
  .pipe(htmlmin({
    collapseWhitespace: true,
    removeComments: true,
    removeAttributeQuotes: true,
    removeEmptyAttributes: true,
    removeScriptTypeAttributes: true,
    removeStyleLinkTypeAttributes: true,
    collapseBooleanAttributes: true,
    quoteCharacter: '\'',
    minifyJS: true,
    minifyCSS: true
  }))
  // Return default behaviour
  .pipe(plumber.stop())
  // Output minified file
  .pipe(gulp.dest('demo'))
});

// Combine various functions into watch
gulp.task('watch', function() {
  gulp.watch('css/**/*.scss', { interval: 500 }, ['scss']);
  gulp.watch('js/*.js', ['js']);
  gulp.watch(['templates/**/*.twig', 'templates/**/*.json'], { interval: 500 }, ['twig']);
  gulp.watch('demo/**/*.html').on('change', reload);
});

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


<commit_before>import {join} from 'path';
import pascalCase from 'pascal-case';
import merge from 'lodash.merge';
import {transform, buildExternalHelpers} from 'babel-core';
import template from './react-class.tmpl';
import dependencyTemplate from './require.tmpl';

export default function createReactCodeFactory(application) {
	const config = application.configuration.transforms['react'] || {};

	return async function createReactCode(file, demo, configuration) {
    try {
      // FIX #13: Merge the environment options with the global options
      let opts = merge({}, config.opts, configuration.opts);

      let helpers = buildExternalHelpers(undefined, 'var');
      let result = convertCode(file, opts);
      let requireBlock = createRequireBlock(getDependencies(file), opts);
      result = helpers + requireBlock + result;
      if (demo) {
        demo.dependencies = {
          pattern: file
        };
        merge(demo.dependencies, file.dependencies);
        let demoResult = convertCode(demo, opts);
        let requireBlock = createRequireBlock(getDependencies(demo), opts);
        demoResult = helpers + requireBlock + demoResult;
        file.demoSource = demo.source;
        file.demoBuffer = new Buffer(demoResult, 'utf-8');
			}
			file.buffer = result;
			return file;
		} catch (error) {
			let patternName = loadPatternJson(file.path).name;
			application.log.warn(`Unable to run react transform for ${patternName}/${file.name}.`);
			application.log.error(error.stack);
			throw error;
		}
	}
}

function convertCode(file, opts) {
	let source = file.buffer.toString('utf-8');
	// TODO: This is a weak criteria to check if we have to create a wrapper
	if (source.indexOf('extends React.Component') === -1 || source.indexOf('React.createClass') !== -1)	 {
		source = createWrappedRenderFunction(file, source, opts);
	} else {
		source = rewriteImportsToGlobalNames(file, source);
	}
	// XXX: This is required to satisfy babel but keep the option to define global vars
	let localOpts = merge({}, opts);
	delete localOpts.globals;
	return transform(source, merge({externalHelpers: true}, localOpts)).code;
}

function createWrappedRenderFunction(file, source, opts) {
	let patternJson = loadPatternJson(file.path);
	let dependencies = writeDependencyImports(file).join('\n');
	return renderCodeTemplate(source, dependencies, template, pascalCase(patternJson.name), opts);
}

function writeDependencyImports(file) {
	let patterns = loadPatternJson(file.path).patterns || {};
	let dependencies = [];
	for (let name of Object.keys(file.dependencies)) {
		dependencies.push(`import ${pascalCase(name)} from '${patterns[name] || name}';`);
	}
	return dependencies;
}

function renderCodeTemplate(source, dependencies, template, className, opts) {
	return template
		.replace('$$dependencies$$', dependencies)
		.replace('$$class-name$$', className)
		.replace('$$render-code$$', matchFirstJsxExpressionAndWrapWithReturn(addImplicitGlobals(source, opts)));
}

function addImplicitGlobals(source, opts) {
	let vars = [];
	if (opts && opts.globals) {
		console.log('WARNING: Deprecated use of global opts');
		for (let key of Object.keys(opts.globals)) {
			vars.push(`this.${key} = ${JSON.stringify(opts.globals[key])};`);
		}
	}
	return vars.join('\n') + '\n' + source;
}

const TAG_START = '<[-_a-z0-9]+';
const ATTRIBUTE_NAME = '[-_a-z0-9]+';
const HTML_ATTRIBUTE_VALUE = `"[^"]*"`;
const REACT_ATTRIBUTE_VALUE = `{(?:{[^}]*}|[^}]*)}`;
const ATTRIBUTE_VALUE = `\\s*=\\s*(?:${HTML_ATTRIBUTE_VALUE}|${REACT_ATTRIBUTE_VALUE})`;
const NAMED_ATTRIBUTE= `(?:${ATTRIBUTE_NAME}(?:${ATTRIBUTE_VALUE})?)`;
const SPREAD_ATTRIBUTE = '{\\.\\.\\.[^}]+}';
const ATTRIBUTE = `(?:${NAMED_ATTRIBUTE}|${SPREAD_ATTRIBUTE})`;
const ATTRIBUTES = `(?:\\s+${ATTRIBUTE})*`;
const TAG_END = '\\s*\\/?>';
const EXPR = new RegExp(`\n\s*(${TAG_START}${ATTRIBUTES}${TAG_END}[^]*)`, 'gi');
//console.log('EXPR', EXPR);

function matchFirstJsxExpressionAndWrapWithReturn(source) {
	return source.replace(EXPR, (match, jsxExpr) => {
		return 'return (\n' + jsxExpr/*.split('\n').map(line => indent + line).join('\n')*/ + '\n);\n'
	});
}

function loadPatternJson(path) {
	return require(
		join(
			path.substring(0,
				path.lastIndexOf('/')), 'pattern.json'));
}

function rewriteImportsToGlobalNames(file, source) {
	let patterns = loadPatternJson(file.path).patterns || {};
	return source.replace(/(import\s+(?:\* as\s)?[^\s]+\s+from\s+["'])([^"']+)(["'];)/g, (match, before, name, after) => {
		return `${before}${patterns[name] || name}${after}`;
	});
}

function getDependencies(file) {
	let patterns = loadPatternJson(file.path).patterns || {};
	let dependencies = {};
	for (let name of Object.keys(file.dependencies)) {
		let globalName = patterns[name] || name;
		let dependencyFile = file.dependencies[name];
		dependencies[globalName] = dependencyFile;
		merge(dependencies, getDependencies(dependencyFile));
	}
	return dependencies;
}

function createRequireBlock(dependencies, opts) {
	let source = [];
	for (let name of Object.keys(dependencies)) {
		source.push(`
			'${name}': function(module, exports, require) {
				${convertCode(dependencies[name], opts).split('\n').map(line => '\t\t\t' + line).join('\n')}
			}
		`);
	}
	return dependencyTemplate.replace('$$localDependencies$$', source.join('\n,'));
}
<commit_msg>Be platform independent when searching for pattern.json in react-transform, fixes #21<commit_after>import {join, dirname} from 'path';
import pascalCase from 'pascal-case';
import merge from 'lodash.merge';
import {transform, buildExternalHelpers} from 'babel-core';
import template from './react-class.tmpl';
import dependencyTemplate from './require.tmpl';

export default function createReactCodeFactory(application) {
	const config = application.configuration.transforms['react'] || {};

	return async function createReactCode(file, demo, configuration) {
    try {
      // FIX #13: Merge the environment options with the global options
      let opts = merge({}, config.opts, configuration.opts);

      let helpers = buildExternalHelpers(undefined, 'var');
      let result = convertCode(file, opts);
      let requireBlock = createRequireBlock(getDependencies(file), opts);
      result = helpers + requireBlock + result;
      if (demo) {
        demo.dependencies = {
          pattern: file
        };
        merge(demo.dependencies, file.dependencies);
        let demoResult = convertCode(demo, opts);
        let requireBlock = createRequireBlock(getDependencies(demo), opts);
        demoResult = helpers + requireBlock + demoResult;
        file.demoSource = demo.source;
        file.demoBuffer = new Buffer(demoResult, 'utf-8');
			}
			file.buffer = result;
			return file;
		} catch (error) {
			let patternName = loadPatternJson(file.path).name;
			application.log.warn(`Unable to run react transform for ${patternName}/${file.name}.`);
			application.log.error(error.stack);
			throw error;
		}
	}
}

function convertCode(file, opts) {
	let source = file.buffer.toString('utf-8');
	// TODO: This is a weak criteria to check if we have to create a wrapper
	if (source.indexOf('extends React.Component') === -1 || source.indexOf('React.createClass') !== -1)	 {
		source = createWrappedRenderFunction(file, source, opts);
	} else {
		source = rewriteImportsToGlobalNames(file, source);
	}
	// XXX: This is required to satisfy babel but keep the option to define global vars
	let localOpts = merge({}, opts);
	delete localOpts.globals;
	return transform(source, merge({externalHelpers: true}, localOpts)).code;
}

function createWrappedRenderFunction(file, source, opts) {
	let patternJson = loadPatternJson(file.path);
	let dependencies = writeDependencyImports(file).join('\n');
	return renderCodeTemplate(source, dependencies, template, pascalCase(patternJson.name), opts);
}

function writeDependencyImports(file) {
	let patterns = loadPatternJson(file.path).patterns || {};
	let dependencies = [];
	for (let name of Object.keys(file.dependencies)) {
		dependencies.push(`import ${pascalCase(name)} from '${patterns[name] || name}';`);
	}
	return dependencies;
}

function renderCodeTemplate(source, dependencies, template, className, opts) {
	return template
		.replace('$$dependencies$$', dependencies)
		.replace('$$class-name$$', className)
		.replace('$$render-code$$', matchFirstJsxExpressionAndWrapWithReturn(addImplicitGlobals(source, opts)));
}

function addImplicitGlobals(source, opts) {
	let vars = [];
	if (opts && opts.globals) {
		console.log('WARNING: Deprecated use of global opts');
		for (let key of Object.keys(opts.globals)) {
			vars.push(`this.${key} = ${JSON.stringify(opts.globals[key])};`);
		}
	}
	return vars.join('\n') + '\n' + source;
}

const TAG_START = '<[-_a-z0-9]+';
const ATTRIBUTE_NAME = '[-_a-z0-9]+';
const HTML_ATTRIBUTE_VALUE = `"[^"]*"`;
const REACT_ATTRIBUTE_VALUE = `{(?:{[^}]*}|[^}]*)}`;
const ATTRIBUTE_VALUE = `\\s*=\\s*(?:${HTML_ATTRIBUTE_VALUE}|${REACT_ATTRIBUTE_VALUE})`;
const NAMED_ATTRIBUTE= `(?:${ATTRIBUTE_NAME}(?:${ATTRIBUTE_VALUE})?)`;
const SPREAD_ATTRIBUTE = '{\\.\\.\\.[^}]+}';
const ATTRIBUTE = `(?:${NAMED_ATTRIBUTE}|${SPREAD_ATTRIBUTE})`;
const ATTRIBUTES = `(?:\\s+${ATTRIBUTE})*`;
const TAG_END = '\\s*\\/?>';
const EXPR = new RegExp(`\n\s*(${TAG_START}${ATTRIBUTES}${TAG_END}[^]*)`, 'gi');
//console.log('EXPR', EXPR);

function matchFirstJsxExpressionAndWrapWithReturn(source) {
	return source.replace(EXPR, (match, jsxExpr) => {
		return 'return (\n' + jsxExpr/*.split('\n').map(line => indent + line).join('\n')*/ + '\n);\n'
	});
}

function loadPatternJson(path) {
	return require(join(dirname(path), 'pattern.json'));
}

function rewriteImportsToGlobalNames(file, source) {
	let patterns = loadPatternJson(file.path).patterns || {};
	return source.replace(/(import\s+(?:\* as\s)?[^\s]+\s+from\s+["'])([^"']+)(["'];)/g, (match, before, name, after) => {
		return `${before}${patterns[name] || name}${after}`;
	});
}

function getDependencies(file) {
	let patterns = loadPatternJson(file.path).patterns || {};
	let dependencies = {};
	for (let name of Object.keys(file.dependencies)) {
		let globalName = patterns[name] || name;
		let dependencyFile = file.dependencies[name];
		dependencies[globalName] = dependencyFile;
		merge(dependencies, getDependencies(dependencyFile));
	}
	return dependencies;
}

function createRequireBlock(dependencies, opts) {
	let source = [];
	for (let name of Object.keys(dependencies)) {
		source.push(`
			'${name}': function(module, exports, require) {
				${convertCode(dependencies[name], opts).split('\n').map(line => '\t\t\t' + line).join('\n')}
			}
		`);
	}
	return dependencyTemplate.replace('$$localDependencies$$', source.join('\n,'));
}
<|endoftext|>


<commit_before>(function(undefined) {

  'use strict';

  /**
   * Requires gulp
   */
  var gulp = require('gulp');

  /**
   * Requires gulp dependencies
   */
  var clean      = require('gulp-clean');
  var concat     = require('gulp-concat');
  var connect    = require('gulp-connect');
  var jade       = require('gulp-jade');
  var jshint     = require('gulp-jshint');
  var livereload = require('gulp-livereload');
  var plumber    = require('gulp-plumber');
  var sourcemaps = require('gulp-sourcemaps');
  var stylus     = require('gulp-stylus');
  var uglify     = require('gulp-uglify');
  var watch      = require('gulp-watch');

  /** Stylus dependencies */
  var jeet    = require('jeet');
  var kouto   = require('kouto-swiss');
  var rupture = require('rupture');

  /** Jshint dependencies */
  var stylish = require('jshint-stylish');

  /**
   * Define paths, sources and destinations
   */
  var stylusSrc   = ['front/stylesheets/paper.styl'];
  var stylusFiles = ['front/stylesheets/**/*.styl'];
  var stylusDest  = 'public/assets/stylesheets';

  var scriptsSrc   = ['front/javascripts/**/*.js'];
  var scriptsFiles = scriptsSrc;
  var scriptsDest  = 'public/assets/javascripts';

  var jadeSrc   = ['front/*.jade'];
  var jadeFiles = jadeSrc;
  var jadeDest  = 'public';

  var templatesSrc = ['front/javascripts/components/**/*.jade'];
  var templatesFiles = templatesSrc;
  var templatesDest = 'public/templates';

  /**
   * Clean task
   *
   * Cleans the build directory
   */
  gulp.task('clean', function() {
    gulp.src('public', {read: false})
      .pipe(clean());
  });

  /**
   * Server task
   *
   * Creates a static server using connect with livereload support
   */
  gulp.task('server', function() {
    connect.server({
      port: 3000,
      root: 'public',
      livereload: true
    });
  });

  /**
   * Jade task
   *
   * Compiles jade files into html
   */
  gulp.task('jade', function() {
    gulp.src(jadeSrc)
      .pipe(plumber())
      .pipe(jade({pretty: true}))
      .pipe(gulp.dest(jadeDest))
      .pipe(livereload());
  });

  /**
   * Templates task
   *
   * Compiles angular templates
   */
  gulp.task('templates', function() {
    gulp.src(templatesSrc)
      .pipe(plumber())
      .pipe(jade({pretty: true}))
      .pipe(gulp.dest(templatesDest))
      .pipe(livereload());
  });

  /**
   * Jade task
   *
   * Concats javascripts files and minifies them
   */
  gulp.task('jshint', function() {
    gulp.src(scriptsFiles)
      .pipe(plumber())
      .pipe(watch(scriptsFiles))
      .pipe(jshint())
      .pipe(jshint.reporter(stylish))
  });

  /**
   * Scripts task
   *
   * Concats javascripts files and minifies them
   */
  gulp.task('scripts', function() {
    gulp.src(scriptsSrc)
      .pipe(plumber())
      .pipe(sourcemaps.init())
      .pipe(concat('paper.js'))
      .pipe(uglify())
      .pipe(sourcemaps.write())
      .pipe(gulp.dest(scriptsDest))
      .pipe(livereload());
  });

  /**
   * Stylus task
   *
   * Compiles stylus files into css files and creates sourcemaps
   */
  gulp.task('stylus', function() {
    var stylusOptions = {
      compress: true,
      use: [jeet(), kouto(), rupture()]
    };

    gulp.src(stylusSrc)
      .pipe(plumber())
      .pipe(sourcemaps.init())
      .pipe(stylus(stylusOptions))
      .pipe(sourcemaps.write())
      .pipe(gulp.dest(stylusDest))
      .pipe(livereload());
  });

  /**
   * Watch task
   *
   * Watches for changes and perform gulp tasks accordingly
   */
  gulp.task('watch', ['jade', 'server', 'scripts', 'stylus', 'templates'], function() {
    livereload.listen();

    gulp.watch(stylusFiles, ['stylus']);
    gulp.watch(scriptsFiles, ['scripts']);
    gulp.watch(jadeFiles, ['jade']);
    gulp.watch(templatesFiles, ['templates']);
  });

})();
<commit_msg>Update scrips path to attend angular needs<commit_after>(function(undefined) {

  'use strict';

  /**
   * Requires gulp
   */
  var gulp = require('gulp');

  /**
   * Requires gulp dependencies
   */
  var clean      = require('gulp-clean');
  var concat     = require('gulp-concat');
  var connect    = require('gulp-connect');
  var jade       = require('gulp-jade');
  var jshint     = require('gulp-jshint');
  var livereload = require('gulp-livereload');
  var plumber    = require('gulp-plumber');
  var sourcemaps = require('gulp-sourcemaps');
  var stylus     = require('gulp-stylus');
  var uglify     = require('gulp-uglify');
  var watch      = require('gulp-watch');

  /** Stylus dependencies */
  var jeet    = require('jeet');
  var kouto   = require('kouto-swiss');
  var rupture = require('rupture');

  /** Jshint dependencies */
  var stylish = require('jshint-stylish');

  /**
   * Define paths, sources and destinations
   */
  var stylusSrc   = ['front/stylesheets/paper.styl'];
  var stylusFiles = ['front/stylesheets/**/*.styl'];
  var stylusDest  = 'public/assets/stylesheets';

  var scriptsSrc   = [
    'front/javascripts/**/*.module.js',
    'front/javascripts/**/*.services.js',
    'front/javascripts/**/*.controllers.js',
    'front/javascripts/**/*.directives.js',
    'front/javascripts/**/*.js'
  ];

  var scriptsFiles = scriptsSrc;
  var scriptsDest  = 'public/assets/javascripts';

  var jadeSrc   = ['front/*.jade'];
  var jadeFiles = jadeSrc;
  var jadeDest  = 'public';

  var templatesSrc = ['front/javascripts/components/**/*.jade'];
  var templatesFiles = templatesSrc;
  var templatesDest = 'public/templates';

  /**
   * Clean task
   *
   * Cleans the build directory
   */
  gulp.task('clean', function() {
    gulp.src('public', {read: false})
      .pipe(clean());
  });

  /**
   * Server task
   *
   * Creates a static server using connect with livereload support
   */
  gulp.task('server', function() {
    connect.server({
      port: 3000,
      root: 'public',
      livereload: true
    });
  });

  /**
   * Jade task
   *
   * Compiles jade files into html
   */
  gulp.task('jade', function() {
    gulp.src(jadeSrc)
      .pipe(plumber())
      .pipe(jade({pretty: true}))
      .pipe(gulp.dest(jadeDest))
      .pipe(livereload());
  });

  /**
   * Templates task
   *
   * Compiles angular templates
   */
  gulp.task('templates', function() {
    gulp.src(templatesSrc)
      .pipe(plumber())
      .pipe(jade({pretty: true}))
      .pipe(gulp.dest(templatesDest))
      .pipe(livereload());
  });

  /**
   * Jade task
   *
   * Concats javascripts files and minifies them
   */
  gulp.task('jshint', function() {
    gulp.src(scriptsFiles)
      .pipe(plumber())
      .pipe(watch(scriptsFiles))
      .pipe(jshint())
      .pipe(jshint.reporter(stylish))
  });

  /**
   * Scripts task
   *
   * Concats javascripts files and minifies them
   */
  gulp.task('scripts', function() {
    gulp.src(scriptsSrc)
      .pipe(plumber())
      .pipe(sourcemaps.init())
      .pipe(concat('paper.js'))
      .pipe(uglify())
      .pipe(sourcemaps.write())
      .pipe(gulp.dest(scriptsDest))
      .pipe(livereload());
  });

  /**
   * Stylus task
   *
   * Compiles stylus files into css files and creates sourcemaps
   */
  gulp.task('stylus', function() {
    var stylusOptions = {
      compress: true,
      use: [jeet(), kouto(), rupture()]
    };

    gulp.src(stylusSrc)
      .pipe(plumber())
      .pipe(sourcemaps.init())
      .pipe(stylus(stylusOptions))
      .pipe(sourcemaps.write())
      .pipe(gulp.dest(stylusDest))
      .pipe(livereload());
  });

  /**
   * Watch task
   *
   * Watches for changes and perform gulp tasks accordingly
   */
  gulp.task('watch', ['jade', 'server', 'scripts', 'stylus', 'templates'], function() {
    livereload.listen();

    gulp.watch(stylusFiles, ['stylus']);
    gulp.watch(scriptsFiles, ['scripts']);
    gulp.watch(jadeFiles, ['jade']);
    gulp.watch(templatesFiles, ['templates']);
  });

})();
<|endoftext|>


<commit_before>var locastyle = locastyle || {};

locastyle.form = (function() {
  'use strict';

  var config = {
    selectors: {
      disable: '.ls-form-disable',
      text: '.ls-form-text'
    }
  }

  function init() {

    formDisable();
    formText();
    masks();
    textareaAutoresize();
    sufixBorder();

  }

  function sufixBorder () {
    console.log('teste')
    $(':input + .ls-label-sufix', '.ls-form').prev().addClass('ls-no-right-radius');
    $('.ls-label-prefix + :input', '.ls-form').addClass('ls-no-left-radius');
  }

  function textareaAutoresize (argument) {
    $('textarea.ls-textarea-autoresize', '.ls-field').each(function (it, textarea) {
      var $textarea = $(textarea);
      var height = $textarea.height();
      $textarea.keyup(function (e) {
        if (!$textarea.prop('scrollTop')) {
          do {
            var b = $textarea.prop('scrollHeight');
            var h = $textarea.height();
            $textarea.height(h - 5);
          } while (b && (b != $textarea.prop('scrollHeight')));
        };
        $textarea.height($textarea.prop('scrollHeight') );
      });
    });
  }

  function masks() {
    $('.ls-mask-date').mask('11/11/1111');
    $('.ls-mask-time').mask('00:00:00');
    $('.ls-mask-date_time').mask('00/00/0000 00:00:00');
    $('.ls-mask-cep').mask('00000-000');
    $('.ls-mask-phone').mask('0000-0000');
    $('.ls-mask-phone_with_ddd').mask('(00) 0000-0000');
    $('.ls-mask-cpf').mask('000.000.000-00', {reverse: true});
    $('.ls-mask-ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}});
    $('.ls-mask-percent').mask('##0,00%', {reverse: true});
  }

  function formDisable() {
    $( config.selectors.disable ).each(function(ic, container){
      $(container).find(':input').each(function(ie, field){
        $(field).attr('disabled', 'disabled')
      });
    });
  }

  function formText() {
    $( config.selectors.text ).each(function(ic, container){
      $(container).find(':input').each(function(ie, field){
        $(field).addClass('ls-form-text');
      });
    });
  }

  return {
    init: init,
  }

}());
<commit_msg>removing missing console.log<commit_after>var locastyle = locastyle || {};

locastyle.form = (function() {
  'use strict';

  var config = {
    selectors: {
      disable: '.ls-form-disable',
      text: '.ls-form-text'
    }
  }

  function init() {

    formDisable();
    formText();
    masks();
    textareaAutoresize();
    sufixBorder();

  }

  function sufixBorder () {
    $(':input + .ls-label-sufix', '.ls-form').prev().addClass('ls-no-right-radius');
    $('.ls-label-prefix + :input', '.ls-form').addClass('ls-no-left-radius');
  }

  function textareaAutoresize (argument) {
    $('textarea.ls-textarea-autoresize', '.ls-field').each(function (it, textarea) {
      var $textarea = $(textarea);
      var height = $textarea.height();
      $textarea.keyup(function (e) {
        if (!$textarea.prop('scrollTop')) {
          do {
            var b = $textarea.prop('scrollHeight');
            var h = $textarea.height();
            $textarea.height(h - 5);
          } while (b && (b != $textarea.prop('scrollHeight')));
        };
        $textarea.height($textarea.prop('scrollHeight') );
      });
    });
  }

  function masks() {
    $('.ls-mask-date').mask('11/11/1111');
    $('.ls-mask-time').mask('00:00:00');
    $('.ls-mask-date_time').mask('00/00/0000 00:00:00');
    $('.ls-mask-cep').mask('00000-000');
    $('.ls-mask-phone').mask('0000-0000');
    $('.ls-mask-phone_with_ddd').mask('(00) 0000-0000');
    $('.ls-mask-cpf').mask('000.000.000-00', {reverse: true});
    $('.ls-mask-ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}});
    $('.ls-mask-percent').mask('##0,00%', {reverse: true});
  }

  function formDisable() {
    $( config.selectors.disable ).each(function(ic, container){
      $(container).find(':input').each(function(ie, field){
        $(field).attr('disabled', 'disabled')
      });
    });
  }

  function formText() {
    $( config.selectors.text ).each(function(ic, container){
      $(container).find(':input').each(function(ie, field){
        $(field).addClass('ls-form-text');
      });
    });
  }

  return {
    init: init,
  }

}());
<|endoftext|>


<commit_before>(function(oCanvas, window, document, undefined){

	// Define the class
	var image = function (settings, thecore) {

		// Return an object when instantiated
		return oCanvas.extend({
			core: thecore,

			shapeType: "rectangular",
			loaded: false,
			firstDrawn: false,
			tile: false,
			tile_width: 0,
			tile_height: 0,
			tile_spacing_x: 0,
			tile_spacing_y: 0,

			// Init method for loading the image resource
			init: function () {
				var _this = this,

					// Get source (settings.image can be either an HTML img element or a string with path to the image)
					source = (this.image.nodeName && this.image.nodeName.toLowerCase() === "img") ? "htmlImg" : "newImg";

				// Get image object (either create a copy of the current element, or a new image)
				this.img = (source === "htmlImg") ? this.image.cloneNode(false) : new Image();

				// Temporarily append it to the canvas to be able to get dimensions
				this.core.canvasElement.appendChild(this.img);

				// Get dimensions when the image is loaded. Also, remove the temp img from DOM
				this.img.onload = function () {
					_this.loaded = true;

					// Set dimensions proportionally (if only one is specified, calculate the other)
					if (_this.width !== 0) {
						if (_this.height === 0) {
							_this.height = _this.width / (this.width / this.height);
						}
					} else {
						_this.width = this.width;
					}
					if (_this.height !== 0) {
						if (_this.width === 0) {
							_this.width = _this.height / (this.height / this.width);
						}
					} else {
						_this.height = this.height;
					}
					_this.tile_width = (_this.tile_width === 0) ? _this.width : _this.tile_width;
					_this.tile_height = (_this.tile_height === 0) ? _this.height : _this.tile_height;
					_this.core.canvasElement.removeChild(this);
					_this.core.redraw();
				};

				// Set the path to the image if a string was passed in
				if (source === "newImg") {
					this.img.src = this.image;
				}
			},

			// Method that draws the image to the canvas once it's loaded
			draw: function () {
				var canvas = this.core.canvas,
					_this = this,
					origin = this.getOrigin(),
					x = this.abs_x - origin.x,
					y = this.abs_y - origin.y,
					width, height;

				// If the image has finished loading, go on and draw
				if (this.loaded && this.core.draw.objects[this.id] !== undefined && this.img.width > 0 && this.img.height > 0) {

					width = (this.width === 0) ? this.img.width : this.width;
					height = (this.height === 0) ? this.img.height : this.height;

					if (this.tile) {

						var num_x = Math.ceil(width / this.tile_width),
							num_y = Math.ceil(height / this.tile_height),
							tile_x, tile_y;

						canvas.save();
						canvas.beginPath();

						// Create clipping path for the rectangle that the tiled images will be drawn inside
						canvas.moveTo(x, y);
						canvas.lineTo(x + width, y);
						canvas.lineTo(x + width, y + height);
						canvas.lineTo(x, y + height);
						canvas.lineTo(x, y);
						canvas.clip();

						// Draw all the tiled images
						for (tile_y = 0; tile_y < num_y; tile_y++) {
							for (tile_x = 0; tile_x < num_x; tile_x++) {
								canvas.drawImage(this.img, x + tile_x * (this.tile_width + this.tile_spacing_x), y + tile_y * (this.tile_height + this.tile_spacing_y), this.tile_width, this.tile_height);
							}
						}

						canvas.closePath();
						canvas.restore();

					} else {

						// Draw the image to the canvas
						canvas.drawImage(this.img, x, y, width, height);

					}

					// Clear the timer if this is the first time it is drawn
					if (this.firstDrawn === false) {
						this.firstDrawn = true;
						clearTimeout(this.loadtimer);
					}
				}

				// If the image hasn't finished loading, set a timer and try again
				else {
					clearTimeout(this.loadtimer);
					this.loadtimer = setTimeout(function () {
						_this.draw();
					}, 100);
				}

				return this;
			}

		}, settings);
	};

	// Register the display object
	oCanvas.registerDisplayObject("image", image, "init");

})(oCanvas, window, document);<commit_msg>Enabled strokes for images.<commit_after>(function(oCanvas, window, document, undefined){

	// Define the class
	var image = function (settings, thecore) {

		// Return an object when instantiated
		return oCanvas.extend({
			core: thecore,

			shapeType: "rectangular",
			loaded: false,
			firstDrawn: false,
			tile: false,
			tile_width: 0,
			tile_height: 0,
			tile_spacing_x: 0,
			tile_spacing_y: 0,

			// Init method for loading the image resource
			init: function () {
				var _this = this,

					// Get source (settings.image can be either an HTML img element or a string with path to the image)
					source = (this.image.nodeName && this.image.nodeName.toLowerCase() === "img") ? "htmlImg" : "newImg";

				// Get image object (either create a copy of the current element, or a new image)
				this.img = (source === "htmlImg") ? this.image.cloneNode(false) : new Image();

				// Temporarily append it to the canvas to be able to get dimensions
				this.core.canvasElement.appendChild(this.img);

				// Get dimensions when the image is loaded. Also, remove the temp img from DOM
				this.img.onload = function () {
					_this.loaded = true;

					// Set dimensions proportionally (if only one is specified, calculate the other)
					if (_this.width !== 0) {
						if (_this.height === 0) {
							_this.height = _this.width / (this.width / this.height);
						}
					} else {
						_this.width = this.width;
					}
					if (_this.height !== 0) {
						if (_this.width === 0) {
							_this.width = _this.height / (this.height / this.width);
						}
					} else {
						_this.height = this.height;
					}
					_this.tile_width = (_this.tile_width === 0) ? _this.width : _this.tile_width;
					_this.tile_height = (_this.tile_height === 0) ? _this.height : _this.tile_height;
					_this.core.canvasElement.removeChild(this);
					_this.core.redraw();
				};

				// Set the path to the image if a string was passed in
				if (source === "newImg") {
					this.img.src = this.image;
				}
			},

			// Method that draws the image to the canvas once it's loaded
			draw: function () {
				var canvas = this.core.canvas,
					_this = this,
					origin = this.getOrigin(),
					x = this.abs_x - origin.x,
					y = this.abs_y - origin.y,
					width, height;

				// If the image has finished loading, go on and draw
				if (this.loaded && this.core.draw.objects[this.id] !== undefined && this.img.width > 0 && this.img.height > 0) {

					width = (this.width === 0) ? this.img.width : this.width;
					height = (this.height === 0) ? this.img.height : this.height;

					if (this.tile) {

						var num_x = Math.ceil(width / this.tile_width),
							num_y = Math.ceil(height / this.tile_height),
							tile_x, tile_y;

						canvas.save();
						canvas.beginPath();

						// Create clipping path for the rectangle that the tiled images will be drawn inside
						canvas.moveTo(x, y);
						canvas.lineTo(x + width, y);
						canvas.lineTo(x + width, y + height);
						canvas.lineTo(x, y + height);
						canvas.lineTo(x, y);
						canvas.clip();

						// Draw all the tiled images
						for (tile_y = 0; tile_y < num_y; tile_y++) {
							for (tile_x = 0; tile_x < num_x; tile_x++) {
								canvas.drawImage(this.img, x + tile_x * (this.tile_width + this.tile_spacing_x), y + tile_y * (this.tile_height + this.tile_spacing_y), this.tile_width, this.tile_height);
							}
						}

						canvas.closePath();
						canvas.restore();

					} else {

						// Draw the image to the canvas
						canvas.drawImage(this.img, x, y, width, height);

					}

					// Do color if stroke width is specified
					if (this.strokeWidth > 0) {
						canvas.lineWidth = this.strokeWidth;
						canvas.strokeStyle = this.strokeColor;
						canvas.strokeRect(x, y, width, height);
					}

					// Clear the timer if this is the first time it is drawn
					if (this.firstDrawn === false) {
						this.firstDrawn = true;
						clearTimeout(this.loadtimer);
					}
				}

				// If the image hasn't finished loading, set a timer and try again
				else {
					clearTimeout(this.loadtimer);
					this.loadtimer = setTimeout(function () {
						_this.draw();
					}, 100);
				}

				return this;
			}

		}, settings);
	};

	// Register the display object
	oCanvas.registerDisplayObject("image", image, "init");

})(oCanvas, window, document);<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name binary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/binary}
*/
setReadOnly( ns, 'binary', require( '@stdlib/strided/base/binary' ) );

/**
* @name binaryAddonDispatch
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/binary-addon-dispatch}
*/
setReadOnly( ns, 'binaryAddonDispatch', require( '@stdlib/strided/base/binary-addon-dispatch' ) );

/**
* @name dmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmap}
*/
setReadOnly( ns, 'dmap', require( '@stdlib/strided/base/dmap' ) );

/**
* @name dmskmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmskmap}
*/
setReadOnly( ns, 'dmskmap', require( '@stdlib/strided/base/dmskmap' ) );

/**
* @name dtypeEnum2Str
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-enum2str}
*/
setReadOnly( ns, 'dtypeEnum2Str', require( '@stdlib/strided/base/dtype-enum2str' ) );

/**
* @name dtypeResolveEnum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-resolve-enum}
*/
setReadOnly( ns, 'dtypeResolveEnum', require( '@stdlib/strided/base/dtype-resolve-enum' ) );

/**
* @name dtypeStr2Enum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-str2enum}
*/
setReadOnly( ns, 'dtypeStr2Enum', require( '@stdlib/strided/base/dtype-str2enum' ) );

/**
* @name mapBy
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/map-by}
*/
setReadOnly( ns, 'mapBy', require( '@stdlib/strided/base/map-by' ) );

/**
* @name metaDataProps
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/meta-data-props}
*/
setReadOnly( ns, 'metaDataProps', require( '@stdlib/strided/base/meta-data-props' ) );

/**
* @name mskunary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/mskunary}
*/
setReadOnly( ns, 'mskunary', require( '@stdlib/strided/base/mskunary' ) );

/**
* @name nullary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/nullary}
*/
setReadOnly( ns, 'nullary', require( '@stdlib/strided/base/nullary' ) );

/**
* @name quaternary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/quaternary}
*/
setReadOnly( ns, 'quaternary', require( '@stdlib/strided/base/quaternary' ) );

/**
* @name quinary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/quinary}
*/
setReadOnly( ns, 'quinary', require( '@stdlib/strided/base/quinary' ) );

/**
* @name smap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/smap}
*/
setReadOnly( ns, 'smap', require( '@stdlib/strided/base/smap' ) );

/**
* @name smskmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/smskmap}
*/
setReadOnly( ns, 'smskmap', require( '@stdlib/strided/base/smskmap' ) );

/**
* @name ternary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/ternary}
*/
setReadOnly( ns, 'ternary', require( '@stdlib/strided/base/ternary' ) );

/**
* @name unary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/unary}
*/
setReadOnly( ns, 'unary', require( '@stdlib/strided/base/unary' ) );

/**
* @name unaryAddonDispatch
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/unary-addon-dispatch}
*/
setReadOnly( ns, 'unaryAddonDispatch', require( '@stdlib/strided/base/unary-addon-dispatch' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name binary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/binary}
*/
setReadOnly( ns, 'binary', require( '@stdlib/strided/base/binary' ) );

/**
* @name binaryAddonDispatch
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/binary-addon-dispatch}
*/
setReadOnly( ns, 'binaryAddonDispatch', require( '@stdlib/strided/base/binary-addon-dispatch' ) );

/**
* @name dmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmap}
*/
setReadOnly( ns, 'dmap', require( '@stdlib/strided/base/dmap' ) );

/**
* @name dmap2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmap2}
*/
setReadOnly( ns, 'dmap2', require( '@stdlib/strided/base/dmap2' ) );

/**
* @name dmskmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmskmap}
*/
setReadOnly( ns, 'dmskmap', require( '@stdlib/strided/base/dmskmap' ) );

/**
* @name dtypeEnum2Str
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-enum2str}
*/
setReadOnly( ns, 'dtypeEnum2Str', require( '@stdlib/strided/base/dtype-enum2str' ) );

/**
* @name dtypeResolveEnum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-resolve-enum}
*/
setReadOnly( ns, 'dtypeResolveEnum', require( '@stdlib/strided/base/dtype-resolve-enum' ) );

/**
* @name dtypeStr2Enum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-str2enum}
*/
setReadOnly( ns, 'dtypeStr2Enum', require( '@stdlib/strided/base/dtype-str2enum' ) );

/**
* @name mapBy
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/map-by}
*/
setReadOnly( ns, 'mapBy', require( '@stdlib/strided/base/map-by' ) );

/**
* @name metaDataProps
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/meta-data-props}
*/
setReadOnly( ns, 'metaDataProps', require( '@stdlib/strided/base/meta-data-props' ) );

/**
* @name mskunary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/mskunary}
*/
setReadOnly( ns, 'mskunary', require( '@stdlib/strided/base/mskunary' ) );

/**
* @name nullary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/nullary}
*/
setReadOnly( ns, 'nullary', require( '@stdlib/strided/base/nullary' ) );

/**
* @name quaternary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/quaternary}
*/
setReadOnly( ns, 'quaternary', require( '@stdlib/strided/base/quaternary' ) );

/**
* @name quinary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/quinary}
*/
setReadOnly( ns, 'quinary', require( '@stdlib/strided/base/quinary' ) );

/**
* @name smap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/smap}
*/
setReadOnly( ns, 'smap', require( '@stdlib/strided/base/smap' ) );

/**
* @name smskmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/smskmap}
*/
setReadOnly( ns, 'smskmap', require( '@stdlib/strided/base/smskmap' ) );

/**
* @name ternary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/ternary}
*/
setReadOnly( ns, 'ternary', require( '@stdlib/strided/base/ternary' ) );

/**
* @name unary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/unary}
*/
setReadOnly( ns, 'unary', require( '@stdlib/strided/base/unary' ) );

/**
* @name unaryAddonDispatch
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/unary-addon-dispatch}
*/
setReadOnly( ns, 'unaryAddonDispatch', require( '@stdlib/strided/base/unary-addon-dispatch' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>var gulp = require('gulp');

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

var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var postcssHexRbga = require('postcss-hexrgba');
var postcssImport = require('postcss-import');
var postcssMediaMinmax = require('postcss-media-minmax');
var postcssNested = require('postcss-nested');
var postcssSimpleVars = require('postcss-simple-vars');
var postcssExtend = require('postcss-extend');
var cssmin = require('gulp-cssmin');

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

gulp.task('serve', function() {
  browserSync({
    server: {
      baseDir: 'dist'
    }
  });
});

gulp.task('css', function () {
  var processors = [
    autoprefixer({ browsers: '> 5%' }),
    postcssImport,
    postcssSimpleVars,
    postcssHexRbga,
    postcssExtend,
    postcssNested,
    postcssMediaMinmax
  ];

    return gulp.src('src/styles/**/*.css')
        .pipe(postcss(processors))
        .pipe(cssmin())
        .pipe(gulp.dest('dist/'))
        .pipe(reload({ stream: true }));
});

gulp.task('html', function() {
  return gulp.src('src/**/*.html')
    .pipe(htmlmin({ collapseWhitespace: true }))
    .pipe(gulp.dest('dist'))
    .pipe(reload({ stream: true }));
});

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

gulp.task('watch', function () {
    gulp.watch('src/styles/**/*.css', [ 'css' ]);
    gulp.watch('src/**/*.html', [ 'html' ]);
});

gulp.task('default', [ 'serve', 'fonts', 'css', 'html', 'watch' ]);
<commit_msg>Adds a rule to copy the robots.txt file<commit_after>var gulp = require('gulp');

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

var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var postcssHexRbga = require('postcss-hexrgba');
var postcssImport = require('postcss-import');
var postcssMediaMinmax = require('postcss-media-minmax');
var postcssNested = require('postcss-nested');
var postcssSimpleVars = require('postcss-simple-vars');
var postcssExtend = require('postcss-extend');
var cssmin = require('gulp-cssmin');

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

gulp.task('serve', function() {
  browserSync({
    server: {
      baseDir: 'dist'
    }
  });
});

gulp.task('css', function () {
  var processors = [
    autoprefixer({ browsers: '> 5%' }),
    postcssImport,
    postcssSimpleVars,
    postcssHexRbga,
    postcssExtend,
    postcssNested,
    postcssMediaMinmax
  ];

    return gulp.src('src/styles/**/*.css')
        .pipe(postcss(processors))
        .pipe(cssmin())
        .pipe(gulp.dest('dist/'))
        .pipe(reload({ stream: true }));
});

gulp.task('html', function() {
  return gulp.src('src/**/*.html')
    .pipe(htmlmin({ collapseWhitespace: true }))
    .pipe(gulp.dest('dist'))
    .pipe(reload({ stream: true }));
});

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

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

gulp.task('watch', function () {
    gulp.watch('src/styles/**/*.css', [ 'css' ]);
    gulp.watch('src/**/*.html', [ 'html' ]);
});

gulp.task('default', [ 'serve', 'fonts', 'css', 'html', 'robots', 'watch' ]);
<|endoftext|>


<commit_before>'use strict';

// Include gulp and tools
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var changed = require('gulp-changed');
var del = require('del');
var gulp = require('gulp');
var gutil = require('gulp-util');
var jshint = require('gulp-jshint');
var notify = require('gulp-notify');
var sass = require('gulp-sass');
var size = require('gulp-size');
var runSequence = require('run-sequence');
var sourcemaps = require('gulp-sourcemaps');
var webpack = require('webpack');

var config = require('./webpack-config');
var reload = browserSync.reload;
var compiler = webpack(config);

var AUTOPREFIXER_BROWSERS = [
	'ie >= 11',
	'ie_mob >= 11',
	'ff >= 30',
	'chrome >= 34',
	'safari >= 8',
	'opera >= 23',
	'ios >= 8',
	'android >= 4.4',
];

// Build JS for the browser
gulp.task('webpack', function(callback){
	compiler.run(function(err, stats) {
		if (err) {
			 notify.onError({
				message: 'webpack error: <%= err.message %>'
			})
		}
		callback();
	})
});

gulp.task('scripts', ['webpack']);

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

// Copy Web Fonts To Dist
gulp.task('fonts:woff', function () {
	return gulp.src('app/styles/fonts/**')
		.pipe(gulp.dest('dist/fonts'))
		.pipe(size({title: 'fonts'}));
});

// Copy Icons To Dist
gulp.task('fonts:ionicons', function () {
	return gulp.src('app/styles/ionicons/font/*.woff')
		.pipe(gulp.dest('dist/ionicons'))
		.pipe(size({title: 'ionicons'}));
});

gulp.task('fonts', ['fonts:woff', 'fonts:ionicons'])

// Automatically Prefix CSS
gulp.task('styles:css', function () {
	return gulp.src('app/styles/**/*.css')
		.pipe(changed('app/styles'))
		.pipe(autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
		.pipe(gulp.dest('dist'))
		.pipe(size({title: 'styles:css'}));
});

// Compile Any Other Sass Files You Added (app/styles)
gulp.task('styles:scss', function () {
	return gulp.src('app/styles/**/*.scss')
		.pipe(sourcemaps.init())
		.pipe(sass())
		.pipe(sourcemaps.write())
		.on('error', notify.onError({
			message: 'styles:scss error: <%= error.message %>'
		}))
		.pipe(autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
		.pipe(gulp.dest('dist'))
		.pipe(size({title: 'styles:scss'}));
});

// Output Final CSS Styles
gulp.task('styles', ['styles:scss', 'styles:css']);

// Copy the html file
gulp.task('html', function () {
	return gulp.src('app/index.html')
		.pipe(gulp.dest('dist'))
		.pipe(size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['dist']));

// Watch Files For Changes & Reload
gulp.task('serve', ['webpack', 'html', 'styles', 'fonts'], function () {
	browserSync({
		notify: true,
		minify: false,
		server: {
			baseDir: ['dist', './']
		}
	});

	gulp.watch(['app/scripts/**/*.{js,es6}'], ['webpack', reload]);
	gulp.watch(['app/styles/**/*.scss'], ['styles:scss']);
	gulp.watch(['dist/**/*.css'], ['styles:css', reload]);
	gulp.watch(['app/scripts/**/*.js'], ['jshint']);
});

gulp.task('default', ['clean'], function(cb) {
	runSequence('styles', ['jshint', 'webpack', 'html', 'fonts'], cb);
});
<commit_msg>Remove some semicolons from gulpfile<commit_after>'use strict';

// Include gulp and tools
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var changed = require('gulp-changed');
var del = require('del');
var gulp = require('gulp');
var gutil = require('gulp-util');
var jshint = require('gulp-jshint');
var notify = require('gulp-notify');
var sass = require('gulp-sass');
var size = require('gulp-size');
var runSequence = require('run-sequence');
var sourcemaps = require('gulp-sourcemaps');
var webpack = require('webpack');

var config = require('./webpack-config');
var reload = browserSync.reload;
var compiler = webpack(config);

var AUTOPREFIXER_BROWSERS = [
	'ie >= 11',
	'ie_mob >= 11',
	'ff >= 30',
	'chrome >= 34',
	'safari >= 8',
	'opera >= 23',
	'ios >= 8',
	'android >= 4.4',
];

// Build JS for the browser
gulp.task('webpack', function(callback){
	compiler.run(function(err, stats) {
		if (err) {
			 notify.onError({
				message: 'webpack error: <%= err.message %>'
			})
		}
		callback();
	})
});

gulp.task('scripts', ['webpack']);

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

// Copy Web Fonts To Dist
gulp.task('fonts:woff', function () {
	return gulp.src('app/styles/fonts/**')
		.pipe(gulp.dest('dist/fonts'))
		.pipe(size({title: 'fonts'}));
});

// Copy Icons To Dist
gulp.task('fonts:ionicons', function () {
	return gulp.src('app/styles/ionicons/font/*.woff')
		.pipe(gulp.dest('dist/ionicons'))
		.pipe(size({title: 'ionicons'}))
});

gulp.task('fonts', ['fonts:woff', 'fonts:ionicons'])

// Automatically Prefix CSS
gulp.task('styles:css', function () {
	return gulp.src('app/styles/**/*.css')
		.pipe(changed('app/styles'))
		.pipe(autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
		.pipe(gulp.dest('dist'))
		.pipe(size({title: 'styles:css'}))
});

// Compile Any Other Sass Files You Added (app/styles)
gulp.task('styles:scss', function () {
	return gulp.src('app/styles/**/*.scss')
		.pipe(sourcemaps.init())
		.pipe(sass())
		.pipe(sourcemaps.write())
		.on('error', notify.onError({
			message: 'styles:scss error: <%= error.message %>'
		}))
		.pipe(autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
		.pipe(gulp.dest('dist'))
		.pipe(size({title: 'styles:scss'}))
});

// Output Final CSS Styles
gulp.task('styles', ['styles:scss', 'styles:css']);

// Copy the html file
gulp.task('html', function () {
	return gulp.src('app/index.html')
		.pipe(gulp.dest('dist'))
		.pipe(size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['dist']));

// Watch Files For Changes & Reload
gulp.task('serve', ['webpack', 'html', 'styles', 'fonts'], function () {
	browserSync({
		notify: true,
		minify: false,
		server: {
			baseDir: ['dist', './']
		}
	});

	gulp.watch(['app/scripts/**/*.{js,es6}'], ['webpack', reload]);
	gulp.watch(['app/styles/**/*.scss'], ['styles:scss']);
	gulp.watch(['dist/**/*.css'], ['styles:css', reload]);
	gulp.watch(['app/scripts/**/*.js'], ['jshint']);
});

gulp.task('default', ['clean'], function(cb) {
	runSequence('styles', ['jshint', 'webpack', 'html', 'fonts'], cb);
});
<|endoftext|>


<commit_before>var env = process.env.NODE_ENV || 'development',
	gulp = require('gulp'),
	browserify = require('browserify'),
	reactify = require('reactify'),
	transform = require('vinyl-transform'),
	nodemon = require('gulp-nodemon'),
	livereload = require('gulp-livereload'),
	stylus = require('gulp-stylus'),
	openWindow = require('gulp-open'),
	uglify = require('gulp-uglify'),
	rename = require('gulp-rename'),
	jasmine = require('gulp-jasmine'),
	paths = require('./configs/paths')[env],
	serverConf = require('./configs/server')[env];

/**
 * Browserify transform
 * @type {*|exports}
 */
var browserified = transform(function(filename) {
	var b = browserify(filename);
	b.transform(reactify, {extension: 'jsx'});
	return b.bundle();
});

/**
 * Sets up browserify bundling for the development environment.
 * Bundles and creates a file at the scripts folder in the assets directory.
 */
gulp.task('clientjs:dev', function() {
	return gulp.src(paths.source.clientMainScript)
		.pipe(browserified)
		.pipe(rename(paths.dist.clientMainScript))
		.pipe(gulp.dest(paths.dist.clientBundle));
});

/**
 * Sets up browserify bundling for the production environment.
 * Bundles, minify and creates a file at the scripts folder in the assets directory.
 */
gulp.task('clientjs:prod', function() {
	return gulp.src(paths.source.clientMainScript)
		.pipe(browserified)
		.pipe(uglify())
		.pipe(rename(paths.dist.clientMainScript))
		.pipe(gulp.dest(paths.dist.clientBundle));
});

/**
 * Sets up stylus compilation and bundling for the development environment.
 * Compiles, bundle and creates a file at the styles folder in the assets directory.
 */
gulp.task('styles:dev', function() {
	return gulp.src(paths.source.stylesMain)
        .pipe(stylus())
        .pipe(gulp.dest(paths.dist.styles));
});

/**
 * Sets up stylus compilation and bundling for the production environment.
 * Compiles, bundle, compress and creates a file at the styles folder in the assets directory.
 */
gulp.task('styles:prod', function() {
	return gulp.src(paths.source.stylesMain)
        .pipe(stylus({
        	compress: true
        }))
        .pipe(gulp.dest(paths.dist.styles));
});

/**
 * Builds the project for the development environment.
 */
gulp.task('build:dev',['clientjs:dev', 'styles:dev']);

/**
 * Builds the project for the production environment.
 */
gulp.task('build:prod', ['clientjs:prod', 'styles:prod']);

/**
 * Starts the server and monitor for any change, reloading the server and browser if any changes occur.
 */
gulp.task('serve:dev', ['build:dev'], function(done) {
	var serverStarted = false;

	livereload.listen();

	return nodemon({
		verbose: true,
		script: 'server.js',
		ext: 'js jsx jade styl',
		env: {'NODE_ENV': 'development', port: serverConf.port},
		ignore: paths.unwatchedFiles
	})
	.on('start', function() {
		if (!serverStarted) {
			done();

			serverStarted = true;
		}
	})
	.on('change', ['build:dev'])
	.on('restart', function() {
		console.log('Server restarted.');

		setTimeout(function() {
			livereload.changed();
		}, 150);
	});
});

/**
 * Starts the server for the production environment
 */
gulp.task('serve:prod', ['build:prod'], function() {
	nodemon({
		script: 'server.js',
		ext: 'js jsx jade styl',
		env: {'NODE_ENV': 'production', port: serverConf.port},
		ignore: paths.unwatchedFiles
	})
	.on('change', ['build:prod'])
	.on('restart', function() {
		console.log('Server restarted.');
	});
});

/**
 * Opens a browser at the server url
 */
gulp.task('start:development', ['serve:dev'], function() {
	return gulp.src(paths.source.clientMainScript)
		.pipe(openWindow('', {url: serverConf.url}))
});

/**
 * Run the tests in the test folder
 */
gulp.task('tests', function() {
	return gulp.src(paths.testsBlob)
		.pipe(jasmine());
});

/**
 * Sets the default task
 */
gulp.task('default', [env === 'development' ? 'start:development' : 'serve:prod']);<commit_msg>Fix broserify build.<commit_after>var env = process.env.NODE_ENV || 'development',
	gulp = require('gulp'),
	browserify = require('browserify'),
	reactify = require('reactify'),
	transform = require('vinyl-transform'),
	nodemon = require('gulp-nodemon'),
	livereload = require('gulp-livereload'),
	stylus = require('gulp-stylus'),
	openWindow = require('gulp-open'),
	uglify = require('gulp-uglify'),
	rename = require('gulp-rename'),
	jasmine = require('gulp-jasmine'),
	paths = require('./configs/paths')[env],
	serverConf = require('./configs/server')[env];

/**
 * Sets up browserify bundling for the development environment.
 * Bundles and creates a file at the scripts folder in the assets directory.
 */
gulp.task('clientjs:dev', function() {
	var browserified = transform(function(filename) {
		var b = browserify(filename);
		b.transform(reactify, {extension: 'jsx'});
		return b.bundle();
	});

	return gulp.src(paths.source.clientMainScript)
		.pipe(browserified)
		.pipe(rename(paths.dist.clientMainScript))
		.pipe(gulp.dest(paths.dist.clientBundle));
});

/**
 * Sets up browserify bundling for the production environment.
 * Bundles, minify and creates a file at the scripts folder in the assets directory.
 */
gulp.task('clientjs:prod', function() {
	var browserified = transform(function(filename) {
		var b = browserify(filename);
		b.transform(reactify, {extension: 'jsx'});
		return b.bundle();
	});

	return gulp.src(paths.source.clientMainScript)
		.pipe(browserified)
		.pipe(uglify())
		.pipe(rename(paths.dist.clientMainScript))
		.pipe(gulp.dest(paths.dist.clientBundle));
});

/**
 * Sets up stylus compilation and bundling for the development environment.
 * Compiles, bundle and creates a file at the styles folder in the assets directory.
 */
gulp.task('styles:dev', function() {
	return gulp.src(paths.source.stylesMain)
        .pipe(stylus())
        .pipe(gulp.dest(paths.dist.styles));
});

/**
 * Sets up stylus compilation and bundling for the production environment.
 * Compiles, bundle, compress and creates a file at the styles folder in the assets directory.
 */
gulp.task('styles:prod', function() {
	return gulp.src(paths.source.stylesMain)
        .pipe(stylus({
        	compress: true
        }))
        .pipe(gulp.dest(paths.dist.styles));
});

/**
 * Builds the project for the development environment.
 */
gulp.task('build:dev',['clientjs:dev', 'styles:dev']);

/**
 * Builds the project for the production environment.
 */
gulp.task('build:prod', ['clientjs:prod', 'styles:prod']);

/**
 * Starts the server and monitor for any change, reloading the server and browser if any changes occur.
 */
gulp.task('serve:dev', ['build:dev'], function(done) {
	var serverStarted = false;

	livereload.listen();

	return nodemon({
		verbose: true,
		script: 'server.js',
		ext: 'js jsx jade styl',
		env: {'NODE_ENV': 'development', port: serverConf.port},
		ignore: paths.unwatchedFiles
	})
	.on('start', function() {
		if (!serverStarted) {
			done();

			serverStarted = true;
		}
	})
	.on('change', ['build:dev'])
	.on('restart', function() {
		console.log('Server restarted.');

		setTimeout(function() {
			livereload.changed();
		}, 150);
	});
});

/**
 * Starts the server for the production environment
 */
gulp.task('serve:prod', ['build:prod'], function() {
	nodemon({
		script: 'server.js',
		ext: 'js jsx jade styl',
		env: {'NODE_ENV': 'production', port: serverConf.port},
		ignore: paths.unwatchedFiles
	})
	.on('change', ['build:prod'])
	.on('restart', function() {
		console.log('Server restarted.');
	});
});

/**
 * Opens a browser at the server url
 */
gulp.task('start:development', ['serve:dev'], function() {
	return gulp.src(paths.source.clientMainScript)
		.pipe(openWindow('', {url: serverConf.url}))
});

/**
 * Run the tests in the test folder
 */
gulp.task('tests', function() {
	return gulp.src(paths.testsBlob)
		.pipe(jasmine());
});

/**
 * Sets the default task
 */
gulp.task('default', [env === 'development' ? 'start:development' : 'serve:prod']);<|endoftext|>