<commit_before>// GULP DEPENDENCIES
// ----------------------------------------------------------------------------
var gulp         = require('gulp');
var sass         = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var minifycss    = require('gulp-minify-css');
var jshint       = require('gulp-jshint');
var concat       = require('gulp-concat');
var uglify       = require('gulp-uglify');
var imageMin     = require('gulp-imagemin');
var notify       = require('gulp-notify');
var rename       = require('gulp-rename');
var cache        = require('gulp-cache');
var del          = require('del');
var scsslint     = require('gulp-scss-lint');

// GULP TASKS.
// ----------------------------------------------------------------------------
gulp.task('styles', function() {
    return sass('./resources/assets/scss/*.scss', { style: 'expanded' })
        .pipe(autoprefixer('last 2 version'))
        .pipe(gulp.dest('./public/css'))
        .pipe(rename({suffix: '.min'}))
        .pipe(minifycss())
        .pipe(gulp.dest('./public/css'))
        .pipe(notify({ message: 'Styles task complete' }));
});

// Lint the scss resources,
// This function is depended on.
// the scss_lint gem.
// You can install it with the following command:
//
// gem install scss_lint
gulp.task('scss-lint', function() {
    return gulp.src('./resources/assets/scss/*.scss')
        .pipe(scsslint());
});

// Clean the assets directories.
gulp.task('clean', function() {
    return del(['./public/styles']);
});

// Gulp default task.
// You can simply run it with `gulp`
gulp.task('default', ['clean'], function() {
    gulp.start('styles');
});

gulp.task('watch', function() {
    // Watch .scss files.
    gulp.watch('./resources/assets/scss/*.scss', ['styles']);
});

<commit_msg>work on comments in the gulpfile<commit_after>// GULP DEPENDENCIES
// ----------------------------------------------------------------------------
var gulp         = require('gulp');
var sass         = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var minifycss    = require('gulp-minify-css');
var jshint       = require('gulp-jshint');
var concat       = require('gulp-concat');
var uglify       = require('gulp-uglify');
var imageMin     = require('gulp-imagemin');
var notify       = require('gulp-notify');
var rename       = require('gulp-rename');
var cache        = require('gulp-cache');
var del          = require('del');
var scsslint     = require('gulp-scss-lint');

// GULP TASKS.
// ----------------------------------------------------------------------------
// TODO: need to set up a help command shell.

gulp.task('styles', function() {
    return sass('./resources/assets/scss/*.scss', { style: 'expanded' })
        .pipe(autoprefixer('last 2 version'))
        .pipe(gulp.dest('./public/css'))
        .pipe(rename({suffix: '.min'}))
        .pipe(minifycss())
        .pipe(gulp.dest('./public/css'))
        .pipe(notify({ message: 'Styles task complete' }));
});

// Lint the scss resources,
// This function is depended on.
// the scss_lint gem.
// You can install it with the following command:
//
// gem install scss_lint
gulp.task('scss-lint', function() {
    return gulp.src('./resources/assets/scss/*.scss')
        .pipe(scsslint());
});

// Clean the assets directories.
gulp.task('clean', function() {
    return del(['./public/styles']);
});

// Gulp default task.
// You can simply run it with `gulp`
gulp.task('default', ['clean'], function() {
    gulp.start('styles');
});

// Watch for changes.
gulp.task('watch', function() {
    // Watch .scss files.
    gulp.watch('./resources/assets/scss/*.scss', ['styles']);
});

<|endoftext|>


<commit_before>APP.controllers.application = (function() {

  function init() {

    APP.components.headerNavigation.init();
    APP.components.stream.init();

    if($(".welocally").exists()) chooseRegionModal();
    $('.txtlinky').linkify({ target: "_blank"});
    jBoxGallery();

    $.ajaxSetup({
			statusCode: {
				401: function(){
					alert('Du musst Dich anmelden oder registrieren, bevor Du fortfahren kannst.');
				},
        422: function(){
					alert('Du musst Dich anmelden oder registrieren, bevor Du fortfahren kannst.');
				}
			}
		});

    // WeLocally Register and Login Choose Region Modal
    function chooseRegionModal() {
      var redirect_path;
      new jBox('Confirm', {
        addClass:'jBox',
        attach: $(".region-select-link"),
        title: 'Wähle deine Region',
        content: $("#select-region-modal-content"),
        trigger: 'click',
        closeOnEsc: true,
        closeOnClick: 'body',
        blockScroll: true,
        animation:{open: 'zoomIn', close: 'zoomOut'},
        cancelButton: 'Abbrechen',
        confirmButton: 'Weiter',
        onOpen: function() {
          redirect_path = this.source.attr('data-urlmethod');
        },
        confirm: function() {
          var redirect_host = $("#select-region-modal-content select").val();
          if (redirect_host != "") {
            var redirect_url =  redirect_host + redirect_path.substring(1);
            window.location.href = redirect_url;
          }
        }
      });
    }

    // Set Screen Mode Class
    enquire
        .register("screen and (max-width:" + APP.config.majorBreakpoints.medium + "px)", {
            deferSetup : true,
            setup : function() {
              $('body').addClass('mob');
            },
            match : function() {
              $('body').addClass('mob');
              $('body').removeClass('desk');
            }
        })
        .register("screen and (min-width:" + APP.config.majorBreakpoints.medium + "px)", {
            deferSetup : true,
            setup : function() {
              $('body').addClass('desk');
            },
            match : function() {
              $('body').addClass('desk');
              $('body').removeClass('mob');
            }
        });

  }
  // END INIT
  // BEGIN OFTEN USED PUBLIC FUNCTIONS

  function scrollToTarget() {
    var target = APP.controllers.application.getUrlVars()["target"];
    if (typeof target !== 'undefined') {
      // Open all Comments
      $("#"+target).parents(".post-comments").find(".show-all-comments-link").click();
      // Scroll to Comment
      $('html, body').animate({
        scrollTop: $('#'+target).offset().top
      }, 600);
    }
  }

  function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
  }

  function initMessengerButton() {
    $('#requestMessengerBtn').on('click', function(event){
      event.preventDefault();
      var href = $(this).attr('href');
      var category = $(this).attr('data-category');
      var label = $(this).attr('data-label');
      gtag(
        "event", label +  " :: Click :: Im Messenger kontaktieren", {
        "event_category": category,
        "event_callback": function() {
          location.href = href;
        }
      });
    });
  }

  function initShowContact() {
    $('#contact-infos-block').hide();
    if ($("#show-contact-block").exists()) {
      $('#contact-infos-block').show();
      $('#show-contact-link').hide();
    }

    $('#show-contact-link').on('click', function(event){
      event.preventDefault();
      $('#contact-infos-block').fadeIn();
      $(this).hide();
      var category = $(this).attr('data-category');
      var label = $(this).attr('data-label');
      gtag(
        "event", label + " :: Click :: Kontaktinformationen einblenden", {
        "event_category": category
      });
    });
  }

  // Login Modal -------------------------
  var loginModal = new jBox('Modal', {
    addClass:'jBox',
    attach: '.login-panel-opener',
    content: $('#login-panel-modal'),
    trigger: 'click',
    closeOnClick:'body',
    blockScroll:true,
    animation:{open: 'zoomIn', close: 'zoomOut'},
    width:750
  });

  // gallery modal -------------------------
  var jBoxGallery = function() {
    new jBox('Image', {
      addClass:'jBoxGallery',
      imageCounter:true,
      preloadFirstImage:false,
      closeOnEsc:true,
      createOnInit:true,
      animation:{open: 'zoomIn', close: 'zoomOut'},
      imageSize: 'contain'
    });
  }

  // video modal -------------------------
  if($("#videoIframe").exists() && $(window).width() < 800) {
    // adjust iframe height on smaller screens
    var iframe = document.getElementById("videoIframe");
    var iframeHeight = $(window).width() * 0.56;
    iframe.style.height = iframeHeight + 'px';
  }
  var vidsrc;
  var videoModal = new jBox('Modal', {
    addClass:'jBox jBoxVideo',
    attach: '.jBoxVideo',
    content: $('#jBoxVideoContent'),
    trigger: 'click',
    closeOnEsc:true,
    closeOnClick:true,
    animation:{open: 'zoomIn', close: 'zoomOut'},
    onOpen: function () {
      vidsrc = $('#videoIframe').attr('src');
      $('#videoIframe').attr('src',vidsrc + "?autoplay=1");
    },
    onClose: function () {
      $('#videoIframe').attr('src', vidsrc);
    }
  });

  // BETA FLASH for WeLocally
  /*
  if (!sessionStorage.getItem('betaflash')) {
    $('#betaflash').show();
  }
  $('#betaflash .close-ico').on('click', function(){
      sessionStorage.setItem('betaflash', true);
      $('#betaflash').fadeOut();
  });
  */
  // ---------------------------------------------------------------------- Returns

  return {
    init: init,
    getUrlVars: getUrlVars,
    scrollToTarget: scrollToTarget,
    initMessengerButton: initMessengerButton,
    initShowContact: initShowContact,
    jBoxGallery: jBoxGallery
  }

})();
<commit_msg>removed js<commit_after>APP.controllers.application = (function() {

  function init() {

    APP.components.headerNavigation.init();
    APP.components.stream.init();

    if($(".welocally").exists()) chooseRegionModal();
    $('.txtlinky').linkify({ target: "_blank"});
    jBoxGallery();

    // WeLocally Register and Login Choose Region Modal
    function chooseRegionModal() {
      var redirect_path;
      new jBox('Confirm', {
        addClass:'jBox',
        attach: $(".region-select-link"),
        title: 'Wähle deine Region',
        content: $("#select-region-modal-content"),
        trigger: 'click',
        closeOnEsc: true,
        closeOnClick: 'body',
        blockScroll: true,
        animation:{open: 'zoomIn', close: 'zoomOut'},
        cancelButton: 'Abbrechen',
        confirmButton: 'Weiter',
        onOpen: function() {
          redirect_path = this.source.attr('data-urlmethod');
        },
        confirm: function() {
          var redirect_host = $("#select-region-modal-content select").val();
          if (redirect_host != "") {
            var redirect_url =  redirect_host + redirect_path.substring(1);
            window.location.href = redirect_url;
          }
        }
      });
    }

    // Set Screen Mode Class
    enquire
        .register("screen and (max-width:" + APP.config.majorBreakpoints.medium + "px)", {
            deferSetup : true,
            setup : function() {
              $('body').addClass('mob');
            },
            match : function() {
              $('body').addClass('mob');
              $('body').removeClass('desk');
            }
        })
        .register("screen and (min-width:" + APP.config.majorBreakpoints.medium + "px)", {
            deferSetup : true,
            setup : function() {
              $('body').addClass('desk');
            },
            match : function() {
              $('body').addClass('desk');
              $('body').removeClass('mob');
            }
        });

  }
  // END INIT
  // BEGIN OFTEN USED PUBLIC FUNCTIONS

  function scrollToTarget() {
    var target = APP.controllers.application.getUrlVars()["target"];
    if (typeof target !== 'undefined') {
      // Open all Comments
      $("#"+target).parents(".post-comments").find(".show-all-comments-link").click();
      // Scroll to Comment
      $('html, body').animate({
        scrollTop: $('#'+target).offset().top
      }, 600);
    }
  }

  function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
  }

  function initMessengerButton() {
    $('#requestMessengerBtn').on('click', function(event){
      event.preventDefault();
      var href = $(this).attr('href');
      var category = $(this).attr('data-category');
      var label = $(this).attr('data-label');
      gtag(
        "event", label +  " :: Click :: Im Messenger kontaktieren", {
        "event_category": category,
        "event_callback": function() {
          location.href = href;
        }
      });
    });
  }

  function initShowContact() {
    $('#contact-infos-block').hide();
    if ($("#show-contact-block").exists()) {
      $('#contact-infos-block').show();
      $('#show-contact-link').hide();
    }

    $('#show-contact-link').on('click', function(event){
      event.preventDefault();
      $('#contact-infos-block').fadeIn();
      $(this).hide();
      var category = $(this).attr('data-category');
      var label = $(this).attr('data-label');
      gtag(
        "event", label + " :: Click :: Kontaktinformationen einblenden", {
        "event_category": category
      });
    });
  }

  // Login Modal -------------------------
  var loginModal = new jBox('Modal', {
    addClass:'jBox',
    attach: '.login-panel-opener',
    content: $('#login-panel-modal'),
    trigger: 'click',
    closeOnClick:'body',
    blockScroll:true,
    animation:{open: 'zoomIn', close: 'zoomOut'},
    width:750
  });

  // gallery modal -------------------------
  var jBoxGallery = function() {
    new jBox('Image', {
      addClass:'jBoxGallery',
      imageCounter:true,
      preloadFirstImage:false,
      closeOnEsc:true,
      createOnInit:true,
      animation:{open: 'zoomIn', close: 'zoomOut'},
      imageSize: 'contain'
    });
  }

  // video modal -------------------------
  if($("#videoIframe").exists() && $(window).width() < 800) {
    // adjust iframe height on smaller screens
    var iframe = document.getElementById("videoIframe");
    var iframeHeight = $(window).width() * 0.56;
    iframe.style.height = iframeHeight + 'px';
  }
  var vidsrc;
  var videoModal = new jBox('Modal', {
    addClass:'jBox jBoxVideo',
    attach: '.jBoxVideo',
    content: $('#jBoxVideoContent'),
    trigger: 'click',
    closeOnEsc:true,
    closeOnClick:true,
    animation:{open: 'zoomIn', close: 'zoomOut'},
    onOpen: function () {
      vidsrc = $('#videoIframe').attr('src');
      $('#videoIframe').attr('src',vidsrc + "?autoplay=1");
    },
    onClose: function () {
      $('#videoIframe').attr('src', vidsrc);
    }
  });

  // BETA FLASH for WeLocally
  /*
  if (!sessionStorage.getItem('betaflash')) {
    $('#betaflash').show();
  }
  $('#betaflash .close-ico').on('click', function(){
      sessionStorage.setItem('betaflash', true);
      $('#betaflash').fadeOut();
  });
  */
  // ---------------------------------------------------------------------- Returns

  return {
    init: init,
    getUrlVars: getUrlVars,
    scrollToTarget: scrollToTarget,
    initMessengerButton: initMessengerButton,
    initShowContact: initShowContact,
    jBoxGallery: jBoxGallery
  }

})();
<|endoftext|>


<commit_before>'use strict';
var gulp = require('gulp');
var jasmine = require('gulp-jasmine');

gulp.task('test', function () {
  return gulp.src('test/**/*.spec.js')
    .pipe(jasmine());
});
<commit_msg>getting rid of gulpfile<commit_after><|endoftext|>


<commit_before>//= require editor

Editor.Formator.prototype.link = function(url) {
  this.editor.restoreRange();

  if (url !== undefined) {
    if (this.isWraped('a')) {
      document.getSelection().selectAllChildren($(this.commonAncestorContainer()).closest('a')[0]);
    }
    if (url !== '') {
      if (!/^http/.test(url)) {
        url = 'http://' + url;
      }
      this.exec('createLink', url);
    } else {
      this.exec('unlink');
    }
    Dialog.hide('#link-modal');
  } else {
    if (this.isWraped('a')) {
      link = $(this.commonAncestorContainer()).closest('a').attr('href');
    }
    Dialog.show('#link-modal');
    $('#link-modal').find('input[name=url]').focus();
  }
};

Editor.Formator.prototype.image = function(url) {
  this.editor.restoreRange();

  if (url !== undefined) {
    if (!/^http/.test(url)) {
      url = 'http://' + url;
    }
    this.exec('insertImage', url);
    Dialog.hide('#image-modal');
  } else {
    Dialog.show('#image-modal');
    $('#image-modal').find('input[name=url]').focus();
  }
};

var ArticleEdit = function() {
  this.editor = new Editor({
    toolbar: '#toolbar',
    editable: '#editarea article'
  });

  this.article = $('#editarea article');

  this.connect('#urlname-form', 'submit', this.saveUrlname);
  this.connect('#save-button', 'click', this.saveArticle);
  this.connect('#publish-button', 'click', this.publishArticle);
  this.connect('#draft-button', 'click', this.draftArticle);
  this.connect('#category-form', 'submit', this.saveCategory);
  this.connect('#new-category-form', 'submit', this.createCategory);
  this.connect('#pick-up-button', 'click', this.pickUpTopbar);

  $('#category-form .dropdown').on('click', '.dropdown-menu li a', this.selectCategory);

  var _this = this;

  if (this.article.hasClass('init')) {
    this.editor.formator.h1();
    this.article.one('input', function() {
      _this.article.removeClass('init');
    });
  }

  $('#link-form').on('submit', function(event) {
    event.preventDefault();
    _this.editor.formator.link($(this).find('input[name=url]').val());
  });

  $('#unlink-button').on('click', function(event) {
    event.preventDefault();
    _this.editor.formator.link('');
  });

  $('#image-form').on('submit', function(event) {
    event.preventDefault();
    _this.editor.formator.image($(this).find('input[name=url]').val());
  });

  Mousetrap.bind(['ctrl+s', 'command+s'], function(event) {
    _this.saveArticle(event);
  });
  Mousetrap.bind(['ctrl+m', 'command+m'], function(event) {
    event.preventDefault();
    if ($('#help-modal').is(':hidden')) {
      Dialog.show('#help-modal');
    } else {
      Dialog.hide('#help-modal');
    }
  });
};

ArticleEdit.prototype = {
  connect: function(element, event, fn) {
    var _this = this;
    $(element).on(event, function(event) {
      fn.call(_this, event, this);
    });
  },

  isPersisted: function() {
    return !!this.article.data('id');
  },

  updateArticle: function(data, success_callback, error_callback) {
    var _this = this;
    AlertMessage.loading('Saving...');
    $.ajax({
      url: '/articles/' + this.article.data('id'),
      data: data,
      type: 'put',
      dataType: 'json'
    }).success(function(data) {
      AlertMessage.clear();
      if (success_callback) {
        success_callback(data);
      }
      _this.updateViewButton(data);
    }).error(function() {
      AlertMessage.error('Save Failed.');
      if (error_callback) {
        error_callback();
      }
    });
  },

  saveUrlname: function(event) {
    event.preventDefault();
    var urlname = $('#article-urlname').val();
    if (this.isPersisted()) {
      this.updateArticle($('#urlname-form').serializeArray(), function(data) {
        Dialog.hide('#urlname-modal');
      });
    } else {
      this.article.data('urlname', urlname);
      Dialog.hide('#urlname-modal');
    }
  },

  saveCategory: function(event) {
    event.preventDefault();
    var categoryId = $('#article-category-id').val();
    var categoryName = $('#category-form .dropdown-toggle').text();
    var _this = this;
    if (this.isPersisted()) {
      this.updateArticle($('#category-form').serializeArray(), function(data) {
        _this.article.data('category-id', categoryId);
        Dialog.hide('#select-category-modal');
      });
    } else {
      this.article.data('category-id', categoryId);
      Dialog.hide('#select-category-modal');
    }
  },

  createCategory: function(event) {
    event.preventDefault();
    $.ajax({
      url: '/categories/',
      data: $('#new-category-form').serializeArray(),
      type: 'post',
      dataType: 'json'
    }).success(function(data) {
      var $li = $('
');
      $li.find('a').text(data.name).data('category-id', data.urlname);
      $('#category-form .dropdown-menu').prepend($li);
      $('#category-form .dropdown-toggle').text(data.name);
      $('#article-category-id').val(data.urlname);
      Dialog.hide('#new-category-modal');
    });
  },

  selectCategory: function(event) {
    event.preventDefault();
    var $item = $(this);
    $item.closest('.dropdown').find('.dropdown-toggle').text($item.text());
    $('#article-category-id').val($item.data('category-id'));
  },

  saveArticle: function(event) {
    event.preventDefault();
    if (this.isPersisted()) {
      this.updateArticle({
        article: {
          title: this.extractTitle(),
          body: this.editor.editable.html()
        }
      });
    } else {
      this.createArticle();
    }

    document.title = this.extractTitle() || 'Untitle';
  },

  extractTitle: function() {
    return this.editor.editable.find('h1').text();
  },

  createArticle: function() {
    var _this = this;
    AlertMessage.loading('Saving...');
    $.ajax({
      url: '/articles',
      data: {
        article: {
          title: this.editor.editable.find('h1').text(),
          body: this.editor.editable.html(),
          urlname: this.article.data('urlname'),
          category_id : this.article.data('category-id'),
          status: this.article.data('status')
        }
      },
      type: 'post',
      dataType: 'json'
    }).success(function(data) {
      AlertMessage.clear();
      _this.article.data('id', data.token);
      _this.updateViewButton(data);
      history.replaceState(null, null, '/articles/' + data.token + '/edit');
    }).error(function() {
      AlertMessage.error('Save Failed.');
    });
  },

  updateViewButton: function(data) {
    $('#view-button').attr('href', data.url);
    if (data.status === 'publish') {
      $('#view-button').closest('li').removeClass('hide');
    } else {
      $('#view-button').closest('li').addClass('hide');
    }
  },

  setPbulishClass: function(isPublish) {
    if (isPublish) {
      $('#draft-button').removeClass('button-actived');
      $('#publish-button').addClass('button-actived');
    } else {
      $('#publish-button').removeClass('button-actived');
      $('#draft-button').addClass('button-actived');
    }
  },

  publishArticle: function(event) {
    var _this = this;
    this.setPbulishClass(true);
    event.preventDefault();
      if (this.isPersisted()) {
      this.updateArticle({
        article: {
          status: 'publish'
        }
      }, null, function(data) {
        this.setPbulishClass(false);
        _this.article.data('status', 'draft');
      });
    } else {
      this.article.data('status', 'publish');
    }
  },

  draftArticle: function(event) {
    var _this = this;
    event.preventDefault();
    this.setPbulishClass(false);
    if (this.isPersisted()) {
      this.updateArticle({
        article: {
          status: 'draft'
        }
      }, null, function(data) {
        _this.setPbulishClass(true);
        this.article.data('status', 'publish');
      });
    } else {
      this.article.data('status', 'draft');
    }
  },

  pickUpTopbar: function() {
    $('body').toggleClass('pick-up-topbar');
    if ($('body').hasClass('pick-up-topbar')) {
      $.cookie('pick_up_topbar', true, { path: '/articles', expires: 14 });
    } else {
      $.removeCookie('pick_up_topbar',  { path: '/articles' });
    }
  }
};

page_ready(function() {
  if ($('body#articles-edit').length) {
    window.articleEdit = new ArticleEdit();
  }
});
<commit_msg>fix create link and image url val.<commit_after>//= require editor

Editor.Formator.prototype.link = function(url) {
  this.editor.restoreRange();

  if (url !== undefined) {
    if (this.isWraped('a')) {
      document.getSelection().selectAllChildren($(this.commonAncestorContainer()).closest('a')[0]);
    }
    if (url !== '') {
      if (!/^http/.test(url)) {
        url = 'http://' + url;
      }
      this.exec('createLink', url);
    } else {
      this.exec('unlink');
    }
    Dialog.hide('#link-modal');
  } else {
    var link = '';
    if (this.isWraped('a')) {
      link = $(this.commonAncestorContainer()).closest('a').attr('href');
    }
    Dialog.show('#link-modal');
    $('#link-modal').find('input[name=url]').val(link).focus();
  }
};

Editor.Formator.prototype.image = function(url) {
  this.editor.restoreRange();

  if (url !== undefined) {
    if (!/^http/.test(url)) {
      url = 'http://' + url;
    }
    this.exec('insertImage', url);
    Dialog.hide('#image-modal');
  } else {
    Dialog.show('#image-modal');
    $('#image-modal').find('input[name=url]').val('').focus();
  }
};

var ArticleEdit = function() {
  this.editor = new Editor({
    toolbar: '#toolbar',
    editable: '#editarea article'
  });

  this.article = $('#editarea article');

  this.connect('#urlname-form', 'submit', this.saveUrlname);
  this.connect('#save-button', 'click', this.saveArticle);
  this.connect('#publish-button', 'click', this.publishArticle);
  this.connect('#draft-button', 'click', this.draftArticle);
  this.connect('#category-form', 'submit', this.saveCategory);
  this.connect('#new-category-form', 'submit', this.createCategory);
  this.connect('#pick-up-button', 'click', this.pickUpTopbar);

  $('#category-form .dropdown').on('click', '.dropdown-menu li a', this.selectCategory);

  var _this = this;

  if (this.article.hasClass('init')) {
    this.editor.formator.h1();
    this.article.one('input', function() {
      _this.article.removeClass('init');
    });
  }

  $('#link-form').on('submit', function(event) {
    event.preventDefault();
    _this.editor.formator.link($(this).find('input[name=url]').val());
  });

  $('#unlink-button').on('click', function(event) {
    event.preventDefault();
    _this.editor.formator.link('');
  });

  $('#image-form').on('submit', function(event) {
    event.preventDefault();
    _this.editor.formator.image($(this).find('input[name=url]').val());
  });

  Mousetrap.bind(['ctrl+s', 'command+s'], function(event) {
    _this.saveArticle(event);
  });
  Mousetrap.bind(['ctrl+m', 'command+m'], function(event) {
    event.preventDefault();
    if ($('#help-modal').is(':hidden')) {
      Dialog.show('#help-modal');
    } else {
      Dialog.hide('#help-modal');
    }
  });
};

ArticleEdit.prototype = {
  connect: function(element, event, fn) {
    var _this = this;
    $(element).on(event, function(event) {
      fn.call(_this, event, this);
    });
  },

  isPersisted: function() {
    return !!this.article.data('id');
  },

  updateArticle: function(data, success_callback, error_callback) {
    var _this = this;
    AlertMessage.loading('Saving...');
    $.ajax({
      url: '/articles/' + this.article.data('id'),
      data: data,
      type: 'put',
      dataType: 'json'
    }).success(function(data) {
      AlertMessage.clear();
      if (success_callback) {
        success_callback(data);
      }
      _this.updateViewButton(data);
    }).error(function() {
      AlertMessage.error('Save Failed.');
      if (error_callback) {
        error_callback();
      }
    });
  },

  saveUrlname: function(event) {
    event.preventDefault();
    var urlname = $('#article-urlname').val();
    if (this.isPersisted()) {
      this.updateArticle($('#urlname-form').serializeArray(), function(data) {
        Dialog.hide('#urlname-modal');
      });
    } else {
      this.article.data('urlname', urlname);
      Dialog.hide('#urlname-modal');
    }
  },

  saveCategory: function(event) {
    event.preventDefault();
    var categoryId = $('#article-category-id').val();
    var categoryName = $('#category-form .dropdown-toggle').text();
    var _this = this;
    if (this.isPersisted()) {
      this.updateArticle($('#category-form').serializeArray(), function(data) {
        _this.article.data('category-id', categoryId);
        Dialog.hide('#select-category-modal');
      });
    } else {
      this.article.data('category-id', categoryId);
      Dialog.hide('#select-category-modal');
    }
  },

  createCategory: function(event) {
    event.preventDefault();
    $.ajax({
      url: '/categories/',
      data: $('#new-category-form').serializeArray(),
      type: 'post',
      dataType: 'json'
    }).success(function(data) {
      var $li = $('
');
      $li.find('a').text(data.name).data('category-id', data.urlname);
      $('#category-form .dropdown-menu').prepend($li);
      $('#category-form .dropdown-toggle').text(data.name);
      $('#article-category-id').val(data.urlname);
      Dialog.hide('#new-category-modal');
    });
  },

  selectCategory: function(event) {
    event.preventDefault();
    var $item = $(this);
    $item.closest('.dropdown').find('.dropdown-toggle').text($item.text());
    $('#article-category-id').val($item.data('category-id'));
  },

  saveArticle: function(event) {
    event.preventDefault();
    if (this.isPersisted()) {
      this.updateArticle({
        article: {
          title: this.extractTitle(),
          body: this.editor.editable.html()
        }
      });
    } else {
      this.createArticle();
    }

    document.title = this.extractTitle() || 'Untitle';
  },

  extractTitle: function() {
    return this.editor.editable.find('h1').text();
  },

  createArticle: function() {
    var _this = this;
    AlertMessage.loading('Saving...');
    $.ajax({
      url: '/articles',
      data: {
        article: {
          title: this.editor.editable.find('h1').text(),
          body: this.editor.editable.html(),
          urlname: this.article.data('urlname'),
          category_id : this.article.data('category-id'),
          status: this.article.data('status')
        }
      },
      type: 'post',
      dataType: 'json'
    }).success(function(data) {
      AlertMessage.clear();
      _this.article.data('id', data.token);
      _this.updateViewButton(data);
      history.replaceState(null, null, '/articles/' + data.token + '/edit');
    }).error(function() {
      AlertMessage.error('Save Failed.');
    });
  },

  updateViewButton: function(data) {
    $('#view-button').attr('href', data.url);
    if (data.status === 'publish') {
      $('#view-button').closest('li').removeClass('hide');
    } else {
      $('#view-button').closest('li').addClass('hide');
    }
  },

  setPbulishClass: function(isPublish) {
    if (isPublish) {
      $('#draft-button').removeClass('button-actived');
      $('#publish-button').addClass('button-actived');
    } else {
      $('#publish-button').removeClass('button-actived');
      $('#draft-button').addClass('button-actived');
    }
  },

  publishArticle: function(event) {
    var _this = this;
    this.setPbulishClass(true);
    event.preventDefault();
      if (this.isPersisted()) {
      this.updateArticle({
        article: {
          status: 'publish'
        }
      }, null, function(data) {
        this.setPbulishClass(false);
        _this.article.data('status', 'draft');
      });
    } else {
      this.article.data('status', 'publish');
    }
  },

  draftArticle: function(event) {
    var _this = this;
    event.preventDefault();
    this.setPbulishClass(false);
    if (this.isPersisted()) {
      this.updateArticle({
        article: {
          status: 'draft'
        }
      }, null, function(data) {
        _this.setPbulishClass(true);
        this.article.data('status', 'publish');
      });
    } else {
      this.article.data('status', 'draft');
    }
  },

  pickUpTopbar: function() {
    $('body').toggleClass('pick-up-topbar');
    if ($('body').hasClass('pick-up-topbar')) {
      $.cookie('pick_up_topbar', true, { path: '/articles', expires: 14 });
    } else {
      $.removeCookie('pick_up_topbar',  { path: '/articles' });
    }
  }
};

page_ready(function() {
  if ($('body#articles-edit').length) {
    window.articleEdit = new ArticleEdit();
  }
});
<|endoftext|>


<commit_before>var   gulp         = require('gulp')
    , notify       = require("gulp-notify")
    , csso         = require('gulp-csso')
    , uglify       = require('gulp-uglify')
    , connect      = require('gulp-connect')
    , compass      = require('gulp-for-compass')
    , concat       = require('gulp-concat')
    , autoprefixer = require('gulp-autoprefixer')
    , imageminJpegtran = require('imagemin-jpegtran')
    , imageminPngquant = require('imagemin-pngquant')
    , imageResize = require('gulp-image-resize');
    ;

//server
gulp.task('server', function() {
    connect.server({
        livereload: true
    });
});

//html
gulp.task('html',function(){
    gulp.src('index.html')
        .pipe(connect.reload())
        .pipe(notify("Change index.html"));
});

//css
gulp.task('css',function(){
    gulp.src('style.css')
        .pipe(connect.reload());
});

//js
gulp.task('js', function() {
    gulp.src('./lib/js/**/*.js')
        .pipe(connect.reload());
});

//compress pic
gulp.task('compress-image', function () {
    gulp.src('./lib/**.jpg')
        .pipe(imageminJpegtran({progressive: true})())
        .pipe(gulp.dest('./build/lib/'));

    gulp.src('./lib/pic/**')
        .pipe(imageResize({ width : 1280 }))
        .pipe(gulp.dest('./build/lib/pic/'));

    gulp.src('./lib/image/**')
        .pipe(imageResize({ width : 300 }))
        .pipe(imageminJpegtran({progressive: true})())
        .pipe(imageminPngquant({quality: '65-80', speed: 4})())
        .pipe(gulp.dest('./build/lib/image/'));
});

//sass
gulp.task('sass', function(){
    gulp.src('./lib/sass/**/*.sass')
        .pipe(compass({
            httpFontsPath:  '../font/',
            httpGeneratedImagesPath: '../pic/',
            cssDir:    './lib/css/',
            sassDir:   './lib/sass/',
            fontsDir:  './lib/font/',
            imagesDir: './lib/pic/',
            force: true
        }))
        .pipe(connect.reload())
        .pipe(notify("Compile SASS"));
});

//concat
gulp.task('concat-js', function() {
    return gulp.src([
            './lib/js/owl.carousel.js',
            //'./lib/js/jquery.stellar.js',
            //'./lib/js/jquery.appear.js',
            './lib/js/app.js',
            './lib/js/map.js'
        ])
        .pipe(concat('app.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./lib/js/'));
});

//watch
gulp.task('watch', function () {
    gulp.watch('./index.html', ['html']);
    gulp.watch('./lib/sass/**/*', ['sass']);
    gulp.watch('./lib/css/**/*', ['css']);
    gulp.watch('./lib/js/**/*', ['concat-js', 'js']);
});

//compress css
gulp.task('compress-css', function() {
    return gulp.src('./lib/css/style.css')
        .pipe(autoprefixer({
            browsers: ['last 10 versions'],
            cascade: false
        }))
        .pipe(csso())
        .pipe(gulp.dest('./build/lib/css/'));
});

//compress js
//gulp.task('compress-js', function() {
//    gulp.src('./public/js/*')
//        .pipe(uglify())
//        .pipe(gulp.dest('./public/js/'))
//});

gulp.task('copy-src',['build-static'],function() {
  gulp.src(['./index.html','./favicon.*'])
    .pipe(gulp.dest('./build'))
  gulp.src(['./lib/font/*'])
    .pipe(gulp.dest('./build/lib/font'))
  gulp.src(['./lib/js/app.min.js'])
    .pipe(gulp.dest('./build/lib/js'))
});

gulp.task('build-static', ['sass', 'css', 'js', 'concat-js']);
gulp.task('default', ['server', 'html', 'build-static', 'watch']);
gulp.task('production', ['build-static', 'compress-css', 'compress-image','copy-src']);
<commit_msg>Copy CSS manually<commit_after>var   gulp         = require('gulp')
    , notify       = require("gulp-notify")
    , csso         = require('gulp-csso')
    , uglify       = require('gulp-uglify')
    , connect      = require('gulp-connect')
    , compass      = require('gulp-for-compass')
    , concat       = require('gulp-concat')
    , autoprefixer = require('gulp-autoprefixer')
    , imageminJpegtran = require('imagemin-jpegtran')
    , imageminPngquant = require('imagemin-pngquant')
    , imageResize = require('gulp-image-resize');
    ;

//server
gulp.task('server', function() {
    connect.server({
        livereload: true
    });
});

//html
gulp.task('html',function(){
    gulp.src('index.html')
        .pipe(connect.reload())
        .pipe(notify("Change index.html"));
});

//css
gulp.task('css',function(){
    gulp.src('style.css')
        .pipe(connect.reload());
});

//js
gulp.task('js', function() {
    gulp.src('./lib/js/**/*.js')
        .pipe(connect.reload());
});

//compress pic
gulp.task('compress-image', function () {
    gulp.src('./lib/**.jpg')
        .pipe(imageminJpegtran({progressive: true})())
        .pipe(gulp.dest('./build/lib/'));

    gulp.src('./lib/pic/**')
        .pipe(imageResize({ width : 1280 }))
        .pipe(gulp.dest('./build/lib/pic/'));

    gulp.src('./lib/image/**')
        .pipe(imageResize({ width : 300 }))
        .pipe(imageminJpegtran({progressive: true})())
        .pipe(imageminPngquant({quality: '65-80', speed: 4})())
        .pipe(gulp.dest('./build/lib/image/'));
});

//sass
gulp.task('sass', function(){
    gulp.src('./lib/sass/**/*.sass')
        .pipe(compass({
            httpFontsPath:  '../font/',
            httpGeneratedImagesPath: '../pic/',
            cssDir:    './lib/css/',
            sassDir:   './lib/sass/',
            fontsDir:  './lib/font/',
            imagesDir: './lib/pic/',
            force: true
        }))
        .pipe(connect.reload())
        .pipe(notify("Compile SASS"));
});

//concat
gulp.task('concat-js', function() {
    return gulp.src([
            './lib/js/owl.carousel.js',
            //'./lib/js/jquery.stellar.js',
            //'./lib/js/jquery.appear.js',
            './lib/js/app.js',
            './lib/js/map.js'
        ])
        .pipe(concat('app.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./lib/js/'));
});

//watch
gulp.task('watch', function () {
    gulp.watch('./index.html', ['html']);
    gulp.watch('./lib/sass/**/*', ['sass']);
    gulp.watch('./lib/css/**/*', ['css']);
    gulp.watch('./lib/js/**/*', ['concat-js', 'js']);
});

//compress css
gulp.task('compress-css', function() {
    return gulp.src('./lib/css/style.css')
        .pipe(autoprefixer({
            browsers: ['last 10 versions'],
            cascade: false
        }))
        .pipe(csso())
        .pipe(gulp.dest('./build/lib/css/'));
});

//compress js
//gulp.task('compress-js', function() {
//    gulp.src('./public/js/*')
//        .pipe(uglify())
//        .pipe(gulp.dest('./public/js/'))
//});

gulp.task('copy-src',['build-static', 'compress-css', 'compress-image'],function() {
  gulp.src(['./index.html','./favicon.*'])
    .pipe(gulp.dest('./build'))
  gulp.src(['./lib/font/*'])
    .pipe(gulp.dest('./build/lib/font'))
  gulp.src(['./lib/css/*'])
    .pipe(gulp.dest('./build/lib/css'))
  gulp.src(['./lib/js/app.min.js'])
    .pipe(gulp.dest('./build/lib/js'))
});

gulp.task('build-static', ['sass', 'css', 'js', 'concat-js']);
gulp.task('default', ['server', 'html', 'build-static', 'watch']);
gulp.task('production', ['build-static', 'copy-src']);
<|endoftext|>


<commit_before>Ext.define('FastExt.view.VMenu', {
    extend:'Ext.tree.Panel',
    requires:['FastExt.store.MWindowMgr'],
    alias: 'widget.vMenu',
    title:'Menu',
    animate:false,
    collapseMode:"mini",
    collapsible:true,
    iconCls:"fast-ext-menu",
    lines:false,
    rootVisible:false,
    split:true,
    dockedItems:[{dock:"top",items:[{xtype:"tbfill"},
        {iconCls:"fast-ext-tree-expand",tooltip:"Expand All",xtype:"button", listeners:{click:{fn:function (sender ,e ,eOpts) {sender.up().up().expandAll();}}}},
        {iconCls:"fast-ext-tree-collapse",tooltip:"Collapse All",xtype:"button", listeners:{click:{fn:function (sender ,e ,eOpts) { sender.up().up().collapseAll(); sender.up().up().getRootNode().expand();}}}}],xtype:"toolbar"}
    ],

    initComponent: function(){
      this.store = Ext.create('Ext.data.TreeStore', {
          autoLoad:true,
          fields:['id', {name:'text', mapping:'title'},'leaf','expanded', 'window'],
          proxy:{
              type:'ajax',
              url:'/fast_ext/m_menu_items.json',
              reader:{
                  type:'json',
                  root:'',
                  record:''
                  //successProperty:''
              }
          },
          root:{
              name:this.title,
              id:'',
              expanded:true
          }
      });
      this.callParent(arguments);
    },

    listeners:{
        itemclick:function(self, record, item, index, e, eOpts){
            this.loadVWindow(self, record, item, index, e, eOpts);
        }
    },

    loadVWindow:function (self, record, item, index, e, eOpts) {
        var c = Ext.getCmp('mycenter');
        c.setLoading(true);
        var id = record.get('window');
        //var id = 'm_list';

        if (record.get('leaf')) {
            FastExt.store.MWindowMgr.load(id, function (obj) {
                var winId = 'win-' + id;
                var win = Ext.getCmp(winId);
                if (!win) {
                    win = Ext.create('FastExt.view.VWindow', {
                        id: winId,
                        valueObject: obj
                    });
                    c.add(win);
                }
                c.setActiveTab(win);
                c.setLoading(false);
            });
        }

    }
});

<commit_msg>update extjs 5.0.1<commit_after>Ext.define('FastExt.view.VMenu', {
    extend:'Ext.tree.Panel',
    requires:['FastExt.store.MWindowMgr'],
    alias: 'widget.vMenu',
    title:'Menu',
    animate:false,
    collapseMode:"mini",
    collapsible:true,
    iconCls:"fast-ext-menu",
    lines:false,
    rootVisible:false,
    split:true,
    dockedItems:[{dock:"top",items:[{xtype:"tbfill"},
        {iconCls:"fast-ext-tree-expand",tooltip:"Expand All",xtype:"button", listeners:{click:{fn:function (sender ,e ,eOpts) {sender.up().up().expandAll();}}}},
        {iconCls:"fast-ext-tree-collapse",tooltip:"Collapse All",xtype:"button", listeners:{click:{fn:function (sender ,e ,eOpts) { sender.up().up().collapseAll(); sender.up().up().getRootNode().expand();}}}}],xtype:"toolbar"}
    ],

    initComponent: function(){
      this.store = Ext.create('Ext.data.TreeStore', {
          autoLoad:true,
          fields:['id', {name:'name', mapping:'title'},'leaf','expanded', 'window'],
          proxy:{
              type:'ajax',
              url:'/fast_ext/m_menu_items.json',
              reader:{
                  type:'json',
                  root:'',
                  record:''
                  //successProperty:''
              }
          },
          root:{
              name:this.title,
              id: 1,
              expanded:true
          }
      });
      this.callParent(arguments);
    },

    listeners:{
        itemclick:function(self, record, item, index, e, eOpts){
            this.loadVWindow(self, record, item, index, e, eOpts);
        }
    },

    loadVWindow:function (self, record, item, index, e, eOpts) {
        var c = Ext.getCmp('mycenter');
        c.setLoading(true);
        var id = record.get('window');
        //var id = 'm_list';

        if (record.get('leaf')) {
            FastExt.store.MWindowMgr.load(id, function (obj) {
                var winId = 'win-' + id;
                var win = Ext.getCmp(winId);
                if (!win) {
                    win = Ext.create('FastExt.view.VWindow', {
                        id: winId,
                        valueObject: obj
                    });
                    c.add(win);
                }
                c.setActiveTab(win);
                c.setLoading(false);
            });
        }

    }
});

<|endoftext|>


<commit_before>/*eslint-env node*/

const fs = require('fs');
const gulp = require('gulp');
const useref = require('gulp-useref');
const cleanCSS = require('gulp-clean-css');
const babelMinify = require('babel-minify');

function minifyJs(fileName) {
	const content = fs.readFileSync(fileName, "utf8");
	const minifiedContent = babelMinify(content).code;
	fs.writeFileSync(fileName, minifiedContent);
	console.log(`[${fileName}]: before -> ${content.length}kb`)
	console.log(`[${fileName}]: after -> ${minifiedContent.length}kb`)
}
gulp.task('copyFiles', [], function() {
	gulp
		.src('src/lib/codemirror/theme/*')
		.pipe(gulp.dest('app/lib/codemirror/theme'));
	gulp
		.src('src/lib/codemirror/mode/**/*')
		.pipe(gulp.dest('app/lib/codemirror/mode'));
	gulp
		.src('src/lib/transpilers/*')
		.pipe(gulp.dest('app/lib/transpilers'));
	gulp.src('src/partials/*').pipe(gulp.dest('app/partials'));
	gulp.src('src/lib/screenlog.js').pipe(gulp.dest('app/lib'));
	gulp.src('src/icon-48.png').pipe(gulp.dest('app'));
	gulp
		.src([
			'src/FiraCode.ttf',
			'src/Fixedsys.ttf',
			'src/Inconsolata.ttf',
			'src/Monoid.ttf'
		])
		.pipe(gulp.dest('app'));
});

gulp.task('useRef', ['copyFiles'], function() {
	return gulp
		.src('src/index.html')
		.pipe(useref())
		.pipe(gulp.dest('app'));
});

gulp.task('minify', ['useRef'], function() {
	minifyJs('app/script.js');
	minifyJs('app/vendor.js');

	gulp.src('app/*.css')
		.pipe(cleanCSS({ debug: true }, (details) => {
			console.log(`${details.name}: ${details.stats.originalSize}`);
			console.log(`${details.name}: ${details.stats.minifiedSize}`);
		}))
		.pipe(gulp.dest('app'));
});

gulp.task('generate-service-worker', ['minify'], function(callback) {
	var swPrecache = require('sw-precache');
	var rootDir = 'app';

	swPrecache.write(
		`${rootDir}/service-worker.js`,
		{
			staticFileGlobs: [
				rootDir + '/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'
			],
			stripPrefix: `${rootDir}/`,

			// has to be increased to around 2.8mb for sass.worker.js
			maximumFileSizeToCacheInBytes: 2900000
		},
		callback
	);
});

gulp.task('default', ['generate-service-worker']);
<commit_msg>gulpfile: minor log styling<commit_after>/*eslint-env node*/

const fs = require('fs');
const gulp = require('gulp');
const useref = require('gulp-useref');
const cleanCSS = require('gulp-clean-css');
const babelMinify = require('babel-minify');

function minifyJs(fileName) {
	const content = fs.readFileSync(fileName, "utf8");
	const minifiedContent = babelMinify(content).code;
	fs.writeFileSync(fileName, minifiedContent);
	console.log(`[${fileName}]: ${content.length}kb -> ${minifiedContent.length}kb`)
}
gulp.task('copyFiles', [], function() {
	gulp
		.src('src/lib/codemirror/theme/*')
		.pipe(gulp.dest('app/lib/codemirror/theme'));
	gulp
		.src('src/lib/codemirror/mode/**/*')
		.pipe(gulp.dest('app/lib/codemirror/mode'));
	gulp
		.src('src/lib/transpilers/*')
		.pipe(gulp.dest('app/lib/transpilers'));
	gulp.src('src/partials/*').pipe(gulp.dest('app/partials'));
	gulp.src('src/lib/screenlog.js').pipe(gulp.dest('app/lib'));
	gulp.src('src/icon-48.png').pipe(gulp.dest('app'));
	gulp
		.src([
			'src/FiraCode.ttf',
			'src/Fixedsys.ttf',
			'src/Inconsolata.ttf',
			'src/Monoid.ttf'
		])
		.pipe(gulp.dest('app'));
});

gulp.task('useRef', ['copyFiles'], function() {
	return gulp
		.src('src/index.html')
		.pipe(useref())
		.pipe(gulp.dest('app'));
});

gulp.task('minify', ['useRef'], function() {
	minifyJs('app/script.js');
	minifyJs('app/vendor.js');

	gulp.src('app/*.css')
		.pipe(cleanCSS({ debug: true }, (details) => {
			console.log(`${details.name}: ${details.stats.originalSize}`);
			console.log(`${details.name}: ${details.stats.minifiedSize}`);
		}))
		.pipe(gulp.dest('app'));
});

gulp.task('generate-service-worker', ['minify'], function(callback) {
	var swPrecache = require('sw-precache');
	var rootDir = 'app';

	swPrecache.write(
		`${rootDir}/service-worker.js`,
		{
			staticFileGlobs: [
				rootDir + '/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'
			],
			stripPrefix: `${rootDir}/`,

			// has to be increased to around 2.8mb for sass.worker.js
			maximumFileSizeToCacheInBytes: 2900000
		},
		callback
	);
});

gulp.task('default', ['generate-service-worker']);
<|endoftext|>


<commit_before>(function($, undefined) {

  function fitToWindowHeight() {
    var shelfbrowser = $(".shelfbrowser");

    if (shelfbrowser.size() > 0) {
      var topOffset = shelfbrowser.offset().top;
      var height    = $(window).innerHeight() - topOffset;

      shelfbrowser.css("height",  height);
      // set a bunch of elements to have same height, CSS tricks
      // to make it expand to fit weren't working esp in IE.
      $(".shelfbrowser-stackview").css("height", height);
      $(".shelfbrowser-browser-column").css("height", height);
      $(".shelfbrowser-info-column").css("height", height);
    }
  }

  window.doit = true;

  function loadItem(base_url, panel, item) {
    // Fade out the existing content with a pretty cheesy effect,
    // ends up less confusing when load is slowish. Cheesy implementation.
    panel.wrapInner("

");
    panel.find(".rails-stackview-panel-wrap").delay(400).fadeTo(600, 0.2);

    if (window.doit) {
    $.ajax({
      url: base_url,
      data: {
        'id': item.system_id,
        'sort_key': item.sort_key,
        'sort_key_display': item.sort_key_display,
        'sort_key_type': item.sort_key_type
      },
      dataType: "html",
      success: function(html, status, xhr) {
        panel.html( html );
      },
      error: function(xhr, status, error) {
        panel.html(errorPanel(error));
      }
    });
    }
  }

  function errorPanel(text) {
    return '
Sorry, we can not display this item.' +
    (text ? (' (' + text + ')') : '') +
    '
';
  }

  // We add origin_sort_key=$sort_key into the current
  // URL using pushState, if in a browser that supports.
  //
  // The intention is to 'remember' the currently selected
  // item on browser back button to this page, etc.
  //
  // It does assume the host app is supporting ?origin_sort_key=$sort_key
  // and passing it to template, to work. Could make more configurable
  // later.
  function replaceSelectedState(item) {
    if ('history' in window && 'replaceState' in history && 'sort_key' in item) {
      var query = location.search;
      if (query.length == 0)
        query = '?';

      // replace origin_sort_key only if it exists
      var re = new RegExp("([\\?&])origin_sort_key=([^&#]*)");
      query = query.replace(re, '$1origin_sort_key=' + encodeURIComponent(item.sort_key));

      history.replaceState({}, '', query + location.hash);
    }
  }

  $( document ).on("ready", function() {
    if ($(".shelfbrowser").length > 0) {
      fitToWindowHeight();

      $( window ).on("resize", function() {
        fitToWindowHeight();
      });

      // If stackview_browser_item_path is defined, click on item
      // should load partial via AJAX, and preventDefault.
      $(document).on("click", ".shelfbrowser .stack-item a", function(event) {
        var target        = $(event.target);
        var item_load_url = target.closest(".shelfbrowser-browse-column").data('stackviewBrowserItemPath');
        var panel         = target.closest(".shelfbrowser").find(".shelfbrowser-info-column .stack-item-panel").filter(":visible");

        var item_attribute_hash = target.closest(".stack-item").data("stackviewItem");

        replaceSelectedState(item_attribute_hash);

        if(item_load_url && panel.length > 0) {
          event.preventDefault();

          loadItem(item_load_url,  panel,  item_attribute_hash );

          $('.active-item').removeClass('active-item');
          $(this).parent().addClass('active-item');
        }
      });

      // Catch stackview.page the FIRST time, so we can find the origin
      // document and add a special class to it, which we'll use to click
      // on it immediately, and set the scroll view so it's centered.
      $(document).on("stackview.pageload.initial-select", function(event) {
        // Find the .stack-item which has data origin:true set, and click it.
        // Since we're only executing on first load, this shouldn't be
        // that many items.

        var item_load_url = $(event.target).closest(".shelfbrowser-browse-column").data('stackviewBrowserItemPath');

        var $origin_item;

        // Add .origin-item to origin, so we can do things with it....
        $(event.target).find(".stack-item").each(function(index, item) {
          if($(item).data("stackviewItem").is_origin_item) {
            $origin_item = $(item);
            // We add stackview-origin class to allow us to
            // find it and position the scroll properly on load.
            $origin_item.addClass("stackview-origin");
          }
        });

        //... we want to simulate clicking the origin, if we have a load url,
        // so we can load it.
        if (item_load_url) {
          $origin_item.find("a").trigger('click');
        }

        //... we want to try to set the scroll such that our origin item is
        // centered.
        // stackview out of the box doesn't quite get this right, it's tricky,
        // we seem to be doing okay.
        var container = $origin_item.closest("ul.stack-items");
        container.scrollTop( $origin_item.get(0).offsetTop - (container.height() / 2) + ($origin_item.height() / 2) )

        // Remove our handler, we only want to do this once.
        $(document).off("stackview.pageload.initial-select");
      });
    }
  });

})(jQuery);<commit_msg>workaround to chrome bug<commit_after>(function($, undefined) {

  function fitToWindowHeight() {
    var shelfbrowser = $(".shelfbrowser");

    if (shelfbrowser.size() > 0) {
      var topOffset = shelfbrowser.offset().top;
      var height    = $(window).innerHeight() - topOffset;

      shelfbrowser.css("height",  height);
      // set a bunch of elements to have same height, CSS tricks
      // to make it expand to fit weren't working esp in IE.
      $(".shelfbrowser-stackview").css("height", height);
      $(".shelfbrowser-browser-column").css("height", height);
      $(".shelfbrowser-info-column").css("height", height);
    }
  }

  window.doit = true;

  function loadItem(base_url, panel, item) {
    // Fade out the existing content with a pretty cheesy effect,
    // ends up less confusing when load is slowish. Cheesy implementation.
    panel.wrapInner("

");
    panel.find(".rails-stackview-panel-wrap").delay(400).fadeTo(600, 0.2);

    if (window.doit) {
    $.ajax({
      url: base_url,
      data: {
        'id': item.system_id,
        'sort_key': item.sort_key,
        'sort_key_display': item.sort_key_display,
        'sort_key_type': item.sort_key_type
      },
      dataType: "html",
      success: function(html, status, xhr) {
        panel.html( html );
      },
      error: function(xhr, status, error) {
        panel.html(errorPanel(error));
      }
    });
    }
  }

  function errorPanel(text) {
    return '
Sorry, we can not display this item.' +
    (text ? (' (' + text + ')') : '') +
    '
';
  }

  // We add origin_sort_key=$sort_key into the current
  // URL using pushState, if in a browser that supports.
  //
  // The intention is to 'remember' the currently selected
  // item on browser back button to this page, etc.
  //
  // It does assume the host app is supporting ?origin_sort_key=$sort_key
  // and passing it to template, to work. Could make more configurable
  // later.
  function replaceSelectedState(item) {
    if ('history' in window && 'replaceState' in history && 'sort_key' in item) {
      var query = location.search;
      if (query.length == 0)
        query = '?';

      // replace origin_sort_key only if it exists
      var re = new RegExp("([\\?&])origin_sort_key=([^&#]*)");
      query = query.replace(re, '$1origin_sort_key=' + encodeURIComponent(item.sort_key));

      history.replaceState({}, '', query + location.hash);
    }
  }

  $( document ).on("ready", function() {
    if ($(".shelfbrowser").length > 0) {
      fitToWindowHeight();

      $( window ).on("resize", function() {
        fitToWindowHeight();
      });

      // If stackview_browser_item_path is defined, click on item
      // should load partial via AJAX, and preventDefault.
      $(document).on("click", ".shelfbrowser .stack-item a", function(event) {
        var target        = $(event.target);
        var item_load_url = target.closest(".shelfbrowser-browse-column").data('stackviewBrowserItemPath');
        var panel         = target.closest(".shelfbrowser").find(".shelfbrowser-info-column .stack-item-panel").filter(":visible");

        var item_attribute_hash = target.closest(".stack-item").data("stackviewItem");

        replaceSelectedState(item_attribute_hash);

        if(item_load_url && panel.length > 0) {
          event.preventDefault();

          loadItem(item_load_url,  panel,  item_attribute_hash );

          $('.active-item').removeClass('active-item');
          $(this).parent().addClass('active-item');

          // Some kind of bug in chrome/webkit is sometimes making
          // parts of the info column be not properly painted, especially
          // on retina screens.  Think we trigger it by changing DOM inside an
          // overflow:auto section.
          // This seems to work around it hackily:
          $(".shelfbrowser-info-column").fadeTo(1, .99).fadeTo(1, 1);
        }
      });

      // Catch stackview.page the FIRST time, so we can find the origin
      // document and add a special class to it, which we'll use to click
      // on it immediately, and set the scroll view so it's centered.
      $(document).on("stackview.pageload.initial-select", function(event) {
        // Find the .stack-item which has data origin:true set, and click it.
        // Since we're only executing on first load, this shouldn't be
        // that many items.

        var item_load_url = $(event.target).closest(".shelfbrowser-browse-column").data('stackviewBrowserItemPath');

        var $origin_item;

        // Add .origin-item to origin, so we can do things with it....
        $(event.target).find(".stack-item").each(function(index, item) {
          if($(item).data("stackviewItem").is_origin_item) {
            $origin_item = $(item);
            // We add stackview-origin class to allow us to
            // find it and position the scroll properly on load.
            $origin_item.addClass("stackview-origin");
          }
        });

        //... we want to simulate clicking the origin, if we have a load url,
        // so we can load it.
        if (item_load_url) {
          $origin_item.find("a").trigger('click');
        }

        //... we want to try to set the scroll such that our origin item is
        // centered.
        // stackview out of the box doesn't quite get this right, it's tricky,
        // we seem to be doing okay.
        var container = $origin_item.closest("ul.stack-items");
        container.scrollTop( $origin_item.get(0).offsetTop - (container.height() / 2) + ($origin_item.height() / 2) )

        // Remove our handler, we only want to do this once.
        $(document).off("stackview.pageload.initial-select");
      });
    }
  });

})(jQuery);<|endoftext|>


<commit_before>var bower = require('gulp-bower');
var del = require('del');
var gulp = require('gulp');
var htmlbeautify = require('gulp-html-beautify');
var manifest = require('gulp-manifest');
var modernizr = require('gulp-modernizr');
var nunjucks = require('gulp-nunjucks');
var rename = require('gulp-rename');

var mainstyle = require('./gulp-tools/mainstyle');
var filecount = require('./gulp-tools/filecount');

var htmlbeautify_options = { 'indent_size': 2, 'max_preserve_newlines': 0 }

gulp.task('all', ['lib']);
gulp.task('build', ['build-static', 'build-boule']);
gulp.task('clean', ['clean-lib', 'clean-build']);
gulp.task('update', ['update-mainstyle']);

gulp.task('lib', ['lib-blob', 'lib-extend', 'lib-filesaver', 'lib-jquery', 'lib-jsdiff', 'lib-modernizr', 'lib-normalize', 'lib-typeahead']);

gulp.task('bower', function () {
    return bower();
});

/**
 * lib/
 **/
gulp.task('lib-blob', ['bower'], function () {
    return gulp.src('bower_components/Blob/Blob.js')
        .pipe(filecount())
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-extend', ['bower'], function () {
    return gulp.src('bower_components/extend/index.js')
        .pipe(filecount())
        .pipe(rename('extend.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-filesaver', ['bower'], function () {
    return gulp.src('bower_components/FileSaver/FileSaver.min.js')
        .pipe(filecount())
        .pipe(rename('FileSaver.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-jsdiff', ['bower'], function () {
    return gulp.src('bower_components/jsdiff/diff.min.js')
        .pipe(filecount())
        .pipe(rename('diff.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-normalize', ['bower'], function () {
    return gulp.src('bower_components/normalize.css/normalize.css')
        .pipe(filecount())
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-jquery', ['bower'], function () {
    return gulp.src('bower_components/jquery/dist/jquery.min.js')
        .pipe(filecount())
        .pipe(rename('jquery.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-typeahead', ['bower'], function () {
    return gulp.src('bower_components/typeahead.js/dist/typeahead.bundle.min.js')
        .pipe(filecount())
        .pipe(rename('typeahead.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-modernizr', function () {
    gulp.src('{core,legacy}/scripts/**/*.js')
        .pipe(filecount())
        .pipe(modernizr())
        .pipe(gulp.dest("lib/"));
});

/**
 * clean
 **/
gulp.task('clean-lib', function () {
    return del('lib');
});

gulp.task('clean-build', function () {
    return del('build');
});

gulp.task('clean-dev', function () {
    return del('dev');
});

/**
 * build
 **/
gulp.task('build-static', ['build-static-images', 'build-static-html', 'build-static-manifest']);

gulp.task('build-static-html', function () {
    return gulp.src('index.html')
        .pipe(filecount())
        .pipe(gulp.dest('build/'));
});

gulp.task('build-static-images', function () {
    return gulp.src('images/*.png')
        .pipe(filecount())
        .pipe(gulp.dest('build/images/'));
});

gulp.task('build-static-manifest', function () {
    return gulp.src(['index.html', 'images/*.png'], { base: './' })
        .pipe(filecount())
        .pipe(manifest({ filename: 'manifest.appcache', timestamp: false, hash: true }))
        .pipe(filecount())
        .pipe(gulp.dest('build/'));
});

/**
 * update
 **/
gulp.task('update-mainstyle', ['lib-normalize'], function () {
    return gulp.src(['lib/*.css', '{core,legacy}/style/*.css', '!core/style/mainstyle.css'], { base: './' })
        .pipe(filecount())
        .pipe(mainstyle())
        .pipe(filecount())
        .pipe(gulp.dest('core/style'));
});

/**
 * build templates
 **/
gulp.task('build-boule', ['build-boule-template']);
gulp.task('build-boule-template', function () {
    return gulp.src('core/templates/index.html')
        .pipe(filecount())
        .pipe(nunjucks.compile({}))
        .pipe(htmlbeautify(htmlbeautify_options))
        .pipe(filecount())
        .pipe(gulp.dest('build/boule/'));
});
<commit_msg>gulpfile.js: reading proper strings (via requirejs) for template-boule<commit_after>var bower = require('gulp-bower');
var del = require('del');
var gulp = require('gulp');
var htmlbeautify = require('gulp-html-beautify');
var manifest = require('gulp-manifest');
var modernizr = require('gulp-modernizr');
var nunjucks = require('gulp-nunjucks');
var rename = require('gulp-rename');

var mainstyle = require('./gulp-tools/mainstyle');
var filecount = require('./gulp-tools/filecount');

var htmlbeautify_options = { 'indent_size': 2, 'max_preserve_newlines': 0 }

gulp.task('all', ['lib']);
gulp.task('build', ['build-static', 'build-boule']);
gulp.task('clean', ['clean-lib', 'clean-build']);
gulp.task('update', ['update-mainstyle']);

gulp.task('lib', ['lib-blob', 'lib-extend', 'lib-filesaver', 'lib-jquery', 'lib-jsdiff', 'lib-modernizr', 'lib-normalize', 'lib-typeahead']);

gulp.task('bower', function () {
    return bower();
});

/**
 * lib/
 **/
gulp.task('lib-blob', ['bower'], function () {
    return gulp.src('bower_components/Blob/Blob.js')
        .pipe(filecount())
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-extend', ['bower'], function () {
    return gulp.src('bower_components/extend/index.js')
        .pipe(filecount())
        .pipe(rename('extend.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-filesaver', ['bower'], function () {
    return gulp.src('bower_components/FileSaver/FileSaver.min.js')
        .pipe(filecount())
        .pipe(rename('FileSaver.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-jsdiff', ['bower'], function () {
    return gulp.src('bower_components/jsdiff/diff.min.js')
        .pipe(filecount())
        .pipe(rename('diff.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-normalize', ['bower'], function () {
    return gulp.src('bower_components/normalize.css/normalize.css')
        .pipe(filecount())
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-jquery', ['bower'], function () {
    return gulp.src('bower_components/jquery/dist/jquery.min.js')
        .pipe(filecount())
        .pipe(rename('jquery.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-typeahead', ['bower'], function () {
    return gulp.src('bower_components/typeahead.js/dist/typeahead.bundle.min.js')
        .pipe(filecount())
        .pipe(rename('typeahead.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-modernizr', function () {
    gulp.src('{core,legacy}/scripts/**/*.js')
        .pipe(filecount())
        .pipe(modernizr())
        .pipe(gulp.dest("lib/"));
});

/**
 * clean
 **/
gulp.task('clean-lib', function () {
    return del('lib');
});

gulp.task('clean-build', function () {
    return del('build');
});

gulp.task('clean-dev', function () {
    return del('dev');
});

/**
 * build
 **/
gulp.task('build-static', ['build-static-images', 'build-static-html', 'build-static-manifest']);

gulp.task('build-static-html', function () {
    return gulp.src('index.html')
        .pipe(filecount())
        .pipe(gulp.dest('build/'));
});

gulp.task('build-static-images', function () {
    return gulp.src('images/*.png')
        .pipe(filecount())
        .pipe(gulp.dest('build/images/'));
});

gulp.task('build-static-manifest', function () {
    return gulp.src(['index.html', 'images/*.png'], { base: './' })
        .pipe(filecount())
        .pipe(manifest({ filename: 'manifest.appcache', timestamp: false, hash: true }))
        .pipe(filecount())
        .pipe(gulp.dest('build/'));
});

/**
 * update
 **/
gulp.task('update-mainstyle', ['lib-normalize'], function () {
    return gulp.src(['lib/*.css', '{core,legacy}/style/*.css', '!core/style/mainstyle.css'], { base: './' })
        .pipe(filecount())
        .pipe(mainstyle())
        .pipe(filecount())
        .pipe(gulp.dest('core/style'));
});

/**
 * build & templates
 **/
gulp.task('build-boule', ['template-boule']);
gulp.task('template-boule', function () {
    var requirejs = require('requirejs').config({
        baseUrl: 'boule/scripts',
        paths: {
            'ui': '../../legacy/scripts/ui/'
        },
        nodeRequire: require
    });

    var strings = requirejs('ui/strings');

    return gulp.src('core/templates/index.html')
        .pipe(filecount())
        .pipe(nunjucks.compile(strings))
        .pipe(filecount())
        .pipe(htmlbeautify(htmlbeautify_options))
        .pipe(filecount())
        .pipe(gulp.dest('boule/'));
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var sass = require('gulp-sass');
var nunjucks = require('gulp-nunjucks-html');
var spritesmith = require('gulp.spritesmith');
var merge = require('merge-stream');
var sourcemaps = require('gulp-sourcemaps');
var cleanCSS = require('gulp-clean-css');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var webserver = require('gulp-webserver');
var argv = require('yargs').argv;
var gulpif = require('gulp-if');
var urlAdjuster = require('gulp-css-url-adjuster');

var settings = {
	build: {
		prod: !!(argv.production || argv.prod),
		version: parseInt(Math.random() * 10000000) + "-" + parseInt(Math.random() * 10000000)
	}
}

console.log('Production mode: ', settings.build.prod);

gulp.task('styles', ['sprite'], function () {
	return gulp.src([
		'./m/_scss/**/*.scss'
	])
		.pipe(sass().on('error', sass.logError))
		.pipe(concat('site.min.css'))
		.pipe(urlAdjuster({
			prepend: '',
		    append: '',
		    replace:  ['../fonts/','../f/'],
		}))
		.pipe(gulpif(!settings.build.prod, sourcemaps.init()))
		.pipe(cleanCSS())
		.pipe(gulpif(!settings.build.prod, sourcemaps.write()))
		.pipe(gulp.dest('./m/css'));
});

gulp.task('html', function () {
	return gulp.src('./m/_templates/*.html')
		.pipe(nunjucks({
			searchPaths: ['./m/_templates'],
			tags: {
				blockStart: '<%',
				blockEnd: '%>',
				variableStart: '<$',
				variableEnd: '$>',
				commentStart: '<#',
				commentEnd: '#>'
			}
		}))
		.pipe(gulp.dest('./'));
});

gulp.task('webfonts', function() {
	return gulp.src([
	])
	.pipe(gulp.dest('./m/f/'));
});

gulp.task('js-pre', function () {
	return gulp.src([
		'./m/_vendor/jquery/dist/jquery.min.js',
		'./m/_vendor/bootstrap-sass/assets/javascripts/bootstrap.min.js',
		'./m/_vendor/helix.jquery.equal-heights/src/jquery.equal-heights.js',
		'./m/_vendor/underscore/underscore-min.js',
		'./m/js/app/pre/**/*.js'
	])
		.pipe(gulpif(!settings.build.prod, sourcemaps.init()))
		.pipe(concat('pre.min.js'))
		.pipe(gulpif(settings.build.prod, uglify()))
		.pipe(gulpif(!settings.build.prod, sourcemaps.write('./')))
		.pipe(gulp.dest('./m/js/'));
});

gulp.task('js-post', function () {
	return gulp.src([
		'./m/js/app/post/**/*.js',
	])
		.pipe(gulpif(!settings.build.prod, sourcemaps.init()))
		.pipe(concat('post.min.js'))
		.pipe(gulpif(settings.build.prod, uglify()))
		.pipe(gulpif(!settings.build.prod, sourcemaps.write('./')))
		.pipe(gulp.dest('./m/js/'));
});

gulp.task('js', ['js-pre', 'js-post'], function () { });

gulp.task('sprite', function () {
	var spriteData = gulp.src('./m/i/_spritesource/**/*.png')
		.pipe(spritesmith({
			padding: 15,
			imgName: 'sprite.png',
			imgPath: '../i/sprite.png?' + settings.build.version,
			cssName: '_sprites.scss',
			retinaSrcFilter: ['./m/i/_spritesource/**/*@2x.png'],
			retinaImgName: 'sprite@2x.png',
			retinaImgPath: '../i/sprite@2x.png?' + settings.build.version,
		}));

	var imgStream = spriteData.img
		.pipe(gulp.dest('./m/i/'));

	var cssStream = spriteData.css
		.pipe(gulp.dest('./m/_scss/'));

	return merge(imgStream, cssStream);
});

gulp.task('webserver', ['default'], function () {
	gulp.src('./')
		.pipe(webserver({
			livereload: {
				enable: true,
				filter: function (fileName) {
					if (fileName.match(/.map$/)) {
						return false;
					} else {
						return true;
					}
				}
			},
			directoryListing: true,
			open: true
		}));
});

gulp.task('process', ['webfonts', 'styles', 'html', 'js'], function () { });

gulp.task('default', ['process'], function () {
	gulp.watch('./m/_scss/**/*', ['styles']);
	gulp.watch('./m/_templates/**/*', ['html']);
	gulp.watch('./m/i/_spritesource/**/*', ['sprite']);
	gulp.watch('./m/_vendor/**/*', ['js']);
	gulp.watch('./m/js/app/**/*', ['js']);
});
<commit_msg>switch from bower vendor folder to node-mnodules<commit_after>var gulp = require('gulp');
var sass = require('gulp-sass');
var nunjucks = require('gulp-nunjucks-html');
var spritesmith = require('gulp.spritesmith');
var merge = require('merge-stream');
var sourcemaps = require('gulp-sourcemaps');
var cleanCSS = require('gulp-clean-css');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var webserver = require('gulp-webserver');
var argv = require('yargs').argv;
var gulpif = require('gulp-if');
var urlAdjuster = require('gulp-css-url-adjuster');

var settings = {
	build: {
		prod: !!(argv.production || argv.prod),
		version: parseInt(Math.random() * 10000000) + "-" + parseInt(Math.random() * 10000000)
	}
}

console.log('Production mode: ', settings.build.prod);

gulp.task('styles', ['sprite'], function () {
	return gulp.src([
		'./m/_scss/**/*.scss'
	])
		.pipe(sass().on('error', sass.logError))
		.pipe(concat('site.min.css'))
		.pipe(urlAdjuster({
			prepend: '',
		    append: '',
		    replace:  ['../fonts/','../f/'],
		}))
		.pipe(gulpif(!settings.build.prod, sourcemaps.init()))
		.pipe(cleanCSS())
		.pipe(gulpif(!settings.build.prod, sourcemaps.write()))
		.pipe(gulp.dest('./m/css'));
});

gulp.task('html', function () {
	return gulp.src('./m/_templates/*.html')
		.pipe(nunjucks({
			searchPaths: ['./m/_templates'],
			tags: {
				blockStart: '<%',
				blockEnd: '%>',
				variableStart: '<$',
				variableEnd: '$>',
				commentStart: '<#',
				commentEnd: '#>'
			}
		}))
		.pipe(gulp.dest('./'));
});

gulp.task('webfonts', function() {
	return gulp.src([
	])
	.pipe(gulp.dest('./m/f/'));
});

gulp.task('js-pre', function () {
	return gulp.src([
		'./node_modules/jquery/dist/jquery.min.js',
		'./node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js',
		'./node_modules/jquery.equal-heights/src/jquery.equal-heights.js',
		'./node_modules/underscore/underscore-min.js',
		'./m/js/app/pre/**/*.js'
	])
		.pipe(gulpif(!settings.build.prod, sourcemaps.init()))
		.pipe(concat('pre.min.js'))
		.pipe(gulpif(settings.build.prod, uglify()))
		.pipe(gulpif(!settings.build.prod, sourcemaps.write('./')))
		.pipe(gulp.dest('./m/js/'));
});

gulp.task('js-post', function () {
	return gulp.src([
		'./m/js/app/post/**/*.js',
	])
		.pipe(gulpif(!settings.build.prod, sourcemaps.init()))
		.pipe(concat('post.min.js'))
		.pipe(gulpif(settings.build.prod, uglify()))
		.pipe(gulpif(!settings.build.prod, sourcemaps.write('./')))
		.pipe(gulp.dest('./m/js/'));
});

gulp.task('js', ['js-pre', 'js-post'], function () { });

gulp.task('sprite', function () {
	var spriteData = gulp.src('./m/i/_spritesource/**/*.png')
		.pipe(spritesmith({
			padding: 15,
			imgName: 'sprite.png',
			imgPath: '../i/sprite.png?' + settings.build.version,
			cssName: '_sprites.scss',
			retinaSrcFilter: ['./m/i/_spritesource/**/*@2x.png'],
			retinaImgName: 'sprite@2x.png',
			retinaImgPath: '../i/sprite@2x.png?' + settings.build.version,
		}));

	var imgStream = spriteData.img
		.pipe(gulp.dest('./m/i/'));

	var cssStream = spriteData.css
		.pipe(gulp.dest('./m/_scss/'));

	return merge(imgStream, cssStream);
});

gulp.task('webserver', ['default'], function () {
	gulp.src('./')
		.pipe(webserver({
			livereload: {
				enable: true,
				filter: function (fileName) {
					if (fileName.match(/.map$/)) {
						return false;
					} else {
						return true;
					}
				}
			},
			directoryListing: true,
			open: true
		}));
});

gulp.task('process', ['webfonts', 'styles', 'html', 'js'], function () { });

gulp.task('default', ['process'], function () {
	gulp.watch('./m/_scss/**/*', ['styles']);
	gulp.watch('./m/_templates/**/*', ['html']);
	gulp.watch('./m/i/_spritesource/**/*', ['sprite']);
	gulp.watch('./m/js/app/**/*', ['js']);
});
<|endoftext|>


<commit_before>class ListLabel {
  constructor(obj) {
    this.id = obj.id;
    this.title = obj.title;
    this.type = obj.type;
    this.color = obj.color;
    this.textColor = obj.text_color;
    this.description = obj.description;
    this.priority = (obj.priority !== null) ? obj.priority : Infinity;
  }
}

window.ListLabel = ListLabel;
<commit_msg>Export class as default<commit_after>export default class ListLabel {
  constructor(obj) {
    this.id = obj.id;
    this.title = obj.title;
    this.type = obj.type;
    this.color = obj.color;
    this.textColor = obj.text_color;
    this.description = obj.description;
    this.priority = (obj.priority !== null) ? obj.priority : Infinity;
  }
}

window.ListLabel = ListLabel;
<|endoftext|>


<commit_before>const path = require('path')
const gulp = require('gulp')
const webpack = require('webpack-stream')
const gutil = require('gulp-util')
const gzip = require('gulp-gzip')
const rename = require('gulp-rename')
const uglify = require('gulp-uglify')
const sourcemaps = require('gulp-sourcemaps')
const webpackConfig = require('./webpack.config.js')

gulp.task('build', (done) => {
  // inprogress.js
  webpack(Object.assign(webpackConfig, {
    entry: path.resolve(__dirname, 'index.js'),
    output: {
      filename: 'inprogress.js'
    }
  }))
    .pipe(gulp.dest('dist'))
    // inprogress.min.js + source map
    .pipe(sourcemaps.init())
    .pipe(uglify().on('error', gutil.log))
    .pipe(gzip())
    .pipe(rename('inprogress.min.js'))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist'))
})
<commit_msg>chore: Add library option<commit_after>const path = require('path')
const gulp = require('gulp')
const webpack = require('webpack-stream')
const gutil = require('gulp-util')
const gzip = require('gulp-gzip')
const rename = require('gulp-rename')
const uglify = require('gulp-uglify')
const sourcemaps = require('gulp-sourcemaps')
const webpackConfig = require('./webpack.config.js')

gulp.task('build', (done) => {
  // inprogress.js
  webpack(Object.assign(webpackConfig, {
    entry: path.resolve(__dirname, 'index.js'),
    output: {
      filename: 'inprogress.js',
      library: 'InProgress',
      libraryTarget: 'umd'
    }
  }))
    .pipe(gulp.dest('dist'))
    // inprogress.min.js + source map
    .pipe(sourcemaps.init())
    .pipe(uglify().on('error', gutil.log))
    .pipe(gzip())
    .pipe(rename('inprogress.min.js'))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist'))
})
<|endoftext|>


<commit_before>"use strict";
var fs = require("fs");
var path = require("path");
var gulp = require("gulp"),
  runSequence = require("run-sequence"),
  del = require("del"),
  jasmine = require("gulp-jasmine"),
  tslint = require("gulp-tslint"),
  tsc = require("gulp-typescript"),
  sourcemaps = require("gulp-sourcemaps");

gulp.task("lint", function () {
  return gulp.src([
    "src/**/**.ts",
    "spec/**.ts",
    "typings/**.d.ts",
    "!lib/**",
    "!maps/**"
  ])
    .pipe(tslint({}))
    .pipe(tslint.report("verbose"));
});

var tsProjectForJs = tsc.createProject("tsconfig.json");
var tsProjectForDts = tsc.createProject("tsconfig.json");
gulp.task("build-js", function () {
  return gulp.src([
    "./**/**.ts",
    "!./spec/**",
    "!./lib/**",
    "!./node_modules/**"
  ])
    .pipe(sourcemaps.init())
    .pipe(tsc(tsProjectForJs))
    .js
    .pipe(sourcemaps.write("../maps", {
      includeContent: false,
      sourceRoot: function (file) {
        // needed to fix relative path in sourceMaps
        var path = "../".repeat((file.relative.match(/\//g) || []).length + 1);
        return path;
      }
    }))
    .pipe(gulp.dest("lib"));
})
gulp.task("build-dts", function () {
  return gulp.src([
    "./**/**.ts",
    "!./spec/**",
    "!./lib/**",
    "!./node_modules/**"
  ])
    .pipe(tsc(tsProjectForDts))
    .dts
    .pipe(gulp.dest("lib"));
})
gulp.task("build-package.json", function () {
  var appPackageJson = JSON.parse(fs.readFileSync(__dirname + "/package.json", "utf8"));
  var npmPackageJson = {
    "name": appPackageJson.name,
    "description": appPackageJson.description,
    "version": appPackageJson.version,
    "author": appPackageJson.author,
    "repository": appPackageJson.repository,
    "main": "system/index.js",      // TODO: generate this from app package.json
    "typings": "system/index.d.ts", // TODO: generate this from app package.json
    "dependencies": appPackageJson.dependencies,
    "keywords": appPackageJson.keywords,
    "license": appPackageJson.license,
    "bugs": appPackageJson.bugs
  }
  fs.mkdirSync(path.join(__dirname, "lib"));
  fs.mkdirSync(path.join(__dirname, "lib", "src"));
  fs.writeFileSync(path.join(__dirname, "lib", "src", "package.json"), JSON.stringify(npmPackageJson, null, 2));
});

gulp.task("copy", function () {
  return gulp.src([
    "./**/**settings.json",
    "README.md",
    "LICENSE"
  ])
    .pipe(gulp.dest("lib/src"));
});

gulp.task("build", function (cb) {
  return runSequence(
    "clean-all",
    ["build-js", "build-dts", "copy", "build-package.json"],
    cb
  );
});

gulp.task("build-spec", function (cb) {
  return gulp.src([
    "./**/**.ts",
    "!./src/**",
    "!./lib/**",
    "!./node_modules/**"
  ])
    .pipe(sourcemaps.init())
    .pipe(tsc(tsProjectForJs))
    .js
    .pipe(sourcemaps.write("../maps", {
      includeContent: false,
      sourceRoot: function (file) {
        // needed to fix relative path in sourceMaps
        var path = "../".repeat((file.relative.match(/\//g) || []).length + 1);
        return path;
      }
    }))
    .pipe(gulp.dest("lib"));
});

gulp.task("tests", ["build-spec"], function () {
  return gulp.src("./")
    .pipe(jasmine({ config: require("./spec/support/jasmine.json"), includeStackTrace: true, verbose: true }));
});

gulp.task("clean-all", function () {
  return del(["./maps", "./lib"]);
});

//alternative name for the "tests" task
gulp.task("specs", ["tests"]);

gulp.task("server", function () {
  require("./lib/src/server");
});
<commit_msg>Unecessary file in copy task removed<commit_after>"use strict";
var fs = require("fs");
var path = require("path");
var gulp = require("gulp"),
  runSequence = require("run-sequence"),
  del = require("del"),
  jasmine = require("gulp-jasmine"),
  tslint = require("gulp-tslint"),
  tsc = require("gulp-typescript"),
  sourcemaps = require("gulp-sourcemaps");

gulp.task("lint", function () {
  return gulp.src([
    "src/**/**.ts",
    "spec/**.ts",
    "typings/**.d.ts",
    "!lib/**",
    "!maps/**"
  ])
    .pipe(tslint({}))
    .pipe(tslint.report("verbose"));
});

var tsProjectForJs = tsc.createProject("tsconfig.json");
var tsProjectForDts = tsc.createProject("tsconfig.json");
gulp.task("build-js", function () {
  return gulp.src([
    "./**/**.ts",
    "!./spec/**",
    "!./lib/**",
    "!./node_modules/**"
  ])
    .pipe(sourcemaps.init())
    .pipe(tsc(tsProjectForJs))
    .js
    .pipe(sourcemaps.write("../maps", {
      includeContent: false,
      sourceRoot: function (file) {
        // needed to fix relative path in sourceMaps
        var path = "../".repeat((file.relative.match(/\//g) || []).length + 1);
        return path;
      }
    }))
    .pipe(gulp.dest("lib"));
})
gulp.task("build-dts", function () {
  return gulp.src([
    "./**/**.ts",
    "!./spec/**",
    "!./lib/**",
    "!./node_modules/**"
  ])
    .pipe(tsc(tsProjectForDts))
    .dts
    .pipe(gulp.dest("lib"));
})
gulp.task("build-package.json", function () {
  var appPackageJson = JSON.parse(fs.readFileSync(__dirname + "/package.json", "utf8"));
  var npmPackageJson = {
    "name": appPackageJson.name,
    "description": appPackageJson.description,
    "version": appPackageJson.version,
    "author": appPackageJson.author,
    "repository": appPackageJson.repository,
    "main": "system/index.js",      // TODO: generate this from app package.json
    "typings": "system/index.d.ts", // TODO: generate this from app package.json
    "dependencies": appPackageJson.dependencies,
    "keywords": appPackageJson.keywords,
    "license": appPackageJson.license,
    "bugs": appPackageJson.bugs
  }
  fs.mkdirSync(path.join(__dirname, "lib"));
  fs.mkdirSync(path.join(__dirname, "lib", "src"));
  fs.writeFileSync(path.join(__dirname, "lib", "src", "package.json"), JSON.stringify(npmPackageJson, null, 2));
});

gulp.task("copy", function () {
  return gulp.src([
    "README.md",
    "LICENSE"
  ])
    .pipe(gulp.dest("lib/src"));
});

gulp.task("build", function (cb) {
  return runSequence(
    "clean-all",
    ["build-js", "build-dts", "copy", "build-package.json"],
    cb
  );
});

gulp.task("build-spec", function (cb) {
  return gulp.src([
    "./**/**.ts",
    "!./src/**",
    "!./lib/**",
    "!./node_modules/**"
  ])
    .pipe(sourcemaps.init())
    .pipe(tsc(tsProjectForJs))
    .js
    .pipe(sourcemaps.write("../maps", {
      includeContent: false,
      sourceRoot: function (file) {
        // needed to fix relative path in sourceMaps
        var path = "../".repeat((file.relative.match(/\//g) || []).length + 1);
        return path;
      }
    }))
    .pipe(gulp.dest("lib"));
});

gulp.task("tests", ["build-spec"], function () {
  return gulp.src("./")
    .pipe(jasmine({ config: require("./spec/support/jasmine.json"), includeStackTrace: true, verbose: true }));
});

gulp.task("clean-all", function () {
  return del(["./maps", "./lib"]);
});

//alternative name for the "tests" task
gulp.task("specs", ["tests"]);

gulp.task("server", function () {
  require("./lib/src/server");
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    eslint = require('gulp-eslint'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    size = require('gulp-size'),
    jasmine = require('gulp-jasmine-phantom');

var source = './nanofeed.js';
var dest = './nanofeed.min.js';

gulp.task('test', function () {
  return gulp.src('spec/*.js')
    .pipe(jasmine({
      integration: true,
      specHtml: './spec/specRunner.html'
    }));
});

gulp.task('lint', ['test'], function () {
  return gulp.src(source)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
    .pipe(eslint.results(function (results) {
      console.log('Total Files: ' + results.length);
      console.log('Total Warnings: ' + results.warningCount);
      console.log('Total Errors: ' + results.errorCount);
    }));
});

gulp.task('default', ['lint'], function () {
  return gulp.src(source)
    .pipe(rename(dest))
    .pipe(uglify())
    .pipe(size())
    .pipe(gulp.dest('./'));
});
<commit_msg>separate lint task from test<commit_after>'use strict';

var gulp = require('gulp'),
    eslint = require('gulp-eslint'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    size = require('gulp-size'),
    jasmine = require('gulp-jasmine-phantom');

var source = './nanofeed.js';
var dest = './nanofeed.min.js';

gulp.task('test', function () {
  return gulp.src('spec/*.js')
    .pipe(jasmine({
      integration: true,
      specHtml: './spec/specRunner.html'
    }));
});

gulp.task('lint', function () {
  return gulp.src(source)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
    .pipe(eslint.results(function (results) {
      console.log('Total Files: ' + results.length);
      console.log('Total Warnings: ' + results.warningCount);
      console.log('Total Errors: ' + results.errorCount);
    }));
});

gulp.task('default', ['test', 'lint'], function () {
  return gulp.src(source)
    .pipe(rename(dest))
    .pipe(uglify())
    .pipe(size())
    .pipe(gulp.dest('./'));
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Gulp tasks.
 */

const execSync = require('child_process').execSync;
const fs = require('fs');
const jsgl = require('js-green-licenses');
const path = require('path');
const rimraf = require('rimraf');

/**
 * Run the license checker for all packages.
 * @return {Promise} A promise.
 */
function checkLicenses() {
  const checker = new jsgl.LicenseChecker({
    // dev: true,
    // verbose: false,
  });
  checker.setDefaultHandlers();
  const pluginsDir = 'plugins';
  const promises = [];
  // Check root package.json.
  promises.push(checker.checkLocalDirectory('.'));
  fs.readdirSync(pluginsDir)
      .filter((file) => {
        return fs.statSync(path.join(pluginsDir, file)).isDirectory();
      }).forEach((plugin) => {
        const pluginDir = path.join(pluginsDir, plugin);
        // Check each plugin package.json.
        promises.push(checker.checkLocalDirectory(pluginDir));
      });
  return Promise.all(promises);
}

/**
 * Publish all plugins that have changed since the last release.
 * @param {boolean=} dryRun True for running through the publish script as a dry
 *     run.
 * @return {Function} Gulp task.
 */
function publish(dryRun) {
  return (done) => {
    // Login to npm.
    execSync(`npm login --registry https://wombat-dressing-room.appspot.com`,
        {stdio: 'inherit'});

    const releaseDir = path.join('..', 'blockly-samples-release');
    // Delete the release directory if it exists.
    if (fs.existsSync(releaseDir)) {
      rimraf.sync(releaseDir);
    }

    // Clone a fresh copy of blockly-samples.
    console.log(`Checking out a fresh copy of blockly-samples under\
  ${path.resolve(releaseDir)}`);
    execSync(`git clone https://github.com/google/blockly-samples ${releaseDir}`,
        {stdio: 'pipe'});

    // Run npm install.
    console.log('Running npm install.');
    execSync(`npm install`, {cwd: releaseDir, stdio: 'inherit'});

    // Run npm publish.
    execSync(`npm run publish:${dryRun ? 'check' : 'release'}`,
        {cwd: releaseDir, stdio: 'inherit'});

    done();
  };
}

/**
 * Publish all plugins.
 * @return {Function} Gulp task.
 */
function publishRelease() {
  return publish();
}

/**
 * Run through a dry run of the release script.
 * @return {Function} Gulp task.
 */
function publishDryRun() {
  return publish(true);
}

module.exports = {
  checkLicenses: checkLicenses,
  publish: publishRelease,
  publishDryRun: publishDryRun,
};
<commit_msg>Use dist instead<commit_after>/**
 * @license
 * Copyright 2020 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Gulp tasks.
 */

const execSync = require('child_process').execSync;
const fs = require('fs');
const jsgl = require('js-green-licenses');
const path = require('path');
const rimraf = require('rimraf');

/**
 * Run the license checker for all packages.
 * @return {Promise} A promise.
 */
function checkLicenses() {
  const checker = new jsgl.LicenseChecker({
    // dev: true,
    // verbose: false,
  });
  checker.setDefaultHandlers();
  const pluginsDir = 'plugins';
  const promises = [];
  // Check root package.json.
  promises.push(checker.checkLocalDirectory('.'));
  fs.readdirSync(pluginsDir)
      .filter((file) => {
        return fs.statSync(path.join(pluginsDir, file)).isDirectory();
      }).forEach((plugin) => {
        const pluginDir = path.join(pluginsDir, plugin);
        // Check each plugin package.json.
        promises.push(checker.checkLocalDirectory(pluginDir));
      });
  return Promise.all(promises);
}

/**
 * Publish all plugins that have changed since the last release.
 * @param {boolean=} dryRun True for running through the publish script as a dry
 *     run.
 * @return {Function} Gulp task.
 */
function publish(dryRun) {
  return (done) => {
    // Login to npm.
    execSync(`npm login --registry https://wombat-dressing-room.appspot.com`,
        {stdio: 'inherit'});

    const releaseDir = 'dist';
    // Delete the release directory if it exists.
    if (fs.existsSync(releaseDir)) {
      rimraf.sync(releaseDir);
    }

    // Clone a fresh copy of blockly-samples.
    console.log(`Checking out a fresh copy of blockly-samples under\
  ${path.resolve(releaseDir)}`);
    execSync(`git clone https://github.com/google/blockly-samples ${releaseDir}`,
        {stdio: 'pipe'});

    // Run npm install.
    console.log('Running npm install.');
    execSync(`npm install`, {cwd: releaseDir, stdio: 'inherit'});

    // Run npm publish.
    execSync(`npm run publish:${dryRun ? 'check' : 'release'}`,
        {cwd: releaseDir, stdio: 'inherit'});

    done();
  };
}

/**
 * Publish all plugins.
 * @return {Function} Gulp task.
 */
function publishRelease() {
  return publish();
}

/**
 * Run through a dry run of the release script.
 * @return {Function} Gulp task.
 */
function publishDryRun() {
  return publish(true);
}

module.exports = {
  checkLicenses: checkLicenses,
  publish: publishRelease,
  publishDryRun: publishDryRun,
};
<|endoftext|>