<commit_before>var gulp = require('gulp'),
    path = require('path'),
    plugins = require('gulp-load-plugins')(),
    stylish = require('jshint-stylish'),
    runSequence = require('run-sequence'),
    java_path = path.resolve('node_modules/closurecompiler/jre/bin');
    process.env.PATH = java_path + ':' + process.env.PATH,
    paths = {
      tmp: '.gulptmp/',
      dest: 'cla_frontend/assets/',
      src: 'cla_frontend/assets-src/',
      images: [],
      fonts: [],
      styles: [],
      ng_partials: [],
      vendor_static: [],
      scripts: {}
    };

// styles
paths.styles.push(paths.src + 'stylesheets/**/*.scss');
// fonts
paths.fonts.push(paths.src + 'fonts/**/*');
// images
paths.images.push(paths.src + 'images/**/*');
// partials
paths.ng_partials.push(paths.src + 'javascripts/app/partials/**/*.html');
// partials
paths.vendor_static.push(paths.src + 'javascripts/vendor/**/*');
// scripts
paths.scripts = {
  vendor: [
    paths.src + 'vendor/lodash/dist/lodash.min.js',
    paths.src + 'vendor/jquery-details/jquery.details.js',
    paths.src + 'vendor/handlebars/handlebars.js',

    paths.src + 'vendor/angular/angular.js',
    paths.src + 'vendor/angular-sanitize/angular-sanitize.js',
    paths.src + 'vendor/angular-animate/angular-animate.js',
    paths.src + 'vendor/angular-resource/angular-resource.js',
    paths.src + 'vendor/angular-ui-router/release/angular-ui-router.js',
    paths.src + 'vendor/angular-i18n/angular-locale_en-gb.js',
    paths.src + 'vendor/moment/moment.js',
    paths.src + 'vendor/angular-moment/angular-moment.js',
    paths.src + 'javascripts/vendor/xeditable.js'
  ],
  app: [
    paths.tmp + 'javascripts/app/js/constants.js', // dynamically generated by gulp task
    paths.tmp + 'javascripts/app/partials/**/*', // dynamically generated by gulp task
    paths.src + 'javascripts/app/js/app.js',
    paths.src + 'javascripts/app/js/**/*.js'
  ],
  moj: [
    paths.src + 'javascripts/moj.Helpers.js',
    paths.src + 'javascripts/modules/*'
  ]
};

// clean out assets folder
gulp.task('clean-pre', function() {
  return gulp
    .src([paths.dest, paths.tmp], {read: false})
    .pipe(plugins.clean());
});
gulp.task('clean-post', function() {
  return gulp
    .src(paths.tmp, {read: false})
    .pipe(plugins.clean());
});

// compile scss
gulp.task('sass', function() {
  gulp
    .src(paths.styles)
    .pipe(plugins.rubySass({
      loadPath: 'node_modules/govuk_frontend_toolkit/' // add node module toolkit path
    }))
    .pipe(gulp.dest(paths.dest + 'stylesheets/'));
});

// copy across web fonts
gulp.task('fonts', function() {
  gulp
    .src(paths.fonts)
    .pipe(gulp.dest(paths.dest + 'fonts'));
});

// optimise images
gulp.task('images', function() {
  gulp
    .src(paths.images)
    .pipe(plugins.imagemin({optimizationLevel: 5}))
    .pipe(gulp.dest(paths.dest + 'images'));
});

// static vendor files
gulp.task('vendor', function() {
  gulp
    .src(paths.vendor_static)
    .pipe(gulp.dest(paths.dest + 'javascripts/vendor/'));
});

// convert django cla_common constants into angular constants
gulp.task('ng-constants', function () {
  return gulp
    .src(paths.src + 'javascripts/app/constants.json')
    .pipe(plugins.ngConstant({
      name: 'cla.constants'
    }))
    // Writes config.js to dist folder
    .pipe(gulp.dest(paths.tmp + 'javascripts/app/js/'));
});

// angular partials
gulp.task('ng-templates', function(){
  return gulp.src(paths.ng_partials)
    .pipe(plugins.angularTemplates({module: 'cla.templates'}))
    .pipe(gulp.dest(paths.tmp + 'javascripts/app/partials/'));
});

// concat js files
gulp.task('js-concat', ['ng-constants', 'ng-templates'], function() {
  var concat = paths.scripts.vendor
                  .concat(paths.scripts.app)
                  .concat(paths.scripts.moj);

  return gulp
    .src(concat)
    .pipe(plugins.concat('cla.main.js'))
    .pipe(gulp.dest(paths.dest + 'javascripts/'));
});

gulp.task('js-compile', ['js-concat'], function(){
  var src_path = paths.dest + 'javascripts/cla.main.js';

  return gulp.src(src_path)
    .pipe(plugins.closureCompiler({
      compilerPath: 'node_modules/closurecompiler/compiler/compiler.jar',
      fileName: 'cla.main.min.js',
      compilerFlags: {
        language_in: 'ECMASCRIPT5',
        warning_level: 'QUIET',
        compilation_level: 'WHITESPACE_ONLY',
      }
    }))
    .pipe(gulp.dest(paths.dest + 'javascripts/'));
});

// jshint js code
gulp.task('lint', function() {
  var files = paths.scripts.app.concat(paths.scripts.moj);

  gulp
    .src(files)
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter(stylish));
});

// setup watches
gulp.task('watch', function() {
  gulp.watch(paths.fonts, ['fonts']);
  gulp.watch(paths.styles, ['sass']);
  gulp.watch(paths.images, ['images']);
  gulp.watch(paths.src_dir + 'javascripts/**/*', ['lint', 'js-release']);
});

// setup default task
gulp.task('default', function() {
  runSequence('clean-pre', ['sass', 'fonts', 'images', 'vendor', 'js-compile']);
});
<commit_msg>Fix broken concat<commit_after>var gulp = require('gulp'),
    path = require('path'),
    plugins = require('gulp-load-plugins')(),
    stylish = require('jshint-stylish'),
    runSequence = require('run-sequence'),
    java_path = path.resolve('node_modules/closurecompiler/jre/bin');
    process.env.PATH = java_path + ':' + process.env.PATH,
    paths = {
      tmp: '.gulptmp/',
      dest: 'cla_frontend/assets/',
      src: 'cla_frontend/assets-src/',
      images: [],
      fonts: [],
      styles: [],
      ng_partials: [],
      vendor_static: [],
      scripts: {}
    };

// styles
paths.styles.push(paths.src + 'stylesheets/**/*.scss');
// fonts
paths.fonts.push(paths.src + 'fonts/**/*');
// images
paths.images.push(paths.src + 'images/**/*');
// partials
paths.ng_partials.push(paths.src + 'javascripts/app/partials/**/*.html');
// partials
paths.vendor_static.push(paths.src + 'javascripts/vendor/**/*');
// scripts
paths.scripts = {
  vendor: [
    paths.src + 'vendor/lodash/dist/lodash.min.js',
    paths.src + 'vendor/jquery-details/jquery.details.js',
    paths.src + 'vendor/handlebars/handlebars.js',
    // angular specific
    paths.src + 'vendor/angular/angular.js',
    paths.src + 'vendor/angular-sanitize/angular-sanitize.js',
    paths.src + 'vendor/angular-animate/angular-animate.js',
    paths.src + 'vendor/angular-resource/angular-resource.js',
    paths.src + 'vendor/angular-ui-router/release/angular-ui-router.js',
    paths.src + 'vendor/angular-i18n/angular-locale_en-gb.js',
    paths.src + 'vendor/moment/moment.js',
    paths.src + 'vendor/angular-moment/angular-moment.js',
    paths.src + 'javascripts/vendor/xeditable.js'
  ],
  app: [
    paths.src + 'javascripts/app/js/app.js',
    paths.tmp + 'javascripts/app/js/constants.js', // dynamically generated by gulp task (ng-constants)
    paths.tmp + 'javascripts/app/partials/**/*', // dynamically generated by gulp task (ng-templates)
    paths.src + 'javascripts/app/js/**/*.js'
  ],
  moj: [
    paths.src + 'javascripts/moj.Helpers.js',
    paths.src + 'javascripts/modules/*'
  ]
};

// clean out assets folder
gulp.task('clean-pre', function() {
  return gulp
    .src([paths.dest, paths.tmp], {read: false})
    .pipe(plugins.clean());
});
gulp.task('clean-post', function() {
  return gulp
    .src(paths.tmp, {read: false})
    .pipe(plugins.clean());
});

// compile scss
gulp.task('sass', function() {
  gulp
    .src(paths.styles)
    .pipe(plugins.rubySass({
      loadPath: 'node_modules/govuk_frontend_toolkit/' // add node module toolkit path
    }))
    .pipe(gulp.dest(paths.dest + 'stylesheets/'));
});

// copy across web fonts
gulp.task('fonts', function() {
  gulp
    .src(paths.fonts)
    .pipe(gulp.dest(paths.dest + 'fonts'));
});

// optimise images
gulp.task('images', function() {
  gulp
    .src(paths.images)
    .pipe(plugins.imagemin({optimizationLevel: 5}))
    .pipe(gulp.dest(paths.dest + 'images'));
});

// static vendor files
gulp.task('vendor', function() {
  gulp
    .src(paths.vendor_static)
    .pipe(gulp.dest(paths.dest + 'javascripts/vendor/'));
});

// convert django cla_common constants into angular constants
gulp.task('ng-constants', function () {
  return gulp
    .src(paths.src + 'javascripts/app/constants.json')
    .pipe(plugins.ngConstant({
      name: 'cla.constants'
    }))
    // Writes config.js to dist folder
    .pipe(gulp.dest(paths.tmp + 'javascripts/app/js/'));
});

// angular partials
gulp.task('ng-templates', function(){
  return gulp.src(paths.ng_partials)
    .pipe(plugins.angularTemplates({module: 'cla.templates'}))
    .pipe(gulp.dest(paths.tmp + 'javascripts/app/partials/'));
});

// concat js files
gulp.task('js-concat', ['ng-constants', 'ng-templates'], function() {
  var concat = paths.scripts.vendor
                  .concat(paths.scripts.app)
                  .concat(paths.scripts.moj);

  return gulp
    .src(concat)
    .pipe(plugins.concat('cla.main.js'))
    .pipe(gulp.dest(paths.dest + 'javascripts/'));
});

gulp.task('js-compile', ['js-concat'], function(){
  var src_path = paths.dest + 'javascripts/cla.main.js';

  return gulp.src(src_path)
    .pipe(plugins.closureCompiler({
      compilerPath: 'node_modules/closurecompiler/compiler/compiler.jar',
      fileName: 'cla.main.min.js',
      compilerFlags: {
        language_in: 'ECMASCRIPT5',
        warning_level: 'QUIET',
        compilation_level: 'WHITESPACE_ONLY',
      }
    }))
    .pipe(gulp.dest(paths.dest + 'javascripts/'));
});

// jshint js code
gulp.task('lint', function() {
  var files = paths.scripts.app.concat(paths.scripts.moj);

  gulp
    .src(files)
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter(stylish));
});

// setup watches
gulp.task('watch', function() {
  gulp.watch(paths.fonts, ['fonts']);
  gulp.watch(paths.styles, ['sass']);
  gulp.watch(paths.images, ['images']);
  gulp.watch(paths.vendor_static, ['vendor']);
  gulp.watch(paths.src + 'javascripts/**/*', ['lint', 'js-concat']);
});

// setup default task
gulp.task('default', function() {
  runSequence('clean-pre', ['sass', 'fonts', 'images', 'vendor', 'js-compile']);
});
<|endoftext|>


<commit_before>import extend from 'extend';
import Delta from 'rich-text/lib/delta';
import Parchment from 'parchment';
import Quill from '../core/quill';
import logger from '../core/logger';
import Module from '../core/module';
import { Range } from '../core/selection';

let debug = logger('quill:toolbar');

class Toolbar extends Module {
  constructor(quill, options) {
    super(quill, options);
    if (Array.isArray(this.options.container)) {
      let container = document.createElement('div');
      addControls(container, this.options.container);
      quill.container.parentNode.insertBefore(container, quill.container);
      this.container = container;
    } else if (typeof this.options.container === 'string') {
      this.container = document.querySelector(this.options.container);
    } else {
      this.container = this.options.container;
    }
    if (!(this.container instanceof HTMLElement)) {
      return debug.error('Container required for toolbar', this.options);
    }
    this.container.classList.add('ql-toolbar');
    this.controls = [];
    this.handlers = {};
    Object.keys(this.options.handlers).forEach((format) => {
      this.addHandler(format, this.options.handlers[format]);
    });
    this.container.addEventListener('mousedown', function(e) {
      e.preventDefault();   // Prevent blur
    });
    [].forEach.call(this.container.querySelectorAll('button, select'), (input) => {
      this.attach(input);
    });
    this.quill.on(Quill.events.EDITOR_CHANGE, (type, range) => {
      if (type === Quill.events.SELECTION_CHANGE) {
        this.update(range);
      }
    });
    this.quill.on(Quill.events.SCROLL_OPTIMIZE, () => {
      let [range, ] = this.quill.selection.getRange();  // quill.getSelection triggers update
      this.update(range);
    });
  }

  addHandler(format, handler) {
    this.handlers[format] = handler;
  }

  attach(input) {
    let format = [].find.call(input.classList, (className) => {
      return className.indexOf('ql-') === 0;
    });
    if (!format) return;
    format = format.slice('ql-'.length);
    if (input.tagName === 'BUTTON') {
      input.setAttribute('type', 'button');
    }
    if (this.handlers[format] == null) {
      if (this.quill.scroll.whitelist != null && this.quill.scroll.whitelist[format] == null) {
        debug.warn('ignoring attaching to disabled format', format, input);
        return;
      }
      if (Parchment.query(format) == null) {
        debug.warn('ignoring attaching to nonexistent format', format, input);
        return;
      }
    }
    let eventName = input.tagName === 'SELECT' ? 'change' : 'click';
    input.addEventListener(eventName, (e) => {
      let value;
      if (input.tagName === 'SELECT') {
        if (input.selectedIndex < 0) return;
        let selected = input.options[input.selectedIndex];
        if (selected.hasAttribute('selected')) {
          value = false;
        } else {
          value = selected.value || false;
        }
      } else {
        if (input.classList.contains('ql-active')) {
          value = false;
        } else {
          value = input.value || !input.hasAttribute('value');
        }
        e.preventDefault();
      }
      this.quill.focus();
      let [range, ] = this.quill.selection.getRange();
      if (this.handlers[format] != null) {
        this.handlers[format].call(this, value);
      } else if (Parchment.query(format).prototype instanceof Parchment.Embed) {
        this.quill.updateContents(new Delta()
          .retain(range.index)
          .delete(range.length)
          .insert({ [format]: true })
        , Quill.sources.USER);
      } else {
        this.quill.format(format, value, Quill.sources.USER);
      }
      this.update(range);
    });
    // TODO use weakmap
    this.controls.push([format, input]);
  }

  update(range) {
    let formats = range == null ? {} : this.quill.getFormat(range);
    this.controls.forEach(function(pair) {
      let [format, input] = pair;
      if (input.tagName === 'SELECT') {
        let option;
        if (range == null) {
          option = null;
        } else if (formats[format] == null) {
          option = input.querySelector('option[selected]');
        } else if (!Array.isArray(formats[format])) {
          let value = formats[format];
          if (typeof value === 'string') {
            value = value.replace(/\"/g, '"');
          }
          option = input.querySelector(`option[value="${value}"]`);
        }
        if (option == null) {
          input.value = '';   // TODO make configurable?
          input.selectedIndex = -1;
        } else {
          option.selected = true;
        }
      } else {
        if (range == null) {
          input.classList.remove('ql-active');
        } else if (input.hasAttribute('value')) {
          // both being null should match (default values)
          // '1' should match with 1 (headers)
          input.classList.toggle('ql-active', formats[format] == input.value || (formats[format] == null && !input.value));
        } else {
          input.classList.toggle('ql-active', formats[format] != null);
        }
      }
    });
  }
}
Toolbar.DEFAULTS = {};

function addButton(container, format, value) {
  let input = document.createElement('button');
  input.setAttribute('type', 'button');
  input.classList.add('ql-' + format);
  if (value != null) {
    input.value = value;
  }
  container.appendChild(input);
}

function addControls(container, groups) {
  if (!Array.isArray(groups[0])) {
    groups = [groups];
  }
  groups.forEach(function(controls) {
    let group = document.createElement('span');
    group.classList.add('ql-formats');
    controls.forEach(function(control) {
      if (typeof control === 'string') {
        addButton(group, control);
      } else {
        let format = Object.keys(control)[0];
        let value = control[format];
        if (Array.isArray(value)) {
          addSelect(group, format, value);
        } else {
          addButton(group, format, value);
        }
      }
    });
    container.appendChild(group);
  });
}

function addSelect(container, format, values) {
  let input = document.createElement('select');
  input.classList.add('ql-' + format);
  values.forEach(function(value) {
    let option = document.createElement('option');
    if (value !== false) {
      option.setAttribute('value', value);
    } else {
      option.setAttribute('selected', 'selected');
    }
    input.appendChild(option);
  });
  container.appendChild(input);
}

Toolbar.DEFAULTS = {
  container: null,
  handlers: {
    clean: function(value) {
      let range = this.quill.getSelection();
      if (range == null) return;
      if (range.length == 0) {
        let formats = this.quill.getFormat();
        Object.keys(formats).forEach((name) => {
          // Clean functionality in existing apps only clean inline formats
          if (Parchment.query(name, Parchment.Scope.INLINE) != null) {
            this.quill.format(name, false);
          }
        });
      } else {
        this.quill.removeFormat(range, Quill.sources.USER);
      }
    },
    direction: function(value) {
      let align = this.quill.getFormat()['align'];
      if (value === 'rtl' && align == null) {
        this.quill.format('align', 'right', Quill.sources.USER);
      } else if (!value && align === 'right') {
        this.quill.format('align', false, Quill.sources.USER);
      }
      this.quill.format('direction', value, Quill.sources.USER);
    },
    indent: function(value) {
      let range = this.quill.getSelection();
      let formats = this.quill.getFormat(range);
      let indent = parseInt(formats.indent || 0);
      if (value === '+1') {
        this.quill.format('indent', indent + 1, Quill.sources.USER);
      } else if (value === '-1') {
        this.quill.format('indent', indent - 1, Quill.sources.USER);
      }
    }
  }
}

export { Toolbar as default, addControls };
<commit_msg>handlers for no theme behavior<commit_after>import extend from 'extend';
import Delta from 'rich-text/lib/delta';
import Parchment from 'parchment';
import Quill from '../core/quill';
import logger from '../core/logger';
import Module from '../core/module';
import { Range } from '../core/selection';

let debug = logger('quill:toolbar');

class Toolbar extends Module {
  constructor(quill, options) {
    super(quill, options);
    if (Array.isArray(this.options.container)) {
      let container = document.createElement('div');
      addControls(container, this.options.container);
      quill.container.parentNode.insertBefore(container, quill.container);
      this.container = container;
    } else if (typeof this.options.container === 'string') {
      this.container = document.querySelector(this.options.container);
    } else {
      this.container = this.options.container;
    }
    if (!(this.container instanceof HTMLElement)) {
      return debug.error('Container required for toolbar', this.options);
    }
    this.container.classList.add('ql-toolbar');
    this.controls = [];
    this.handlers = {};
    Object.keys(this.options.handlers).forEach((format) => {
      this.addHandler(format, this.options.handlers[format]);
    });
    this.container.addEventListener('mousedown', function(e) {
      e.preventDefault();   // Prevent blur
    });
    [].forEach.call(this.container.querySelectorAll('button, select'), (input) => {
      this.attach(input);
    });
    this.quill.on(Quill.events.EDITOR_CHANGE, (type, range) => {
      if (type === Quill.events.SELECTION_CHANGE) {
        this.update(range);
      }
    });
    this.quill.on(Quill.events.SCROLL_OPTIMIZE, () => {
      let [range, ] = this.quill.selection.getRange();  // quill.getSelection triggers update
      this.update(range);
    });
  }

  addHandler(format, handler) {
    this.handlers[format] = handler;
  }

  attach(input) {
    let format = [].find.call(input.classList, (className) => {
      return className.indexOf('ql-') === 0;
    });
    if (!format) return;
    format = format.slice('ql-'.length);
    if (input.tagName === 'BUTTON') {
      input.setAttribute('type', 'button');
    }
    if (this.handlers[format] == null) {
      if (this.quill.scroll.whitelist != null && this.quill.scroll.whitelist[format] == null) {
        debug.warn('ignoring attaching to disabled format', format, input);
        return;
      }
      if (Parchment.query(format) == null) {
        debug.warn('ignoring attaching to nonexistent format', format, input);
        return;
      }
    }
    let eventName = input.tagName === 'SELECT' ? 'change' : 'click';
    input.addEventListener(eventName, (e) => {
      let value;
      if (input.tagName === 'SELECT') {
        if (input.selectedIndex < 0) return;
        let selected = input.options[input.selectedIndex];
        if (selected.hasAttribute('selected')) {
          value = false;
        } else {
          value = selected.value || false;
        }
      } else {
        if (input.classList.contains('ql-active')) {
          value = false;
        } else {
          value = input.value || !input.hasAttribute('value');
        }
        e.preventDefault();
      }
      this.quill.focus();
      let [range, ] = this.quill.selection.getRange();
      if (this.handlers[format] != null) {
        this.handlers[format].call(this, value);
      } else if (Parchment.query(format).prototype instanceof Parchment.Embed) {
        value = prompt(`Enter ${format}`);
        if (!value) return;
        this.quill.updateContents(new Delta()
          .retain(range.index)
          .delete(range.length)
          .insert({ [format]: value })
        , Quill.sources.USER);
      } else {
        this.quill.format(format, value, Quill.sources.USER);
      }
      this.update(range);
    });
    // TODO use weakmap
    this.controls.push([format, input]);
  }

  update(range) {
    let formats = range == null ? {} : this.quill.getFormat(range);
    this.controls.forEach(function(pair) {
      let [format, input] = pair;
      if (input.tagName === 'SELECT') {
        let option;
        if (range == null) {
          option = null;
        } else if (formats[format] == null) {
          option = input.querySelector('option[selected]');
        } else if (!Array.isArray(formats[format])) {
          let value = formats[format];
          if (typeof value === 'string') {
            value = value.replace(/\"/g, '"');
          }
          option = input.querySelector(`option[value="${value}"]`);
        }
        if (option == null) {
          input.value = '';   // TODO make configurable?
          input.selectedIndex = -1;
        } else {
          option.selected = true;
        }
      } else {
        if (range == null) {
          input.classList.remove('ql-active');
        } else if (input.hasAttribute('value')) {
          // both being null should match (default values)
          // '1' should match with 1 (headers)
          input.classList.toggle('ql-active', formats[format] == input.value || (formats[format] == null && !input.value));
        } else {
          input.classList.toggle('ql-active', formats[format] != null);
        }
      }
    });
  }
}
Toolbar.DEFAULTS = {};

function addButton(container, format, value) {
  let input = document.createElement('button');
  input.setAttribute('type', 'button');
  input.classList.add('ql-' + format);
  if (value != null) {
    input.value = value;
  }
  container.appendChild(input);
}

function addControls(container, groups) {
  if (!Array.isArray(groups[0])) {
    groups = [groups];
  }
  groups.forEach(function(controls) {
    let group = document.createElement('span');
    group.classList.add('ql-formats');
    controls.forEach(function(control) {
      if (typeof control === 'string') {
        addButton(group, control);
      } else {
        let format = Object.keys(control)[0];
        let value = control[format];
        if (Array.isArray(value)) {
          addSelect(group, format, value);
        } else {
          addButton(group, format, value);
        }
      }
    });
    container.appendChild(group);
  });
}

function addSelect(container, format, values) {
  let input = document.createElement('select');
  input.classList.add('ql-' + format);
  values.forEach(function(value) {
    let option = document.createElement('option');
    if (value !== false) {
      option.setAttribute('value', value);
    } else {
      option.setAttribute('selected', 'selected');
    }
    input.appendChild(option);
  });
  container.appendChild(input);
}

Toolbar.DEFAULTS = {
  container: null,
  handlers: {
    clean: function(value) {
      let range = this.quill.getSelection();
      if (range == null) return;
      if (range.length == 0) {
        let formats = this.quill.getFormat();
        Object.keys(formats).forEach((name) => {
          // Clean functionality in existing apps only clean inline formats
          if (Parchment.query(name, Parchment.Scope.INLINE) != null) {
            this.quill.format(name, false);
          }
        });
      } else {
        this.quill.removeFormat(range, Quill.sources.USER);
      }
    },
    direction: function(value) {
      let align = this.quill.getFormat()['align'];
      if (value === 'rtl' && align == null) {
        this.quill.format('align', 'right', Quill.sources.USER);
      } else if (!value && align === 'right') {
        this.quill.format('align', false, Quill.sources.USER);
      }
      this.quill.format('direction', value, Quill.sources.USER);
    },
    link: function(value) {
      if (value === true) {
        value = prompt('Enter link URL:');
      }
      this.quill.format('link', value, Quill.sources.USER);
    },
    indent: function(value) {
      let range = this.quill.getSelection();
      let formats = this.quill.getFormat(range);
      let indent = parseInt(formats.indent || 0);
      if (value === '+1') {
        this.quill.format('indent', indent + 1, Quill.sources.USER);
      } else if (value === '-1') {
        this.quill.format('indent', indent - 1, Quill.sources.USER);
      }
    }
  }
}

export { Toolbar as default, addControls };
<|endoftext|>


<commit_before>// require esphinx/support/array
// require esphinx/support/singleton

// require esphinx_ui
// require esphinx/support/ajax
// require esphinx/observer

"use strict";

var
    esPhinx,
    Singleton;

(function ($module) {

    var
        minimized = [],
        visible;

    $module.extend({

        windows: {

            modal: {

                hide: function (animation) {
                    visible.hide(animation);
                },

                close: function () {
                    visible.close();
                },

                // functions are objects in js
                new: function (options) {
                    var
                        self = $module.windows.modal.new,
                        mainReference = this,
                        args = Array.from(arguments),

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

                        modal,
                        mask,
                        main,
                        container,
                        closeButton,
                        hideButton,
                        headers,
                        params,
                        asynchronousAnswer,
                        imgControl,
                        singleton,
                        index,
                        _windowController,

                        isMinimized = function () {
                            var
                                index;

                            if (index = minimized
                                .indexPerEquivalence(this)) {
                                return index;
                            }

                            return false;
                        },

                        addToMinimized = function () {
                            if (!isMinimized.call(this)) {
                                minimized.push(this);
                            }
                        },

                        removeFromMinimized = function () {
                            var
                                index;

                            if (index = isMinimized.call(this)) {
                                minimized.delete(index);
                            }
                        },

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

                            visible = mainReference;
                            // debugger

                            removeFromMinimized.call(this);
                        },

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

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

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

                            if (typeof options.windowController != "boolean") {
                                _windowController = false;
                            } else {
                                _windowController = options.windowController;
                            }

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

                            if (options.content) {
                                options.url = false;
                            }
                        },

                        resolveHeaderActions = function (main, options) {
                            var
                                container = main.find(".container"),
                                childNodesCount = container.childNodes()
                                    .count(),
                                imgsCount = container.find("img").count(),
                                header,
                                actions;

                            if (childNodesCount == 1
                                && imgsCount == 1
                                && !_windowController) {
                                _windowController = false;
                            } else {
                                _windowController = true;
                            }

                            if (_windowController) {
                                header = $("");
                                actions = $("

").addClass("actions");
                                hideButton = $('')
                                    .addClass("hide-button");

                                header.append(actions);

                                if (options.closeButton) {
                                    closeButton = $('')
                                        .addClass("close-button");
                                    actions.append(closeButton);
                                }

                                actions.append(hideButton);

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

                                bindHeaderEventListeners();
                            }
                        },

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

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

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

                        },

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

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

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

                                            return false;
                                        },
                                        ready: function () {
                                            mainReference.hide(false);

                                            resolveHeaderActions(main, options);
                                            main.centralizeAt(document);
                                            if (!asynchronousAnswer) {
                                                mainReference.show();
                                            }

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

                                } else {
                                    resolveHeaderActions(main, options);
                                    main.centralizeAt(document);
                                    if (options.complete) {
                                        options.complete.call(mainReference);
                                    }
                                }

                                this.disconnect();
                            });
                        },

                        create = function () {
                            modal = $("

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

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

").addClass("container");

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

                            body.append(modal);

                            observeContent(main, options);

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

                        };

                    resolveParams();

                    if (!(this instanceof self)) {
                        // debugger
                        // if (!self.instance) {
                        //     return self.singleton(arguments);
                        // } else if (isMinimized.call(self.instance)) {
                        //     self.instance.show();
                        // }

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

                    } else {

                        // global scope (public)

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

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

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

                            mask.addClass("transparent");
                            addToMinimized.call(this);

                            return mainReference;
                        };

                        this.show = function () {
                            show(mainReference);

                            return mainReference;
                        };

                        this.close = function () {
                            main.hide();

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

                            mask.addClass("transparent");
                            modal.remove(maskTransitionDuration(mask));
                            mainReference.deleteSingleton();

                            return mainReference;
                        };

                        create();
                    }

                    return mainReference;
                }

            }

        }

    });

}(esPhinx.ui));
<commit_msg>refactor modal<commit_after>// require esphinx/support/array
// require esphinx/support/singleton

// require esphinx_ui
// require esphinx/support/ajax
// require esphinx/observer

"use strict";

var
    esPhinx,
    Singleton;

(function ($module) {

    var
        minimized = [],
        visible;

    $module.extend({

        windows: {

            modal: {

                hide: function (animation) {
                    visible.hide(animation);
                },

                close: function () {
                    visible.close();
                },

                // functions are objects in js
                new: function (options) {
                    var
                        self = $module.windows.modal.new,
                        mainReference = this,
                        args = Array.from(arguments),

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

                        modal,
                        mask,
                        main,
                        container,
                        closeButton,
                        hideButton,
                        headers,
                        params,
                        asynchronousAnswer,
                        imgControl,
                        singleton,
                        index,
                        _windowController,

                        isMinimized = function () {
                            var
                                index;

                            if (index = minimized
                                .indexPerEquivalence(this)) {
                                return index;
                            }

                            return false;
                        },

                        addToMinimized = function () {
                            if (!isMinimized.call(this)) {
                                minimized.push(this);
                            }
                        },

                        removeFromMinimized = function () {
                            var
                                index;

                            if (index = isMinimized.call(this)) {
                                minimized.delete(index);
                            }
                        },

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

                            visible = mainReference;
                            // debugger

                            removeFromMinimized.call(this);
                        },

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

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

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

                            if (typeof options.windowController != "boolean") {
                                _windowController = false;
                            } else {
                                _windowController = options.windowController;
                            }

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

                            if (options.content) {
                                options.url = false;
                            }
                        },

                        resolveHeaderActions = function (main, options) {
                            var
                                container = main.find(".container"),
                                childNodesCount = container.childNodes()
                                    .count(),
                                imgsCount = container.find("img").count(),
                                header,
                                actions;

                            if (childNodesCount > 1
                                || (childNodesCount == 1 && !imgsCount)
                                || _windowController) {
                                header = $("");
                                actions = $("

").addClass("actions");
                                hideButton = $('')
                                    .addClass("hide-button");

                                header.append(actions);

                                if (options.closeButton) {
                                    closeButton = $('')
                                        .addClass("close-button");
                                    actions.append(closeButton);
                                }

                                actions.append(hideButton);

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

                                bindHeaderEventListeners();
                            }

                        },

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

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

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

                        },

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

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

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

                                            return false;
                                        },
                                        ready: function () {
                                            mainReference.hide(false);

                                            resolveHeaderActions(main, options);
                                            main.centralizeAt(document);
                                            if (!asynchronousAnswer) {
                                                mainReference.show();
                                            }

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

                                } else {
                                    resolveHeaderActions(main, options);
                                    main.centralizeAt(document);
                                    if (options.complete) {
                                        options.complete.call(mainReference);
                                    }
                                }

                                this.disconnect();
                            });
                        },

                        create = function () {
                            modal = $("

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

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

").addClass("container");

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

                            body.append(modal);

                            observeContent(main, options);

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

                        };

                    resolveParams();

                    if (!(this instanceof self)) {
                        // debugger
                        // if (!self.instance) {
                        //     return self.singleton(arguments);
                        // } else if (isMinimized.call(self.instance)) {
                        //     self.instance.show();
                        // }

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

                    } else {

                        // global scope (public)

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

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

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

                            mask.addClass("transparent");
                            addToMinimized.call(this);

                            return mainReference;
                        };

                        this.show = function () {
                            show(mainReference);

                            return mainReference;
                        };

                        this.close = function () {
                            main.hide();

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

                            mask.addClass("transparent");
                            modal.remove(maskTransitionDuration(mask));
                            mainReference.deleteSingleton();

                            return mainReference;
                        };

                        create();
                    }

                    return mainReference;
                }

            }

        }

    });

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


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

const child   = require( 'child_process' );
const fs      = require( 'fs' );
const util    = require( 'util' );
const rimraf  = require( 'rimraf-promise' );
const mkdirp  = util.promisify( require( 'mkdirp' ) );
const replace = require( 'replace' );

const libphonenumberVersion =
	fs.readFileSync( 'libphonenumber.version', 'utf8' ).toString( ).trim( );

const buildRoot = './build';
const libphonenumberUrl = 'https://github.com/googlei18n/libphonenumber/';
const closureLibraryUrl = 'https://github.com/google/closure-library/';
const closureLinterUrl = 'https://github.com/google/closure-linter';
const pythonGflagsUrl = 'https://github.com/google/python-gflags.git';
const antName = 'apache-ant-1.10.5';
const antTar = `${antName}.tar.gz`;
const antUrl = `http://apache.mirrors.spacedump.net/ant/binaries/${antName}-bin.tar.gz`;

const isDebug = process.env.DEBUG && process.env.DEBUG !== '0';

gulp.task( 'clean', ( ) =>
	rimraf( buildRoot )
);

gulp.task( 'make-build-dir', ( ) =>
	mkdirp( buildRoot )
);

gulp.task( 'clone-libphonenumber', gulp.series( 'make-build-dir', ( ) =>
	gitClone( libphonenumberUrl, 'libphonenumber', libphonenumberVersion )
) );

gulp.task( 'clone-closure-library', gulp.series( 'make-build-dir', ( ) =>
	gitClone( closureLibraryUrl, 'closure-library', 'v20171112' )
) );

gulp.task( 'checkout-closure-linter', gulp.series( 'make-build-dir', ( ) =>
	gitClone( closureLinterUrl, 'closure-linter' )
) );

gulp.task( 'checkout-python-gflags', gulp.series( 'make-build-dir', ( ) =>
	gitClone( pythonGflagsUrl, 'python-gflags' )
) );

gulp.task( 'download-ant', gulp.series(
	'make-build-dir',
	( ) =>
		runCommand(
			'curl',
			[ '-L', '-o', antTar, antUrl ],
			{ cwd: buildRoot }
		),
	( ) =>
		runCommand(
			'tar',
			[ 'zxf', antTar ],
			{ cwd: buildRoot }
		)
) );

gulp.task( 'download-deps', gulp.parallel(
	'clone-libphonenumber',
	'clone-closure-library',
	'checkout-closure-linter',
	'checkout-python-gflags',
	'download-ant'
) );

gulp.task( 'build-deps', gulp.series( 'download-deps' ) );

gulp.task( 'build-libphonenumber', ( ) => {
	var args = [ '-f', 'build.xml', 'compile-exports' ];
	return runCommand( `${buildRoot}/${antName}/bin/ant`, args, { cwd: '.' } );
} );

gulp.task( 'build', gulp.series( 'build-deps', 'build-libphonenumber' ) );

gulp.task( 'update-readme', ( ) =>
	updateReadme( )
);

gulp.task( 'default', gulp.series( 'clean', 'build', 'update-readme' ) );

async function updateReadme( )
{
	replace( {
		regex: 'Uses libphonenumber ([A-Za-z.0-9]+)',
		replacement: `Uses libphonenumber ${libphonenumberVersion}`,
		paths: [ 'README.md' ],
		silent: true,
	} );
}

function gitClone( url, name, branch )
{
	const args = [ '--depth=1' ];
	if ( branch )
		args.push( '--branch=' + branch );

	return runCommand( 'git', [ 'clone', ...args, url, name ] );
}

function runCommand( cmd, args, opts )
{
	opts = opts || {
		cwd   : './build',
		stdio : [ null, null, isDebug ? process.stderr : null ]
	};

	return new Promise( function( resolve, reject ) {
		var cp = child.spawn( cmd, args, opts );
		cp.stdout.on( 'data', data => {
			if ( isDebug )
				console.log( data.toString( ) );
		} );
		cp.on( 'close', code => {
			if ( code === 0 )
				return resolve( );
			reject( new Error(
				`${cmd} exited with exitcode ${code}. Args: ${args}` ) );
		} );
		cp.on( 'error', err => reject( err ) );
	} );
}
<commit_msg>build(ant): Bumped version<commit_after>
const gulp = require( 'gulp' );

const child   = require( 'child_process' );
const fs      = require( 'fs' );
const util    = require( 'util' );
const rimraf  = require( 'rimraf-promise' );
const mkdirp  = util.promisify( require( 'mkdirp' ) );
const replace = require( 'replace' );

const libphonenumberVersion =
	fs.readFileSync( 'libphonenumber.version', 'utf8' ).toString( ).trim( );

const buildRoot = './build';
const libphonenumberUrl = 'https://github.com/googlei18n/libphonenumber/';
const closureLibraryUrl = 'https://github.com/google/closure-library/';
const closureLinterUrl = 'https://github.com/google/closure-linter';
const pythonGflagsUrl = 'https://github.com/google/python-gflags.git';
const antName = 'apache-ant-1.10.7';
const antTar = `${antName}.tar.gz`;
const antUrl = `http://apache.mirrors.spacedump.net/ant/binaries/${antName}-bin.tar.gz`;

const isDebug = process.env.DEBUG && process.env.DEBUG !== '0';

gulp.task( 'clean', ( ) =>
	rimraf( buildRoot )
);

gulp.task( 'make-build-dir', ( ) =>
	mkdirp( buildRoot )
);

gulp.task( 'clone-libphonenumber', gulp.series( 'make-build-dir', ( ) =>
	gitClone( libphonenumberUrl, 'libphonenumber', libphonenumberVersion )
) );

gulp.task( 'clone-closure-library', gulp.series( 'make-build-dir', ( ) =>
	gitClone( closureLibraryUrl, 'closure-library', 'v20171112' )
) );

gulp.task( 'checkout-closure-linter', gulp.series( 'make-build-dir', ( ) =>
	gitClone( closureLinterUrl, 'closure-linter' )
) );

gulp.task( 'checkout-python-gflags', gulp.series( 'make-build-dir', ( ) =>
	gitClone( pythonGflagsUrl, 'python-gflags' )
) );

gulp.task( 'download-ant', gulp.series(
	'make-build-dir',
	( ) =>
		runCommand(
			'curl',
			[ '-L', '-o', antTar, antUrl ],
			{ cwd: buildRoot }
		),
	( ) =>
		runCommand(
			'tar',
			[ 'zxf', antTar ],
			{ cwd: buildRoot }
		)
) );

gulp.task( 'download-deps', gulp.parallel(
	'clone-libphonenumber',
	'clone-closure-library',
	'checkout-closure-linter',
	'checkout-python-gflags',
	'download-ant'
) );

gulp.task( 'build-deps', gulp.series( 'download-deps' ) );

gulp.task( 'build-libphonenumber', ( ) => {
	var args = [ '-f', 'build.xml', 'compile-exports' ];
	return runCommand( `${buildRoot}/${antName}/bin/ant`, args, { cwd: '.' } );
} );

gulp.task( 'build', gulp.series( 'build-deps', 'build-libphonenumber' ) );

gulp.task( 'update-readme', ( ) =>
	updateReadme( )
);

gulp.task( 'default', gulp.series( 'clean', 'build', 'update-readme' ) );

async function updateReadme( )
{
	replace( {
		regex: 'Uses libphonenumber ([A-Za-z.0-9]+)',
		replacement: `Uses libphonenumber ${libphonenumberVersion}`,
		paths: [ 'README.md' ],
		silent: true,
	} );
}

function gitClone( url, name, branch )
{
	const args = [ '--depth=1' ];
	if ( branch )
		args.push( '--branch=' + branch );

	return runCommand( 'git', [ 'clone', ...args, url, name ] );
}

function runCommand( cmd, args, opts )
{
	opts = opts || {
		cwd   : './build',
		stdio : [ null, null, isDebug ? process.stderr : null ]
	};

	return new Promise( function( resolve, reject ) {
		var cp = child.spawn( cmd, args, opts );
		cp.stdout.on( 'data', data => {
			if ( isDebug )
				console.log( data.toString( ) );
		} );
		cp.on( 'close', code => {
			if ( code === 0 )
				return resolve( );
			reject( new Error(
				`${cmd} exited with exitcode ${code}. Args: ${args}` ) );
		} );
		cp.on( 'error', err => reject( err ) );
	} );
}
<|endoftext|>


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

"use strict";

var
    jQuery,
    esPhinx,
    Singleton,
    Ajax,
    Constructor;

(function ($module) {

    $module.extend({

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

                    var
                        ModalConstructor = $module.windows.modal.new,
                        self = this,

                        $ = jQuery,
                        ajax = Ajax,
                        body = $("body"),

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

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

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

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

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

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

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

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

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

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

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

                                bindHeaderEventListeners();
                            }
                        },

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

                            btnHide.click(function () {
                                self.hide();
                            });

                            btnClose.click(function () {
                                self.close();
                            });
                        },

                        observeContent = function () {
                            var
                                imgs,
                                length = 0;

                            esPhinx(main[0]).observe(function (observer) {
                                imgs = main.find("img");
                                if (imgs.length) {
                                    imgs.each(function (i, img) {
                                        esPhinx(img).on("load", function () {
                                            length += 1;
                                        });
                                    });

                                    FlowControl.new({
                                        condition: function (condition) {
                                            // when processing is synchronous
                                            if (!options.remote) {
                                                if (!calledBack) {
                                                    calledBack = true;
                                                    if (options.loading) {
                                                        options.loading(main);
                                                    }
                                                    self.show();
                                                }
                                            }

                                            condition(length === imgs.length);
                                        },
                                        ready: function () {
                                            if (!asynchronousAnswer) {
                                                container.html(contentSource);
                                                main.html(container);
                                            }

                                            length = 0;
                                            resolveHeaderActions(main, options);

                                            if (options.complete) {
                                                self.hide(false);
                                                options.complete(self);
                                            }
                                        }
                                    })

                                } else {
                                    resolveHeaderActions(main, options);

                                    if (options.complete) {
                                        options.complete(self);
                                    }
                                }

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

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

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

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

").addClass("container");

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

                            body.append(modal);

                            observeContent();

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

                        };

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

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

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

                        self.deleteSingleton();
                    };

                    this.hide = function (animation = true) {
                        main.hide();

                        restartTransition(mask);

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

                        mask.addClass("transparent");
                    };

                    this.show = function () {
                        modal.css("z-index", 0);

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

                        main.centralizeAt($(document));
                        main.show();
                        // debugger
                    };

                    if (!(this instanceof ModalConstructor)) {
                        self = Singleton.exists(ModalConstructor, arguments);
                        if (self) {
                            self.show();
                        } else {
                            return ModalConstructor.singleton(arguments);
                        }
                    // that "else" will should to exit for the "show" method can be used by who instanciates it
                    } else {
                        resolveParams();
                        create();
                    }

                    return self;
                }
            }
        }
    });

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

"use strict";

var
    jQuery,
    esPhinx,
    Singleton,
    Ajax,
    Constructor;

(function ($module) {

    $module.extend({

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

                    var
                        ModalConstructor = $module.windows.modal.new,
                        self = this,

                        $ = jQuery,
                        ajax = Ajax,
                        body = $("body"),

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

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

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

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

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

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

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

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

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

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

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

                                bindHeaderEventListeners();
                            }
                        },

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

                            btnHide.click(function () {
                                self.hide();
                            });

                            btnClose.click(function () {
                                self.close();
                            });
                        },

                        observeContent = function () {
                            var
                                imgs,
                                length = 0;

                            esPhinx(main[0]).observe(function (observer) {
                                imgs = main.find("img");
                                if (imgs.length) {
                                    imgs.each(function (i, img) {
                                        esPhinx(img).on("load", function () {
                                            length += 1;
                                        });
                                    });

                                    FlowControl.new({
                                        condition: function (condition) {
                                            // when processing is synchronous
                                            if (!options.remote) {
                                                if (options.loading) {
                                                    options.loading(main);
                                                }
                                                if (!calledBack) {
                                                    calledBack = true;
                                                    self.show();
                                                }
                                            }

                                            condition(length === imgs.length);
                                        },
                                        ready: function () {
                                            if (!asynchronousAnswer) {
                                                container.html(contentSource);
                                                main.html(container);
                                            }

                                            length = 0;
                                            resolveHeaderActions(main, options);

                                            if (options.complete) {
                                                self.hide(false);
                                                options.complete(self);
                                            }
                                        }
                                    })

                                } else {
                                    resolveHeaderActions(main, options);

                                    if (options.complete) {
                                        options.complete(self);
                                    }
                                }

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

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

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

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

").addClass("container");

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

                            body.append(modal);

                            observeContent();

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

                        };

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

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

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

                        self.deleteSingleton();
                    };

                    this.hide = function (animation = true) {
                        main.hide();

                        restartTransition(mask);

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

                        mask.addClass("transparent");
                    };

                    this.show = function () {
                        modal.css("z-index", 0);

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

                        main.centralizeAt($(document));
                        main.show();
                        debugger
                    };

                    if (!(this instanceof ModalConstructor)) {
                        self = Singleton.exists(ModalConstructor, arguments);
                        if (self) {
                            self.show();
                        } else {
                            return ModalConstructor.singleton(arguments);
                        }
                    // that "else" will should to exit for the "show" method can be used by who instanciates it
                    } else {
                        resolveParams();
                        create();
                    }

                    return self;
                }
            }
        }
    });

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


<commit_before>const gulp = require('gulp');
const pump = require('pump');
const rename = require('gulp-rename');
const sass = require('gulp-sass');
const wp = require('webpack');
const webpack = require('webpack-stream');
const uglify = require('gulp-uglify');

var config = {
  "pug": {
    "src": "./app/pug/*.pug",
    "dest": "./"
  },
  "sass": {
    "src": "./app/sass/*.scss",
    "dest": "./css/"
  },
  "js": {
    "src": "./app/js/*.js",
    "dest": "./js/"
  }
};

gulp.task('pug', () => {
  return gulp.src(config.pug.src)
  .pipe(pug())
  .pipe(gulp.dest(config.pug.dest))
});

gulp.task('sass', () => {
  return gulp.src(config.sass.src)
  .pipe(sass())
  .pipe(gulp.dest(config.sass.dest))
});

gulp.task('js', function() {
  return gulp.src(config.js.src)
  .pipe(webpack({
    devtool: 'cheap-module-source-map',
    watch: true,
    module: {
      loaders: [
        { test: /\.jsx?/, loader: 'babel' },
      ],
    },
    plugins: [
      new wp.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      })
    ],
  }))
  .pipe(rename(function(path) {
    path.basename = 'app'
  }))
  .pipe(gulp.dest('./js/'));
});

gulp.task('watch', () => {
  gulp.watch(config.sass.src, ['sass']);
  gulp.watch(config.js.src, ['js']);
});

gulp.task('default', ['watch']);<commit_msg>Extend sass gulp task to lint before compilation ✨<commit_after>const gulp = require('gulp');
const pump = require('pump');
const rename = require('gulp-rename');
const sass = require('gulp-sass');
const sassLint = require('gulp-sass-lint');
const wp = require('webpack');
const webpack = require('webpack-stream');
const uglify = require('gulp-uglify');

var config = {
  "pug": {
    "src": "./app/pug/*.pug",
    "dest": "./"
  },
  "sass": {
    "src": "./app/sass/*.scss",
    "dest": "./css/"
  },
  "js": {
    "src": "./app/js/*.js",
    "dest": "./js/"
  }
};

gulp.task('pug', () => {
  return gulp.src(config.pug.src)
  .pipe(pug())
  .pipe(gulp.dest(config.pug.dest))
});

gulp.task('sass', () => {
  return gulp.src(config.sass.src)
  .pipe(sassLint())
  .pipe(sassLint.format())
  .pipe(sassLint.failOnError())
  .pipe(sass())
  .pipe(gulp.dest(config.sass.dest))
});

gulp.task('js', () => {
  return gulp.src(config.js.src)
  .pipe(webpack({
    devtool: 'cheap-module-source-map',
    watch: true,
    module: {
      loaders: [
        { test: /\.jsx?/, loader: 'babel' },
      ],
    },
    plugins: [
      new wp.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      })
    ],
  }))
  .pipe(rename((path) => {
    path.basename = 'app'
  }))
  .pipe(gulp.dest('./js/'));
});

gulp.task('watch', () => {
  gulp.watch(config.sass.src, ['sass']);
  gulp.watch(config.js.src, ['js']);
});

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


<commit_before>var gulp = require('gulp');
var minify = require('gulp-minify');
var cleanCss = require('gulp-clean-css');
var rename = require('gulp-rename');

gulp.task('pack-js', function () {
    return gulp.src([
        'gollahalli_me/static/static_dirs/js/fitvids.js',
        'gollahalli_me/static/static_dirs/js/script.js'
    ])
        .pipe(minify({
            ext: {
                min: '.js'
            },
            noSource: true
        }))
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('gollahalli_me/static/static_dirs/js'));
});

gulp.task('pack-js-external', function () {
    return gulp.src([
        'gollahalli_me/static/static_dirs/external/prism.js'
    ])
        .pipe(minify({
            ext: {
                min: '.js'
            },
            noSource: true
        }))
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('gollahalli_me/static/static_dirs/external'));
});

gulp.task('pack-css', function () {
    return gulp.src([
        'gollahalli_me/static/static_dirs/css/gollahalli.css',
        'gollahalli_me/static/static_dirs/css/magnific-popup.css',
        'gollahalli_me/static/static_dirs/css/style.css',
        'gollahalli_me/static/static_dirs/css/owl.carousel.css',
        'gollahalli_me/static/static_dirs/css/linea.css'
    ])
        .pipe(cleanCss())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('gollahalli_me/static/static_dirs/css'));
});

gulp.task('pack-css-external', function () {
    return gulp.src([
        'gollahalli_me/static/static_dirs/external/prism.css'
    ])
        .pipe(cleanCss())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('gollahalli_me/static/static_dirs/external'));
});

gulp.task('default', ['pack-js', 'pack-css', 'pack-js-external', 'pack-css-external']);<commit_msg>updated<commit_after>var gulp = require('gulp');
var minify = require('gulp-minify');
var cleanCss = require('gulp-clean-css');
var rename = require('gulp-rename');

gulp.task('pack-js', function () {
    return gulp.src([
        'gollahalli_com/static/static_dirs/js/fitvids.js',
        'gollahalli_com/static/static_dirs/js/script.js'
    ])
        .pipe(minify({
            ext: {
                min: '.js'
            },
            noSource: true
        }))
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('gollahalli_com/static/static_dirs/js'));
});

gulp.task('pack-js-external', function () {
    return gulp.src([
        'gollahalli_com/static/static_dirs/external/prism.js'
    ])
        .pipe(minify({
            ext: {
                min: '.js'
            },
            noSource: true
        }))
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('gollahalli_com/static/static_dirs/external'));
});

gulp.task('pack-css', function () {
    return gulp.src([
        'gollahalli_com/static/static_dirs/css/gollahalli.css',
        'gollahalli_com/static/static_dirs/css/magnific-popup.css',
        'gollahalli_com/static/static_dirs/css/style.css',
        'gollahalli_com/static/static_dirs/css/owl.carousel.css',
        'gollahalli_com/static/static_dirs/css/linea.css'
    ])
        .pipe(cleanCss())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('gollahalli_com/static/static_dirs/css'));
});

gulp.task('pack-css-external', function () {
    return gulp.src([
        'gollahalli_com/static/static_dirs/external/prism.css'
    ])
        .pipe(cleanCss())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('gollahalli_com/static/static_dirs/external'));
});

gulp.task('default', ['pack-js', 'pack-css', 'pack-js-external', 'pack-css-external']);<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    plugins = require('gulp-load-plugins')(),
    scripts = {
      src: ['admin/views/assets/javascripts/components/*.js'],
      dest: 'admin/views/assets/javascripts',
      lib: 'admin/views/assets/javascripts/lib',
      main: 'admin/views/assets/javascripts/main.js'
    },
    styles = {
      src: ['admin/views/assets/stylesheets/scss/**/*.scss'],
      dest: 'admin/views/assets/stylesheets',
      lib: 'admin/views/assets/stylesheets/lib',
      main: 'admin/views/assets/stylesheets/scss/main.scss'
    };

gulp.task('js', function () {
  return gulp.src(scripts.src)
  .pipe(plugins.jshint())
  .pipe(plugins.jshint.reporter('default'))
  // .pipe(plugins.jscs())
  .pipe(plugins.concat('main.js'))
  .pipe(plugins.uglify())
  .pipe(gulp.dest(scripts.dest));
});

gulp.task('concat', function () {
  return gulp.src(scripts.src)
  .pipe(plugins.concat('main.js'))
  .pipe(gulp.dest(scripts.dest))
});

gulp.task('jsComponents', function () {
  return gulp.src([
    'bower_components/jquery/dist/jquery.js',
    'bower_components/jquery/dist/jquery.min.js',
    'bower_components/bootstrap/dist/js/bootstrap.js',
    'bower_components/bootstrap/dist/js/bootstrap.min.js'
  ])
  .pipe(gulp.dest(scripts.lib))
});

gulp.task('css', function () {
  return gulp.src(styles.main)
  .pipe(plugins.sass())
  .pipe(plugins.csslint())
  .pipe(plugins.autoprefixer())
  .pipe(plugins.minifyCss())
  .pipe(gulp.dest(styles.dest));
});

gulp.task('sass', function () {
  return gulp.src(styles.main)
  .pipe(plugins.sass())
  .pipe(gulp.dest(styles.dest))
});

gulp.task('cssComponents', ['fonts'], function () {
  return gulp.src([
    'bower_components/bootstrap/dist/css/bootstrap.css',
    'bower_components/bootstrap/dist/css/bootstrap.css.map',
    'bower_components/bootstrap/dist/css/bootstrap.min.css'
  ])
  .pipe(gulp.dest(styles.lib))
});

gulp.task('watch', function () {
  gulp.watch(scripts.src, ['concat']);
  gulp.watch(styles.src, ['sass']);
});

gulp.task('default', ['watch']);
<commit_msg>Assign config file path<commit_after>'use strict';

var gulp = require('gulp'),
    plugins = require('gulp-load-plugins')(),
    scripts = {
      src: ['admin/views/assets/javascripts/components/*.js'],
      dest: 'admin/views/assets/javascripts',
      lib: 'admin/views/assets/javascripts/lib',
      main: 'admin/views/assets/javascripts/main.js'
    },
    styles = {
      src: ['admin/views/assets/stylesheets/scss/**/*.scss'],
      dest: 'admin/views/assets/stylesheets',
      lib: 'admin/views/assets/stylesheets/lib',
      main: 'admin/views/assets/stylesheets/scss/main.scss'
    };

gulp.task('js', function () {
  return gulp.src(scripts.src)
  .pipe(plugins.jscs('admin/views/assets/javascripts/.jscsrc'))
  .pipe(plugins.jshint('admin/views/assets/javascripts/.jshintrc'))
  .pipe(plugins.jshint.reporter('default'))
  .pipe(plugins.concat('main.js'))
  .pipe(plugins.uglify())
  .pipe(gulp.dest(scripts.dest));
});

gulp.task('concat', function () {
  return gulp.src(scripts.src)
  .pipe(plugins.concat('main.js'))
  .pipe(gulp.dest(scripts.dest))
});

gulp.task('jsComponents', function () {
  return gulp.src([
    'bower_components/jquery/dist/jquery.js',
    'bower_components/jquery/dist/jquery.min.js',
    'bower_components/bootstrap/dist/js/bootstrap.js',
    'bower_components/bootstrap/dist/js/bootstrap.min.js'
  ])
  .pipe(gulp.dest(scripts.lib))
});

gulp.task('css', function () {
  return gulp.src(styles.main)
  .pipe(plugins.sass())
  .pipe(plugins.csslint())
  .pipe(plugins.autoprefixer())
  .pipe(plugins.minifyCss())
  .pipe(gulp.dest(styles.dest));
});

gulp.task('sass', function () {
  return gulp.src(styles.main)
  .pipe(plugins.sass())
  .pipe(gulp.dest(styles.dest))
});

gulp.task('cssComponents', ['fonts'], function () {
  return gulp.src([
    'bower_components/bootstrap/dist/css/bootstrap.css',
    'bower_components/bootstrap/dist/css/bootstrap.css.map',
    'bower_components/bootstrap/dist/css/bootstrap.min.css'
  ])
  .pipe(gulp.dest(styles.lib))
});

gulp.task('watch', function () {
  gulp.watch(scripts.src, ['concat']);
  gulp.watch(styles.src, ['sass']);
});

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