<commit_before>/*global module:false */

module.exports = function(grunt) {

	grunt.initConfig({

		pkg: grunt.file.readJSON('package.json'),

		meta: {

			banner_long: '/*!\n' +
			             ' * <%= pkg.title || pkg.name %>\n' +
			             '<%= pkg.description ? " * " + pkg.description + "\\n" : "" %>' +
			             ' *\n' +
			             '<%= pkg.author.name ? " * @author " + pkg.author.name + "\\n" : "" %>' +
			             '<%= pkg.author.url ? " * @link " + pkg.author.url + "\\n" : "" %>' +
			             '<%= pkg.homepage ? " * @docs " + pkg.homepage + "\\n" : "" %>' +
			             ' * @copyright Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>.\n' +
			             '<%= pkg.licenses ? " * @license Released under the " + _.pluck(pkg.licenses, "type").join(", ") + ".\\n" : "" %>' +
			             '<%= pkg.version ? " * @version " + pkg.version + "\\n" : "" %>' +
			             ' * @date <%= grunt.template.today("yyyy/mm/dd") %>\n' +
			             ' */\r\r',

			banner_short: '/*! ' +
			              '<%= pkg.title || pkg.name %>' +
			              '<%= pkg.version ? " v" + pkg.version : "" %>' +
			              '<%= pkg.licenses ? " | " + _.pluck(pkg.licenses, "type").join(", ") : "" %>' +
			              '<%= pkg.homepage ? " | " + pkg.homepage : "" %>' +
			              ' */'

		},

		//----------------------------------

		/**
		 * @see http://www.jshint.com/docs/
		 */

		jshint: {

			options: {

				smarttabs: true,
				browser: true,
				quotmark: true,
				curly: true

			},

			init: [

				'./Gruntfile.js',
				'./src/jquery.<%= pkg.name %>.js'

			]

		},

		//----------------------------------

		/**
		 * @see https://github.com/gruntjs/grunt-contrib-uglify
		 */

		uglify: {

			my_target: {

				options: {

					banner: '<%= meta.banner_short %>'

				},

				files: {

					'../<%= pkg.name %>/jquery.<%= pkg.name %>.min.js': ['./src/jquery.<%= pkg.name %>.js']

				}

			}

		},

		//----------------------------------

		/**
		 * @see https://github.com/gruntjs/grunt-contrib-concat
		 */

		concat: {

			options: {

				banner: '<%= meta.banner_long %>'

			},

			dist: {

				src: ['./src/jquery.<%= pkg.name %>.js'],
				dest: '../<%= pkg.name %>/jquery.<%= pkg.name %>.js'

			}

		},

	});

	//--------------------------------------------------------------------

	grunt.loadNpmTasks('grunt-contrib-jshint');

	grunt.loadNpmTasks('grunt-contrib-uglify');

	grunt.loadNpmTasks('grunt-contrib-concat');

	//----------------------------------

	grunt.registerTask('default', ['jshint', 'uglify', 'concat']);

};
<commit_msg>Changed "my_target" to "target".<commit_after>/*global module:false */

module.exports = function(grunt) {

	grunt.initConfig({

		pkg: grunt.file.readJSON('package.json'),

		meta: {

			banner_long: '/*!\n' +
			             ' * <%= pkg.title || pkg.name %>\n' +
			             '<%= pkg.description ? " * " + pkg.description + "\\n" : "" %>' +
			             ' *\n' +
			             '<%= pkg.author.name ? " * @author " + pkg.author.name + "\\n" : "" %>' +
			             '<%= pkg.author.url ? " * @link " + pkg.author.url + "\\n" : "" %>' +
			             '<%= pkg.homepage ? " * @docs " + pkg.homepage + "\\n" : "" %>' +
			             ' * @copyright Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>.\n' +
			             '<%= pkg.licenses ? " * @license Released under the " + _.pluck(pkg.licenses, "type").join(", ") + ".\\n" : "" %>' +
			             '<%= pkg.version ? " * @version " + pkg.version + "\\n" : "" %>' +
			             ' * @date <%= grunt.template.today("yyyy/mm/dd") %>\n' +
			             ' */\r\r',

			banner_short: '/*! ' +
			              '<%= pkg.title || pkg.name %>' +
			              '<%= pkg.version ? " v" + pkg.version : "" %>' +
			              '<%= pkg.licenses ? " | " + _.pluck(pkg.licenses, "type").join(", ") : "" %>' +
			              '<%= pkg.homepage ? " | " + pkg.homepage : "" %>' +
			              ' */'

		},

		//----------------------------------

		/**
		 * @see http://www.jshint.com/docs/
		 */

		jshint: {

			options: {

				smarttabs: true,
				browser: true,
				quotmark: true,
				curly: true

			},

			init: [

				'./Gruntfile.js',
				'./src/jquery.<%= pkg.name %>.js'

			]

		},

		//----------------------------------

		/**
		 * @see https://github.com/gruntjs/grunt-contrib-uglify
		 */

		uglify: {

			target: {

				options: {

					banner: '<%= meta.banner_short %>'

				},

				files: {

					'../<%= pkg.name %>/jquery.<%= pkg.name %>.min.js': ['./src/jquery.<%= pkg.name %>.js']

				}

			}

		},

		//----------------------------------

		/**
		 * @see https://github.com/gruntjs/grunt-contrib-concat
		 */

		concat: {

			options: {

				banner: '<%= meta.banner_long %>'

			},

			dist: {

				src: ['./src/jquery.<%= pkg.name %>.js'],
				dest: '../<%= pkg.name %>/jquery.<%= pkg.name %>.js'

			}

		},

	});

	//--------------------------------------------------------------------

	grunt.loadNpmTasks('grunt-contrib-jshint');

	grunt.loadNpmTasks('grunt-contrib-uglify');

	grunt.loadNpmTasks('grunt-contrib-concat');

	//----------------------------------

	grunt.registerTask('default', ['jshint', 'uglify', 'concat']);

};
<|endoftext|>


<commit_before>elation.component.add('filehost.filelist', function() {
  this.init = function() {
    elation.html.addclass(this.container, 'filehost_filelist');
    this.directory = this.args.directory || false;

    var sortargs = { sortby: 'filename', sortreverse: false };
    if (this.directory && this.directory.metadata) {
      if (this.directory.metadata.sortby) sortargs.sortby = this.directory.metadata.sortby;
      if (this.directory.metadata.sortreverse) sortargs.sortreverse = this.directory.metadata.sortreverse;
    }

    if (this.args.files) {
      this.header = elation.ui.panel(null, elation.html.create({append: this.container}), {orientation: 'horizontal', classname: 'filehost_filelist_commands'});
      //this.viewselect = this.header.add(elation.ui.select(null, elation.html.create(), { label: 'View', items: 'details;list;slideshow' }, { "ui_select_change": elation.bind(this, this.processViewChange)}));
      this.sortbyselect = this.header.add(elation.ui.select(null, elation.html.create(), { label: 'Sort by', items: 'filename;filetype;filesize;modified_time', selected: sortargs.sortby }, { "ui_select_change": elation.bind(this, this.processSortbyChange)}));
      this.sortorderselect = this.header.add(elation.ui.select(null, elation.html.create(), { items: 'ascending;descending', selected: (sortargs.sortreverse ? 'descending' : 'ascending') }, { "ui_select_change": elation.bind(this, this.processSortbyChange)}));

      this.list = elation.ui.list(null, elation.html.create({append: this.container}), {orientation: 'inline', sortbydefault: sortargs.sortby, sortorderdefault: sortargs.sortreverse});

      this.updateFiles(this.args.files);
    }
    this.setView(this.args.view || 'details');
  }
  this.setDirectory = function(dirname) {
    this.dirname = dirname;
    elation.ajax.Get("/filehost/files.js?dirname=" + dirname, null, {
      callback: elation.bind(this, this.processDirectoryChange)
    });
  }
  this.setView = function(view) {
    if (this.view) {
      elation.html.removeclass('ui_list_view_' + this.view);
    }
    this.view = view;
    elation.html.addclass('ui_list_view_' + this.view);
  }
  this.updateFiles = function(files) {
    this.files = files;
    var items = [];
    for (var k in files) {
      items.push(elation.filehost.file(null, elation.html.create(), files[k]));
    }
    this.list.setItems(items);
  }
  this.processDirectoryChange = function(jsonstr) {
    var response = JSON.parse(jsonstr);
    var data = response.data;
    if (data.files) {
      this.updateFiles(data.files);
    }
  }
  this.processSortbyChange = function(ev) {
    this.list.sort(this.sortbyselect.value, (this.sortorderselect.value == 'descending'));
  }
  this.processViewChange = function(ev) {
    console.log('set view to ' + ev.data, this.list);
    this.list.setOrientation(ev.data);
  }
});
<commit_msg>Inherit from ui.base<commit_after>elation.require(['ui.base'], function() {
  elation.component.add('filehost.filelist', function() {
    this.init = function() {
      elation.html.addclass(this.container, 'filehost_filelist');
      this.directory = this.args.directory || false;

      var sortargs = { sortby: 'filename', sortreverse: false };
      if (this.directory && this.directory.metadata) {
        if (this.directory.metadata.sortby) sortargs.sortby = this.directory.metadata.sortby;
        if (this.directory.metadata.sortreverse) sortargs.sortreverse = this.directory.metadata.sortreverse;
      }

      if (this.args.files) {
        this.header = elation.ui.panel(null, elation.html.create({append: this.container}), {orientation: 'horizontal', classname: 'filehost_filelist_commands'});
        //this.viewselect = this.header.add(elation.ui.select(null, elation.html.create(), { label: 'View', items: 'details;list;slideshow' }, { "ui_select_change": elation.bind(this, this.processViewChange)}));
        this.sortbyselect = this.header.add(elation.ui.select(null, elation.html.create(), { label: 'Sort by', items: 'filename;filetype;filesize;modified_time', selected: sortargs.sortby }, { "ui_select_change": elation.bind(this, this.processSortbyChange)}));
        this.sortorderselect = this.header.add(elation.ui.select(null, elation.html.create(), { items: 'ascending;descending', selected: (sortargs.sortreverse ? 'descending' : 'ascending') }, { "ui_select_change": elation.bind(this, this.processSortbyChange)}));

        this.list = elation.ui.list(null, elation.html.create({append: this.container}), {orientation: 'inline', sortbydefault: sortargs.sortby, sortorderdefault: sortargs.sortreverse});

        this.updateFiles(this.args.files);
      }
      this.setView(this.args.view || 'details');
    }
    this.setDirectory = function(dirname) {
      this.dirname = dirname;
      elation.ajax.Get("/filehost/files.js?dirname=" + dirname, null, {
        callback: elation.bind(this, this.processDirectoryChange)
      });
    }
    this.setView = function(view) {
      if (this.view) {
        this.removeclass('ui_list_view_' + this.view);
      }
      this.view = view;
      this.addclass('ui_list_view_' + this.view);
    }
    this.updateFiles = function(files) {
      this.files = files;
      var items = [];
      for (var k in files) {
        items.push(elation.filehost.file(null, elation.html.create(), files[k]));
      }
      this.list.setItems(items);
    }
    this.processDirectoryChange = function(jsonstr) {
      var response = JSON.parse(jsonstr);
      var data = response.data;
      if (data.files) {
        this.updateFiles(data.files);
      }
    }
    this.processSortbyChange = function(ev) {
      this.list.sort(this.sortbyselect.value, (this.sortorderselect.value == 'descending'));
    }
    this.processViewChange = function(ev) {
      console.log('set view to ' + ev.data, this.list);
      this.list.setOrientation(ev.data);
    }
  }, elation.ui.base);
});
<|endoftext|>


<commit_before>String.toLocaleString({

	"it": {
		"%game-intro"           : "Join the Cupcakes!",
		"%restart-button"       : "Play Again",
		"%keep-playing-button"  : "Keep going",
		"%retry-button"         : "Try again",
		"%game-won"             : "You win!",
		"%game-over"            : "Game over!",
		"%game-explanation"     : "How to play: Use your arrow keys to move the tiles. When two tiles with the same symbol touch, they get promoted!",
		"%disclaimer"           : "Note: This site git.io/starwars is a spin-off of the official version of 2048 created by Gabriele Cirulli.",
		"%credits"              : "Cupcakes images by Georgetown Cupcake.",
		"%tweet1"               : "I scored \"",
		"%tweet2"               : "\" at 2048-STARWARS #2048game",
		"%tile-legend"          : "Tile Legend:",
		'%2'                    : 'vanilla birthday',
    '%4'                    : 'bubblegum pink',
    '%8'                    : 'sunshine vanilla',
    '%16'                   : 'valrhona blonde ganache',
    '%32'                   : 'chocolare peanut butter cheesecake',
    '%64'                   : 'chocolate mint fudge',
    '%128'                  : 'chocolate spider web',
    '%256'                  : 'toasted marshmallow',
    '%512'                  : 'cookies and creme',
    '%1024'                 : 'chocolate sundae',
    '%2048'                 : 'white chocolate peppermint',
		'%p0'                   : 'vanilla birthday',
    '%p4'                   : 'bubblegum pink',
    '%p8'                   : 'sunshine vanilla',
    '%p16'                  : 'valrhona blonde ganache',
    '%p32'                  : 'choc. peanut butter cheesecake',
    '%p64'                  : 'choc. mint fudge',
    '%p128'                 : 'choc. spider web',
    '%p256'                 : 'toasted marshmallow',
    '%p512'                 : 'cookies and creme',
    '%p1024'                : 'choc. sundae',
    '%p2048'                : 'white choc. peppermint',
	},

	"en": {
		"%game-intro"           : "Unisci le tessere e distruggi l'IMPERO!",
		"%restart-button"       : "Play Again",
		"%keep-playing-button"  : "Continua",
		"%retry-button"         : "Riprova",
		"%game-won"             : "Hai vinto!",
		"%game-over"            : "Hai perso!",
		"%game-explanation"     : "Come giocare: Usare i tasti freccia per muovere le tessere. Quando due tessere con lo stesso simbolo si scontrano c'è la promozione!",
		"%disclaimer"           : "Nota: Questo sito git.io/starwars è uno spin-off della versione ufficiale di 2048 creata da Gabriele Cirulli.",
		"%tile-legend"          : "Legenda Tessere:",
		"%credits"              : "Icone Star Wars di Jory Raphael.",
		"%tweet1"               : "Ho raggiunto \"",
		"%tweet2"               : "\" a 2048-STARWARS #2048game",
		'%2'                    : 'vanilla birthday',
    '%4'                    : 'bubblegum pink',
    '%8'                    : 'sunshine vanilla',
    '%16'                   : 'valrhona blonde ganache',
    '%32'                   : 'chocolare peanut butter cheesecake',
    '%64'                   : 'chocolate mint fudge',
    '%128'                  : 'chocolate spider web',
    '%256'                  : 'toasted marshmallow',
    '%512'                  : 'cookies and creme',
    '%1024'                 : 'chocolate sundae',
    '%2048'                 : 'white chocolate peppermint',
		'%p0'                   : 'vanilla birthday',
    '%p4'                   : 'bubblegum pink',
    '%p8'                   : 'sunshine vanilla',
    '%p16'                  : 'valrhona blonde ganache',
    '%p32'                  : 'choc. peanut butter cheesecake',
    '%p64'                  : 'choc. mint fudge',
    '%p128'                 : 'choc. spider web',
    '%p256'                 : 'toasted marshmallow',
    '%p512'                 : 'cookies and creme',
    '%p1024'                : 'choc. sundae',
    '%p2048'                : 'white choc. peppermint',
	}

});<commit_msg>localization problem<commit_after>String.toLocaleString({

	"it": {
		"%game-intro"           : "Join the Cupcakes!",
		"%restart-button"       : "Play Again",
		"%keep-playing-button"  : "Keep going",
		"%retry-button"         : "Try again",
		"%game-won"             : "You win!",
		"%game-over"            : "Game over!",
		"%game-explanation"     : "How to play: Use your arrow keys to move the tiles. When two tiles with the same symbol touch, they get promoted!",
		"%disclaimer"           : "Note: This site git.io/cupcakes is a spin-off of the official version of 2048 created by Gabriele Cirulli.",
		"%credits"              : "Cupcakes images by Georgetown Cupcake.",
		"%tweet1"               : "I scored \"",
		"%tweet2"               : "\" at 2048-CUPCAKES #2048game",
		"%tile-legend"          : "Tile Legend:",
		'%2'                    : 'vanilla birthday',
    '%4'                    : 'bubblegum pink',
    '%8'                    : 'sunshine vanilla',
    '%16'                   : 'valrhona blonde ganache',
    '%32'                   : 'chocolare peanut butter cheesecake',
    '%64'                   : 'chocolate mint fudge',
    '%128'                  : 'chocolate spider web',
    '%256'                  : 'toasted marshmallow',
    '%512'                  : 'cookies and creme',
    '%1024'                 : 'chocolate sundae',
    '%2048'                 : 'white chocolate peppermint',
		'%p0'                   : 'vanilla birthday',
    '%p4'                   : 'bubblegum pink',
    '%p8'                   : 'sunshine vanilla',
    '%p16'                  : 'valrhona blonde ganache',
    '%p32'                  : 'choc. peanut butter cheesecake',
    '%p64'                  : 'choc. mint fudge',
    '%p128'                 : 'choc. spider web',
    '%p256'                 : 'toasted marshmallow',
    '%p512'                 : 'cookies and creme',
    '%p1024'                : 'choc. sundae',
    '%p2048'                : 'white choc. peppermint',
	},

	"en": {
		"%game-intro"           : "Join the Cupcakes!",
		"%restart-button"       : "Play Again",
		"%keep-playing-button"  : "Keep going",
		"%retry-button"         : "Try again",
		"%game-won"             : "You win!",
		"%game-over"            : "Game over!",
		"%game-explanation"     : "How to play: Use your arrow keys to move the tiles. When two tiles with the same symbol touch, they get promoted!",
		"%disclaimer"           : "Note: This site git.io/cupcakes is a spin-off of the official version of 2048 created by Gabriele Cirulli.",
		"%credits"              : "Cupcakes images by Georgetown Cupcake.",
		"%tweet1"               : "I scored \"",
		"%tweet2"               : "\" at 2048-CUPCAKES #2048game",
		"%tile-legend"          : "Tile Legend:",
		'%2'                    : 'vanilla birthday',
    '%4'                    : 'bubblegum pink',
    '%8'                    : 'sunshine vanilla',
    '%16'                   : 'valrhona blonde ganache',
    '%32'                   : 'chocolare peanut butter cheesecake',
    '%64'                   : 'chocolate mint fudge',
    '%128'                  : 'chocolate spider web',
    '%256'                  : 'toasted marshmallow',
    '%512'                  : 'cookies and creme',
    '%1024'                 : 'chocolate sundae',
    '%2048'                 : 'white chocolate peppermint',
		'%p0'                   : 'vanilla birthday',
    '%p4'                   : 'bubblegum pink',
    '%p8'                   : 'sunshine vanilla',
    '%p16'                  : 'valrhona blonde ganache',
    '%p32'                  : 'choc. peanut butter cheesecake',
    '%p64'                  : 'choc. mint fudge',
    '%p128'                 : 'choc. spider web',
    '%p256'                 : 'toasted marshmallow',
    '%p512'                 : 'cookies and creme',
    '%p1024'                : 'choc. sundae',
    '%p2048'                : 'white choc. peppermint',
	}

});<|endoftext|>


<commit_before>const {Bookmark} = require('../models')

module.exports = {
  async index (req, res) {
    try {
      const {songId, userId} = req.query

      const bookmark = await Bookmark.findOne({
        where: {
          SongId: songId,
          UserId: userId
        }
      })
      res.send(bookmark)
    } catch (err) {
        res.status(500).send({
        error: 'An error has occured.'
      })
    }
  },

  async post (req, res) {
    try {
      const bookmark = req.body

      await Bookmark.create(bookmark)
      res.send(bookmark)
    } catch (err) {
        res.status(500).send({
        error: 'An error has occured.'
      })
    }
  },

  async delete (req, res) {
    try {
      const {bookmarkId} = req.params

      const bookmark = await Bookmark.findById(bookmarkId)
      await bookmark.destroy()
      res.send(bookmark)
    } catch (err) {
        res.status(500).send({
        error: 'An error has occured.'
      })
    }
  }
}
<commit_msg>Update add & delete bookmark on backend<commit_after>const {Bookmark} = require('../models')

module.exports = {
  async index (req, res) {
    try {
      const {songId, userId} = req.query

      const bookmark = await Bookmark.findOne({
        where: {
          SongId: songId,
          UserId: userId
        }
      })
      res.send(bookmark)
    } catch (err) {
        return res.status(500).send({
        error: 'An error has occured.'
      })
    }
  },

  async post (req, res) {
    try {
      const {songId, userId} = req.body.params
      const bookmark = await Bookmark.findOne({
        where: {
          SongId: songId,
          UserId: songId
        }
      })
      if (bookmark) {
        return res.status(400).send({
          error: 'You already have this set as a bookmark'
        })
      }

      const newBookmark = await Bookmark.create({
        SongId: songId,
        UserId: userId
      })
      res.status(201).send(newBookmark)
    } catch (err) {
      return res.status(500).send({
        error: 'An internal error has occured.'
      })
    }
  },

  async delete (req, res) {
    try {
      const {bookmarkId} = req.params

      const bookmark = await Bookmark.findById(bookmarkId)
      await bookmark.destroy()
      res.send(bookmark)
    } catch (err) {
        res.status(500).send({
        error: 'An error has occured.'
      })
    }
  }
}
<|endoftext|>


<commit_before>/*
 * Licensed to Apereo under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Apereo licenses this file to you 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 the following location:
 *
 *   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.
 */
define(['angular'], function(angular) {
  /* Keep in sync with docs/markdown/configuration.md*/
  return angular.module('app-config', [])
        .value('APP_FLAGS', {
            'showSearch': true,
            'isWeb': false,
            'defaultTheme': 0,
            'showUserSettingsPage': false,
            'debug': false,
            'campusIdAttribute': null,
        })
        .value('APP_OPTIONS', {
            'appMenuTemplateURL': null,
            'appMenuItems': [],
            'enablePushContentMenu': false,
        })
        .value('SERVICE_LOC', {
            'aboutURL': null,
            'aboutPageURL': null,
            'groupURL': '/portal/api/groups',
            'kvURL': '/storage',
            'loginSilentURL': '/portal/Login?silent=true',
            'messagesURL': '', // staticFeeds/sample-messages.json
            'sessionInfo': 'staticFeeds/session.json',
            'shibbolethSessionURL': 'staticFeeds/Shibboleth.sso/Session.json',
            'portalLayoutRestEndpoint': null, // '/portal/api/layout',
            'widgetApi': {
              'entry': '/portal/api/marketplace/entry/', // 'staticFeeds/'
              'entrySuffix': '.json',
              'entries': '/portal/api/marketplace/entries.json',
            },
        })
        .value('NAMES', {
          // you can name your app whatever you want
            'title': 'Frame app',
            'guestUserName': 'guest',
            'fname': 'sample-fname',
        })
        .value('SEARCH', {
            'searchURL': '/web/apps/search/',
        })
        .value('MESSAGES', {
            'notificationsPageURL': '/web/notifications',
        })
        .value('MISC_URLS', {
            'feedbackURL': 'https://my.wisc.edu/portal/p/feedback',
            'helpdeskURL': 'https://kb.wisc.edu/helpdesk/',
            'loginURL': '/portal/Login?profile=bucky',
            'logoutURL': '/portal/Logout',
            'myuwHome': 'https://my.wisc.edu',
            'resetLayoutURL': '/portal/p/reset-my-layout',
            'rootURL': '/web',
            'addToHomeURLS': {
              'layoutURL': '/portal/web/layoutDoc?tab=UW Bucky Home',
              'addToHomeActionURL':
                '/portal/web/layout?tabName=UW Bucky Home' +
                '&action=addPortlet&fname=',
            },

        })
        .value('FOOTER_URLS', [
          {'url': '/web/features',
            'target': '_blank',
            'title': 'What\'s New',
          },
        ])
        .value('APP_BETA_FEATURES', [
          {
            'id': 'toggleSomething',
            'title': 'Sample Toggle',
            'description':
              'This is just an example of a toggle. ' +
              'Look at your localStorage after you ' +
              'switch this on for the first time.',
          },
        ]);
});
<commit_msg>fix: remove what's new from base config<commit_after>/*
 * Licensed to Apereo under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Apereo licenses this file to you 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 the following location:
 *
 *   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.
 */
define(['angular'], function(angular) {
  /* Keep in sync with docs/markdown/configuration.md*/
  return angular.module('app-config', [])
        .value('APP_FLAGS', {
            'showSearch': true,
            'isWeb': false,
            'defaultTheme': 0,
            'showUserSettingsPage': false,
            'debug': false,
            'campusIdAttribute': null,
        })
        .value('APP_OPTIONS', {
            'appMenuTemplateURL': null,
            'appMenuItems': [],
            'enablePushContentMenu': false,
        })
        .value('SERVICE_LOC', {
            'aboutURL': null,
            'aboutPageURL': null,
            'groupURL': '/portal/api/groups',
            'kvURL': '/storage',
            'loginSilentURL': '/portal/Login?silent=true',
            'messagesURL': '', // staticFeeds/sample-messages.json
            'sessionInfo': 'staticFeeds/session.json',
            'shibbolethSessionURL': 'staticFeeds/Shibboleth.sso/Session.json',
            'portalLayoutRestEndpoint': null, // '/portal/api/layout',
            'widgetApi': {
              'entry': '/portal/api/marketplace/entry/', // 'staticFeeds/'
              'entrySuffix': '.json',
              'entries': '/portal/api/marketplace/entries.json',
            },
        })
        .value('NAMES', {
          // you can name your app whatever you want
            'title': 'Frame app',
            'guestUserName': 'guest',
            'fname': 'sample-fname',
        })
        .value('SEARCH', {
            'searchURL': '/web/apps/search/',
        })
        .value('MESSAGES', {
            'notificationsPageURL': '/web/notifications',
        })
        .value('MISC_URLS', {
            'feedbackURL': 'https://my.wisc.edu/portal/p/feedback',
            'helpdeskURL': 'https://kb.wisc.edu/helpdesk/',
            'loginURL': '/portal/Login?profile=bucky',
            'logoutURL': '/portal/Logout',
            'myuwHome': 'https://my.wisc.edu',
            'resetLayoutURL': '/portal/p/reset-my-layout',
            'rootURL': '/web',
            'addToHomeURLS': {
              'layoutURL': '/portal/web/layoutDoc?tab=UW Bucky Home',
              'addToHomeActionURL':
                '/portal/web/layout?tabName=UW Bucky Home' +
                '&action=addPortlet&fname=',
            },

        })
        .value('APP_BETA_FEATURES', [
          {
            'id': 'toggleSomething',
            'title': 'Sample Toggle',
            'description':
              'This is just an example of a toggle. ' +
              'Look at your localStorage after you ' +
              'switch this on for the first time.',
          },
        ]);
});
<|endoftext|>


<commit_before>var fs = require('fs');
var _ = require('underscore');
var packageCache = require('./package-cache.js');

var BootstrapCatalogPrebuilt = function (uniloadDir) {
  var self = this;

  // The uniload catalog needs its own package cache.
  self.packageCache = new packageCache.PackageCache(self);
};

_.extend(BootstrapCatalogPrebuilt.prototype, {
  initialize: function (options) {
    var self = this;
    if (!options.uniloadDir)
      throw Error("no uniloadDir?");
    self.uniloadDir = options.uniloadDir;

    // Make empty data structures for all the things.
    self.reset();

    self._knownPackages = {};
    _.each(fs.readdirSync(options.uniloadDir), function (package) {
      if (fs.existsSync(path.join(options.uniloadDir, package,
                                  'unipackage.json'))) {
        self._knownPackages[package] = true;

        // XXX do we have to also put stuff in self.packages/versions/builds?
        //     probably.
      }
    });

    self.initialized = true;
  },

  resolveConstraints: function () {
    throw Error("uniload resolving constraints? that's wrong.");
  },

  // Ignores version (and constraintSolverOpts) because we just have a bunch of
  // precompiled packages.
  getLoadPathForPackage: function (name, version, constraintSolverOpts) {
    var self = this;
    self._requireInitialized();
    if (_.has(self._knownPackages, name)) {
      return path.join(self.uniloadDir, name);
    }
    return null;
  }

});

exports.BootstrapCatalogPrebuilt = BootstrapCatalogPrebuilt;<commit_msg>fix mistakes<commit_after>var fs = require('fs');
var _ = require('underscore');
var packageCache = require('./package-cache.js');
var path = require('path');

// The BootstrapCatalogPrebuilt is a catalog that represents the packages used to bootstrap meteor
// It is meant to work when we are running meteor in the "real" format
// This catalog is typically never used directly by the user.
// An instance of this catalog is created in catalog.js
var BootstrapCatalogPrebuilt = function (uniloadDir) {
  var self = this;

  // The uniload catalog needs its own package cache.
  self.packageCache = new packageCache.PackageCache(self);
};

_.extend(BootstrapCatalogPrebuilt.prototype, {
  initialize: function (options) {
    var self = this;
    if (!options.uniloadDir)
      throw Error("no uniloadDir?");
    self.uniloadDir = options.uniloadDir;

    self._knownPackages = {};
    _.each(fs.readdirSync(options.uniloadDir), function (package) {
      if (fs.existsSync(path.join(options.uniloadDir, package,
                                  'unipackage.json'))) {
        self._knownPackages[package] = true;

        // XXX do we have to also put stuff in self.packages/versions/builds?
        //     probably.
      }
    });

    self.initialized = true;
  },

  resolveConstraints: function () {
    throw Error("uniload resolving constraints? that's wrong.");
  },

  // Ignores version (and constraintSolverOpts) because we just have a bunch of
  // precompiled packages.
  getLoadPathForPackage: function (name, version, constraintSolverOpts) {
    var self = this;
    self._requireInitialized();
    if (_.has(self._knownPackages, name)) {
      return path.join(self.uniloadDir, name);
    }
    return null;
  }

});

exports.BootstrapCatalogPrebuilt = BootstrapCatalogPrebuilt;<|endoftext|>


<commit_before>/*! =========================================================
 *
 * Material Kit PRO - v1.1.1
 *
 * =========================================================
 *
 * Product Page: https://www.creative-tim.com/product/material-kit-pro
 * Available with purchase of license from http://www.creative-tim.com/product/material-kit-pro
 * Copyright 2017 Creative Tim (https://www.creative-tim.com)
 * License Creative Tim (https://www.creative-tim.com/license)
 *
 * ========================================================= */

var big_image;
(function($){
 $(document).ready(function(){

     // Init Material scripts for buttons ripples, inputs animations etc, more info on the next link https://github.com/FezVrasta/bootstrap-material-design#materialjs
     $.material.init();

     window_width = $(window).width();

     $navbar = $('.navbar[color-on-scroll]');
     scroll_distance = $navbar.attr('color-on-scroll') || 500;

     $navbar_collapse = $('.navbar').find('.navbar-collapse');

     //  Activate the Tooltips
     $('[data-toggle="tooltip"], [rel="tooltip"]').tooltip();

     //    Activate bootstrap-select
     if($(".selectpicker").length != 0){
         $(".selectpicker").selectpicker();
     }

     // Activate Popovers
     //$('[data-toggle="popover"]').popover();

     // Active Carousel
    //$('.carousel').carousel({
     //  interval: 3000
     //});

     //Activate tags
     //removed class label and label-color from tag span and replaced with data-color
     var tagClass = $('.tagsinput').data('color');

     //$('.tagsinput').tagsinput({
     //    tagClass: ' tag-'+ tagClass +' '
     //});

     if($('.navbar-color-on-scroll').length != 0){
         $(window).on('scroll', materialKit.checkScrollForTransparentNavbar)
     }

     if (window_width >= 768){
         big_image = $('.page-header[data-parallax="true"]');
         if(big_image.length != 0){
            $(window).on('scroll', materialKitDemo.checkScrollForParallax);
         }

     }
 });

 $(window).on("load", function() {
      //initialise rotating cards
      materialKit.initRotateCard();

      //initialise colored shadow
      materialKit.initColoredShadows();

      //initialise animation effect on images
      materialKit.initAtvImg();
  });

 $(document).on('click', '.card-rotate .btn-rotate', function(){
     var $rotating_card_container = $(this).closest('.rotating-card-container');

     if($rotating_card_container.hasClass('hover')){
         $rotating_card_container.removeClass('hover');
     } else {
         $rotating_card_container.addClass('hover');
     }
 });

 $(document).on('click', '.navbar-toggle', function(){
     $toggle = $(this);

     if(materialKit.misc.navbar_menu_visible == 1) {
         $('html').removeClass('nav-open');
         materialKit.misc.navbar_menu_visible = 0;
         $('#bodyClick').remove();
          setTimeout(function(){
             $toggle.removeClass('toggled');
          }, 550);

         $('html').removeClass('nav-open-absolute');
     } else {
         setTimeout(function(){
             $toggle.addClass('toggled');
         }, 580);

         div = '

';
         $(div).appendTo("body").click(function() {
             $('html').removeClass('nav-open');

             if($('nav').hasClass('navbar-absolute')){
                 $('html').removeClass('nav-open-absolute');
             }
             materialKit.misc.navbar_menu_visible = 0;
             $('#bodyClick').remove();
              setTimeout(function(){
                 $toggle.removeClass('toggled');
              }, 550);
         });

         if($('nav').hasClass('navbar-absolute')){
             $('html').addClass('nav-open-absolute');
         }

         $('html').addClass('nav-open');
         materialKit.misc.navbar_menu_visible = 1;
     }
 });

 $(window).on('resize', function(){
     materialKit.initRotateCard();
 });

 materialKit = {
     misc:{
         navbar_menu_visible: 0,
         window_width: 0,
         transparent: true,
         colored_shadows: true,
         fixedTop: false,
         navbar_initialized: false,
         isWindow: document.documentMode || /Edge/.test(navigator.userAgent)
     },

     initAtvImg: function(){
        $('.card-atv').each(function(){
            var $atv_div = $(this).find('.atvImg');
            var $atv_img = $atv_div.find('img');

            var img_src = $atv_img.attr('src');
            var atv_image_layer = '
';

            $atv_div.css('height',$atv_img.height() + 'px');
            $atv_div.append(atv_image_layer);

        });

        atvImg();
    },
    initSliderHome: function(){
        $('#autoplay-slider').slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            arrows: !0,
            appendArrows: "#slider-container",
            prevArrow: 'keyboard_arrow_left',
            nextArrow: 'keyboard_arrow_right',
            autoplay: !0,
            autoplaySpeed: 4e3
        });

        $('#center-slider').slick({
            centerMode: true,
            centerPadding: '60px',
            slidesToShow: 1,
            infinite: true,
            variableWidth: true,
            variableHeight: true,
            arrows: !0,
            appendArrows: "#features-slider-container",
            prevArrow: 'keyboard_arrow_left',
            nextArrow: 'keyboard_arrow_right',
            responsive: [
                {
                    breakpoint: 768,
                    settings: {
                        arrows: false,
                        centerMode: true,
                        centerPadding: '40px',
                        slidesToShow: 1,
                        infinite: true,
                        variableWidth: true,
                        variableHeight: true
                    }
                },
                {
                    breakpoint: 480,
                    settings: "unslick"
                }
            ]
        });
    },
    initColoredShadows: function(){
        if(materialKit.misc.colored_shadows == true){

            if(!materialKit.misc.isWindows){
                $('.card:not([data-colored-shadow="false"]) .card-image').each(function(){
                    var $card_img = $(this);

                    is_on_dark_screen = $(this).closest('.section-dark, .section-image').length;

                    // we block the generator of the colored shadows on dark sections, because they are not natural
                    if(is_on_dark_screen == 0){
                        var img_source = $card_img.find('img').attr('src');
                        var is_rotating = $card_img.closest('.card-rotate').length == 1 ? true : false;
                        var $append_div = $card_img;

                        var colored_shadow_div = $('
');

                        if(is_rotating){
                            var card_image_height = $card_img.height();
                            var card_image_width = $card_img.width();

                            $(this).find('.back').css({
                                'height': card_image_height + 'px',
                                'width': card_image_width + 'px'
                            });
                            var $append_div = $card_img.find('.front');
                        }

                        colored_shadow_div.css({'background-image': 'url(' + img_source +')'}).appendTo($append_div);

                        if($card_img.width() > 700){
                            colored_shadow_div.addClass('colored-shadow-big');
                        }

                        setTimeout(function(){
                            colored_shadow_div.css('opacity',1);
                        }, 200)
                    }

                });
            }
        }
    },

     initRotateCard: debounce(function(){

         $('.card-rotate .card-image > .back').each(function(){
             var card_image_height = $(this).parent().height();
             var card_image_width = $(this).parent().width();

             $(this).css({
                 'height': card_image_height + 'px',
                 'width': card_image_width + 'px'
             });

             if($(this).hasClass('back-background')){
                 var img_src = $(this).siblings('.front').find('img').attr('src');
                 $(this).css('background-image','url("' + img_src + '")');
             }
         });
     }, 17),

     checkScrollForTransparentNavbar: debounce(function() {
             if($(document).scrollTop() > scroll_distance ) {
                 if(materialKit.misc.transparent) {
                     materialKit.misc.transparent = false;
                     $('.navbar-color-on-scroll').removeClass('navbar-transparent');
                 }
             } else {
                 if( !materialKit.misc.transparent ) {
                     materialKit.misc.transparent = true;
                     $('.navbar-color-on-scroll').addClass('navbar-transparent');
                 }
             }
     }, 17),

     initSliders: function(){
         // Sliders for demo purpose
         var slider = document.getElementById('sliderRegular');

         noUiSlider.create(slider, {
             start: 40,
             connect: [true,false],
             range: {
                 min: 0,
                 max: 100
             }
         });

         var slider2 = document.getElementById('sliderDouble');

         noUiSlider.create(slider2, {
             start: [ 20, 60 ],
             connect: true,
             range: {
                 min:  0,
                 max:  100
             }
         });
     }
 }

 materialKitDemo = {

     checkScrollForParallax: debounce(function(){
        if(isElementInViewport(big_image)){
             var current_scroll = $(this).scrollTop();
             oVal = ($(window).scrollTop() / 3);
             big_image.css({
                 'transform':'translate3d(0,' + oVal +'px,0)',
                 '-webkit-transform':'translate3d(0,' + oVal +'px,0)',
                 '-ms-transform':'translate3d(0,' + oVal +'px,0)',
                 '-o-transform':'translate3d(0,' + oVal +'px,0)'
             });
        }
     }, 4)
 }
 // Returns a function, that, as long as it continues to be invoked, will not
 // be triggered. The function will be called after it stops being called for
 // N milliseconds. If `immediate` is passed, trigger the function on the
 // leading edge, instead of the trailing.

 function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        }, wait);
        if (immediate && !timeout) func.apply(context, args);
    };
 };

 function isElementInViewport(elem) {
     var $elem = $(elem);

     // Get the scroll position of the page.
     var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
     var viewportTop = $(scrollElem).scrollTop();
     var viewportBottom = viewportTop + $(window).height();

     // Get the position of the element on the page.
     var elemTop = Math.round( $elem.offset().top );
     var elemBottom = elemTop + $elem.height();

     return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
 }
 })(jQuery); <commit_msg>Slider changes<commit_after>/*! =========================================================
 *
 * Material Kit PRO - v1.1.1
 *
 * =========================================================
 *
 * Product Page: https://www.creative-tim.com/product/material-kit-pro
 * Available with purchase of license from http://www.creative-tim.com/product/material-kit-pro
 * Copyright 2017 Creative Tim (https://www.creative-tim.com)
 * License Creative Tim (https://www.creative-tim.com/license)
 *
 * ========================================================= */

var big_image;
(function($){
 $(document).ready(function(){

     // Init Material scripts for buttons ripples, inputs animations etc, more info on the next link https://github.com/FezVrasta/bootstrap-material-design#materialjs
     $.material.init();

     window_width = $(window).width();

     $navbar = $('.navbar[color-on-scroll]');
     scroll_distance = $navbar.attr('color-on-scroll') || 500;

     $navbar_collapse = $('.navbar').find('.navbar-collapse');

     //  Activate the Tooltips
     $('[data-toggle="tooltip"], [rel="tooltip"]').tooltip();

     //    Activate bootstrap-select
     if($(".selectpicker").length != 0){
         $(".selectpicker").selectpicker();
     }

     // Activate Popovers
     //$('[data-toggle="popover"]').popover();

     // Active Carousel
    //$('.carousel').carousel({
     //  interval: 3000
     //});
     $(".sliderProductPicker").slick({
        infinite: false,
        slidesToShow: 2,
        slidesToScroll: 2,
        centermode: false
      });
     //Activate tags
     //removed class label and label-color from tag span and replaced with data-color
     var tagClass = $('.tagsinput').data('color');

     //$('.tagsinput').tagsinput({
     //    tagClass: ' tag-'+ tagClass +' '
     //});

     if($('.navbar-color-on-scroll').length != 0){
         $(window).on('scroll', materialKit.checkScrollForTransparentNavbar)
     }

     if (window_width >= 768){
         big_image = $('.page-header[data-parallax="true"]');
         if(big_image.length != 0){
            $(window).on('scroll', materialKitDemo.checkScrollForParallax);
         }

     }
 });

 $(window).on("load", function() {
      //initialise rotating cards
      materialKit.initRotateCard();

      //initialise colored shadow
      materialKit.initColoredShadows();

      //initialise animation effect on images
      materialKit.initAtvImg();
  });

 $(document).on('click', '.card-rotate .btn-rotate', function(){
     var $rotating_card_container = $(this).closest('.rotating-card-container');

     if($rotating_card_container.hasClass('hover')){
         $rotating_card_container.removeClass('hover');
     } else {
         $rotating_card_container.addClass('hover');
     }
 });

 $(document).on('click', '.navbar-toggle', function(){
     $toggle = $(this);

     if(materialKit.misc.navbar_menu_visible == 1) {
         $('html').removeClass('nav-open');
         materialKit.misc.navbar_menu_visible = 0;
         $('#bodyClick').remove();
          setTimeout(function(){
             $toggle.removeClass('toggled');
          }, 550);

         $('html').removeClass('nav-open-absolute');
     } else {
         setTimeout(function(){
             $toggle.addClass('toggled');
         }, 580);

         div = '

';
         $(div).appendTo("body").click(function() {
             $('html').removeClass('nav-open');

             if($('nav').hasClass('navbar-absolute')){
                 $('html').removeClass('nav-open-absolute');
             }
             materialKit.misc.navbar_menu_visible = 0;
             $('#bodyClick').remove();
              setTimeout(function(){
                 $toggle.removeClass('toggled');
              }, 550);
         });

         if($('nav').hasClass('navbar-absolute')){
             $('html').addClass('nav-open-absolute');
         }

         $('html').addClass('nav-open');
         materialKit.misc.navbar_menu_visible = 1;
     }
 });

 $(window).on('resize', function(){
     materialKit.initRotateCard();
 });

 materialKit = {
     misc:{
         navbar_menu_visible: 0,
         window_width: 0,
         transparent: true,
         colored_shadows: true,
         fixedTop: false,
         navbar_initialized: false,
         isWindow: document.documentMode || /Edge/.test(navigator.userAgent)
     },

     initAtvImg: function(){
        $('.card-atv').each(function(){
            var $atv_div = $(this).find('.atvImg');
            var $atv_img = $atv_div.find('img');

            var img_src = $atv_img.attr('src');
            var atv_image_layer = '
';

            $atv_div.css('height',$atv_img.height() + 'px');
            $atv_div.append(atv_image_layer);

        });

        atvImg();
    },
    initSliderHome: function(){
        $('#autoplay-slider').slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            arrows: !0,
            appendArrows: "#slider-container",
            prevArrow: 'keyboard_arrow_left',
            nextArrow: 'keyboard_arrow_right',
            autoplay: !0,
            autoplaySpeed: 4e3
        });

        $('#center-slider').slick({
            centerMode: true,
            centerPadding: '60px',
            slidesToShow: 1,
            infinite: true,
            variableWidth: true,
            variableHeight: true,
            arrows: !0,
            appendArrows: "#features-slider-container",
            prevArrow: 'keyboard_arrow_left',
            nextArrow: 'keyboard_arrow_right',
            responsive: [
                {
                    breakpoint: 768,
                    settings: {
                        arrows: false,
                        centerMode: true,
                        centerPadding: '40px',
                        slidesToShow: 1,
                        infinite: true,
                        variableWidth: true,
                        variableHeight: true
                    }
                },
                {
                    breakpoint: 480,
                    settings: "unslick"
                }
            ]
        });
    },
    initColoredShadows: function(){
        if(materialKit.misc.colored_shadows == true){

            if(!materialKit.misc.isWindows){
                $('.card:not([data-colored-shadow="false"]) .card-image').each(function(){
                    var $card_img = $(this);

                    is_on_dark_screen = $(this).closest('.section-dark, .section-image').length;

                    // we block the generator of the colored shadows on dark sections, because they are not natural
                    if(is_on_dark_screen == 0){
                        var img_source = $card_img.find('img').attr('src');
                        var is_rotating = $card_img.closest('.card-rotate').length == 1 ? true : false;
                        var $append_div = $card_img;

                        var colored_shadow_div = $('
');

                        if(is_rotating){
                            var card_image_height = $card_img.height();
                            var card_image_width = $card_img.width();

                            $(this).find('.back').css({
                                'height': card_image_height + 'px',
                                'width': card_image_width + 'px'
                            });
                            var $append_div = $card_img.find('.front');
                        }

                        colored_shadow_div.css({'background-image': 'url(' + img_source +')'}).appendTo($append_div);

                        if($card_img.width() > 700){
                            colored_shadow_div.addClass('colored-shadow-big');
                        }

                        setTimeout(function(){
                            colored_shadow_div.css('opacity',1);
                        }, 200)
                    }

                });
            }
        }
    },

     initRotateCard: debounce(function(){

         $('.card-rotate .card-image > .back').each(function(){
             var card_image_height = $(this).parent().height();
             var card_image_width = $(this).parent().width();

             $(this).css({
                 'height': card_image_height + 'px',
                 'width': card_image_width + 'px'
             });

             if($(this).hasClass('back-background')){
                 var img_src = $(this).siblings('.front').find('img').attr('src');
                 $(this).css('background-image','url("' + img_src + '")');
             }
         });
     }, 17),

     checkScrollForTransparentNavbar: debounce(function() {
             if($(document).scrollTop() > scroll_distance ) {
                 if(materialKit.misc.transparent) {
                     materialKit.misc.transparent = false;
                     $('.navbar-color-on-scroll').removeClass('navbar-transparent');
                 }
             } else {
                 if( !materialKit.misc.transparent ) {
                     materialKit.misc.transparent = true;
                     $('.navbar-color-on-scroll').addClass('navbar-transparent');
                 }
             }
     }, 17),

     initSliders: function(){
         // Sliders for demo purpose
         var slider = document.getElementById('sliderRegular');

         noUiSlider.create(slider, {
             start: 40,
             connect: [true,false],
             range: {
                 min: 0,
                 max: 100
             }
         });

         var slider2 = document.getElementById('sliderDouble');

         noUiSlider.create(slider2, {
             start: [ 20, 60 ],
             connect: true,
             range: {
                 min:  0,
                 max:  100
             }
         });
     }
 }

 materialKitDemo = {

     checkScrollForParallax: debounce(function(){
        if(isElementInViewport(big_image)){
             var current_scroll = $(this).scrollTop();
             oVal = ($(window).scrollTop() / 3);
             big_image.css({
                 'transform':'translate3d(0,' + oVal +'px,0)',
                 '-webkit-transform':'translate3d(0,' + oVal +'px,0)',
                 '-ms-transform':'translate3d(0,' + oVal +'px,0)',
                 '-o-transform':'translate3d(0,' + oVal +'px,0)'
             });
        }
     }, 4)
 }
 // Returns a function, that, as long as it continues to be invoked, will not
 // be triggered. The function will be called after it stops being called for
 // N milliseconds. If `immediate` is passed, trigger the function on the
 // leading edge, instead of the trailing.

 function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        }, wait);
        if (immediate && !timeout) func.apply(context, args);
    };
 };

 function isElementInViewport(elem) {
     var $elem = $(elem);

     // Get the scroll position of the page.
     var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
     var viewportTop = $(scrollElem).scrollTop();
     var viewportBottom = viewportTop + $(window).height();

     // Get the position of the element on the page.
     var elemTop = Math.round( $elem.offset().top );
     var elemBottom = elemTop + $elem.height();

     return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
 }
 })(jQuery); <|endoftext|>


<commit_before>const path = require('path')
const marked = require('marked')
const to = require('./utils/to')
const ignore = require('./config/ignore')
const { failLog, generalLog } = require('./utils/log')
const { parseComponentMarkdown, parseDocMarkdown, parseDemoMarkdown } = require('./utils/parse')
const { readUTF8FilePromise, readDirPromise, stableWriteFile } = require('./utils/file')
const { getFilesByExtension, generateCamelName } = require('./utils/utils')

const resolve = dir => {
  return path.join(__dirname, '..', dir)
}

marked.setOptions({
  highlight (code) {
    return require('highlight.js').highlightAuto(code).value
  }
})
const generateNormalVue = (oriPath, oriDir, targetPath, type = 'doc', demos = []) => {
  const componentMarkdownFile = getFilesByExtension(oriDir, '.md')
  componentMarkdownFile.forEach(async file => {
    if (file.indexOf('zh-CN') === -1 && file.indexOf('en-US') === -1) return
    const lang = file.indexOf('zh-CN') > -1 ? 'zh-CN' : 'en-US'
    const route = path.join(oriPath, file)
    let mdErr, mdContent, mdJson
    ;[mdErr, mdContent] = await to(readUTF8FilePromise(route))
    if (mdErr) {
      failLog(`读取文件${route}失败`)
    } else {
      mdJson = type === 'component' ? parseComponentMarkdown(mdContent, lang) : parseDocMarkdown(mdContent, lang)
    }
    const data = generateVueContainer(mdJson, demos)
    stableWriteFile(targetPath, file.replace('.md', '.vue'), data)
  })
}

const generateVueContainer = (main, demos = []) => {
  const generateCodeJson = (demos, isOne) => {
    const renderCodeTowCols = (even, odd) => {
      const string = `
        <atu-col :span="12">
          ${even}
        </atu-col>
        <atu-col :span="12">
          ${odd}
        </atu-col>`
      return string
    }

    const renderCodeOneCol = (code) => {
      const string = `
        <atu-col :span="24">
          ${code}
        </atu-col>
      `
      return string
    }

    const renderCodeRow = (isOneCol, code, odd) => {
      const h2 = `<div class="markdown"><h2> 代码展示 </h2></div>`
      const col = isOneCol ? renderCodeOneCol(code) : renderCodeTowCols(code, odd)
      const string = `
      ${h2}
      <atu-row :gutter="12">
        ${col}
      </atu-row>
      `
      return code ? string : ''
    }

    const renderCodeShowCode = (title, desc, display, code) => {
      const string = `

          <template slot="desc">${desc}</template>
          ${display}
          <template slot="code">${code}</template>

      `
      return string
    }

    const codeInfoArray = (codes) => {
      return codes
        .sort((a, b) => a.header.order - b.header.order)
        .map((el, index) => {
          const desc = lang === 'zh-CN' ? marked(el.zhCN) : marked(el.enUS)
          const title = lang === 'zh-CN' ? el.header['zh-CN'] : el.header['en-US']
          const codeHtml = marked(el.codeMd)
          const componentName = generateCamelName(el.component, el.name)
          const code = renderCodeShowCode(title, desc, el.display, codeHtml)
          return {
            code,
            index,
            componentName,
            name: el.name
          }
        })
    }

    const renderImportString = (component, file) => {
      return `import ${component} from './demo/${file}'`
    }

    const renderComponentsString = (component) => {
      return `    ${component},`
    }

    const mergeInfo = (infos, isOne) => {
      const imports = infos.map(el => renderImportString(el.componentName, el.name)).join('\n')
      const components = infos.map(el => renderComponentsString(el.componentName)).join('\n')
      const all = infos.map(el => el.code).join('')
      const odd = infos.filter(el => el.index % 2).map(el => el.code).join('')
      const even = infos.filter(el => !(el.index % 2)).map(el => el.code).join('')
      const code = isOne ? renderCodeRow(isOne, all) : renderCodeRow(isOne, even, odd)
      return {
        imports,
        components,
        code
      }
    }

    return mergeInfo(codeInfoArray(demos), isOne)
  }
  const lang = main.lang
  const isOne = !!main.header.cols

  const handleMainContent = (content) => {
    return {
      title: content.header.title || '',
      subtitle: content.header.subtitle || '',
      beforeCode: content.beforeCode ? marked(content.beforeCode) : '',
      afterCode: content.afterCode ? marked(content.afterCode) : '',
      content: content.content ? marked(content.content) : ''
    }
  }
  const result = handleMainContent(main)
  const code = generateCodeJson(demos, isOne)
  const template =
`<template>
  <container>
    <template slot="before">

${result.title} ${result.subtitle}

      ${result.beforeCode}
      ${result.content}
    </template>
    <template slot="code">
      ${code.code}
    </template>
    <template slot="after">
      ${result.afterCode}
    </template>
  </container>
</template>\n
`
  return template
}

const generateComponents = (components) => {
  const readDemoMds = async (route, component, name) => {
    let mdErr, md
    ;[mdErr, md] = await to(readUTF8FilePromise(route))
    return mdErr ? failLog(`读取文件${route}失败`) : parseDemoMarkdown(md, component, name)
  }

  const generateDomes = (route, demos) => {
    demos.forEach(demo => {
      stableWriteFile(route, `${demo.name}.vue`, demo.code)
    })
  }

  const generateComponent = async (component) => {
    const componentsPath = resolve('components')
    const componentsComponentPath = path.join(componentsPath, component)
    let componentsComponentErr, componentsComponentDir
    ;[componentsComponentErr, componentsComponentDir] = await to(readDirPromise(componentsComponentPath))
    if (componentsComponentErr) {
      failLog(`${componentsComponentPath}打开失败。`)
      return
    }
    const componentDemoPath = path.join(componentsPath, component, 'demo')
    let demos = []
    let componentDemoMdErr, componentDemoMdPaths
    ;[componentDemoMdErr, componentDemoMdPaths] = await to(readDirPromise(componentDemoPath))
    if (componentDemoMdErr) {
      generalLog(`${componentDemoPath}不存在，已跳过。`)
    } else {
      const vaildComponentDemoMdPaths = getFilesByExtension(componentDemoMdPaths, '.md')
      vaildComponentDemoMdPaths && await Promise.all(vaildComponentDemoMdPaths.map(componentDemoMdPath => {
        const route = path.join(componentDemoPath, componentDemoMdPath)
        const name = componentDemoMdPath.replace('.md', '')
        return readDemoMds(route, component, name)
      })).then(v => {
        demos = v
      })
    }

    const siteDocPath = path.join(resolve('site'), 'components', component)
    generateDomes(path.join(siteDocPath, 'demo'), demos)
    generateNormalVue(componentsComponentPath, componentsComponentDir, siteDocPath, 'component', demos)
  }

  components.forEach(component => {
    ignore.components.indexOf(component) === -1 && generateComponent(component)
  })
}

const generateDocs = (docs) => {
  const generateDoc = async (doc) => {
    const docsPath = resolve('docs')
    const docsDocPath = path.join(docsPath, doc)
    let docsDocErr, docsDocDir
    ;[docsDocErr, docsDocDir] = await to(readDirPromise(docsDocPath))
    if (docsDocErr) {
      generalLog(`${docsDocDir}不是文件夹，已跳过。`)
      return
    }
    const siteDocPath = path.join(resolve('site'), 'docs', doc)
    generateNormalVue(docsDocPath, docsDocDir, siteDocPath)
  }

  docs.forEach(doc => {
    ignore.docs.indexOf(doc) === -1 && generateDoc(doc)
  })
}

const generateComponentsRouterConfig = async () => {
  const sitePath = resolve('site')
  let importString = `import Vue from 'vue'\nimport Router from 'vue-router'\n`
  let configString = ''
  await Promise.all(['components', 'docs'].map(async dir => {
    let err, components
    ;[err, components] = await to(readDirPromise(path.join(sitePath, dir)))
    err !== null && console.log(err)
    await Promise.all(components.map(async component => {
      let err, files
      ;[err, files] = await to(readDirPromise(path.join(sitePath, dir, component)))
      err !== null && console.log(err)
      getFilesByExtension(files, '.vue').forEach(file => {
        let lang = file.indexOf('zh-CN') > -1 ? 'zh' : 'en'
        let mdName = file.split('.')[0]
        let dirName = dir.slice(0, 4)
        let name = generateCamelName(dirName, component, mdName, lang)
        importString += `import ${name} from './${dir}/${component}/${file}'\n`
        configString += `    {\n      path: '/${dir}/${component}/${mdName}/${lang}',\n      component: ${name},\n      name: '${name}'\n    },\n`
      })
    }))
  }))
  configString = configString.substring(0, configString.length - 2)
  importString += 'Vue.use(Router)\n'
  const config = '\nlet router = new Router({\n  routes: [\n' + configString + '\n  ]\n})\n\nexport default router\n'
  stableWriteFile(sitePath, 'router.js', importString + config)
}

const generate = async (params) => {
  const cDir = await readDirPromise(resolve('components'))
  const dDir = await readDirPromise(resolve('docs'))
  if (params[0] === '-a') {
    generateDocs(dDir)
    generateComponents(cDir)
  } else if (params[0] === '-c') {
    generateComponents(cDir)
  } else if (params[0] === '-d') {
    generateDocs(dDir)
  } else if (params[0] === '-r') {
    generateComponentsRouterConfig().catch(err => console.log(err))
  }
}

const params = process.argv.splice(2)
generate(params)
<commit_msg>add redirect route in generate<commit_after>const path = require('path')
const marked = require('marked')
const to = require('./utils/to')
const ignore = require('./config/ignore')
const { failLog, generalLog } = require('./utils/log')
const { parseComponentMarkdown, parseDocMarkdown, parseDemoMarkdown } = require('./utils/parse')
const { readUTF8FilePromise, readDirPromise, stableWriteFile } = require('./utils/file')
const { getFilesByExtension, generateCamelName } = require('./utils/utils')

const resolve = dir => {
  return path.join(__dirname, '..', dir)
}

marked.setOptions({
  highlight (code) {
    return require('highlight.js').highlightAuto(code).value
  }
})
const generateNormalVue = (oriPath, oriDir, targetPath, type = 'doc', demos = []) => {
  const componentMarkdownFile = getFilesByExtension(oriDir, '.md')
  componentMarkdownFile.forEach(async file => {
    if (file.indexOf('zh-CN') === -1 && file.indexOf('en-US') === -1) return
    const lang = file.indexOf('zh-CN') > -1 ? 'zh-CN' : 'en-US'
    const route = path.join(oriPath, file)
    let mdErr, mdContent, mdJson
    ;[mdErr, mdContent] = await to(readUTF8FilePromise(route))
    if (mdErr) {
      failLog(`读取文件${route}失败`)
    } else {
      mdJson = type === 'component' ? parseComponentMarkdown(mdContent, lang) : parseDocMarkdown(mdContent, lang)
    }
    const data = generateVueContainer(mdJson, demos)
    stableWriteFile(targetPath, file.replace('.md', '.vue'), data)
  })
}

const generateVueContainer = (main, demos = []) => {
  const generateCodeJson = (demos, isOne) => {
    const renderCodeTowCols = (even, odd) => {
      const string = `
        <atu-col :span="12">
          ${even}
        </atu-col>
        <atu-col :span="12">
          ${odd}
        </atu-col>`
      return string
    }

    const renderCodeOneCol = (code) => {
      const string = `
        <atu-col :span="24">
          ${code}
        </atu-col>
      `
      return string
    }

    const renderCodeRow = (isOneCol, code, odd) => {
      const h2 = `<div class="markdown"><h2> 代码展示 </h2></div>`
      const col = isOneCol ? renderCodeOneCol(code) : renderCodeTowCols(code, odd)
      const string = `
      ${h2}
      <atu-row :gutter="12">
        ${col}
      </atu-row>
      `
      return code ? string : ''
    }

    const renderCodeShowCode = (title, desc, display, code) => {
      const string = `

          <template slot="desc">${desc}</template>
          ${display}
          <template slot="code">${code}</template>

      `
      return string
    }

    const codeInfoArray = (codes) => {
      return codes
        .sort((a, b) => a.header.order - b.header.order)
        .map((el, index) => {
          const desc = lang === 'zh-CN' ? marked(el.zhCN) : marked(el.enUS)
          const title = lang === 'zh-CN' ? el.header['zh-CN'] : el.header['en-US']
          const codeHtml = marked(el.codeMd)
          const componentName = generateCamelName(el.component, el.name)
          const code = renderCodeShowCode(title, desc, el.display, codeHtml)
          return {
            code,
            index,
            componentName,
            name: el.name
          }
        })
    }

    const renderImportString = (component, file) => {
      return `import ${component} from './demo/${file}'`
    }

    const renderComponentsString = (component) => {
      return `    ${component},`
    }

    const mergeInfo = (infos, isOne) => {
      const imports = infos.map(el => renderImportString(el.componentName, el.name)).join('\n')
      const components = infos.map(el => renderComponentsString(el.componentName)).join('\n')
      const all = infos.map(el => el.code).join('')
      const odd = infos.filter(el => el.index % 2).map(el => el.code).join('')
      const even = infos.filter(el => !(el.index % 2)).map(el => el.code).join('')
      const code = isOne ? renderCodeRow(isOne, all) : renderCodeRow(isOne, even, odd)
      return {
        imports,
        components,
        code
      }
    }

    return mergeInfo(codeInfoArray(demos), isOne)
  }
  const lang = main.lang
  const isOne = !!main.header.cols

  const handleMainContent = (content) => {
    return {
      title: content.header.title || '',
      subtitle: content.header.subtitle || '',
      beforeCode: content.beforeCode ? marked(content.beforeCode) : '',
      afterCode: content.afterCode ? marked(content.afterCode) : '',
      content: content.content ? marked(content.content) : ''
    }
  }
  const result = handleMainContent(main)
  const code = generateCodeJson(demos, isOne)
  const template =
`<template>
  <container>
    <template slot="before">

${result.title} ${result.subtitle}

      ${result.beforeCode}
      ${result.content}
    </template>
    <template slot="code">
      ${code.code}
    </template>
    <template slot="after">
      ${result.afterCode}
    </template>
  </container>
</template>\n
`
  return template
}

const generateComponents = (components) => {
  const readDemoMds = async (route, component, name) => {
    let mdErr, md
    ;[mdErr, md] = await to(readUTF8FilePromise(route))
    return mdErr ? failLog(`读取文件${route}失败`) : parseDemoMarkdown(md, component, name)
  }

  const generateDomes = (route, demos) => {
    demos.forEach(demo => {
      stableWriteFile(route, `${demo.name}.vue`, demo.code)
    })
  }

  const generateComponent = async (component) => {
    const componentsPath = resolve('components')
    const componentsComponentPath = path.join(componentsPath, component)
    let componentsComponentErr, componentsComponentDir
    ;[componentsComponentErr, componentsComponentDir] = await to(readDirPromise(componentsComponentPath))
    if (componentsComponentErr) {
      failLog(`${componentsComponentPath}打开失败。`)
      return
    }
    const componentDemoPath = path.join(componentsPath, component, 'demo')
    let demos = []
    let componentDemoMdErr, componentDemoMdPaths
    ;[componentDemoMdErr, componentDemoMdPaths] = await to(readDirPromise(componentDemoPath))
    if (componentDemoMdErr) {
      generalLog(`${componentDemoPath}不存在，已跳过。`)
    } else {
      const vaildComponentDemoMdPaths = getFilesByExtension(componentDemoMdPaths, '.md')
      vaildComponentDemoMdPaths && await Promise.all(vaildComponentDemoMdPaths.map(componentDemoMdPath => {
        const route = path.join(componentDemoPath, componentDemoMdPath)
        const name = componentDemoMdPath.replace('.md', '')
        return readDemoMds(route, component, name)
      })).then(v => {
        demos = v
      })
    }

    const siteDocPath = path.join(resolve('site'), 'components', component)
    generateDomes(path.join(siteDocPath, 'demo'), demos)
    generateNormalVue(componentsComponentPath, componentsComponentDir, siteDocPath, 'component', demos)
  }

  components.forEach(component => {
    ignore.components.indexOf(component) === -1 && generateComponent(component)
  })
}

const generateDocs = (docs) => {
  const generateDoc = async (doc) => {
    const docsPath = resolve('docs')
    const docsDocPath = path.join(docsPath, doc)
    let docsDocErr, docsDocDir
    ;[docsDocErr, docsDocDir] = await to(readDirPromise(docsDocPath))
    if (docsDocErr) {
      generalLog(`${docsDocDir}不是文件夹，已跳过。`)
      return
    }
    const siteDocPath = path.join(resolve('site'), 'docs', doc)
    generateNormalVue(docsDocPath, docsDocDir, siteDocPath)
  }

  docs.forEach(doc => {
    ignore.docs.indexOf(doc) === -1 && generateDoc(doc)
  })
}

const generateComponentsRouterConfig = async () => {
  const sitePath = resolve('site')
  let importString = `import Vue from 'vue'\nimport Router from 'vue-router'\n`
  let configString = ''
  const redirectString = `    { path: '/', redirect: '/docs/development/first/zh' },\n`
  await Promise.all(['components', 'docs'].map(async dir => {
    let err, components
    ;[err, components] = await to(readDirPromise(path.join(sitePath, dir)))
    err !== null && console.log(err)
    await Promise.all(components.map(async component => {
      let err, files
      ;[err, files] = await to(readDirPromise(path.join(sitePath, dir, component)))
      err !== null && console.log(err)
      getFilesByExtension(files, '.vue').forEach(file => {
        let lang = file.indexOf('zh-CN') > -1 ? 'zh' : 'en'
        let mdName = file.split('.')[0]
        let dirName = dir.slice(0, 4)
        let name = generateCamelName(dirName, component, mdName, lang)
        importString += `import ${name} from './${dir}/${component}/${file}'\n`
        configString += `    {\n      path: '/${dir}/${component}/${mdName}/${lang}',\n      component: ${name},\n      name: '${name}'\n    },\n`
      })
    }))
  }))
  configString = redirectString + configString.substring(0, configString.length - 2)
  importString += 'Vue.use(Router)\n'
  const config = '\nlet router = new Router({\n  routes: [\n' + configString + '\n  ]\n})\n\nexport default router\n'
  stableWriteFile(sitePath, 'router.js', importString + config)
}

const generate = async (params) => {
  const cDir = await readDirPromise(resolve('components'))
  const dDir = await readDirPromise(resolve('docs'))
  if (params[0] === '-a') {
    generateDocs(dDir)
    generateComponents(cDir)
  } else if (params[0] === '-c') {
    generateComponents(cDir)
  } else if (params[0] === '-d') {
    generateDocs(dDir)
  } else if (params[0] === '-r') {
    generateComponentsRouterConfig().catch(err => console.log(err))
  }
}

const params = process.argv.splice(2)
generate(params)
<|endoftext|>


<commit_before>// Code goes here

var myApp = angular.module('myApp', ['angularUtils.directives.dirPagination']);

function MyController($scope, $http) {

  $scope.currentPage = 1;
  $scope.pageSize = 20;
  $scope.items = [];
 $http.get("level2.json")
    .then(function(response) {
        $scope.items = response.data;
    });
 $http.get("level.json")
    .then(function(response) {
        $scope.level = response.data;
    });

  $scope.pageChangeHandler = function(num) {

  };
}

function OtherController($scope) {
  $scope.pageChangeHandler = function(num) {

  };
}

myApp.controller('MyController', MyController);
myApp.controller('OtherController', OtherController);
<commit_msg>Update app.js<commit_after>// Code goes here

var myApp = angular.module('myApp', ['angularUtils.directives.dirPagination']);

function MyController($scope, $http) {

  $scope.currentPage = 1;
  $scope.pageSize = 25;
  $scope.items = [];
 $http.get("level2.json")
    .then(function(response) {
        $scope.items = response.data;
    });
 $http.get("level.json")
    .then(function(response) {
        $scope.level = response.data;
    });

  $scope.pageChangeHandler = function(num) {

  };
}

function OtherController($scope) {
  $scope.pageChangeHandler = function(num) {

  };
}

myApp.controller('MyController', MyController);
myApp.controller('OtherController', OtherController);
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StatsPlugin = require('stats-webpack-plugin');

module.exports = {
  entry: [
    path.join(__dirname, '../../app/entry.jsx'),
  ],
  output: {
    path: path.join(__dirname, '../dist/'),
    filename: '[name]-[hash].min.js',
    publicPath: '/',
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new HtmlWebpackPlugin({
      template: 'app/index.tpl.html',
      inject: 'body',
      filename: 'index.html',
    }),
    new ExtractTextPlugin('[name]-[hash].min.css'),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false,
        screw_ie8: true,
      },
    }),
    new StatsPlugin('webpack.stats.json', {
      source: false,
      modules: false,
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    }),
  ],
  module: {
    loaders: [{
      test: /(\.js$|\.jsx$)/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-0'],
      },
    }, {
      test: /\.json?$/,
      loader: 'json',
    }, {
      test: /(\.scss$|\.css$)/,
      loaders: ['style', 'css', 'sass'],
    }],
  },
  postcss: [
    require('autoprefixer'),
  ],
};
<commit_msg>removed react-hmr from webpack config<commit_after>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StatsPlugin = require('stats-webpack-plugin');

module.exports = {
  entry: [
    path.join(__dirname, '../../app/entry.jsx'),
  ],
  output: {
    path: path.join(__dirname, '../dist/'),
    filename: '[name]-[hash].min.js',
    publicPath: '/',
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new HtmlWebpackPlugin({
      template: 'app/index.tpl.html',
      inject: 'body',
      filename: 'index.html',
    }),
    new ExtractTextPlugin('[name]-[hash].min.css'),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false,
        screw_ie8: true,
      },
    }),
    new StatsPlugin('webpack.stats.json', {
      source: false,
      modules: false,
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    }),
  ],
  module: {
    loaders: [{
      test: /(\.js$|\.jsx$)/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-0'],
      },
    }, {
      test: /\.json?$/,
      loader: 'json',
    }, {
      test: /(\.scss$|\.css$)/,
      loaders: [
        'style',
        'css-loader?modules&importLoaders=1' +
        '&localIdentName=[path][local]__[hash:base64:5]!sass',
        'sass',
      ],
    }],
  },
  postcss: [
    require('autoprefixer'),
  ],
};
<|endoftext|>


<commit_before>
var at = require('../js/ast_tools');

module.exports = function(flowData){
  function packKey(key){
    return l10nIndex.keys.hasOwnProperty(key)
      ? '#' + l10nIndex.keys[key].toString(36)
      : '';
  }

  function packBind(name){
    if (name.substr(0, 5) == 'l10n:')
    {
      var packed = packKey(name.substr(5));

      if (packed)
      {
        packed = 'l10n:' + packed;

        fconsole.log(name + ' -> ' + packed);

        return packed;
      }
      else
        fconsole.log('[!] l10n key ' + packed + ' not found (ignored)');
    }

    return name;
  }

  var fconsole = flowData.console;

  if (flowData.options.l10nPack)
  {
    var l10nIndex = flowData.l10n.index;

    if (!l10nIndex)
      throw 'l10n index must be built before compression';

    //
    // pack definitions
    //
    fconsole.log('Pack createDictionary');
    fconsole.incDeep();
    flowData.l10n.defList.forEach(function(entry){
      fconsole.log(entry.name);

      var dict = {};
      dict[entry.name] = entry.keys;

      entry.args[2] = ['array', packDictionary(dict, l10nIndex.map).map(function(token){
        return [typeof token == 'number' ? 'num' : 'string', token];
      })];
    });
    fconsole.decDeep();
    fconsole.log();

    //
    // pack getToken
    //
    fconsole.log('Pack getToken');
    fconsole.incDeep();
    flowData.l10n.getTokenList.forEach(function(entry){
      var key = entry.args[0][1];
      var packed = packKey(key);

      if (packed)
      {
        fconsole.log(key + ' -> ' + packed);
        entry.args[0][1] = packed;
      }
      else
        fconsole.log('[!] l10n key ' + key + ' not found (ignored)');

    });
    fconsole.decDeep();
    fconsole.log();

    //
    // pack packages
    //
    fconsole.log('Pack packages');
    fconsole.incDeep();
    flowData.l10n.packages.forEach(function(file){
      fconsole.log(file.jsRef);
      file.jsResourceContent = packDictionary(file.jsResourceContent, l10nIndex.map);
    });
    fconsole.decDeep();
    fconsole.log();

    //
    // process templates
    //
    var tmplAt = require('../tmpl/ast_tools');

    fconsole.log('Pack keys in templates');
    fconsole.incDeep();
    flowData.files.queue.forEach(function(file){
      if (file.type == 'template')
      {
        fconsole.log(file.relpath);
        fconsole.incDeep();

        tmplAt.walk(file.ast, {
          text: function(token){
            if (token[1])
              token[1] = packBind(token[1]);
          },
          attr: function(token){
            if (token[3] != 'class' && token[3] != 'style' && token[1])
              token[1][0] = token[1][0].map(packBind)
          }
        });

        fconsole.decDeep();
        fconsole.log();
      }
    });
    fconsole.decDeep();
    fconsole.log();

    //
    // add index to resources
    //
    fconsole.log('# Add index into resource map');
    flowData.files.add({
      jsRef: '_l10nIndex_',
      type: 'text',
      isResource: true,
      jsResourceContent: l10nIndex.content
    });

    //
    // if l10n module exists, inject index initialization
    //
    fconsole.log('# Inject index init into basis.l10n');
    if (flowData.l10n.module)
    {
      at.append(flowData.l10n.module.ast, at.parse('(' + function(){
        var parts = basis.resource('_l10nIndex_').fetch().split(/([\<\>\#])/);
        var stack = [];
        for (var i = 0; i < parts.length; i++)
        {
          switch(parts[i])
          {
            case '#': stack.length = 0; break;
            case '<': stack.pop(); break;
            case '>': break;
            default:
              if (parts[i])
              {
                stack.push(parts[i]);
                getToken(stack.join('.'));
              }
          }
        }
      } + ')()'));
    }
  }
  else
  {
    fconsole.log('Skiped.')
    fconsole.log('Use option --l10n-pack for compression');
  }
}

module.exports.handlerName = '[l10n] Compress';

//
// tools
//

function packDictionary(dict, map){
  var result = [];
  var flattenDict = {};

  // linear
  for (var dictName in dict){
    for (var key in dict[dictName]){
      flattenDict[dictName + '.' + key] = dict[dictName][key];
    }
  }

  // pack
  for (var i = 0, gap = -1; i < map.length; i++)
  {
    if (flattenDict[map[i]])
    {
      if (gap != -1)
        result.push(gap);

      result.push(flattenDict[map[i]]);

      gap = -1;
    }
    else
      gap++;
  }

  if (typeof result[result.length - 1] == 'number')
    result.pop();

  return result;
}
<commit_msg>replace log + incDeep -> start<commit_after>
var at = require('../js/ast_tools');

module.exports = function(flowData){
  function packKey(key){
    return l10nIndex.keys.hasOwnProperty(key)
      ? '#' + l10nIndex.keys[key].toString(36)
      : '';
  }

  function packBind(name){
    if (name.substr(0, 5) == 'l10n:')
    {
      var packed = packKey(name.substr(5));

      if (packed)
      {
        packed = 'l10n:' + packed;

        fconsole.log(name + ' -> ' + packed);

        return packed;
      }
      else
        fconsole.log('[!] l10n key ' + packed + ' not found (ignored)');
    }

    return name;
  }

  var fconsole = flowData.console;

  if (flowData.options.l10nPack)
  {
    var l10nIndex = flowData.l10n.index;

    if (!l10nIndex)
      throw 'l10n index must be built before compression';

    //
    // pack definitions
    //
    fconsole.start('Pack createDictionary');
    flowData.l10n.defList.forEach(function(entry){
      fconsole.log(entry.name);

      var dict = {};
      dict[entry.name] = entry.keys;

      entry.args[2] = ['array', packDictionary(dict, l10nIndex.map).map(function(token){
        return [typeof token == 'number' ? 'num' : 'string', token];
      })];
    });
    fconsole.endl();

    //
    // pack getToken
    //
    fconsole.start('Pack getToken');
    flowData.l10n.getTokenList.forEach(function(entry){
      var key = entry.args[0][1];
      var packed = packKey(key);

      if (packed)
      {
        fconsole.log(key + ' -> ' + packed);
        entry.args[0][1] = packed;
      }
      else
        fconsole.log('[!] l10n key ' + key + ' not found (ignored)');

    });
    fconsole.endl();

    //
    // pack packages
    //
    fconsole.start('Pack packages');
    flowData.l10n.packages.forEach(function(file){
      fconsole.log(file.jsRef);
      file.jsResourceContent = packDictionary(file.jsResourceContent, l10nIndex.map);
    });
    fconsole.endl();

    //
    // process templates
    //
    var tmplAt = require('../tmpl/ast_tools');

    fconsole.start('Pack keys in templates');
    flowData.files.queue.forEach(function(file){
      if (file.type == 'template')
      {
        fconsole.start(file.relpath);

        tmplAt.walk(file.ast, {
          text: function(token){
            if (token[1])
              token[1] = packBind(token[1]);
          },
          attr: function(token){
            if (token[3] != 'class' && token[3] != 'style' && token[1])
              token[1][0] = token[1][0].map(packBind)
          }
        });

        fconsole.endl();
      }
    });
    fconsole.endl();

    //
    // add index to resources
    //
    fconsole.log('# Add index into resource map');
    flowData.files.add({
      jsRef: '_l10nIndex_',
      type: 'text',
      isResource: true,
      jsResourceContent: l10nIndex.content
    });

    //
    // if l10n module exists, inject index initialization
    //
    fconsole.log('# Inject index init into basis.l10n');
    if (flowData.l10n.module)
    {
      at.append(flowData.l10n.module.ast, at.parse('(' + function(){
        var parts = basis.resource('_l10nIndex_').fetch().split(/([\<\>\#])/);
        var stack = [];
        for (var i = 0; i < parts.length; i++)
        {
          switch(parts[i])
          {
            case '#': stack.length = 0; break;
            case '<': stack.pop(); break;
            case '>': break;
            default:
              if (parts[i])
              {
                stack.push(parts[i]);
                getToken(stack.join('.'));
              }
          }
        }
      } + ')()'));
    }
  }
  else
  {
    fconsole.log('Skiped.')
    fconsole.log('Use option --l10n-pack for compression');
  }
}

module.exports.handlerName = '[l10n] Compress';

//
// tools
//

function packDictionary(dict, map){
  var result = [];
  var flattenDict = {};

  // linear
  for (var dictName in dict){
    for (var key in dict[dictName]){
      flattenDict[dictName + '.' + key] = dict[dictName][key];
    }
  }

  // pack
  for (var i = 0, gap = -1; i < map.length; i++)
  {
    if (flattenDict[map[i]])
    {
      if (gap != -1)
        result.push(gap);

      result.push(flattenDict[map[i]]);

      gap = -1;
    }
    else
      gap++;
  }

  if (typeof result[result.length - 1] == 'number')
    result.pop();

  return result;
}
<|endoftext|>


<commit_before>  var XDeck = undefined;

  (function() {
    var localDoc = document.currentScript.ownerDocument;
    var proto = Object.create(HTMLElement.prototype);

    proto.createdCallback = function() {
      if(this.createShadowRoot) {
        this._root = this.createShadowRoot();
      } else {
        this._root = this.webkitCreateShadowRoot();
      }

      var tplContent = localDoc.querySelector("template#deck").content;
      this._root.appendChild(tplContent.cloneNode(true));
    };

    var changeSlide = function(direction) {
        var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
        var slideShown     = document.querySelector("x-slide.active"),
            slideToBeShown = slideShown;

        var transitFunc = (direction == "next" ? function(node) { return node.nextSibling;     }
                                               : function(node) { return node.previousSibling; });

        while((slideToBeShown = transitFunc(slideToBeShown)) && slideToBeShown.tagName !== "X-SLIDE");

        if(!slideToBeShown) return;

        slideToBeShown.classList.add("active");
        slideShown.classList.remove("active");

    }

    var addKeyboardListener = function() {
      document.addEventListener("keyup", function(event) {
        var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;

        if(event.keyCode == 37) {         // left
          document.location.hash = --currentSlideIndex;
          changeSlide("previous");
        } else if(event.keyCode == 39 ) { // right
          document.location.hash = ++currentSlideIndex;
          changeSlide("next");
        } else { return; }
      });
    }

    var addTouchListener = function() {
      var slides = document.querySelectorAll("x-slide");

      for(var i=0;i<slides.length;i++) {
        Hammer(slides[i]).on("swipeleft", function(event) {
          console.log("Touchy");
          var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
          document.location.hash = ++currentSlideIndex;
          changeSlide("next");
          e.stopPropagation();
        });

        Hammer(slides[i]).on("swiperight", function(event) {
          console.log("Touchy");
          var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
          document.location.hash = --currentSlideIndex;
          changeSlide("prev");
          e.stopPropagation();
        });

      }
    }

    proto.attachedCallback = function() {
      var self = this;
      var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
      document.location.hash = "#" + currentSlideIndex;

      self.querySelector("x-slide:nth-child(" + currentSlideIndex + ")").classList.add("active");

      addKeyboardListener();
      addTouchListener();
    };

    XDeck = document.registerElement("x-deck", { prototype: proto });
  })();
<commit_msg>Using the _currentScript fallback<commit_after>  var XDeck = undefined;

  (function() {
    if(document.currentScript) {
      var localDoc = document.currentScript.ownerDocument;
    } else {
      var localDoc = document._currentScript.ownerDocument;
    }
    var proto = Object.create(HTMLElement.prototype);

    proto.createdCallback = function() {
      if(this.createShadowRoot) {
        this._root = this.createShadowRoot();
      } else {
        this._root = this.webkitCreateShadowRoot();
      }

      var tplContent = localDoc.querySelector("template#deck").content;
      this._root.appendChild(tplContent.cloneNode(true));
    };

    var changeSlide = function(direction) {
        var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
        var slideShown     = document.querySelector("x-slide.active"),
            slideToBeShown = slideShown;

        var transitFunc = (direction == "next" ? function(node) { return node.nextSibling;     }
                                               : function(node) { return node.previousSibling; });

        while((slideToBeShown = transitFunc(slideToBeShown)) && slideToBeShown.tagName !== "X-SLIDE");

        if(!slideToBeShown) return;

        slideToBeShown.classList.add("active");
        slideShown.classList.remove("active");

    }

    var addKeyboardListener = function() {
      document.addEventListener("keyup", function(event) {
        var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;

        if(event.keyCode == 37) {         // left
          document.location.hash = --currentSlideIndex;
          changeSlide("previous");
        } else if(event.keyCode == 39 ) { // right
          document.location.hash = ++currentSlideIndex;
          changeSlide("next");
        } else { return; }
      });
    }

    var addTouchListener = function() {
      var slides = document.querySelectorAll("x-slide");

      for(var i=0;i<slides.length;i++) {
        Hammer(slides[i]).on("swipeleft", function(event) {
          console.log("Touchy");
          var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
          document.location.hash = ++currentSlideIndex;
          changeSlide("next");
          e.stopPropagation();
        });

        Hammer(slides[i]).on("swiperight", function(event) {
          console.log("Touchy");
          var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
          document.location.hash = --currentSlideIndex;
          changeSlide("prev");
          e.stopPropagation();
        });

      }
    }

    proto.attachedCallback = function() {
      var self = this;
      var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
      document.location.hash = "#" + currentSlideIndex;

      self.querySelector("x-slide:nth-child(" + currentSlideIndex + ")").classList.add("active");

      addKeyboardListener();
      addTouchListener();
    };

    XDeck = document.registerElement("x-deck", { prototype: proto });
  })();
<|endoftext|>


<commit_before>var cloneProperties = "font,color,display,borderRadius,border,verticalAlign,textAlign,textShadow,background,opacity,padding,boxSizing,boxShadow,overflow,height,width,position,writingMode,blockSize,wordSpacing,letterSpacing,textIndent".split(",");
function cloneVisible(node, parentPosition) {
    if (!node || node.nodeType > 3 || node.nodeType == 2) return;
    var style = node.style;
    if (!style) return node.cloneNode();
    style = getComputedStyle(node);
    if (style.display === "none") return;
    if (style.visibility === "hidden" || style.visibility === "collapse") return;
    if (+style.opacity === 0) return;
    if (style.position === "fixed") return;
    if (style.overflow === "hidden") {
        if (node.offsetHeight === 0 || node.offsetWidth === 0) return;
    }
    var clone = createElement(node.tagName);
    var children = node.childNodes;
    var cloneStyle = clone.style;
    for (var cx = 0, dx = cloneProperties.length; cx < dx; cx++) {
        var k = cloneProperties[cx];
        if (k in cloneStyle) {
            cloneStyle[k] = style[k];
        }
    }
    var screenPosition = getScreenPosition(node);
    clone.value = node.value;
    if (parentPosition && cloneStyle.position === "absolute") {
        cloneStyle.left = (screenPosition.left - parentPosition.left) + "px";
        cloneStyle.top = (screenPosition.top - parentPosition.top) + "px";
    }
    for (var cx = 0, dx = children.length; cx < dx; cx++) {
        var child = children[cx];
        var childClone = cloneVisible(child, screenPosition);
        if (childClone) clone.appendChild(childClone);
    }
    return clone;
}<commit_msg>支持单边边框复制<commit_after>var cloneProperties = "font,color,display,borderRadius,border-top,border-right,border-bottom,border-left,verticalAlign,textAlign,textShadow,background,opacity,padding,boxSizing,boxShadow,overflow,height,width,position,writingMode,blockSize,wordSpacing,letterSpacing,textIndent".split(",");
function cloneVisible(node, parentPosition) {
    if (!node || node.nodeType > 3 || node.nodeType == 2) return;
    var style = node.style;
    if (!style) return node.cloneNode();
    style = getComputedStyle(node);
    if (style.display === "none") return;
    if (style.visibility === "hidden" || style.visibility === "collapse") return;
    if (+style.opacity === 0) return;
    if (style.position === "fixed") return;
    if (style.overflow === "hidden") {
        if (node.offsetHeight === 0 || node.offsetWidth === 0) return;
    }
    var clone = createElement(node.tagName);
    var children = node.childNodes;
    var cloneStyle = clone.style;
    for (var cx = 0, dx = cloneProperties.length; cx < dx; cx++) {
        var k = cloneProperties[cx];
        if (k in cloneStyle) {
            cloneStyle[k] = style[k];
        }
    }
    var screenPosition = getScreenPosition(node);
    clone.value = node.value;
    if (parentPosition && cloneStyle.position === "absolute") {
        cloneStyle.left = (screenPosition.left - parentPosition.left) + "px";
        cloneStyle.top = (screenPosition.top - parentPosition.top) + "px";
    }
    for (var cx = 0, dx = children.length; cx < dx; cx++) {
        var child = children[cx];
        var childClone = cloneVisible(child, screenPosition);
        if (childClone) clone.appendChild(childClone);
    }
    return clone;
}<|endoftext|>