<commit_before>var OjsArticleSubmision = {
    articleId: null,
    languages: [],
    step1Show: function () {
        $("#step1-container").removeClass("hide", 200, "easeInBack");
    },
    step1Hide: function () {
        $("#step1-container").addClass("hide", 200, "easeInBack");
    },
    step2Show: function () {
        $("#step2-container").removeClass("hide", 200, "easeInBack");
    },
    step2Hide: function () {
        $("#step1-container").slideUp("fast", 200, "easeInBack");
    },
    activateFirstLanguageTab: function () {
        firsttab = $("#step1 .tab-pane").first().attr('id');
        if (firsttab) {
            $("li.lang a[href=#" + firsttab + "]").tab("show");
        }
    },
    step1AddLanguageForm: function (langcode, langtitle) {
        // check if selected language tab already exists
        if (OjstrCommon.inArray(langcode, OjsArticleSubmision.languages)) {
            return false;
        }

        var step1_template = $('#step1_tpl').html();
        var step1_rendered = Mustache.render(step1_template);

        var step2_template = $('#step2_tpl').html();
        var step2_rendered = Mustache.render(step2_template);

        $("#step1").append('
' +
                '
' + step1_rendered + '
' +
                '
' + step2_rendered + '
' +
                '
');

        OjsArticleSubmision.languages.push(langcode);
        $("div#" + langcode + " textarea.editor").wysihtml5({
            toolbar: {
                "font-styles": false,
                "emphasis": true,
                "lists": false,
                "html": false,
                "link": true,
                "image": false,
                "color": false,
                "blockquote": true
            }
        });
        tabhtml = '
' +
                langtitle + '' +
                '
';
        $("ul#mainTabs li.lang").last().before(tabhtml);
        OjsArticleSubmision.activateFirstLanguageTab();
    },
    step1RemoveLanguageForm: function (langcode, $tab) {
        check = confirm("Are you sure to remove this language tab?");
        if (!check) {
            return false;
        }
        for (var i in this.languages) {
            if (this.languages[i] === langcode) {
                this.languages.splice(i, 1);
            }
        }
        $tab.remove();
        $('#t_' + langcode).remove();
        this.activateFirstLanguageTab();
    },
    step1: function (actionUrl) {
        forms = $(".tab-pane");
        if (forms.length === 0) {
            OjstrCommon.errorModal("Add at least one language to your submission.");
            return false;
        }
        $primaryLang = $("select[name=primaryLanguage] option:selected").val();

        // prepare post params
        articleParams = false;
        translationParams = [];
        forms.each(function () {
            data = $("form", this).serializeObject();
            locale = $(this).attr('id');
            data.locale = locale;
            postUrl = actionUrl.replace('locale', locale);
            tmpParam = {"data": data, "postUrl": postUrl};
            if ($primaryLang === locale) {
                // article main data
                tmpParam.data.journalId = $("input[name=journalId]").val();
                tmpParam.data.primaryLanguage = $("select[name=primaryLanguage] option:selected").val();
                articleParams = tmpParam;
            } else {
                translationParams.push(tmpParam);
            }
        });
        if (!articleParams) {
            OjstrCommon.errorModal("Please select and fill metadata for article's language.");
            return;
        }
        /**
         * 1. post primaryLanguage's meta data
         * 2. get articleId from response
         * 3. post other meta datas for other languages
         */
        OjstrCommon.waitModal();
        if (translationParams) {
            articleParams.data.translations = JSON.stringify(translationParams);
        }
        $.post(articleParams.postUrl, articleParams.data, function (response) {
            OjstrCommon.hideallModals();
            if (response.id) {
                OjsArticleSubmision.articleId = response.id;
                OjsArticleSubmision.step2ShowCitationForm();
            } else {
                OjstrCommon.errorModal("Error occured. Try again.");
            }

        });
    },
    step2ShowCitationForm: function () {
        OjstrCommon.scrollTop();
        $("ul.submission-progress li").removeClass("active");
        $("ul.submission-progress li#submission-progress-step2").addClass("active");
        OjsArticleSubmision.step1Hide();
        OjsArticleSubmision.step2Show();
    }
};

$(document).ready(function () {
    $('select').select2({placeholder: '', allowClear: true, closeOnSelect: false});
    $("ul#mainTabs li a").click(function (e) {
        e.preventDefault();
    });
    $("ul#languageDropList li a").click(function (e) {
        e.preventDefault();
        langcode = $(this).attr('code');
        langtitle = $(this).attr('lang');
        OjsArticleSubmision.step1AddLanguageForm(langcode, langtitle);
    });
    $("body").on("click", "span.removelang", function (e) {
        e.preventDefault();
        langcode = $(this).parent().attr("href").replace("#", "");
        $tab = $("#" + langcode);
        OjsArticleSubmision.step1RemoveLanguageForm(langcode, $tab);
    });
    // article file uploader
    $('#article_file_upload').fileupload({});
    $('#article_file_upload').bind('fileuploadsend', function (e, data) {
        $(this).parent().next('.upload_progress').show();
        $(this).parent().next('.upload_progress').html("Uploading...");
    }).bind('fileuploaddone', function (e, data) {
        $(this).parent().next('.upload_progress').html("Done.");
        $('.filename', $(this).parent()).attr('value', JSON.parse(data.result).files.name);
    });
});<commit_msg>article_submission.js updated <commit_after>window.onbeforeunload = function () {
    var message = "Are you sure you want to navigate away from this page?\n\nYour changes may be lost.";
    return confirm(message);
};

var OjsArticleSubmision = {
    articleId: null,
    languages: [],
    step1Show: function () {
        $("#step1-container").removeClass("hide", 200, "easeInBack");
    },
    step1Hide: function () {
        $("#step1-container").addClass("hide", 200, "easeInBack");
    },
    step2Show: function () {
        $("#step2-container").removeClass("hide", 200, "easeInBack");
    },
    step2Hide: function () {
        $("#step1-container").slideUp("fast", 200, "easeInBack");
    },
    activateFirstLanguageTab: function () {
        firsttab = $("#step1 .tab-pane").first().attr('id');
        if (firsttab) {
            $("li.lang a[href=#" + firsttab + "]").tab("show");
        }
    },
    step1AddLanguageForm: function (langcode, langtitle) {
        // check if selected language tab already exists
        if (OjstrCommon.inArray(langcode, OjsArticleSubmision.languages)) {
            return false;
        }

        var step1_template = $('#step1_tpl').html();
        var step1_rendered = Mustache.render(step1_template);

        var step2_template = $('#step2_tpl').html();
        var step2_rendered = Mustache.render(step2_template);

        $("#step1").append('
' +
                '
' + step1_rendered + '
' +
                '
' + step2_rendered + '
' +
                '
');

        OjsArticleSubmision.languages.push(langcode);
        $("div#" + langcode + " textarea.editor").wysihtml5({
            toolbar: {
                "font-styles": false,
                "emphasis": true,
                "lists": false,
                "html": false,
                "link": true,
                "image": false,
                "color": false,
                "blockquote": true
            }
        });
        tabhtml = '
' +
                langtitle + '' +
                '
';
        $("ul#mainTabs li.lang").last().before(tabhtml);
        OjsArticleSubmision.activateFirstLanguageTab();
    },
    step1RemoveLanguageForm: function (langcode, $tab) {
        check = confirm("Are you sure to remove this language tab?");
        if (!check) {
            return false;
        }
        for (var i in this.languages) {
            if (this.languages[i] === langcode) {
                this.languages.splice(i, 1);
            }
        }
        $tab.remove();
        $('#t_' + langcode).remove();
        this.activateFirstLanguageTab();
    },
    step1: function (actionUrl) {
        forms = $(".tab-pane");
        if (forms.length === 0) {
            OjstrCommon.errorModal("Add at least one language to your submission.");
            return false;
        }
        $primaryLang = $("select[name=primaryLanguage] option:selected").val();

        // prepare post params
        articleParams = false;
        translationParams = [];
        forms.each(function () {
            data = $("form", this).serializeObject();
            locale = $(this).attr('id');
            data.locale = locale;
            postUrl = actionUrl.replace('locale', locale);
            tmpParam = {"data": data, "postUrl": postUrl};
            if ($primaryLang === locale) {
                // article main data
                tmpParam.data.journalId = $("input[name=journalId]").val();
                tmpParam.data.primaryLanguage = $("select[name=primaryLanguage] option:selected").val();
                articleParams = tmpParam;
            } else {
                translationParams.push(tmpParam);
            }
        });
        if (!articleParams) {
            OjstrCommon.errorModal("Please select and fill metadata for article's language.");
            return;
        }
        /**
         * 1. post primaryLanguage's meta data
         * 2. get articleId from response
         * 3. post other meta datas for other languages
         */
        OjstrCommon.waitModal();
        if (translationParams) {
            articleParams.data.translations = JSON.stringify(translationParams);
        }
        $.post(articleParams.postUrl, articleParams.data, function (response) {
            OjstrCommon.hideallModals();
            if (response.id) {
                OjsArticleSubmision.articleId = response.id;
                OjsArticleSubmision.step2ShowCitationForm();
            } else {
                OjstrCommon.errorModal("Error occured. Try again.");
            }

        });
    },
    step2ShowCitationForm: function () {
        OjstrCommon.scrollTop();
        $("ul.submission-progress li").removeClass("active");
        $("ul.submission-progress li#submission-progress-step2").addClass("active");
        OjsArticleSubmision.step1Hide();
        OjsArticleSubmision.step2Show();
    }
};

$(document).ready(function () {
    $('select').select2({placeholder: '', allowClear: true, closeOnSelect: false});
    $("ul#mainTabs li a").click(function (e) {
        e.preventDefault();
    });
    $("ul#languageDropList li a").click(function (e) {
        e.preventDefault();
        langcode = $(this).attr('code');
        langtitle = $(this).attr('lang');
        OjsArticleSubmision.step1AddLanguageForm(langcode, langtitle);
    });
    $("body").on("click", "span.removelang", function (e) {
        e.preventDefault();
        langcode = $(this).parent().attr("href").replace("#", "");
        $tab = $("#" + langcode);
        OjsArticleSubmision.step1RemoveLanguageForm(langcode, $tab);
    });
    // article file uploader
    $('#article_file_upload').fileupload({});
    $('#article_file_upload').bind('fileuploadsend', function (e, data) {
        $(this).parent().next('.upload_progress').show();
        $(this).parent().next('.upload_progress').html("Uploading...");
    }).bind('fileuploaddone', function (e, data) {
        $(this).parent().next('.upload_progress').html("Done.");
        $('.filename', $(this).parent()).attr('value', JSON.parse(data.result).files.name);
    });
});<|endoftext|>


<commit_before>/* eslint max-len: 0 */
import React from 'react';
import PropTypes from 'prop-types';

// Components
import Page from 'layout/page';

// Redux
import withRedux from 'next-redux-wrapper';
import { initStore } from 'store';
import * as actions from 'layout/topics/topics-actions';

import { getStaticData } from 'redactions/static_pages';

import Topics from 'layout/topics';

class TopicsPage extends Page {
  static propTypes = {
    user: PropTypes.object,
    topics: PropTypes.object,
    locale: PropTypes.string.isRequired
  };

  static async getInitialProps(context) {
    const props = await super.getInitialProps(context);

    // Dashboard thumbnail list
    context.store.dispatch(actions.setSelected(null));

    await context.store.dispatch(actions.fetchTopics({
      filters: { 'filter[published]': 'true' }
    }));

    await context.store.dispatch(getStaticData('topics'));

    return { ...props };
  }

  render() {
    return <Topics />;
  }
}

export default withRedux(
  initStore,
  null,
  actions
)(TopicsPage);
<commit_msg>updated libs<commit_after>/* eslint max-len: 0 */
import React from 'react';
import PropTypes from 'prop-types';

// Components
import Page from 'layout/page';

// Redux
import withRedux from 'next-redux-wrapper';
import { initStore } from 'store';
import * as actions from 'layout/topics/topics-actions';

import { getStaticData } from 'redactions/static_pages';

import Topics from 'layout/topics';

class TopicsPage extends Page {
  static propTypes = {
    user: PropTypes.object,
    topics: PropTypes.object
  };

  static async getInitialProps(context) {
    const props = await super.getInitialProps(context);

    // Dashboard thumbnail list
    context.store.dispatch(actions.setSelected(null));

    await context.store.dispatch(actions.fetchTopics({
      filters: { 'filter[published]': 'true' }
    }));

    await context.store.dispatch(getStaticData('topics'));

    return { ...props };
  }

  render() {
    return <Topics />;
  }
}

export default withRedux(
  initStore,
  null,
  actions
)(TopicsPage);
<|endoftext|>


<commit_before>'use strict';

var lazyReq = require('lazy-req')(require);
var inquirer = lazyReq('inquirer');
var through = lazyReq('through2');
var path = lazyReq('path');
var livereload = lazyReq('gulp-livereload');
var watch = lazyReq('gulp-watch');
var fs = require('fs-extra');
var runSequence = require('run-sequence');

var PLUGIN_PATHS = {
  SCRIPTS: 'plugin/res/js/angularjs',
  SCRIPT_DEPENDENCIES: 'plugin/res/js/angularjs/metadata',
  TEXT: 'plugin/res/lang/feature'
};

module.exports = function (gulp, gutil) {
  var scripts, sandboxApi, text, plugin, pluginUpload, pluginServer, lrListening, skins, server;

  function getScripts() {
    return scripts ? scripts : scripts = require('../lib/scripts.js')(gulp, gutil);
  }

  function getSandboxApi() {
    return sandboxApi ? sandboxApi : sandboxApi = require('../lib/sandbox-api-hack.js')(gulp, gutil);
  }

  function getText() {
    return text ? text : text = require('../lib/text.js')(gulp, gutil);;
  }

  function getPlugin() {
    return plugin ? plugin : plugin = require('../lib/plugin-create.js')(gulp, gutil);
  }

  function getSkins() {
    return skins ? skins : skins = require('../lib/skins.js')(gulp, gutil);
  }

  function getServer() {
    return server ? server : server = require('../lib/server.js')(gulp, gutil);
  }

  runSequence = runSequence.use(gulp);

  function getPluginServer() {
    if (!pluginServer) {
      pluginServer = require('../lib/plugin-server.js')(gulp, gutil);
    }

    return pluginServer;
  }

  gulp.task('plugin-scripts', function () {
    return getScripts().process(
      [
        getScripts().JS_MAIN_PATTERN,
        getScripts().TPL_MAIN_PATTERN,
        getScripts().DEPENDENCIES
      ],
      PLUGIN_PATHS.SCRIPTS,
      undefined,
      false,
      true
    );
  });

  gulp.task('plugin-script-deps', ['plugin-scripts'], function () {
    return getScripts().createDependencies(
      PLUGIN_PATHS.SCRIPTS,
      PLUGIN_PATHS.SCRIPT_DEPENDENCIES);
  });

  gulp.task('plugin-text', function () {
    var textPropPattern = gutil.env.ng.textProperties.map(function (dir) {
      return path().join(dir, getText().FILES_PATTERN);
    });
    return getText().process(textPropPattern, PLUGIN_PATHS.TEXT);
  });

  gulp.task('plugin-git-version', function (cb) {
    if (gutil.env.gitStatusVersion) {
      var gitVersion = require('../lib/git-version.js')(gulp, gutil);
      return gitVersion.create('plugin');
    } else {
      cb();
      return gutil.noop();
    }
  });

  gulp.task('plugin-ng', [
    'plugin-script-deps',
    'plugin-text'
  ]);

  gulp.task('plugin-res', gutil.env.ng ? ['plugin-ng'] : [], function () {
    return gulp.src(['res/**', '!res/**/README.md', '!res/**/*.example'])
      .pipe(gulp.dest('plugin/res'));
  });

  gulp.task('plugin-web', gutil.env.ng ? ['plugin-ng'] : [], function () {
    return gulp.src(['web/**', '!web/**/README.md', '!web/**/*.example'])
      .pipe(gulp.dest('plugin/web'));
  });

  /* plugin task */
  gulp.task('plugin-build', function (cb) {
    runSequence('clean',
      [
        'plugin-res',
        'plugin-web',
        'plugin-git-version'
      ],
      cb);
  });

  gulp.task('plugin-verify', ['plugin-build'], function (cb) {
    var originalTask = gutil.env._[0];
    if (gutil.env.verifyPlugin === false && originalTask !== 'plugin-verify') {
      cb();
    } else {
      return getPlugin().verify();
    }
  });

  gulp.task('plugin-ready', ['plugin-verify'], function (cb) {
    gutil.log(gutil.colors.green('Done compiling plugin: ' +
      path().join(process.cwd(), '/plugin')));
    cb();
  });

  gulp.task('plugin-upload', ['plugin-ready'], function () {
    var stream = through().obj();
    var server = getPluginServer().getServer();
    var uploadCallBack = function() {
      if ((gutil.env['force'] || server.force()) && !gutil.env['prompt']) {
        if (!pluginUpload) {
          pluginUpload = require('../lib/plugin-upload.js')(gulp, gutil);
        }
        pluginUpload.upload(server, {
          debugMode: gutil.env['debug']
        }).pipe(stream);
      } else {
        inquirer().prompt({
          name: 'pluginUpload',
          message: 'Would you like to upload plugin to server?',
          type: 'confirm'
        }, function (answers) {
          if (answers.pluginUpload) {
            if (!pluginUpload) {
              pluginUpload = require('../lib/plugin-upload.js')(gulp, gutil);
            }
            pluginUpload.upload(server, {
              debugMode: gutil.env['debug']
            }).pipe(stream);
          } else {
            stream.end();
          }
        });
      }
      return stream;
    };

    if (!gutil.env['skip-version-check']) {
        var versioncheck = require('../lib/version-check.js')(gulp, gutil);
        versioncheck.validate(server.serverUrl(), server.pluginToken(), server, uploadCallBack);
    } else {
        uploadCallBack();
    }
    return;
  });

  var pluginTaskDependencies = [];

  if (gutil.env['skip-upload']) {
    pluginTaskDependencies.push('plugin-ready');
  } else {
    pluginTaskDependencies.push('plugin-upload');
  }
  gulp.task('plugin', pluginTaskDependencies);

  gulp.task('plugin-dev-clean', function () {
    return getSandboxApi().deletePlugin();
  });

  gulp.task('plugin-dev-sync', ['plugin-dev-clean', 'plugin-ready'], function (cb) {
    return getSandboxApi().syncPlugin();
  });

  gulp.task('plugin-dev-refresh', ['plugin-dev-sync'], function (cb) {
    return getSandboxApi().refreshPlugin({ all: true });
  });

  function startLr() {
    if (!lrListening) {
      lrListening = true;
      livereload().listen();
    }
  }

  function addWatch(pattern, callback, cb, usePluginCacheClear) {
    startLr();

    watch()(pattern, function (file) {
      callback(file, function () {
        gutil.log(gutil.colors.cyan('Staging file for upload: ', file.path));

        if (usePluginCacheClear) {
          getSandboxApi().syncPlugin().then(function () {
            var reloadQuery = getSandboxApi().createReloadQuery(file.relative);
            return getSandboxApi().refreshPlugin(reloadQuery);
          }).then(function () {
            livereload().reload(file);
          });
        }
      });
    });
    cb();
  }

  gulp.task('watch-scripts', function (cb) {
    addWatch(
      [getScripts().JS_MAIN_PATTERN, getScripts().TPL_MAIN_PATTERN],
      function (file, done) {
        return getScripts().process(
          [getScripts().JS_MAIN_PATTERN, getScripts().TPL_MAIN_PATTERN],
          PLUGIN_PATHS.SCRIPTS,
          [file.path],
          true,
          true
        ).on('end', done);
      },
      cb,
      true
    );
  });

  gulp.task('watch-script-deps', ['plugin-ready'], function (cb) {
    addWatch(
      './sdk.conf.json',
      function (file, done) {
        return getScripts().createDependencies(
          PLUGIN_PATHS.SCRIPTS,
          PLUGIN_PATHS.SCRIPT_DEPENDENCIES,
          true
        ).on('end', done);
      },
      cb,
      true
    );
  });

  gulp.task('watch-text', function (cb) {
    var textPropPattern = gutil.env.ng.textProperties.map(function (dir) {
      return path().join(dir, getText().FILES_PATTERN);
    });
    // TODO: currently goes through all files -
    // try optimizing this for processing updated file only
    addWatch(
      textPropPattern,
      function (file, done) {
        return getText().process(textPropPattern, PLUGIN_PATHS.TEXT).on('end', done);
      },
      cb,
      true
    );
  });

  gulp.task('watch-res', function (cb) {
    addWatch(
      ['res/**', '!res/**/*.scss'].concat(gutil.env.watchResIgnore || []),
      function (file, done) {
        fs.copy(file.path, file.path.replace(process.cwd(), 'plugin'), done);
      },
      cb,
      true
    );
  });

  gulp.task('watch-res-sass', function (cb) {
    if (getServer().useLocalCompile) {
      startLr();
      getSkins().compile(livereload());
      getSkins().server();
    }

    addWatch(
        ['res/**/*.scss'].concat(gutil.env.watchResIgnore || []),
        function (file, done) {
          if (getServer().useLocalCompile) {
            getSkins().compile(livereload()).on('end', done);
          } else {
            fs.copy(file.path, file.path.replace(process.cwd(), 'plugin'), done);
          }
        },
        cb,
        !getServer().useLocalCompile
    );
  });

  gulp.task('watch-web', function (cb) {
    addWatch(
      'web/**',
      function (file, done) {
        fs.copy(file.path, file.path.replace(process.cwd(), 'plugin'), done);
      },
      cb,
      true
    );
  });

  gulp.task('watch-ng', gutil.env.ng ? [
    'watch-scripts',
    'watch-script-deps',
    'watch-text'
  ] : []);

  gulp.task('dev', [
    'plugin-dev-refresh',
    'plugin-ready',
    'watch-ng',
    'watch-res',
    'watch-web'
  ]);

  gulp.task('default', ['dev']);

};
<commit_msg>Add task<commit_after>'use strict';

var lazyReq = require('lazy-req')(require);
var inquirer = lazyReq('inquirer');
var through = lazyReq('through2');
var path = lazyReq('path');
var livereload = lazyReq('gulp-livereload');
var watch = lazyReq('gulp-watch');
var fs = require('fs-extra');
var runSequence = require('run-sequence');

var PLUGIN_PATHS = {
  SCRIPTS: 'plugin/res/js/angularjs',
  SCRIPT_DEPENDENCIES: 'plugin/res/js/angularjs/metadata',
  TEXT: 'plugin/res/lang/feature'
};

module.exports = function (gulp, gutil) {
  var scripts, sandboxApi, text, plugin, pluginUpload, pluginServer, lrListening, skins, server;

  function getScripts() {
    return scripts ? scripts : scripts = require('../lib/scripts.js')(gulp, gutil);
  }

  function getSandboxApi() {
    return sandboxApi ? sandboxApi : sandboxApi = require('../lib/sandbox-api-hack.js')(gulp, gutil);
  }

  function getText() {
    return text ? text : text = require('../lib/text.js')(gulp, gutil);;
  }

  function getPlugin() {
    return plugin ? plugin : plugin = require('../lib/plugin-create.js')(gulp, gutil);
  }

  function getSkins() {
    return skins ? skins : skins = require('../lib/skins.js')(gulp, gutil);
  }

  function getServer() {
    return server ? server : server = require('../lib/server.js')(gulp, gutil);
  }

  runSequence = runSequence.use(gulp);

  function getPluginServer() {
    if (!pluginServer) {
      pluginServer = require('../lib/plugin-server.js')(gulp, gutil);
    }

    return pluginServer;
  }

  gulp.task('plugin-scripts', function () {
    return getScripts().process(
      [
        getScripts().JS_MAIN_PATTERN,
        getScripts().TPL_MAIN_PATTERN,
        getScripts().DEPENDENCIES
      ],
      PLUGIN_PATHS.SCRIPTS,
      undefined,
      false,
      true
    );
  });

  gulp.task('plugin-script-deps', ['plugin-scripts'], function () {
    return getScripts().createDependencies(
      PLUGIN_PATHS.SCRIPTS,
      PLUGIN_PATHS.SCRIPT_DEPENDENCIES);
  });

  gulp.task('plugin-text', function () {
    var textPropPattern = gutil.env.ng.textProperties.map(function (dir) {
      return path().join(dir, getText().FILES_PATTERN);
    });
    return getText().process(textPropPattern, PLUGIN_PATHS.TEXT);
  });

  gulp.task('plugin-git-version', function (cb) {
    if (gutil.env.gitStatusVersion) {
      var gitVersion = require('../lib/git-version.js')(gulp, gutil);
      return gitVersion.create('plugin');
    } else {
      cb();
      return gutil.noop();
    }
  });

  gulp.task('plugin-ng', [
    'plugin-script-deps',
    'plugin-text'
  ]);

  gulp.task('plugin-res', gutil.env.ng ? ['plugin-ng'] : [], function () {
    return gulp.src(['res/**', '!res/**/README.md', '!res/**/*.example'])
      .pipe(gulp.dest('plugin/res'));
  });

  gulp.task('plugin-web', gutil.env.ng ? ['plugin-ng'] : [], function () {
    return gulp.src(['web/**', '!web/**/README.md', '!web/**/*.example'])
      .pipe(gulp.dest('plugin/web'));
  });

  /* plugin task */
  gulp.task('plugin-build', function (cb) {
    runSequence('clean',
      [
        'plugin-res',
        'plugin-web',
        'plugin-git-version'
      ],
      cb);
  });

  gulp.task('plugin-verify', ['plugin-build'], function (cb) {
    var originalTask = gutil.env._[0];
    if (gutil.env.verifyPlugin === false && originalTask !== 'plugin-verify') {
      cb();
    } else {
      return getPlugin().verify();
    }
  });

  gulp.task('plugin-ready', ['plugin-verify'], function (cb) {
    gutil.log(gutil.colors.green('Done compiling plugin: ' +
      path().join(process.cwd(), '/plugin')));
    cb();
  });

  gulp.task('plugin-upload', ['plugin-ready'], function () {
    var stream = through().obj();
    var server = getPluginServer().getServer();
    var uploadCallBack = function() {
      if ((gutil.env['force'] || server.force()) && !gutil.env['prompt']) {
        if (!pluginUpload) {
          pluginUpload = require('../lib/plugin-upload.js')(gulp, gutil);
        }
        pluginUpload.upload(server, {
          debugMode: gutil.env['debug']
        }).pipe(stream);
      } else {
        inquirer().prompt({
          name: 'pluginUpload',
          message: 'Would you like to upload plugin to server?',
          type: 'confirm'
        }, function (answers) {
          if (answers.pluginUpload) {
            if (!pluginUpload) {
              pluginUpload = require('../lib/plugin-upload.js')(gulp, gutil);
            }
            pluginUpload.upload(server, {
              debugMode: gutil.env['debug']
            }).pipe(stream);
          } else {
            stream.end();
          }
        });
      }
      return stream;
    };

    if (!gutil.env['skip-version-check']) {
        var versioncheck = require('../lib/version-check.js')(gulp, gutil);
        versioncheck.validate(server.serverUrl(), server.pluginToken(), server, uploadCallBack);
    } else {
        uploadCallBack();
    }
    return;
  });

  var pluginTaskDependencies = [];

  if (gutil.env['skip-upload']) {
    pluginTaskDependencies.push('plugin-ready');
  } else {
    pluginTaskDependencies.push('plugin-upload');
  }
  gulp.task('plugin', pluginTaskDependencies);

  gulp.task('plugin-dev-clean', function () {
    return getSandboxApi().deletePlugin();
  });

  gulp.task('plugin-dev-sync', ['plugin-dev-clean', 'plugin-ready'], function (cb) {
    return getSandboxApi().syncPlugin();
  });

  gulp.task('plugin-dev-refresh', ['plugin-dev-sync'], function (cb) {
    return getSandboxApi().refreshPlugin({ all: true });
  });

  function startLr() {
    if (!lrListening) {
      lrListening = true;
      livereload().listen();
    }
  }

  function addWatch(pattern, callback, cb, usePluginCacheClear) {
    startLr();

    watch()(pattern, function (file) {
      callback(file, function () {
        gutil.log(gutil.colors.cyan('Staging file for upload: ', file.path));

        if (usePluginCacheClear) {
          getSandboxApi().syncPlugin().then(function () {
            var reloadQuery = getSandboxApi().createReloadQuery(file.relative);
            return getSandboxApi().refreshPlugin(reloadQuery);
          }).then(function () {
            livereload().reload(file);
          });
        }
      });
    });
    cb();
  }

  gulp.task('watch-scripts', function (cb) {
    addWatch(
      [getScripts().JS_MAIN_PATTERN, getScripts().TPL_MAIN_PATTERN],
      function (file, done) {
        return getScripts().process(
          [getScripts().JS_MAIN_PATTERN, getScripts().TPL_MAIN_PATTERN],
          PLUGIN_PATHS.SCRIPTS,
          [file.path],
          true,
          true
        ).on('end', done);
      },
      cb,
      true
    );
  });

  gulp.task('watch-script-deps', ['plugin-ready'], function (cb) {
    addWatch(
      './sdk.conf.json',
      function (file, done) {
        return getScripts().createDependencies(
          PLUGIN_PATHS.SCRIPTS,
          PLUGIN_PATHS.SCRIPT_DEPENDENCIES,
          true
        ).on('end', done);
      },
      cb,
      true
    );
  });

  gulp.task('watch-text', function (cb) {
    var textPropPattern = gutil.env.ng.textProperties.map(function (dir) {
      return path().join(dir, getText().FILES_PATTERN);
    });
    // TODO: currently goes through all files -
    // try optimizing this for processing updated file only
    addWatch(
      textPropPattern,
      function (file, done) {
        return getText().process(textPropPattern, PLUGIN_PATHS.TEXT).on('end', done);
      },
      cb,
      true
    );
  });

  gulp.task('watch-res', function (cb) {
    addWatch(
      ['res/**', '!res/**/*.scss'].concat(gutil.env.watchResIgnore || []),
      function (file, done) {
        fs.copy(file.path, file.path.replace(process.cwd(), 'plugin'), done);
      },
      cb,
      true
    );
  });

  gulp.task('watch-res-sass', function (cb) {
    if (getServer().useLocalCompile) {
      startLr();
      getSkins().compile(livereload());
      getSkins().server();
    }

    addWatch(
        ['res/**/*.scss'].concat(gutil.env.watchResIgnore || []),
        function (file, done) {
          if (getServer().useLocalCompile) {
            getSkins().compile(livereload()).on('end', done);
          } else {
            fs.copy(file.path, file.path.replace(process.cwd(), 'plugin'), done);
          }
        },
        cb,
        !getServer().useLocalCompile
    );
  });

  gulp.task('watch-web', function (cb) {
    addWatch(
      'web/**',
      function (file, done) {
        fs.copy(file.path, file.path.replace(process.cwd(), 'plugin'), done);
      },
      cb,
      true
    );
  });

  gulp.task('watch-ng', gutil.env.ng ? [
    'watch-scripts',
    'watch-script-deps',
    'watch-text'
  ] : []);

  gulp.task('dev', [
    'plugin-dev-refresh',
    'plugin-ready',
    'watch-ng',
    'watch-res',
    'watch-res-sass',
    'watch-web'
  ]);

  gulp.task('default', ['dev']);

};
<|endoftext|>


<commit_before>angular.module('app', [
  'ionic',
  'ngCordova',
  'ngMessages'
])

  .run(function ($ionicPlatform) {
    $ionicPlatform.ready(function () {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      if (window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      }
      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }
    });

    // localforage is the global for offline map tiles
    localforage.config({
      // driver: localforage.WEBSQL,
      name: 'offlineMapTiles'
    });

    // global LF for map names
    mapNamesDb = localforage.createInstance({
      // driver: localforage.WEBSQL,
      name: 'MapNames'
    });

    // global LF for spot data
    spotsDb = localforage.createInstance({
      // driver: localforage.WEBSQL,
      name: 'Spots'
    });

    // global LF for configuration data
    configDb = localforage.createInstance({
      // driver: localforage.WEBSQL,
      name: 'Config'
    });
  })

  .config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider

      .state('login', {
        cache: false,
        url: '/login',
        templateUrl: 'templates/login.html',
        controller: 'LoginCtrl'
      })

      .state('app', {
        url: "/app",
        abstract: true,
        templateUrl: "templates/menu.html"
      })

      .state('app.map', {
        cache: false,
        url: "/map",
        views: {
          'menuContent': {
            templateUrl: "templates/map.html",
            controller: 'MapCtrl'
          }
        }
      })

      .state('app.offlinemap', {
        cache: false,
        url: "/offlinemap",
        views: {
          'menuContent': {
            templateUrl: "templates/offlinemap.html",
            controller: "OfflineMapCtrl"
          }
        }
      })

      .state('app.search', {
        url: "/search",
        views: {
          'menuContent': {
            templateUrl: "templates/search.html"
          }
        }
      })

      .state('app.settings', {
        cache: false,
        url: "/settings",
        views: {
          'menuContent': {
            templateUrl: "templates/settings.html",
            controller: "SettingsCtrl"
          }
        }
      })

      .state('app.spots', {
        cache: false,
        url: "/spots",
        views: {
          'menuContent': {
            templateUrl: "templates/spots.html",
            controller: 'SpotsCtrl'
          }
        }
      })

      // setup an abstract state for the spot tabs directive
      .state('spotTab', {
        url: "/spotTab",
        abstract: true,
        templateUrl: "templates/spot.html",
        controller: 'SpotCtrl'
      })

      .state('spotTab.details', {
        cache: false,
        url: "/:spotId/details",
        views: {
          'spottab-childview': {
            templateUrl: 'templates/tabs/details.html',
            controller: 'SpotTabDetailCtrl'
          }
        }
      })

      .state('spotTab.notes', {
        cache: false,
        url: "/:spotId/notes",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/notes.html",
            controller: 'SpotTabNotesCtrl'
          }
        }
      })

      .state('spotTab.photos', {
        cache: false,
        url: "/:spotId/photos",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/pictures.html",
            controller: 'SpotTabPhotosCtrl'
          }
        }
      })

      .state('spotTab.georeference', {
        cache: false,
        url: "/:spotId/georeference",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/georeference.html",
            controller: 'SpotTabGeoreferenceCtrl'
          }
        }
      })

      .state('spotTab.links', {
        cache: false,
        url: "/:spotId/links",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/links.html",
            controller: 'SpotTabLinksCtrl'
          }
        }
      })

      .state('spotTab.groups', {
        cache: false,
        url: "/:spotId/groups",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/groups.html",
            controller: 'SpotTabGroupsCtrl'
          }
        }
      })

      .state('spotTab.groupmembers', {
        cache: false,
        url: "/:spotId/groupmembers",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/groupmembers.html",
            controller: 'SpotTabGroupmembersCtrl'
          }
        }
      })

      .state('spotTab.rockdescription', {
        cache: false,
        url: "/:spotId/rockdescription",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/rockdescription.html",
            controller: 'SpotTabRockdescriptionCtrl'
          }
        }
      })

      .state('spotTab.rocksample', {
        cache: false,
        url: "/:spotId/rocksample",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/rocksample.html",
            controller: 'SpotTabRocksampleCtrl'
          }
        }
      })

      .state('spotTab.custom', {
        cache: false,
        url: "/:spotId/custom",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/custom.html",
            controller: 'SpotTabCustomCtrl'
          }
        }
      })

      .state('app.archiveTiles', {
        url: "/map/archiveTiles",
        views: {
          'menuContent': {
            templateUrl: "templates/archiveTiles.html",
            controller: 'ArchiveTilesCtrl'
          }
        }
      })

      .state('app.debug', {
        url: "/debug",
        views: {
          'menuContent': {
            templateUrl: "templates/debug.html",
            controller: 'DebugCtrl'
          }
        }
      })

      .state('app.about', {
        url: "/about",
        views: {
          'menuContent': {
            templateUrl: "templates/about.html"
          }
        }
      });

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/login');
  });
<commit_msg>let localforage choose which is the best driver for that platform<commit_after>angular.module('app', [
  'ionic',
  'ngCordova',
  'ngMessages'
])

  .run(function ($ionicPlatform) {
    $ionicPlatform.ready(function () {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      if (window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      }
      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }
    });

    // localforage is the global for offline map tiles
    localforage.config({
      // driver: localforage.WEBSQL,  // removing the driver lets localforage choose the best driver available to that platform
      name: 'offlineMapTiles'
    });

    // global LF for map names
    mapNamesDb = localforage.createInstance({
      // driver: localforage.WEBSQL,  // removing the driver lets localforage choose the best driver available to that platform
      name: 'MapNames'
    });

    // global LF for spot data
    spotsDb = localforage.createInstance({
      // driver: localforage.WEBSQL,  // removing the driver lets localforage choose the best driver available to that platform
      name: 'Spots'
    });

    // global LF for configuration data
    configDb = localforage.createInstance({
      // driver: localforage.WEBSQL,  // removing the driver lets localforage choose the best driver available to that platform
      name: 'Config'
    });
  })

  .config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider

      .state('login', {
        cache: false,
        url: '/login',
        templateUrl: 'templates/login.html',
        controller: 'LoginCtrl'
      })

      .state('app', {
        url: "/app",
        abstract: true,
        templateUrl: "templates/menu.html"
      })

      .state('app.map', {
        cache: false,
        url: "/map",
        views: {
          'menuContent': {
            templateUrl: "templates/map.html",
            controller: 'MapCtrl'
          }
        }
      })

      .state('app.offlinemap', {
        cache: false,
        url: "/offlinemap",
        views: {
          'menuContent': {
            templateUrl: "templates/offlinemap.html",
            controller: "OfflineMapCtrl"
          }
        }
      })

      .state('app.search', {
        url: "/search",
        views: {
          'menuContent': {
            templateUrl: "templates/search.html"
          }
        }
      })

      .state('app.settings', {
        cache: false,
        url: "/settings",
        views: {
          'menuContent': {
            templateUrl: "templates/settings.html",
            controller: "SettingsCtrl"
          }
        }
      })

      .state('app.spots', {
        cache: false,
        url: "/spots",
        views: {
          'menuContent': {
            templateUrl: "templates/spots.html",
            controller: 'SpotsCtrl'
          }
        }
      })

      // setup an abstract state for the spot tabs directive
      .state('spotTab', {
        url: "/spotTab",
        abstract: true,
        templateUrl: "templates/spot.html",
        controller: 'SpotCtrl'
      })

      .state('spotTab.details', {
        cache: false,
        url: "/:spotId/details",
        views: {
          'spottab-childview': {
            templateUrl: 'templates/tabs/details.html',
            controller: 'SpotTabDetailCtrl'
          }
        }
      })

      .state('spotTab.notes', {
        cache: false,
        url: "/:spotId/notes",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/notes.html",
            controller: 'SpotTabNotesCtrl'
          }
        }
      })

      .state('spotTab.photos', {
        cache: false,
        url: "/:spotId/photos",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/pictures.html",
            controller: 'SpotTabPhotosCtrl'
          }
        }
      })

      .state('spotTab.georeference', {
        cache: false,
        url: "/:spotId/georeference",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/georeference.html",
            controller: 'SpotTabGeoreferenceCtrl'
          }
        }
      })

      .state('spotTab.links', {
        cache: false,
        url: "/:spotId/links",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/links.html",
            controller: 'SpotTabLinksCtrl'
          }
        }
      })

      .state('spotTab.groups', {
        cache: false,
        url: "/:spotId/groups",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/groups.html",
            controller: 'SpotTabGroupsCtrl'
          }
        }
      })

      .state('spotTab.groupmembers', {
        cache: false,
        url: "/:spotId/groupmembers",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/groupmembers.html",
            controller: 'SpotTabGroupmembersCtrl'
          }
        }
      })

      .state('spotTab.rockdescription', {
        cache: false,
        url: "/:spotId/rockdescription",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/rockdescription.html",
            controller: 'SpotTabRockdescriptionCtrl'
          }
        }
      })

      .state('spotTab.rocksample', {
        cache: false,
        url: "/:spotId/rocksample",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/rocksample.html",
            controller: 'SpotTabRocksampleCtrl'
          }
        }
      })

      .state('spotTab.custom', {
        cache: false,
        url: "/:spotId/custom",
        views: {
          'spottab-childview': {
            templateUrl: "templates/tabs/custom.html",
            controller: 'SpotTabCustomCtrl'
          }
        }
      })

      .state('app.archiveTiles', {
        url: "/map/archiveTiles",
        views: {
          'menuContent': {
            templateUrl: "templates/archiveTiles.html",
            controller: 'ArchiveTilesCtrl'
          }
        }
      })

      .state('app.debug', {
        url: "/debug",
        views: {
          'menuContent': {
            templateUrl: "templates/debug.html",
            controller: 'DebugCtrl'
          }
        }
      })

      .state('app.about', {
        url: "/about",
        views: {
          'menuContent': {
            templateUrl: "templates/about.html"
          }
        }
      });

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/login');
  });
<|endoftext|>


<commit_before>/*
 * grunt-html-head-urls-min-toggle
 * https://github.com/pinestec/html-head-urls-min-toggle
 *
 * Copyright (c) 2017 Michael Hartung
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
	// Please see the Grunt documentation for more information regarding task
	// creation: http://gruntjs.com/creating-tasks
	grunt.registerMultiTask('html_head_urls_min_toggle',
	    'Point the html-head href and src urls to minified sources and vice versa.', function() {
		    // grunt.log.write("\n" + JSON.stringify(this) + "\n\n");
		    var global_functions = {};
		    global_functions = require('./html_head_urls_min_toggle__global_functions.js');
		    var reference_options_object = {
		      action : [ 'switch', 'clean' ],
		      direction : [ 'min', 'regular' ],
		      file_source : [ 'wildcard', 'list' ]
		    };
		    if (global_functions.private_action_checker(this, reference_options_object, true)) {
			    if (this.data.options.action === 'clean') {
				    console.log("CLEANING SECTION...!");
			    }
			    if (this.data.options.action === 'switch') {
				    if (this.data.options.file_source === 'list') {
					    console.log("SWITCHING SECTION LIST...!");
				    } else {
					    console.log("SWITCHING SECTION WILDCARD...!");
					    console.log(this.data.files[0].src);
					    // var current_files_array =
					    // global_functions.process_wildcard_input('dummy',
					    // this.data.files[k].src,
					    // this.data.files[k].cwd);

				    }
			    }
		    }

		    if (this.data.files) {
			    for (var k = 0; k < this.data.files.length; k++) {
				    if (this.data.files[k].expand) {
					    var current_files_array = global_functions.process_wildcard_input(this.data.files[k].direction,
					        this.data.files[k].src, this.data.files[k].cwd);
					    if (current_files_array) {
						    for (var l = 0; l < current_files_array.length; l++) {
							    grunt.log.write("\t" + (l + 1) + ": \"" + current_files_array[l] + "\"");
							    if (global_functions.toggle_all_head_links(this.data.files[k].direction, current_files_array[l])) {
								    grunt.log.write("\t- to \""['green'] + this.data.files[k].direction['green'] + "\" o.k."['green'] +
								        "\n");
							    } else {
								    grunt.log.write("\t- to \""['red'] + this.data.files[k].direction['red'] +
								        "\">>> Failed...! <<<"['red'] + "\n");
							    }
						    }
						    grunt.log.write("\n");
					    }
				    }
			    }
		    } else {
			    var min_targets_array = [];
			    var regular_targets_array = [];
			    try {
				    min_targets_array = this.data.min_targets;
				    if (typeof min_targets_array === 'undefined') {
					    min_targets_array = [];
				    }
			    } catch (exception) {
				    min_targets_array = [];
			    }
			    try {
				    regular_targets_array = this.data.regular_targets;
				    if (typeof regular_targets_array === 'undefined') {
					    regular_targets_array = [];
				    }
			    } catch (exception) {
				    regular_targets_array = [];
			    }
			    if (min_targets_array.length === 1) {
				    grunt.log.write("\nOne file specified to switch all it's \"head links\" to \"minified sources\"...:\n");
			    } else {
				    grunt.log.write("\n" + min_targets_array.length +
				        " Files specified to switch all their \"head links\" to \"minified sources\"...:\n");
			    }

			    if (min_targets_array.length > 0) {
				    for (var i = 0; i < min_targets_array.length; i++) {
					    grunt.log.write("\t" + (i + 1) + ": \"" + min_targets_array[i] + "\"");
					    if (global_functions.toggle_all_head_links('min', min_targets_array[i])) {
						    grunt.log.write("\t- to \""['green'] + "min"['green'] + "\" o.k."['green'] + "\n");
					    } else {
						    grunt.log.write("\t- to \""['red'] + "min"['red'] + "\" >>> Failed...! <<<"['red'] + "\n");
					    }
				    }
			    } else {
				    grunt.log
				        .write("\n>>> NO \"HTML Files\" listed to switch their \"head links\" to \"minified sources\"... <<<\n");
			    }
			    grunt.log.write("\n");

			    if (regular_targets_array.length > 0) {
				    if (regular_targets_array.length === 1) {
					    grunt.log.write("One file specified to switch all it's \"head links\" to \"regular sources\"...\n");
				    } else {
					    grunt.log.write(regular_targets_array.length +
					        " Files specified to switch all their \"head links\" to \"regular sources\"...\n");
				    }
				    for (var j = 0; j < regular_targets_array.length; j++) {
					    grunt.log.write("\t" + (j + 1) + ": \"" + regular_targets_array[j] + "\"");
					    if (global_functions.toggle_all_head_links('regular', regular_targets_array[j])) {
						    grunt.log.write("\t- to \""['green'] + "regular"['green'] + "\" o.k."['green'] + "\n");
					    } else {
						    grunt.log.write("\t- to \""['red'] + "regular"['red'] + "\" >>> Failed...! <<<"['red'] + "\n");
					    }
				    }
			    } else {
				    grunt.log
				        .write("\n>>> NO \"HTML Files\" listed to switch their \"head links\" to \"regular sources\"... <<<\n");
			    }
		    }
	    });
};
<commit_msg>Looks nicely up to here... - MH - PT<commit_after>/*
 * grunt-html-head-urls-min-toggle
 * https://github.com/pinestec/html-head-urls-min-toggle
 *
 * Copyright (c) 2017 Michael Hartung
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
	// Please see the Grunt documentation for more information regarding task
	// creation: http://gruntjs.com/creating-tasks
	grunt.registerMultiTask('html_head_urls_min_toggle',
	    'Point the html-head href and src urls to minified sources and vice versa.', function() {
		    // grunt.log.write("\n" + JSON.stringify(this) + "\n\n");
		    var global_functions = {};
		    global_functions = require('./html_head_urls_min_toggle__global_functions.js');
		    var reference_options_object = {
		      action : [ 'switch', 'clean' ],
		      direction : [ 'min', 'regular' ],
		      file_source : [ 'wildcard', 'list' ]
		    };
		    if (global_functions.private_action_checker(this, reference_options_object, true)) {
			    if (this.data.options.action === 'clean') {
				    console.log("CLEANING SECTION...!");
			    }
			    if (this.data.options.action === 'switch') {
				    if (this.data.options.file_source === 'list') {
					    console.log("SWITCHING SECTION LIST...!");
				    } else {
					    console.log("SWITCHING SECTION WILDCARD...!");
					    for (var i = 0; i < this.data.files.length; i++) {
						    if (this.data.files[i].hasOwnProperty('cwd') && this.data.files[i].hasOwnProperty('src')) {

						    } else {
							    console.log("MISSING NEEDED \"WILDCARD\" FILE PROPERTIES...!");
						    }
					    }

					    // var current_files_array =
					    // global_functions.process_wildcard_input('dummy',
					    // this.data.files[k].src,
					    // this.data.files[k].cwd);

				    }
			    }
		    }

		    if (this.data.files) {
			    for (var k = 0; k < this.data.files.length; k++) {
				    if (this.data.files[k].expand) {
					    var current_files_array = global_functions.process_wildcard_input(this.data.files[k].direction,
					        this.data.files[k].src, this.data.files[k].cwd);
					    if (current_files_array) {
						    for (var l = 0; l < current_files_array.length; l++) {
							    grunt.log.write("\t" + (l + 1) + ": \"" + current_files_array[l] + "\"");
							    if (global_functions.toggle_all_head_links(this.data.files[k].direction, current_files_array[l])) {
								    grunt.log.write("\t- to \""['green'] + this.data.files[k].direction['green'] + "\" o.k."['green'] +
								        "\n");
							    } else {
								    grunt.log.write("\t- to \""['red'] + this.data.files[k].direction['red'] +
								        "\">>> Failed...! <<<"['red'] + "\n");
							    }
						    }
						    grunt.log.write("\n");
					    }
				    }
			    }
		    } else {
			    var min_targets_array = [];
			    var regular_targets_array = [];
			    try {
				    min_targets_array = this.data.min_targets;
				    if (typeof min_targets_array === 'undefined') {
					    min_targets_array = [];
				    }
			    } catch (exception) {
				    min_targets_array = [];
			    }
			    try {
				    regular_targets_array = this.data.regular_targets;
				    if (typeof regular_targets_array === 'undefined') {
					    regular_targets_array = [];
				    }
			    } catch (exception) {
				    regular_targets_array = [];
			    }
			    if (min_targets_array.length === 1) {
				    grunt.log.write("\nOne file specified to switch all it's \"head links\" to \"minified sources\"...:\n");
			    } else {
				    grunt.log.write("\n" + min_targets_array.length +
				        " Files specified to switch all their \"head links\" to \"minified sources\"...:\n");
			    }

			    if (min_targets_array.length > 0) {
				    for (var i = 0; i < min_targets_array.length; i++) {
					    grunt.log.write("\t" + (i + 1) + ": \"" + min_targets_array[i] + "\"");
					    if (global_functions.toggle_all_head_links('min', min_targets_array[i])) {
						    grunt.log.write("\t- to \""['green'] + "min"['green'] + "\" o.k."['green'] + "\n");
					    } else {
						    grunt.log.write("\t- to \""['red'] + "min"['red'] + "\" >>> Failed...! <<<"['red'] + "\n");
					    }
				    }
			    } else {
				    grunt.log
				        .write("\n>>> NO \"HTML Files\" listed to switch their \"head links\" to \"minified sources\"... <<<\n");
			    }
			    grunt.log.write("\n");

			    if (regular_targets_array.length > 0) {
				    if (regular_targets_array.length === 1) {
					    grunt.log.write("One file specified to switch all it's \"head links\" to \"regular sources\"...\n");
				    } else {
					    grunt.log.write(regular_targets_array.length +
					        " Files specified to switch all their \"head links\" to \"regular sources\"...\n");
				    }
				    for (var j = 0; j < regular_targets_array.length; j++) {
					    grunt.log.write("\t" + (j + 1) + ": \"" + regular_targets_array[j] + "\"");
					    if (global_functions.toggle_all_head_links('regular', regular_targets_array[j])) {
						    grunt.log.write("\t- to \""['green'] + "regular"['green'] + "\" o.k."['green'] + "\n");
					    } else {
						    grunt.log.write("\t- to \""['red'] + "regular"['red'] + "\" >>> Failed...! <<<"['red'] + "\n");
					    }
				    }
			    } else {
				    grunt.log
				        .write("\n>>> NO \"HTML Files\" listed to switch their \"head links\" to \"regular sources\"... <<<\n");
			    }
		    }
	    });
};
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs'),
	gulp = require('gulp'),
	sync = require('browser-sync'),
	wiredep = require('wiredep').stream,
	config = require('./config');

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

/**
 *	Watch task
 *	@desc Run watcher for dist folder
 */

gulp.task('build:watch', function() {

	sync({
		open: false,
		startPath: '/',
		server: {
			baseDir: config.dist,
			index: 'index.html'
		}
	});

});

/**
 *	Clean task
 *	@desc Remove temp and dist folders
 */

gulp.task('build:clean', function() {

	gulp.src([config.dist, config.src + config.tmp])
		.pipe($.rimraf({ force: true }));

});

/**
 *	Copy task
 *	@desc Copy files from root folder
 *	@return
 */

gulp.task('build:copy', function() {

	if(config.copyfiles.length) {

		for(var i = 0, l = config.copyfiles.length; i < l; i++) {
			config.copyfiles[i] = config.src + config.copyfiles[i];
		}

		return gulp.src(config.copyfiles)
			.pipe(gulp.dest(config.dist))
			.pipe($.size());

	}

});

/**
 *	Fonts task
 *	@desc Copy fonts to dist folder
 *	@return
 */

gulp.task('build:fonts', function() {

	if(config.folder.fonts) {

		return gulp.src(config.src + config.folder.fonts + '/**/*.{eot,svg,ttf,woff}')
			.pipe(gulp.dest(config.dist + config.folder.fonts))
			.pipe($.size());

	}

});

/**
 *	Images task
 *	@desc Optimization images and copy files to dist folder
 *	@return
 */

gulp.task('build:images', function() {

	var path = [];

	if(config.folder.icons) { path.push(config.folder.icons); }
	if(config.folder.images) { path.push(config.folder.images); }
	if(config.folder.pictures) { path.push(config.folder.pictures); }

	path.forEach(function(folder) {

		return gulp.src(config.src + folder + '/**/*.{jpg,png,gif,svg}')
			.pipe($.plumber())
			.pipe($.imagemin({
				optimizationLevel: 3,
				progressive: true,
				interlaced: true,
				svgoPlugins: [
					{ removeViewBox: true },
					{ removeEmptyAttrs: true }
				]
			}))
			.pipe(gulp.dest(config.dist + folder))
			.pipe($.size());

	});

});

/**
 *	Css task
 *	@desc Concatenate css and copy file to temp folder
 *	@return
 */

gulp.task('build:css', function() {

	if(config.folder.styles && config.csstype === 'css') {

		return gulp.src(config.src + config.folder.styles + '/**/*.css')
			.pipe($.plumber())
			.pipe($.concat('style.css'))
			.pipe(gulp.dest(config.src + config.tmp))
			.pipe($.size());

	}

});

/**
 *	Less task
 *	@desc Concatenate/compress less and copy file to temp folder
 *	@return
 */

gulp.task('build:less', function() {

	if(config.folder.styles && config.csstype === 'less') {

		return gulp.src(config.src + config.folder.styles + '/style.less')
			.pipe($.plumber())
			.pipe($.less())
			.pipe(gulp.dest(config.src + config.tmp))
			.pipe($.size());

	}

});

/**
 *	Sass task
 *	@desc Concatenate/compress sass and copy file to temp folder
 *	@return
 */

gulp.task('build:sass', function() {

	if(config.folder.styles && config.csstype === 'sass') {

		return gulp.src(config.src + config.folder.styles + '/style.scss')
			.pipe($.plumber())
			.pipe($.sass({
				style: 'compressed'
			}))
			.pipe(gulp.dest(config.src + config.tmp))
			.pipe($.size());

	}

});

/**
 *	Stylus task
 *	@desc Concatenate/compress stylus, copy file to temp folder
 *	@return
 */

gulp.task('build:stylus', function() {

	if(config.folder.styles && config.csstype === 'stylus') {

		return gulp.src(config.src + config.folder.styles + '/style.styl')
			.pipe($.plumber())
			.pipe($.stylus({
				compress: true
			}))
			.pipe(gulp.dest(config.src + config.tmp))
			.pipe($.size());

	}

});

/**
 *	Pug task
 *	@desc Compile pug templates
 *	@return
 */

gulp.task('build:pug', function() {

	if(config.folder.pug) {

		return gulp.src(config.src + config.folder.pug + '/**/[^_]*.pug')
			.pipe($.plumber())
			.pipe($.pug({ pretty: '\t' }))
			.pipe(gulp.dest(config.src))
			.pipe($.size());

	}

});

/**
 *	Bower task
 *	@extends pug
 *	@desc Inject bower dependencies to html
 *	@return
 */

gulp.task('build:wiredep', ['build:pug'], function() {

	if(config.folder.vendors && fs.existsSync(config.src + config.folder.vendors)) {

		return gulp.src([config.src + '**/*.html', '!' + config.src + config.folder.vendors + '/**'])
			.pipe(wiredep({
				directory: config.src + config.folder.vendors
			}))
			.pipe(gulp.dest(config.src));

	}

});

/**
 *	Inject task
 *	@extends css, less, sass, stylus, wiredep, pug
 *	@desc Inject js and css files to html
 *	@return
 */

gulp.task('build:inject', ['build:css', 'build:less', 'build:sass', 'build:stylus', 'build:wiredep', 'build:pug'], function() {

	var sources = [
		config.src + config.tmp + '/**/*.css'
	];

	if(config.folder.scripts) {
		sources.push(config.src + config.folder.scripts + '/**/*.js');
	}

	var transform = {
		transform: function(filepath, file, i, length, targetFile) {

			var root = config.src.slice(2),
				targetpath = targetFile.path.slice(targetFile.path.indexOf(root) + root.length);

			filepath = filepath.slice(filepath.slice(1).indexOf('/') + 2);

			if(targetpath.indexOf('/') + 1) {
				filepath = '../' + filepath;
			}

			return $.inject.transform.apply($.inject.transform, [filepath, file, i, length, targetFile]);

		}
	};

	return gulp.src([config.src + '**/*.html', '!' + config.src + config.folder.vendors + '/**'])
		.pipe($.inject(gulp.src(sources), transform))
		.pipe(gulp.dest(config.src));

});

/**
 *	Assets task
 *	@extends inject
 *	@desc Concatenate/compress js and css files, copy files to dist folder, add hash to files name if rev flag set as true
 *	@return
 */

gulp.task('build:assets', ['build:inject'], function() {

	var jsFilter = $.filter('**/*.js'),
		cssFilter = $.filter('**/*.css');

	return gulp.src([config.src + '**/*.html', '!' + config.src + config.folder.vendors + '/**'])
		.pipe($.useref.assets())
		.pipe($.if(config.rev, $.rev()))
		.pipe(jsFilter)
		.pipe($.uglify())
		.pipe(jsFilter.restore())
		.pipe(cssFilter)
		.pipe($.csso())
		.pipe($.autoprefixer({
			browsers: config.browsers,
			cascade: false
		}))
		.pipe(cssFilter.restore())
		.pipe(gulp.dest(config.dist))
		.pipe($.size());

});

/**
 *	Build task
 *	@extends copy, fonts, images, assets
 *	@desc Inject js and css files to html, compress html and replace paths
 */

gulp.task('build', ['build:copy', 'build:fonts', 'build:images', 'build:assets'], function() {

	gulp.src([config.src + '**/*.html', '!' + config.src + config.folder.vendors + '/**'])
		.pipe($.inject(gulp.src(config.dist + 'css/**/*.css', { read: true }), { relative: true }))
		.pipe($.inject(gulp.src(config.dist + 'scripts/**/*.js', { read: true }), { relative: true }))
		.pipe($.removeCode({ build: true }))
		.pipe($.if($.util.env.abspaths, $.replace('.' + config.dist, '/'), $.replace('.' + config.dist, '')))
		.pipe($.minifyHtml({
			comments: false,
			empty: false,
			conditionals: true,
			cdata: true,
			quotes: true,
			spare: true
		}))
		.pipe($.notify({
			title: 'Gulp',
			message: 'Build is ready',
			sound: "Pop",
			icon: false
		}))
		.pipe(gulp.dest(config.dist))
		.pipe($.size());

});<commit_msg>update gulp-notify config<commit_after>'use strict';

var fs = require('fs'),
	gulp = require('gulp'),
	sync = require('browser-sync'),
	wiredep = require('wiredep').stream,
	config = require('./config');

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

/**
 *	Watch task
 *	@desc Run watcher for dist folder
 */

gulp.task('build:watch', function() {

	sync({
		open: false,
		startPath: '/',
		server: {
			baseDir: config.dist,
			index: 'index.html'
		}
	});

});

/**
 *	Clean task
 *	@desc Remove temp and dist folders
 */

gulp.task('build:clean', function() {

	gulp.src([config.dist, config.src + config.tmp])
		.pipe($.rimraf({ force: true }));

});

/**
 *	Copy task
 *	@desc Copy files from root folder
 *	@return
 */

gulp.task('build:copy', function() {

	if(config.copyfiles.length) {

		for(var i = 0, l = config.copyfiles.length; i < l; i++) {
			config.copyfiles[i] = config.src + config.copyfiles[i];
		}

		return gulp.src(config.copyfiles)
			.pipe(gulp.dest(config.dist))
			.pipe($.size());

	}

});

/**
 *	Fonts task
 *	@desc Copy fonts to dist folder
 *	@return
 */

gulp.task('build:fonts', function() {

	if(config.folder.fonts) {

		return gulp.src(config.src + config.folder.fonts + '/**/*.{eot,svg,ttf,woff}')
			.pipe(gulp.dest(config.dist + config.folder.fonts))
			.pipe($.size());

	}

});

/**
 *	Images task
 *	@desc Optimization images and copy files to dist folder
 *	@return
 */

gulp.task('build:images', function() {

	var path = [];

	if(config.folder.icons) { path.push(config.folder.icons); }
	if(config.folder.images) { path.push(config.folder.images); }
	if(config.folder.pictures) { path.push(config.folder.pictures); }

	path.forEach(function(folder) {

		return gulp.src(config.src + folder + '/**/*.{jpg,png,gif,svg}')
			.pipe($.plumber())
			.pipe($.imagemin({
				optimizationLevel: 3,
				progressive: true,
				interlaced: true,
				svgoPlugins: [
					{ removeViewBox: true },
					{ removeEmptyAttrs: true }
				]
			}))
			.pipe(gulp.dest(config.dist + folder))
			.pipe($.size());

	});

});

/**
 *	Css task
 *	@desc Concatenate css and copy file to temp folder
 *	@return
 */

gulp.task('build:css', function() {

	if(config.folder.styles && config.csstype === 'css') {

		return gulp.src(config.src + config.folder.styles + '/**/*.css')
			.pipe($.plumber())
			.pipe($.concat('style.css'))
			.pipe(gulp.dest(config.src + config.tmp))
			.pipe($.size());

	}

});

/**
 *	Less task
 *	@desc Concatenate/compress less and copy file to temp folder
 *	@return
 */

gulp.task('build:less', function() {

	if(config.folder.styles && config.csstype === 'less') {

		return gulp.src(config.src + config.folder.styles + '/style.less')
			.pipe($.plumber())
			.pipe($.less())
			.pipe(gulp.dest(config.src + config.tmp))
			.pipe($.size());

	}

});

/**
 *	Sass task
 *	@desc Concatenate/compress sass and copy file to temp folder
 *	@return
 */

gulp.task('build:sass', function() {

	if(config.folder.styles && config.csstype === 'sass') {

		return gulp.src(config.src + config.folder.styles + '/style.scss')
			.pipe($.plumber())
			.pipe($.sass({
				style: 'compressed'
			}))
			.pipe(gulp.dest(config.src + config.tmp))
			.pipe($.size());

	}

});

/**
 *	Stylus task
 *	@desc Concatenate/compress stylus, copy file to temp folder
 *	@return
 */

gulp.task('build:stylus', function() {

	if(config.folder.styles && config.csstype === 'stylus') {

		return gulp.src(config.src + config.folder.styles + '/style.styl')
			.pipe($.plumber())
			.pipe($.stylus({
				compress: true
			}))
			.pipe(gulp.dest(config.src + config.tmp))
			.pipe($.size());

	}

});

/**
 *	Pug task
 *	@desc Compile pug templates
 *	@return
 */

gulp.task('build:pug', function() {

	if(config.folder.pug) {

		return gulp.src(config.src + config.folder.pug + '/**/[^_]*.pug')
			.pipe($.plumber())
			.pipe($.pug({ pretty: '\t' }))
			.pipe(gulp.dest(config.src))
			.pipe($.size());

	}

});

/**
 *	Bower task
 *	@extends pug
 *	@desc Inject bower dependencies to html
 *	@return
 */

gulp.task('build:wiredep', ['build:pug'], function() {

	if(config.folder.vendors && fs.existsSync(config.src + config.folder.vendors)) {

		return gulp.src([config.src + '**/*.html', '!' + config.src + config.folder.vendors + '/**'])
			.pipe(wiredep({
				directory: config.src + config.folder.vendors
			}))
			.pipe(gulp.dest(config.src));

	}

});

/**
 *	Inject task
 *	@extends css, less, sass, stylus, wiredep, pug
 *	@desc Inject js and css files to html
 *	@return
 */

gulp.task('build:inject', ['build:css', 'build:less', 'build:sass', 'build:stylus', 'build:wiredep', 'build:pug'], function() {

	var sources = [
		config.src + config.tmp + '/**/*.css'
	];

	if(config.folder.scripts) {
		sources.push(config.src + config.folder.scripts + '/**/*.js');
	}

	var transform = {
		transform: function(filepath, file, i, length, targetFile) {

			var root = config.src.slice(2),
				targetpath = targetFile.path.slice(targetFile.path.indexOf(root) + root.length);

			filepath = filepath.slice(filepath.slice(1).indexOf('/') + 2);

			if(targetpath.indexOf('/') + 1) {
				filepath = '../' + filepath;
			}

			return $.inject.transform.apply($.inject.transform, [filepath, file, i, length, targetFile]);

		}
	};

	return gulp.src([config.src + '**/*.html', '!' + config.src + config.folder.vendors + '/**'])
		.pipe($.inject(gulp.src(sources), transform))
		.pipe(gulp.dest(config.src));

});

/**
 *	Assets task
 *	@extends inject
 *	@desc Concatenate/compress js and css files, copy files to dist folder, add hash to files name if rev flag set as true
 *	@return
 */

gulp.task('build:assets', ['build:inject'], function() {

	var jsFilter = $.filter('**/*.js'),
		cssFilter = $.filter('**/*.css');

	return gulp.src([config.src + '**/*.html', '!' + config.src + config.folder.vendors + '/**'])
		.pipe($.useref.assets())
		.pipe($.if(config.rev, $.rev()))
		.pipe(jsFilter)
		.pipe($.uglify())
		.pipe(jsFilter.restore())
		.pipe(cssFilter)
		.pipe($.csso())
		.pipe($.autoprefixer({
			browsers: config.browsers,
			cascade: false
		}))
		.pipe(cssFilter.restore())
		.pipe(gulp.dest(config.dist))
		.pipe($.size());

});

/**
 *	Build task
 *	@extends copy, fonts, images, assets
 *	@desc Inject js and css files to html, compress html and replace paths
 */

gulp.task('build', ['build:copy', 'build:fonts', 'build:images', 'build:assets'], function() {

	gulp.src([config.src + '**/*.html', '!' + config.src + config.folder.vendors + '/**'])
		.pipe($.inject(gulp.src(config.dist + 'css/**/*.css', { read: true }), { relative: true }))
		.pipe($.inject(gulp.src(config.dist + 'scripts/**/*.js', { read: true }), { relative: true }))
		.pipe($.removeCode({ build: true }))
		.pipe($.if($.util.env.abspaths, $.replace('.' + config.dist, '/'), $.replace('.' + config.dist, '')))
		.pipe($.minifyHtml({
			comments: false,
			empty: false,
			conditionals: true,
			cdata: true,
			quotes: true,
			spare: true
		}))
		.pipe($.notify({
			title: 'Gulp',
			message: 'Build is ready',
			sound: 'Pop',
			icon: false,
			onLast: true
		}))
		.pipe(gulp.dest(config.dist))
		.pipe($.size());

});<|endoftext|>


<commit_before>window.expect = chai.expect;
window.should = chai.should();

before(function(done) {
  fixtures.load("../../../base/test/index.html");
  fixtures.window().addEventListener("WebComponentsReady", function() {
    done();
  });
});
<commit_msg>Improved test setup a bit<commit_after>window.expect = chai.expect;
window.win = fixtures.window();
window.doc = window.win.document;

before(function(done) {
  fixtures.load("../../../base/test/index.html");
  fixtures.window().console = console;
  fixtures.window().addEventListener("WebComponentsReady", function() {
    done();
  });
});
<|endoftext|>


<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/**
 * Module bk.sessionManager
 */
(function() {
  'use strict';
  var module = angular.module('bk.sessionManager',[
    'bk.utils',
    'bk.session',
    'bk.notebookCellModelManager',
    'bk.notebookNamespaceModelManager',
    'bk.recentMenu',
    'bk.evaluatorManager'
  ]);

  module.factory('bkSessionManager', function(
      bkUtils,
      bkSession,
      bkNotebookCellModelManager,
      bkNotebookNamespaceModelManager,
      bkEvaluatorManager,
      bkRecentMenu) {

    var _notebookUri = (function() {
      var DEFAULT_VALUE = null;
      var _v = DEFAULT_VALUE;
      return {
        reset: function() {
          this.set(DEFAULT_VALUE);
        },
        get: function() {
          return _v;
        },
        set: function(v) {
          _v = v;
          if (!_.isEmpty(_v)) {
            bkRecentMenu.recordRecentDocument(generateRecentDocumentItem());
          }
        }
      };
    })();

    var _uriType = null;
    var _readOnly = null;
    var _format = null;
    var _sessionId = null;
    var _edited = false;

    var _notebookModel = (function() {
      var _v = {};
      return {
        reset: function() {
          this.set({});
        },
        get: function() {
          return _v;
        },
        set: function(v) {
          _v = v;
          bkNotebookCellModelManager.reset(_v.cells);
        },
        isEmpty: function() {
          return _.isEmpty(_v);
        },
        isLocked: function() {
          return !this.isEmpty() && !!_v.locked;
        },
        toJson: function() {
          return angular.toJson(_v);
        },
        toPrettyJson: function() {
          return bkUtils.toPrettyJson(_v);
        }
      };
    })();

    var generateBackupData = function() {
      return {
        notebookUri: _notebookUri.get(),
        uriType: _uriType,
        readOnly: _readOnly,
        format: _format,
        notebookModelJson: _notebookModel.toJson(),
        edited: _edited
      };
    };
    var generateRecentDocumentItem = function () {
      var data = {
        uri: _notebookUri.get(),
        type: _.isEmpty(_uriType) ? "" : _uriType,
        readOnly: !!_readOnly ? true : false,
        format: _.isEmpty(_format) ? "" : _format
      };
      return angular.toJson(data);
    };

    var generateSaveData = function() {
      return {
        uriType: _uriType,
        notebookUri: _notebookUri.get(),
        notebookModelAsString: _notebookModel.toPrettyJson()
      };
    };

    return {
      reset: function(notebookUri, uriType, readOnly, format, notebookModel, edited, sessionId) {

        // backup existing session if it's not empty.
        if (_sessionId && !_notebookModel.isEmpty()) {
          bkSession.backup(_sessionId, generateBackupData());
        }

        bkEvaluatorManager.reset();

        // check inputs
        if (!sessionId) {
          sessionId = bkUtils.generateId(6);
        }

        // reset
        _uriType = uriType;
        _readOnly = readOnly;
        _format = format;
        _notebookUri.set(notebookUri);
        _notebookModel.set(notebookModel);
        _edited = !!edited;
        _sessionId = sessionId;

        bkNotebookNamespaceModelManager.init(sessionId, notebookModel);
      },
      clear: function() {
        bkEvaluatorManager.reset();
        bkNotebookNamespaceModelManager.clear(_sessionId);
        _notebookUri.reset();
        _uriType = null;
        _readOnly = null;
        _format = null;
        _notebookModel.reset();
        _sessionId = null;
        _edited = false;
      },
      close: function() {
        var self = this;
        var close = function() {
          bkEvaluatorManager.exitAndRemoveAllEvaluators();
          self.clear();
        };
        if (_sessionId) {
          return bkSession.close(_sessionId).then(close);
        } else{
          close();
          return bkUtils.newPromise();
        }
      },
      backup: function() {
        if (_sessionId && !_notebookModel.isEmpty()) {
          return bkSession.backup(_sessionId, generateBackupData());
        } else {
          return bkUtils.newPromise();
        }
      },
      updateNotebookUri: function(notebookUri, uriType, readOnly, format) {
        // to be used by save-as
        _uriType = uriType;
        _readOnly = readOnly;
        _format = format;
        _notebookUri.set(notebookUri);
      },
      getNotebookTitle: function() {
        if (_notebookUri.get()) {
          return _notebookUri.get().replace(/^.*[\\\/]/, '');
        } else {
          return "New Notebook";
        }
      },
      isSavable: function() {
        return _notebookUri && !_readOnly;
      },
      getSaveData: function() {
        return generateSaveData();
      },
      getNotebookModelAsString: function() {
        return _notebookModel.toJson();
      },
      getRawNotebookModel: function() {
        return _notebookModel.get();
      },
      getSessionId: function() {
        return _sessionId;
      },
      // TODO, move the following impl to a dedicated notebook model manager
      // but still expose it here
      setNotebookModelEdited: function(edited) {
        _edited = edited;
      },
      isNotebookModelEdited: function() {
        return _edited;
      },
      isNotebookLocked: function() {
        return _notebookModel.isLocked();
      },
      toggleNotebookLocked: function() {
        if (!_notebookModel.isEmpty()) {
          if (!_notebookModel.isLocked()) {
            _notebookModel.get().locked = true;
          } else {
            _notebookModel.get().locked = undefined;
          }
          _edited = true;
        }
      },
      addEvaluator: function(evaluator) {
        _notebookModel.get().evaluators.push(evaluator);
        _edited = true;
      },
      getNotebookCellOp: function() {
        return bkNotebookCellModelManager;
      },
      getNotebookNewCellFactory: function() {
        return {
          newCodeCell: function(evaluator, id) {
            if (!evaluator) {
              evaluator = _notebookModel.get().evaluators[0].name;
            }
            if (!id) {
              id = "code" + bkUtils.generateId(6);
            }
            return {
              "id": id,
              "type": "code",
              "evaluator": evaluator,
              "input": {
                "body": ""
              },
              "output": {}
            };
          },
          newSectionCell: function(level, title, id) {
            if (!level && level !== 0) {
              level = 1;
            }
            if (level <= 0) {
              throw "creating section cell with level " + level + " is not allowed";
            }
            if (!title) {
              title = "New Section H" + level;
            }

            if (!id) {
              id = "section" + bkUtils.generateId(6);
            }
            return {
              "id": id,
              "type": "section",
              "title": title,
              "level": level
            };
          },
          newTextCell: function(id) {
            if (!id) {
              id = "text" + bkUtils.generateId(6);
            }
            return {
              "id": id,
              "type": "text",
              "body": "New text cell"
            };
          },
          newMarkdownCell: function(id) {
            var tail = _notebookModel.get().cells.length - 1;
            if (!id) {
              id = "markdown" + bkUtils.generateId(6);
            }
            return {
              "id": id,
              "type": "markdown",
              "body": ""
            };
          }
        };
      },
      isRootCellInitialization: function() {
        return _notebookModel.get().initializeAll;
      },
      setRootCellInitialization: function(initialization) {
        if (initialization === true) {
          _notebookModel.get().initializeAll = true;
        } else {
          _notebookModel.get().initializeAll = undefined;
        }
      },
      notebookModelAddEvaluator: function(newEvaluator) {
        _notebookModel.get().evaluators.push(newEvaluator);
      },
      notebookModelGetInitializationCells: function() {
        if (_notebookModel.get().initializeAll) {
          return this.getNotebookCellOp().getAllCodeCells("root");
        } else {
          return this.getNotebookCellOp().getInitializationCells();
        }
      }
    };
  });
})();
<commit_msg>Fix #254, strip off the shellIDs when saving notebooks<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/**
 * Module bk.sessionManager
 */
(function() {
  'use strict';
  var module = angular.module('bk.sessionManager',[
    'bk.utils',
    'bk.session',
    'bk.notebookCellModelManager',
    'bk.notebookNamespaceModelManager',
    'bk.recentMenu',
    'bk.evaluatorManager'
  ]);

  module.factory('bkSessionManager', function(
      bkUtils,
      bkSession,
      bkNotebookCellModelManager,
      bkNotebookNamespaceModelManager,
      bkEvaluatorManager,
      bkRecentMenu) {

    var _notebookUri = (function() {
      var DEFAULT_VALUE = null;
      var _v = DEFAULT_VALUE;
      return {
        reset: function() {
          this.set(DEFAULT_VALUE);
        },
        get: function() {
          return _v;
        },
        set: function(v) {
          _v = v;
          if (!_.isEmpty(_v)) {
            bkRecentMenu.recordRecentDocument(generateRecentDocumentItem());
          }
        }
      };
    })();

    var _uriType = null;
    var _readOnly = null;
    var _format = null;
    var _sessionId = null;
    var _edited = false;

    var _notebookModel = (function() {
      var _v = {};
      return {
        reset: function() {
          this.set({});
        },
        get: function() {
          return _v;
        },
        set: function(v) {
          _v = v;
          bkNotebookCellModelManager.reset(_v.cells);
        },
        isEmpty: function() {
          return _.isEmpty(_v);
        },
        isLocked: function() {
          return !this.isEmpty() && !!_v.locked;
        },
        toJson: function() {
          return angular.toJson(_v);
        },
        toPrettyJson: function() {
          return bkUtils.toPrettyJson(_v);
        },
        toCleanPrettyJson: function() {
          //strip out the shell IDs
          var shellIds = _(_v.evaluators).map(function(evaluator) {
            var shellId = evaluator.shellID;
            delete evaluator.shellID;
            return shellId;
          });
          // generate pretty JSON
          var prettyJson = bkUtils.toPrettyJson(_v);
          // put the shell IDs back
          _(_v.evaluators).each(function(evaluator, index) {
            evaluator.shellID = shellIds[index];
          });
          return prettyJson;
        }
      };
    })();

    var generateBackupData = function() {
      return {
        notebookUri: _notebookUri.get(),
        uriType: _uriType,
        readOnly: _readOnly,
        format: _format,
        notebookModelJson: _notebookModel.toJson(),
        edited: _edited
      };
    };
    var generateRecentDocumentItem = function () {
      var data = {
        uri: _notebookUri.get(),
        type: _.isEmpty(_uriType) ? "" : _uriType,
        readOnly: !!_readOnly ? true : false,
        format: _.isEmpty(_format) ? "" : _format
      };
      return angular.toJson(data);
    };

    var generateSaveData = function() {
      return {
        uriType: _uriType,
        notebookUri: _notebookUri.get(),
        notebookModelAsString: _notebookModel.toCleanPrettyJson()
      };
    };

    return {
      reset: function(notebookUri, uriType, readOnly, format, notebookModel, edited, sessionId) {

        // backup existing session if it's not empty.
        if (_sessionId && !_notebookModel.isEmpty()) {
          bkSession.backup(_sessionId, generateBackupData());
        }

        bkEvaluatorManager.reset();

        // check inputs
        if (!sessionId) {
          sessionId = bkUtils.generateId(6);
        }

        // reset
        _uriType = uriType;
        _readOnly = readOnly;
        _format = format;
        _notebookUri.set(notebookUri);
        _notebookModel.set(notebookModel);
        _edited = !!edited;
        _sessionId = sessionId;

        bkNotebookNamespaceModelManager.init(sessionId, notebookModel);
      },
      clear: function() {
        bkEvaluatorManager.reset();
        bkNotebookNamespaceModelManager.clear(_sessionId);
        _notebookUri.reset();
        _uriType = null;
        _readOnly = null;
        _format = null;
        _notebookModel.reset();
        _sessionId = null;
        _edited = false;
      },
      close: function() {
        var self = this;
        var close = function() {
          bkEvaluatorManager.exitAndRemoveAllEvaluators();
          self.clear();
        };
        if (_sessionId) {
          return bkSession.close(_sessionId).then(close);
        } else{
          close();
          return bkUtils.newPromise();
        }
      },
      backup: function() {
        if (_sessionId && !_notebookModel.isEmpty()) {
          return bkSession.backup(_sessionId, generateBackupData());
        } else {
          return bkUtils.newPromise();
        }
      },
      updateNotebookUri: function(notebookUri, uriType, readOnly, format) {
        // to be used by save-as
        _uriType = uriType;
        _readOnly = readOnly;
        _format = format;
        _notebookUri.set(notebookUri);
      },
      getNotebookTitle: function() {
        if (_notebookUri.get()) {
          return _notebookUri.get().replace(/^.*[\\\/]/, '');
        } else {
          return "New Notebook";
        }
      },
      isSavable: function() {
        return _notebookUri && !_readOnly;
      },
      getSaveData: function() {
        return generateSaveData();
      },
      getNotebookModelAsString: function() {
        return _notebookModel.toJson();
      },
      getRawNotebookModel: function() {
        return _notebookModel.get();
      },
      getSessionId: function() {
        return _sessionId;
      },
      // TODO, move the following impl to a dedicated notebook model manager
      // but still expose it here
      setNotebookModelEdited: function(edited) {
        _edited = edited;
      },
      isNotebookModelEdited: function() {
        return _edited;
      },
      isNotebookLocked: function() {
        return _notebookModel.isLocked();
      },
      toggleNotebookLocked: function() {
        if (!_notebookModel.isEmpty()) {
          if (!_notebookModel.isLocked()) {
            _notebookModel.get().locked = true;
          } else {
            _notebookModel.get().locked = undefined;
          }
          _edited = true;
        }
      },
      addEvaluator: function(evaluator) {
        _notebookModel.get().evaluators.push(evaluator);
        _edited = true;
      },
      getNotebookCellOp: function() {
        return bkNotebookCellModelManager;
      },
      getNotebookNewCellFactory: function() {
        return {
          newCodeCell: function(evaluator, id) {
            if (!evaluator) {
              evaluator = _notebookModel.get().evaluators[0].name;
            }
            if (!id) {
              id = "code" + bkUtils.generateId(6);
            }
            return {
              "id": id,
              "type": "code",
              "evaluator": evaluator,
              "input": {
                "body": ""
              },
              "output": {}
            };
          },
          newSectionCell: function(level, title, id) {
            if (!level && level !== 0) {
              level = 1;
            }
            if (level <= 0) {
              throw "creating section cell with level " + level + " is not allowed";
            }
            if (!title) {
              title = "New Section H" + level;
            }

            if (!id) {
              id = "section" + bkUtils.generateId(6);
            }
            return {
              "id": id,
              "type": "section",
              "title": title,
              "level": level
            };
          },
          newTextCell: function(id) {
            if (!id) {
              id = "text" + bkUtils.generateId(6);
            }
            return {
              "id": id,
              "type": "text",
              "body": "New text cell"
            };
          },
          newMarkdownCell: function(id) {
            var tail = _notebookModel.get().cells.length - 1;
            if (!id) {
              id = "markdown" + bkUtils.generateId(6);
            }
            return {
              "id": id,
              "type": "markdown",
              "body": ""
            };
          }
        };
      },
      isRootCellInitialization: function() {
        return _notebookModel.get().initializeAll;
      },
      setRootCellInitialization: function(initialization) {
        if (initialization === true) {
          _notebookModel.get().initializeAll = true;
        } else {
          _notebookModel.get().initializeAll = undefined;
        }
      },
      notebookModelAddEvaluator: function(newEvaluator) {
        _notebookModel.get().evaluators.push(newEvaluator);
      },
      notebookModelGetInitializationCells: function() {
        if (_notebookModel.get().initializeAll) {
          return this.getNotebookCellOp().getAllCodeCells("root");
        } else {
          return this.getNotebookCellOp().getInitializationCells();
        }
      }
    };
  });
})();
<|endoftext|>