<commit_before>/*jslint node: true */
"use strict";

module.exports = function(grunt) {

  var cwd = process.cwd();

  // Project configuration.
  grunt.initConfig({
    // Metadata.
    pkg: grunt.file.readJSON('package.json'),
    banner: '/*! ==================================================\n' +
      '* <%= pkg.title || pkg.name %> - v<%= pkg.version %> -' +
      '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
      '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
      '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
      ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %>\n'+
      '================================================== */',

    folders: {
      // <%= folders.source %>
      source: 'src',
      // <%= folders.build %>
      build: 'dist',
      // Centurion path
      // <%= folders.centurion %>
      centurion: '_grunt/node_modules/centurion-framework/lib/sass/'
    },

    // Task configuration.
    connect: {
      local: {
        options: {
          livereload: false,
          hostname: 'localhost',
          port: 9001,
          base: '<%= folders.build %>'
        }
      }
    },

    open: {
      server: {
        url: 'http://localhost:9001'
      }
    },

    'sass': {
      expanded: {
        options: {
          style: 'expanded',
          sourcemap: 'none',
          loadPath: '<%= folders.centurion %>',
          banner: '<%= banner %>',
        },
        files: [{
          expand: true,
          cwd: '<%= folders.source %>/sass',
          src: ['*.scss'],
          dest: '<%= folders.build %>/css',
          ext: '.css'
        }]
      },
      minify: {
        options: {
          style: 'compressed',
          sourcemap: 'none',
          loadPath: '<%= folders.centurion %>',
          banner: '<%= banner %>',
        },
        files: [{
          expand: true,
          cwd: '<%= folders.source %>/sass',
          src: ['*.scss'],
          dest: '<%= folders.build %>/css',
          ext: '.min.css'
        }]
      }
    },

    concat: {
      options: {
        banner: '<%= banner %>',
        stripBanners: true
      },
      dist: {
        src: [
          '<%= folders.source %>/js/libs/**/*.js',
          '<%= folders.source %>/js/<%= pkg.name %>.js'
        ],
        dest: '<%= folders.build %>/js/<%= pkg.name %>.js'
      }
    },

    uglify: {
      options: {
        banner: '<%= banner %>'
      },
      dist: {
        src: [
          '<%= folders.source %>/js/libs/**/*.js',
          '<%= folders.source %>/js/<%= pkg.name %>.js'
        ],
        dest: '<%= folders.build %>/js/<%= pkg.name %>.min.js'
      }
    },

    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        unused: true,
        boss: true,
        eqnull: true,
        globals: {
          browser: true,
          document: true,
          window: true,
          location: true,
          "$": true,
          "jQuery": true
        }
      },
      gruntfile: {
        src: '_grunt/Gruntfile.js'
      },
      lib_test: {
        src: [
          '<%= folders.source %>/js/<%= pkg.name %>.js',
          '!<%= folders.source %>/js/libs/**/*.js',
        ]
      }
    },

    copy: {
      dist: {
        files: [
          {expand: true, cwd: '<%= folders.source %>/img', src: ['**'], dest: '<%= folders.build %>/img'},
        ]
      }
    },

    processhtml: {
      dist: {
        options: {
          process: true,
          data: {
            site_title: 'Grunt Project Setup',
            page_title: 'Page Title',
            meta_description: '_______',
            meta_keywords: '_______',
            message: 'insert a message here'
          },
          customBlockTypes: ['<%= folders.source %>/js/change-text.js'],
          recursive: true
        },
        files: [{
          expand: true,
          cwd: '<%= folders.source %>/',
          src: ['*.html'],
          dest: '<%= folders.build %>/',
          ext: '.html'
        }]
      },
    },

    watch: {
      options: {
        cliArgs: ['--gruntfile', require('path').join(cwd, 'Gruntfile.js')],
        livereload: true,
      },
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile'],
      },
      html: {
        files: ['<%= folders.source %>/**/*.html'],
        tasks: ['copy', 'html'],
      },
      javascript: {
        files: '<%= jshint.lib_test.src %>',
        tasks: ['jshint:lib_test', 'concat', 'uglify'],
      },
      sass: {
        files: ['<%= folders.source %>/sass/*.scss'],
        tasks: ['sass:expanded'],
      },
    },

  });

  require('load-grunt-tasks')(grunt);
  grunt.file.setBase('../');

  // Default Task
  grunt.registerTask('default', ['html', 'build', 'serve', 'open', 'watch']);

  // Generate HTML
  grunt.registerTask('html', ['processhtml:dist']);

  // Create local server
  grunt.registerTask('serve', ['connect']);

  // Minify code
  //grunt.registerTask('build-minify', ['sass:minify', 'jshint', 'concat', 'uglify']);

  // Build code
  grunt.registerTask('build', ['copy', 'sass', 'jshint', 'concat', 'uglify']);

};
<commit_msg>imagemin for image optimization<commit_after>/*jslint node: true */
"use strict";

module.exports = function(grunt) {

  var cwd = process.cwd();

  // Project configuration.
  grunt.initConfig({
    // Metadata.
    pkg: grunt.file.readJSON('package.json'),
    banner: '/*! ==================================================\n' +
      '* <%= pkg.title || pkg.name %> - v<%= pkg.version %> -' +
      '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
      '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
      '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
      ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %>\n'+
      '================================================== */',

    folders: {
      // <%= folders.source %>
      source: 'src',
      // <%= folders.build %>
      build: 'dist',
      // Centurion path
      // <%= folders.centurion %>
      centurion: '_grunt/node_modules/centurion-framework/lib/sass/'
    },

    // Task configuration.
    connect: {
      local: {
        options: {
          livereload: false,
          hostname: 'localhost',
          port: 9001,
          base: '<%= folders.build %>'
        }
      }
    },

    open: {
      server: {
        url: 'http://localhost:9001'
      }
    },

    'sass': {
      expanded: {
        options: {
          style: 'expanded',
          sourcemap: 'none',
          loadPath: '<%= folders.centurion %>',
          banner: '<%= banner %>',
        },
        files: [{
          expand: true,
          cwd: '<%= folders.source %>/sass',
          src: ['*.scss'],
          dest: '<%= folders.build %>/css',
          ext: '.css'
        }]
      },
      minify: {
        options: {
          style: 'compressed',
          sourcemap: 'none',
          loadPath: '<%= folders.centurion %>',
          banner: '<%= banner %>',
        },
        files: [{
          expand: true,
          cwd: '<%= folders.source %>/sass',
          src: ['*.scss'],
          dest: '<%= folders.build %>/css',
          ext: '.min.css'
        }]
      }
    },

    concat: {
      options: {
        banner: '<%= banner %>',
        stripBanners: true
      },
      dist: {
        src: [
          '<%= folders.source %>/js/libs/**/*.js',
          '<%= folders.source %>/js/<%= pkg.name %>.js'
        ],
        dest: '<%= folders.build %>/js/<%= pkg.name %>.js'
      }
    },

    uglify: {
      options: {
        banner: '<%= banner %>'
      },
      dist: {
        src: [
          '<%= folders.source %>/js/libs/**/*.js',
          '<%= folders.source %>/js/<%= pkg.name %>.js'
        ],
        dest: '<%= folders.build %>/js/<%= pkg.name %>.min.js'
      }
    },

    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        unused: true,
        boss: true,
        eqnull: true,
        globals: {
          browser: true,
          document: true,
          window: true,
          location: true,
          "$": true,
          "jQuery": true
        }
      },
      gruntfile: {
        src: '_grunt/Gruntfile.js'
      },
      lib_test: {
        src: [
          '<%= folders.source %>/js/<%= pkg.name %>.js',
          '!<%= folders.source %>/js/libs/**/*.js',
        ]
      }
    },

    imagemin: {
      recursive: {
        files: [{
          expand: true,
          cwd: '<%= jshint.gruntfile.src %>/',
          src: ['**/*.{png,jpg,gif,ico}'],
          dest: '<%= jshint.gruntfile.build %>/'
        }]
      }
    },

    processhtml: {
      dist: {
        options: {
          process: true,
          data: {
            site_title: 'Grunt Project Setup',
            page_title: 'Page Title',
            meta_description: '_______',
            meta_keywords: '_______',
            message: 'insert a message here'
          },
          customBlockTypes: ['<%= folders.source %>/js/change-text.js'],
          recursive: true
        },
        files: [{
          expand: true,
          cwd: '<%= folders.source %>/',
          src: ['*.html'],
          dest: '<%= folders.build %>/',
          ext: '.html'
        }]
      },
    },

    watch: {
      options: {
        cliArgs: ['--gruntfile', require('path').join(cwd, 'Gruntfile.js')],
        livereload: true,
      },
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile'],
      },
      html: {
        files: ['<%= folders.source %>/**/*.html'],
        tasks: ['copy', 'html'],
      },
      javascript: {
        files: '<%= jshint.lib_test.src %>',
        tasks: ['jshint:lib_test', 'concat', 'uglify'],
      },
      sass: {
        files: ['<%= folders.source %>/sass/*.scss'],
        tasks: ['sass:expanded'],
      },
    },

  });

  require('load-grunt-tasks')(grunt);
  grunt.file.setBase('../');

  // Default Task
  grunt.registerTask('default', ['html', 'build', 'serve', 'open', 'watch']);

  // Generate HTML
  grunt.registerTask('html', ['processhtml:dist']);

  // Create local server
  grunt.registerTask('serve', ['connect']);

  // Minify code
  //grunt.registerTask('build-minify', ['sass:minify', 'jshint', 'concat', 'uglify']);

  // Build code
  grunt.registerTask('build', ['copy', 'sass', 'jshint', 'concat', 'uglify']);

};
<|endoftext|>


<commit_before>/*
 * fuse.js
 *
 * Copyright (C) 2019-20 by RStudio, PBC
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

const { task, context } = require("fuse-box/sparky");
const { FuseBox, CSSPlugin, WebIndexPlugin, QuantumPlugin } = require("fuse-box");

const path = require('path');
const fs = require('fs');

const kLibraryName = "Panmirror"
const kLibraryNameLower = kLibraryName.toLowerCase()
const kIdeJsDir = "../../../www/js"
const kIdeOutputDir = path.join(kIdeJsDir, kLibraryNameLower);

context(
  class {
    getConfig(outputDir, webIndex = false, vendorSrcMap = false) {
      return FuseBox.init({
        homeDir: "src",
        modulesFolder: "./node_modules",
        target: "browser@es6",
        globals: { default: kLibraryName },
        output: path.join(outputDir, "$name.js"),
        sourceMaps: { inline: true , project: true, vendor: vendorSrcMap },
        plugins: [
          CSSPlugin(),
          webIndex && WebIndexPlugin({ template: "dev/index.html" }),
          this.isProduction && QuantumPlugin({ uglify: { es6: true }, bakeApiIntoBundle: true, containedAPI: true }),
        ],
      });
    }
  },
);

const bundle = (fuse) => {
  return fuse
    .bundle(kLibraryNameLower)
    .instructions("> editor.ts")
}

const watch = (fuse, hmrReload) => {
  return fuse
    .hmr({ reload: hmrReload })
    .watch()
}

const dev = (context, webIndex, watchChanges, hmrReload, outputDir) => {

  // setup fuse for development
  const fuse = context.getConfig(outputDir, webIndex, true);
  const bdl = bundle(fuse)
  if (watchChanges)
    watch(bdl, hmrReload)

  // copy prosemirror-devtools
  const devtools = 'prosemirror-dev-tools.min.js';
  fs.copyFileSync(
    path.join('./node_modules/prosemirror-dev-tools/dist/umd', devtools),
    path.join(outputDir, devtools)
  );

  return fuse;
}

const dist = (context, outputDir) => {
  context.isProduction = true;
  const fuse = context.getConfig(outputDir);
  bundle(fuse);
  return fuse;
}

task("ide-dev", async context => {
  await dev(context, false, false, false, kIdeOutputDir).run()
});

task("ide-dev-watch", async context => {
  const fuse = dev(context, false, true, true, kIdeOutputDir);
  fuse.dev();
  await fuse.run();
})

task("ide-dist",async context => {
  await dist(context, kIdeOutputDir).run();
});

<commit_msg>don't create vensor sourcemaps in production<commit_after>/*
 * fuse.js
 *
 * Copyright (C) 2019-20 by RStudio, PBC
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

const { task, context } = require("fuse-box/sparky");
const { FuseBox, CSSPlugin, WebIndexPlugin, QuantumPlugin } = require("fuse-box");

const path = require('path');
const fs = require('fs');

const kLibraryName = "Panmirror"
const kLibraryNameLower = kLibraryName.toLowerCase()
const kIdeJsDir = "../../../www/js"
const kIdeOutputDir = path.join(kIdeJsDir, kLibraryNameLower);

context(
  class {
    getConfig(outputDir, webIndex = false, vendorSrcMap = false) {
      return FuseBox.init({
        homeDir: "src",
        modulesFolder: "./node_modules",
        target: "browser@es6",
        globals: { default: kLibraryName },
        output: path.join(outputDir, "$name.js"),
        sourceMaps: { inline: true , project: true, vendor: vendorSrcMap && !this.isProduction },
        plugins: [
          CSSPlugin(),
          webIndex && WebIndexPlugin({ template: "dev/index.html" }),
          this.isProduction && QuantumPlugin({ uglify: { es6: true }, bakeApiIntoBundle: true, containedAPI: true }),
        ],
      });
    }
  },
);

const bundle = (fuse) => {
  return fuse
    .bundle(kLibraryNameLower)
    .instructions("> editor.ts")
}

const watch = (fuse, hmrReload) => {
  return fuse
    .hmr({ reload: hmrReload })
    .watch()
}

const dev = (context, webIndex, watchChanges, hmrReload, outputDir) => {

  // setup fuse for development
  const fuse = context.getConfig(outputDir, webIndex, true);
  const bdl = bundle(fuse)
  if (watchChanges)
    watch(bdl, hmrReload)

  // copy prosemirror-devtools
  const devtools = 'prosemirror-dev-tools.min.js';
  fs.copyFileSync(
    path.join('./node_modules/prosemirror-dev-tools/dist/umd', devtools),
    path.join(outputDir, devtools)
  );

  return fuse;
}

const dist = (context, outputDir) => {
  context.isProduction = true;
  const fuse = context.getConfig(outputDir);
  bundle(fuse);
  return fuse;
}

task("ide-dev", async context => {
  await dev(context, false, false, false, kIdeOutputDir).run()
});

task("ide-dev-watch", async context => {
  const fuse = dev(context, false, true, true, kIdeOutputDir);
  fuse.dev();
  await fuse.run();
})

task("ide-dist",async context => {
  await dist(context, kIdeOutputDir).run();
});

<|endoftext|>


<commit_before>/*
 * mongo-redact.js
 *
 * A mongo shell script to redact sensitive information
 * read from MongoDB, while retaining the shape of the data.
 *
 * Copyright (c) 2015, Jon Rangel
 */

var Redact = (function() {
    "use strict";

    function redactValue(val) {
        if (typeof val == "number") {
            if (val === (val|0)) {
                return 999;
            } else {
                return 999.123;
            }
        } else if (val instanceof NumberLong) {
            return new NumberLong(999999);
        } else if (typeof val == "string") {
            var s = "";
            for (var i = 0; i < val.length; i++) {
                s += "X";
            }
            return s;
        } else if (val instanceof Date) {
            // return the same date
        } else if (val instanceof ObjectId) {
            // return the same Object ID
        } else if (val instanceof Array) {
            return redactArray(val);
        } else if (val instanceof Object) {
            return redactDoc(val);
        }

        return val;
    }

    function redactArray(arr) {
        for (var i = 0; i < arr.length; i++) {
            arr[i] = redactValue(arr[i]);
        }

        return arr;
    }

    function redactDoc(doc) {
        for (var prop in doc) {
            if (doc.hasOwnProperty(prop)) {
                doc[prop] = redactValue(doc[prop]);
            }
        }

        return doc;
    }

    function printRedactedDoc(doc) {
        printjson(redactDoc(doc));
    }

    /*
     * Override DBQuery.prototype.next() method to allow for automatic redaction.
     */
    (function() {
        var re = /^\$cmd|^system/;
        var proxied = DBQuery.prototype.next;
        DBQuery.prototype.next = function() {
            var res = proxied.apply(this, arguments);
            if (this._autoRedact && !this._collection.getName().match(re)) {
                res = redactDoc(res);
            }
            return res;
        };
    })();

    /*
     * Override DBCommandCursor.prototype.next() method to allow for automatic redaction.
     */
    (function() {
        var proxied = DBCommandCursor.prototype.next;
        DBCommandCursor.prototype.next = function() {
            var res = proxied.apply(this, arguments);
            if (this._autoRedact) {
                res = redactDoc(res);
            }
            return res;
        };
    })();

    /*
     * Enable automatic redaction by default when this script is loaded.
     */
    DBQuery.prototype._autoRedact = true;
    DBCommandCursor.prototype._autoRedact = true;

    /*
     * Enable/disable automatic redaction globally.
     */
    function setAutoRedaction(value) {
        if (value == undefined) value = true;
        DBQuery.prototype._autoRedact = value;
        DBCommandCursor.prototype._autoRedact = value;
    }

    /*
     * Enable/disable redaction on a per query basis (for find()).
     */
    DBQuery.prototype.redact = function(value) {
        if (value == undefined) value = true;
        this._autoRedact = value;
        return this;
    };

    return {
        redactValue: redactValue,
        redactArray: redactArray,
        redactDoc: redactDoc,
        printRedactedDoc: printRedactedDoc,
        setAutoRedaction: setAutoRedaction
    };
})();
<commit_msg>Add MD5 generation module<commit_after>/*
 * mongo-redact.js
 *
 * A mongo shell script to redact sensitive information
 * read from MongoDB, while retaining the shape of the data.
 *
 * Copyright (c) 2015, Jon Rangel
 */

var Redact = (function() {
    "use strict";

    function redactValue(val) {
        if (typeof val == "number") {
            if (val === (val|0)) {
                return 999;
            } else {
                return 999.123;
            }
        } else if (val instanceof NumberLong) {
            return new NumberLong(999999);
        } else if (typeof val == "string") {
            var s = "";
            for (var i = 0; i < val.length; i++) {
                s += "X";
            }
            return s;
        } else if (val instanceof Date) {
            // return the same date
        } else if (val instanceof ObjectId) {
            // return the same Object ID
        } else if (val instanceof Array) {
            return redactArray(val);
        } else if (val instanceof Object) {
            return redactDoc(val);
        }

        return val;
    }

    function redactArray(arr) {
        for (var i = 0; i < arr.length; i++) {
            arr[i] = redactValue(arr[i]);
        }

        return arr;
    }

    function redactDoc(doc) {
        for (var prop in doc) {
            if (doc.hasOwnProperty(prop)) {
                doc[prop] = redactValue(doc[prop]);
            }
        }

        return doc;
    }

    function printRedactedDoc(doc) {
        printjson(redactDoc(doc));
    }

    /*
     * Override DBQuery.prototype.next() method to allow for automatic redaction.
     */
    (function() {
        var re = /^\$cmd|^system/;
        var proxied = DBQuery.prototype.next;
        DBQuery.prototype.next = function() {
            var res = proxied.apply(this, arguments);
            if (this._autoRedact && !this._collection.getName().match(re)) {
                res = redactDoc(res);
            }
            return res;
        };
    })();

    /*
     * Override DBCommandCursor.prototype.next() method to allow for automatic redaction.
     */
    (function() {
        var proxied = DBCommandCursor.prototype.next;
        DBCommandCursor.prototype.next = function() {
            var res = proxied.apply(this, arguments);
            if (this._autoRedact) {
                res = redactDoc(res);
            }
            return res;
        };
    })();

    /*
     * Enable automatic redaction by default when this script is loaded.
     */
    DBQuery.prototype._autoRedact = true;
    DBCommandCursor.prototype._autoRedact = true;

    /*
     * Enable/disable automatic redaction globally.
     */
    function setAutoRedaction(value) {
        if (value == undefined) value = true;
        DBQuery.prototype._autoRedact = value;
        DBCommandCursor.prototype._autoRedact = value;
    }

    /*
     * Enable/disable redaction on a per query basis (for find()).
     */
    DBQuery.prototype.redact = function(value) {
        if (value == undefined) value = true;
        this._autoRedact = value;
        return this;
    };

    return {
        redactValue: redactValue,
        redactArray: redactArray,
        redactDoc: redactDoc,
        printRedactedDoc: printRedactedDoc,
        setAutoRedaction: setAutoRedaction
    };
})();

/****************************************************************************/

var MD5Hash = (function() {
    "use strict";

    /*
     * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
     * Digest Algorithm, as defined in RFC 1321.
     * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
     * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
     * Distributed under the BSD License
     * See http://pajhome.org.uk/crypt/md5 for more info.
     */

    /*
     * Configurable variables. You may need to tweak these to be compatible with
     * the server-side, but the defaults work in most cases.
     */
    var hexcase = 0;   /* hex output format. 0 - lowercase; 1 - uppercase        */
    var b64pad  = "";  /* base-64 pad character. "=" for strict RFC compliance   */

    /*
     * These are the functions you'll usually want to call
     * They take string arguments and return either hex or base-64 encoded strings
     */
    function hex_md5(s)    { return rstr2hex(rstr_md5(str2rstr_utf8(s))); }
    function b64_md5(s)    { return rstr2b64(rstr_md5(str2rstr_utf8(s))); }
    function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); }
    function hex_hmac_md5(k, d)
      { return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
    function b64_hmac_md5(k, d)
      { return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
    function any_hmac_md5(k, d, e)
      { return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); }

    /*
     * Perform a simple self-test to see if the VM is working
     */
    function md5_vm_test()
    {
      return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72";
    }

    /*
     * Calculate the MD5 of a raw string
     */
    function rstr_md5(s)
    {
      return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
    }

    /*
     * Calculate the HMAC-MD5, of a key and some data (raw strings)
     */
    function rstr_hmac_md5(key, data)
    {
      var bkey = rstr2binl(key);
      if(bkey.length > 16) bkey = binl_md5(bkey, key.length * 8);

      var ipad = Array(16), opad = Array(16);
      for(var i = 0; i < 16; i++)
      {
        ipad[i] = bkey[i] ^ 0x36363636;
        opad[i] = bkey[i] ^ 0x5C5C5C5C;
      }

      var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
      return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
    }

    /*
     * Convert a raw string to a hex string
     */
    function rstr2hex(input)
    {
      try { hexcase } catch(e) { hexcase=0; }
      var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
      var output = "";
      var x;
      for(var i = 0; i < input.length; i++)
      {
        x = input.charCodeAt(i);
        output += hex_tab.charAt((x >>> 4) & 0x0F)
               +  hex_tab.charAt( x        & 0x0F);
      }
      return output;
    }

    /*
     * Convert a raw string to a base-64 string
     */
    function rstr2b64(input)
    {
      try { b64pad } catch(e) { b64pad=''; }
      var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      var output = "";
      var len = input.length;
      for(var i = 0; i < len; i += 3)
      {
        var triplet = (input.charCodeAt(i) << 16)
                    | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
                    | (i + 2 < len ? input.charCodeAt(i+2)      : 0);
        for(var j = 0; j < 4; j++)
        {
          if(i * 8 + j * 6 > input.length * 8) output += b64pad;
          else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
        }
      }
      return output;
    }

    /*
     * Convert a raw string to an arbitrary string encoding
     */
    function rstr2any(input, encoding)
    {
      var divisor = encoding.length;
      var i, j, q, x, quotient;

      /* Convert to an array of 16-bit big-endian values, forming the dividend */
      var dividend = Array(Math.ceil(input.length / 2));
      for(i = 0; i < dividend.length; i++)
      {
        dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
      }

      /*
       * Repeatedly perform a long division. The binary array forms the dividend,
       * the length of the encoding is the divisor. Once computed, the quotient
       * forms the dividend for the next step. All remainders are stored for later
       * use.
       */
      var full_length = Math.ceil(input.length * 8 /
                                        (Math.log(encoding.length) / Math.log(2)));
      var remainders = Array(full_length);
      for(j = 0; j < full_length; j++)
      {
        quotient = Array();
        x = 0;
        for(i = 0; i < dividend.length; i++)
        {
          x = (x << 16) + dividend[i];
          q = Math.floor(x / divisor);
          x -= q * divisor;
          if(quotient.length > 0 || q > 0)
            quotient[quotient.length] = q;
        }
        remainders[j] = x;
        dividend = quotient;
      }

      /* Convert the remainders to the output string */
      var output = "";
      for(i = remainders.length - 1; i >= 0; i--)
        output += encoding.charAt(remainders[i]);

      return output;
    }

    /*
     * Encode a string as utf-8.
     * For efficiency, this assumes the input is valid utf-16.
     */
    function str2rstr_utf8(input)
    {
      var output = "";
      var i = -1;
      var x, y;

      while(++i < input.length)
      {
        /* Decode utf-16 surrogate pairs */
        x = input.charCodeAt(i);
        y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
        if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
        {
          x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
          i++;
        }

        /* Encode output as utf-8 */
        if(x <= 0x7F)
          output += String.fromCharCode(x);
        else if(x <= 0x7FF)
          output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
                                        0x80 | ( x         & 0x3F));
        else if(x <= 0xFFFF)
          output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
                                        0x80 | ((x >>> 6 ) & 0x3F),
                                        0x80 | ( x         & 0x3F));
        else if(x <= 0x1FFFFF)
          output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
                                        0x80 | ((x >>> 12) & 0x3F),
                                        0x80 | ((x >>> 6 ) & 0x3F),
                                        0x80 | ( x         & 0x3F));
      }
      return output;
    }

    /*
     * Encode a string as utf-16
     */
    function str2rstr_utf16le(input)
    {
      var output = "";
      for(var i = 0; i < input.length; i++)
        output += String.fromCharCode( input.charCodeAt(i)        & 0xFF,
                                      (input.charCodeAt(i) >>> 8) & 0xFF);
      return output;
    }

    function str2rstr_utf16be(input)
    {
      var output = "";
      for(var i = 0; i < input.length; i++)
        output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
                                       input.charCodeAt(i)        & 0xFF);
      return output;
    }

    /*
     * Convert a raw string to an array of little-endian words
     * Characters >255 have their high-byte silently ignored.
     */
    function rstr2binl(input)
    {
      var output = Array(input.length >> 2);
      for(var i = 0; i < output.length; i++)
        output[i] = 0;
      for(var i = 0; i < input.length * 8; i += 8)
        output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (i%32);
      return output;
    }

    /*
     * Convert an array of little-endian words to a string
     */
    function binl2rstr(input)
    {
      var output = "";
      for(var i = 0; i < input.length * 32; i += 8)
        output += String.fromCharCode((input[i>>5] >>> (i % 32)) & 0xFF);
      return output;
    }

    /*
     * Calculate the MD5 of an array of little-endian words, and a bit length.
     */
    function binl_md5(x, len)
    {
      /* append padding */
      x[len >> 5] |= 0x80 << ((len) % 32);
      x[(((len + 64) >>> 9) << 4) + 14] = len;

      var a =  1732584193;
      var b = -271733879;
      var c = -1732584194;
      var d =  271733878;

      for(var i = 0; i < x.length; i += 16)
      {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;

        a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
        d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
        c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
        b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
        a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
        d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
        c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
        b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
        a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
        d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
        c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
        b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
        a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
        d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
        c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
        b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

        a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
        d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
        c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
        b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
        a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
        d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
        c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
        b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
        a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
        d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
        c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
        b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
        a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
        d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
        c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
        b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

        a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
        d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
        c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
        b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
        a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
        d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
        c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
        b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
        a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
        d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
        c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
        b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
        a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
        d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
        c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
        b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

        a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
        d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
        c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
        b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
        a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
        d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
        c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
        b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
        a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
        d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
        c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
        b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
        a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
        d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
        c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
        b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

        a = safe_add(a, olda);
        b = safe_add(b, oldb);
        c = safe_add(c, oldc);
        d = safe_add(d, oldd);
      }
      return Array(a, b, c, d);
    }

    /*
     * These functions implement the four basic operations the algorithm uses.
     */
    function md5_cmn(q, a, b, x, s, t)
    {
      return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
    }
    function md5_ff(a, b, c, d, x, s, t)
    {
      return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
    }
    function md5_gg(a, b, c, d, x, s, t)
    {
      return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
    }
    function md5_hh(a, b, c, d, x, s, t)
    {
      return md5_cmn(b ^ c ^ d, a, b, x, s, t);
    }
    function md5_ii(a, b, c, d, x, s, t)
    {
      return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
    }

    /*
     * Add integers, wrapping at 2^32. This uses 16-bit operations internally
     * to work around bugs in some JS interpreters.
     */
    function safe_add(x, y)
    {
      var lsw = (x & 0xFFFF) + (y & 0xFFFF);
      var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
      return (msw << 16) | (lsw & 0xFFFF);
    }

    /*
     * Bitwise rotate a 32-bit number to the left.
     */
    function bit_rol(num, cnt)
    {
      return (num << cnt) | (num >>> (32 - cnt));
    }

    return {
        hex_md5: hex_md5,
        b64_md5: b64_md5,
        any_md5: any_md5,
        hex_hmac_md5: hex_hmac_md5,
        b64_hmac_md5: b64_hmac_md5,
        any_hmac_md5: any_hmac_md5
    };
})();
<|endoftext|>


<commit_before>(function () {

var Remote = require('remote');
var Ipc = require('ipc');
var Util = require('util');
var Path = require('fire-path');
var Url = require('fire-url');
var Async = require('async');

/**
 * Page Level Editor
 */
window.Editor = window.Editor || {};
Editor.require = function ( path ) {
    return require( Editor.url(path) );
};

// init argument list sending from core by url?queries
// format: '?foo=bar&hell=world'
// skip '?'
var queryString = decodeURIComponent(location.search.substr(1));
var queryList = queryString.split('&');
var queries = {};
for ( var i = 0; i < queryList.length; ++i ) {
    var pair = queryList[i].split('=');
    if ( pair.length === 2) {
        queries[pair[0]] = pair[1];
    }
}
Editor.argv = queries;

// init & cache remote
Editor.remote = Remote.getGlobal('Editor');
Editor.cwd = Editor.remote.url('app://');
Editor.frameworkPath = Editor.remote.url('editor-framework://');
Editor.isDev = Editor.remote.isDev;

var _urlToPath = function ( base, urlInfo ) {
    if ( urlInfo.pathname ) {
        return Path.join( base, urlInfo.host, urlInfo.pathname );
    }
    return Path.join( base, urlInfo.host );
};

// url
Editor.url = function (url) {
    // NOTE: we cache app:// and editor-framework:// protocol to get rid of ipc-sync function calls
    var urlInfo = Url.parse(url);
    if ( urlInfo.protocol === 'app:' ) {
        return _urlToPath( Editor.cwd, urlInfo );
    }
    else if ( urlInfo.protocol === 'editor-framework:' ) {
        return _urlToPath( Editor.frameworkPath, urlInfo );
    }

    // try ipc-sync function
    return Editor.remote.url(url);
};

// ==========================
// console log API
// ==========================

/**
 * Log the normal message and show on the console.
 * The method will send ipc message `console:log` to core.
 * @param {...*} [arg] - whatever arguments the message needs
 */
Editor.log = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.log(text);
    Editor.sendToCore('console:log', text);
};

Editor.success = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.log('%c' + text, 'color: green');
    Editor.sendToCore('console:success', text);
};

Editor.failed = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.log('%c' + text, 'color: red');
    Editor.sendToCore('console:failed', text);
};

Editor.info = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.info(text);
    Editor.sendToCore('console:info', text);
};

Editor.warn = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.warn(text);

    var e = new Error('dummy');
    var lines = e.stack.split('\n');
    text = text + '\n' + lines.splice(2).join('\n');

    Editor.sendToCore('console:warn', text);
};

Editor.error = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.error(text);

    var e = new Error('dummy');
    var lines = e.stack.split('\n');
    text = text + '\n' + lines.splice(2).join('\n');

    Editor.sendToCore('console:error',text);
};

// ==========================
// pre-require modules
// ==========================

Editor.require('editor-framework://share/platform');
Editor.JS = Editor.require('editor-framework://share/js-utils');
Editor.Utils = Editor.require('editor-framework://share/editor-utils');
Editor.require('editor-framework://share/math');
Editor.Easing = Editor.require('editor-framework://share/easing');
Editor.require('editor-framework://page/ipc-init');
Editor.Selection = Editor.require('editor-framework://share/selection');
Editor.KeyCode = Editor.require('editor-framework://share/keycode');

// ==========================
// Layout API
// ==========================

Editor.loadLayout = function ( anchorEL, cb ) {
    Editor.sendRequestToCore( 'window:query-layout', Editor.requireIpcEvent, function (layout) {
        if ( !layout ) {
            cb();
            return;
        }

        Editor.resetLayout( anchorEL, layout, cb );
    });
};

var _layouting = false;
Editor.resetLayout = function ( anchorEL, layoutInfo, cb ) {
    _layouting = true;

    Editor.Panel.closeAll(function () {
        var importList = EditorUI.createLayout( anchorEL, layoutInfo );
        Async.each( importList, function ( item, done ) {
            Editor.Panel.load (item.panelID, function ( err, frameEL ) {
                if ( err ) {
                    done();
                    return;
                }

                var dockAt = item.dockEL;
                dockAt.add(frameEL);
                if ( item.active ) {
                    dockAt.select(frameEL);
                }
                done();
            });
        }, function ( err ) {
            _layouting = false;

            // close error panels
            EditorUI.DockUtils.flushWithCollapse();
            Editor.saveLayout();
            if ( cb ) cb ();
        });
    });
};

Editor.saveLayout = function () {
    // don't save layout when we are layouting
    if ( _layouting )
        return;

    window.requestAnimationFrame ( function () {
        Editor.sendToCore('window:save-layout', Editor.Panel.dumpLayout(), Editor.requireIpcEvent);
    });
};

// ==========================
// Ipc events
// ==========================

Ipc.on( 'editor:reset-layout', function ( layoutInfo ) {
    var anchorEL = document.body;
    if ( EditorUI.DockUtils.root ) {
        anchorEL = Polymer.dom(EditorUI.DockUtils.root).parentNode;
    }

    Editor.resetLayout( anchorEL, layoutInfo, function () {
        EditorUI.DockUtils.reset();
    });
});

Ipc.on( 'ipc-debugger:query', function ( reply ) {
    var ipcInfos = [];
    for ( var p in Ipc._events ) {
        var listeners = Ipc._events[p];
        var count = Array.isArray(listeners) ? listeners.length : 1;
        ipcInfos.push({
            name: p,
            level: 'page',
            count: count,
        });
    }
    reply(ipcInfos);
});

// ==========================
// extends
// ==========================

Editor.registerPanel = function ( panelID, obj ) {
    if ( window[panelID] !== undefined ) {
        Editor.error('Failed to register panel %s, panelID has been registered.', panelID);
        return;
    }

    window[panelID] = Polymer(obj);
};

// ==========================
// load modules
// ==========================

Editor.Window = Editor.require('editor-framework://page/editor-window' );
Editor.Menu = Editor.require('editor-framework://page/editor-menu');
Editor.Panel = Editor.require('editor-framework://page/editor-panel');
Editor.Package = Editor.require('editor-framework://page/editor-package');

Editor.MainMenu = Editor.require('editor-framework://page/main-menu');
Editor.CmdP = Editor.require('editor-framework://page/cmdp');

})();
<commit_msg>add register widget method<commit_after>(function () {

var Remote = require('remote');
var Ipc = require('ipc');
var Util = require('util');
var Path = require('fire-path');
var Url = require('fire-url');
var Async = require('async');

/**
 * Page Level Editor
 */
window.Editor = window.Editor || {};
Editor.require = function ( path ) {
    return require( Editor.url(path) );
};

// init argument list sending from core by url?queries
// format: '?foo=bar&hell=world'
// skip '?'
var queryString = decodeURIComponent(location.search.substr(1));
var queryList = queryString.split('&');
var queries = {};
for ( var i = 0; i < queryList.length; ++i ) {
    var pair = queryList[i].split('=');
    if ( pair.length === 2) {
        queries[pair[0]] = pair[1];
    }
}
Editor.argv = queries;

// init & cache remote
Editor.remote = Remote.getGlobal('Editor');
Editor.cwd = Editor.remote.url('app://');
Editor.frameworkPath = Editor.remote.url('editor-framework://');
Editor.isDev = Editor.remote.isDev;

var _urlToPath = function ( base, urlInfo ) {
    if ( urlInfo.pathname ) {
        return Path.join( base, urlInfo.host, urlInfo.pathname );
    }
    return Path.join( base, urlInfo.host );
};

// url
Editor.url = function (url) {
    // NOTE: we cache app:// and editor-framework:// protocol to get rid of ipc-sync function calls
    var urlInfo = Url.parse(url);
    if ( urlInfo.protocol === 'app:' ) {
        return _urlToPath( Editor.cwd, urlInfo );
    }
    else if ( urlInfo.protocol === 'editor-framework:' ) {
        return _urlToPath( Editor.frameworkPath, urlInfo );
    }

    // try ipc-sync function
    return Editor.remote.url(url);
};

// ==========================
// console log API
// ==========================

/**
 * Log the normal message and show on the console.
 * The method will send ipc message `console:log` to core.
 * @param {...*} [arg] - whatever arguments the message needs
 */
Editor.log = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.log(text);
    Editor.sendToCore('console:log', text);
};

Editor.success = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.log('%c' + text, 'color: green');
    Editor.sendToCore('console:success', text);
};

Editor.failed = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.log('%c' + text, 'color: red');
    Editor.sendToCore('console:failed', text);
};

Editor.info = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.info(text);
    Editor.sendToCore('console:info', text);
};

Editor.warn = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.warn(text);

    var e = new Error('dummy');
    var lines = e.stack.split('\n');
    text = text + '\n' + lines.splice(2).join('\n');

    Editor.sendToCore('console:warn', text);
};

Editor.error = function ( text ) {
    'use strict';

    if ( arguments.length <= 1 ) {
        text = '' + text;
    } else {
        text = Util.format.apply(Util, arguments);
    }
    console.error(text);

    var e = new Error('dummy');
    var lines = e.stack.split('\n');
    text = text + '\n' + lines.splice(2).join('\n');

    Editor.sendToCore('console:error',text);
};

// ==========================
// pre-require modules
// ==========================

Editor.require('editor-framework://share/platform');
Editor.JS = Editor.require('editor-framework://share/js-utils');
Editor.Utils = Editor.require('editor-framework://share/editor-utils');
Editor.require('editor-framework://share/math');
Editor.Easing = Editor.require('editor-framework://share/easing');
Editor.require('editor-framework://page/ipc-init');
Editor.Selection = Editor.require('editor-framework://share/selection');
Editor.KeyCode = Editor.require('editor-framework://share/keycode');

// ==========================
// Layout API
// ==========================

Editor.loadLayout = function ( anchorEL, cb ) {
    Editor.sendRequestToCore( 'window:query-layout', Editor.requireIpcEvent, function (layout) {
        if ( !layout ) {
            cb();
            return;
        }

        Editor.resetLayout( anchorEL, layout, cb );
    });
};

var _layouting = false;
Editor.resetLayout = function ( anchorEL, layoutInfo, cb ) {
    _layouting = true;

    Editor.Panel.closeAll(function () {
        var importList = EditorUI.createLayout( anchorEL, layoutInfo );
        Async.each( importList, function ( item, done ) {
            Editor.Panel.load (item.panelID, function ( err, frameEL ) {
                if ( err ) {
                    done();
                    return;
                }

                var dockAt = item.dockEL;
                dockAt.add(frameEL);
                if ( item.active ) {
                    dockAt.select(frameEL);
                }
                done();
            });
        }, function ( err ) {
            _layouting = false;

            // close error panels
            EditorUI.DockUtils.flushWithCollapse();
            Editor.saveLayout();
            if ( cb ) cb ();
        });
    });
};

Editor.saveLayout = function () {
    // don't save layout when we are layouting
    if ( _layouting )
        return;

    window.requestAnimationFrame ( function () {
        Editor.sendToCore('window:save-layout', Editor.Panel.dumpLayout(), Editor.requireIpcEvent);
    });
};

// ==========================
// Ipc events
// ==========================

Ipc.on( 'editor:reset-layout', function ( layoutInfo ) {
    var anchorEL = document.body;
    if ( EditorUI.DockUtils.root ) {
        anchorEL = Polymer.dom(EditorUI.DockUtils.root).parentNode;
    }

    Editor.resetLayout( anchorEL, layoutInfo, function () {
        EditorUI.DockUtils.reset();
    });
});

Ipc.on( 'ipc-debugger:query', function ( reply ) {
    var ipcInfos = [];
    for ( var p in Ipc._events ) {
        var listeners = Ipc._events[p];
        var count = Array.isArray(listeners) ? listeners.length : 1;
        ipcInfos.push({
            name: p,
            level: 'page',
            count: count,
        });
    }
    reply(ipcInfos);
});

// ==========================
// extends
// ==========================

Editor.registerPanel = function ( panelID, obj ) {
    if ( window[panelID] !== undefined ) {
        Editor.error('Failed to register panel %s, panelID has been registered.', panelID);
        return;
    }

    window[panelID] = Polymer(obj);
};

Editor.registerWidget = function ( widgetName, obj ) {
    if ( !window.widgets ) {
        window.widgets = {};
    }

    if ( window.widgets[widgetName] ) {
        Editor.error('Failed to register widget %s, already exists.', widgetName );
        return;
    }

    window.widgets[widgetName] = Polymer(obj);
};

// ==========================
// load modules
// ==========================

Editor.Window = Editor.require('editor-framework://page/editor-window' );
Editor.Menu = Editor.require('editor-framework://page/editor-menu');
Editor.Panel = Editor.require('editor-framework://page/editor-panel');
Editor.Package = Editor.require('editor-framework://page/editor-package');

Editor.MainMenu = Editor.require('editor-framework://page/main-menu');
Editor.CmdP = Editor.require('editor-framework://page/cmdp');

})();
<|endoftext|>


<commit_before>Spider.defineWidget('Spider.Forms.FileInput', 'Spider.Forms.Input', {

	autoInit: true,

	ready: function(){
		var self = this;
		var fileLink = $('.file-link', this.el);
		if (fileLink.size() == 1){
			var changeLabel = $('.change-label', this.el).text();
			var changeDiv = $('.change', this.el);
			changeDiv.hide();
			$('.clear', this.el).hide();
			var clearCheckBox = $('.clear input:checkbox', this.el);
			var fileInput = $('.change input', this.el);

			var link = $('');
			link.text(changeLabel+'...')
				.insertAfter(fileLink)
				.click(function(e){
					e.preventDefault();
					if (clearCheckBox.is(':checked')){
						link.removeClass('open');
						fileLink.removeClass('deleted');
						clearCheckBox.attr('checked', false);
						changeDiv.hide();
					}
					else{
						fileLink.addClass('deleted');
						clearCheckBox.attr('checked', true);
						link.addClass('open');
						changeDiv.show();
					}
				});
		}

	}
});<commit_msg>Indentation<commit_after>Spider.defineWidget('Spider.Forms.FileInput', 'Spider.Forms.Input', {

	autoInit: true,

	ready: function(){
		var self = this;
		var fileLink = $('.file-link', this.el);
		if (fileLink.size() == 1){
			var changeLabel = $('.change-label', this.el).text();
			var changeDiv = $('.change', this.el);
			changeDiv.hide();
			$('.clear', this.el).hide();
			var clearCheckBox = $('.clear input:checkbox', this.el);
			var fileInput = $('.change input', this.el);

			var link = $('');
			link.text(changeLabel+'...')
				.insertAfter(fileLink)
				.click(function(e){
					e.preventDefault();
					if (clearCheckBox.is(':checked')){
						link.removeClass('open');
						fileLink.removeClass('deleted');
						clearCheckBox.attr('checked', false);
						changeDiv.hide();
					}
					else{
						fileLink.addClass('deleted');
						clearCheckBox.attr('checked', true);
						link.addClass('open');
						changeDiv.show();
					}
			});
		}

	}
});<|endoftext|>


<commit_before>/*
 * Copyright 2017, Maha Farhat
 *
 * This file is part of the software gentb, consisting of custom
 * code for the GenTB's django-based website.
 *
 * gentb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * gentb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with gentb.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function() {

  $('#lineage-store').data('json-signal', function(data) {
    $("#row1").empty(); $("#row2").empty();
    chartLineageData(data);
  });
});

function chartLineageData(data) {
  var numPlots = data.children.length;
  var height = numPlots <= 2 ? 600 : 300;

  // Splits the charts across two rows, with the bottom row having more elements when `numPlots` is odd
  var counts = {'#row1': Math.floor(numPlots/2), '#row2': Math.ceil(numPlots/2)};
  for (var idx = 0; idx < numPlots; idx++) {
    if (data.children[idx].children.length == 0) {
      data.children[idx].children.push({});
    }
    // Puts two-lineage case in the same row to optimize space
    if (numPlots == 2) {
      var row = '#row1'; var width = 500;
    } else {
      var row = (idx+1)*2 <= numPlots ? '#row1' : '#row2';
      var width = 1000 / counts[row];
    }
    var chart = nv.models.sunburstChart().mode('size');
    var svg = d3.select(row)
          .append('svg');
          svg.datum([data.children[idx]])
          .attr('width', width)
          .attr('height', height)
          .attr('viewBox', '0 0 ' + width + ' ' + height)
          .attr('class', 'lineages')
          .call(chart);
    svg.append('text')
          .text(data.children[idx].name + ' ' + data.children[idx].value)
          .attr('x', '50%')
          .attr('y', '50%')
          .attr('class', 'lineage_text');
          // Selects/deselects the clicked drug
    chart.sunburst.dispatch.on("elementClick", function(e) {
        toggleTabData('lineage', e.data.name.slice(1), e.data.name.slice(1), 'map-marker');
          });

     // Deselects all lineages
     $('#clear').click(function(e) {

        unsetTabData('lineage');
          });

  }
}
<commit_msg>fixed sidebar lineage label<commit_after>/*
 * Copyright 2017, Maha Farhat
 *
 * This file is part of the software gentb, consisting of custom
 * code for the GenTB's django-based website.
 *
 * gentb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * gentb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with gentb.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function() {

  $('#lineage-store').data('json-signal', function(data) {
    $("#row1").empty(); $("#row2").empty();
    chartLineageData(data);
  });
});

function chartLineageData(data) {
  var numPlots = data.children.length;
  var height = numPlots <= 2 ? 600 : 300;

  // Splits the charts across two rows, with the bottom row having more elements when `numPlots` is odd
  var counts = {'#row1': Math.floor(numPlots/2), '#row2': Math.ceil(numPlots/2)};
  for (var idx = 0; idx < numPlots; idx++) {
    if (data.children[idx].children.length == 0) {
      data.children[idx].children.push({});
    }
    // Puts two-lineage case in the same row to optimize space
    if (numPlots == 2) {
      var row = '#row1'; var width = 500;
    } else {
      var row = (idx+1)*2 <= numPlots ? '#row1' : '#row2';
      var width = 1000 / counts[row];
    }
    var chart = nv.models.sunburstChart().mode('size');
    var svg = d3.select(row)
          .append('svg');
          svg.datum([data.children[idx]])
          .attr('width', width)
          .attr('height', height)
          .attr('viewBox', '0 0 ' + width + ' ' + height)
          .attr('class', 'lineages')
          .call(chart);
    svg.append('text')
          .text(data.children[idx].name + ' ' + data.children[idx].value)
          .attr('x', '50%')
          .attr('y', '50%')
          .attr('class', 'lineage_text');
          // Selects/deselects the clicked drug
    chart.sunburst.dispatch.on("elementClick", function(e) {
        toggleTabData('lineage', e.data.name.slice(1), e.data.name, 'map-marker');
          });

     // Deselects all lineages
     $('#clear').click(function(e) {

        unsetTabData('lineage');
          });

  }
}
<|endoftext|>


<commit_before>$(function () {

    var dashboardsApi = ues.utils.tenantPrefix() + 'apis/dashboards';

    var rolesApi = ues.utils.relativePrefix() + 'apis/roles';

    var userApi = ues.utils.relativePrefix() + 'apis/user';

    var dashboard = ues.global.dashboard;

    var permissions = dashboard.permissions;

    var viewers = permissions.viewers;

    var editors = permissions.editors;

    var url = dashboardsApi + '/' + dashboard.id;

    var permissionMenuHbs = Handlebars.compile($("#permission-menu-hbs").html() || '');

    var tokenUrl = ues.utils.tenantPrefix() + 'apis/tokensettings/' + dashboard.id;

	var user = null;

    /**
     * Generate Noty Messages as to the content given using parameters.
     * @param1 text {String}
     * @param2 ok {Object}
     * @param3 cancel {Object}
     * @param4 type {String}
     * @param5 layout {String}
     * @param6 timeout {Number}
     * @return {Object}
     * @private
     * */
    var generateMessage = function (text, ok, cancel, type, layout, timeout) {
        var properties = {};
        properties.text = text;
        if (ok || cancel) {
            properties.buttons = [
                {
                    addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {
                    $noty.close();
                    if (ok) {
                        ok();
                    }
                }
                },
                {
                    addClass: 'btn btn-danger', text: 'Cancel', onClick: function ($noty) {
                    $noty.close();
                    if (cancel) {
                        cancel();
                    }
                }
                }
            ];
        }

        if (timeout) {
            properties.timeout = timeout;
        }

        properties.layout = layout;
        properties.theme = 'wso2';
        properties.type = type;
        properties.dismissQueue = true;
        properties.killer = true;
        properties.maxVisible = 1;
        properties.animation = {
            open: {height: 'toggle'},
            close: {height: 'toggle'},
            easing: 'swing',
            speed: 500
        };

        return noty(properties);
    };

    var saveDashboard = function (callback) {
        $.ajax({
            url: url,
            method: 'PUT',
            data: JSON.stringify(dashboard),
            contentType: 'application/json'
        }).success(function (data) {
            generateMessage("Saved Successfully", null, null, "success", "bottom", 2000);
            console.log('dashboard saved successfully');

            if (callback) {
                callback();
            }
        }).error(function () {
            generateMessage("Error Saving Dashboard", null, null, "error", "bottom", 2000);
            console.log('error saving dashboard');
        });
    };

    var getOauthSettings = function () {
        $.ajax({
            url: tokenUrl,
            type: "GET",
            dataType: "json",
            data: {
                id: dashboard.id
            }
        }).success(function (data) {
            if ($.trim(data.accessTokenUrl) == '' || $.trim(data.key) == '' || $.trim(data.secret) == '') {
                setOAuthSettingsFields('', '', '');
            } else {
                setOAuthSettingsFields(data.accessTokenUrl, data.key, data.secret);
                $("#ues-oauth-settings-inputs").show();
                generateMessage("Saved Successfully", null, null, "success", "bottom", 2000);
            }
        }).error(function () {
            generateMessage("Error Getting OAuth settings", null, null, "error", "bottom", 2000);
            console.log('error getting oauth settings');
        });
    };

    /**
     * Set field values for OAuth settings
     * @param1 access token url
     * @param2 api key
     * @param3 api secret
     * @private
     * */
    var setOAuthSettingsFields = function (aturl, ak, as) {
        $("#ues-access-token-url").text(aturl);
        $("#ues-api-key").text(ak);
        $("#ues-api-secret").text(as);
    };

    var sharedRoleHbs = Handlebars.compile($("#ues-shared-role-hbs").html() || '');

    var viewer = function (el, role) {
        var permissions = dashboard.permissions;
        var viewers = permissions.viewers;
        if (!isExistingPermission(viewers, role)) {
            viewers.push(role);
            saveDashboard();
            $('#ues-dashboard-settings').find('.ues-shared-view').append(sharedRoleHbs(role));
        }
        el.typeahead('val', '');
    };

    var editor = function (el, role) {
        var permissions = dashboard.permissions;
        var editors = permissions.editors;
        if (!isExistingPermission(editors, role)) {
            editors.push(role);
            saveDashboard();
            $('#ues-dashboard-settings').find('.ues-shared-edit').append(sharedRoleHbs(role));
        }
        el.typeahead('val', '');
    };

    /**
     * Sanitize the given event's key code.
     * @param1 event
     * @param1 regEx
     * @return boolean
     * @private
     * */
    var sanitizeOnKeyPress = function (element, event, regEx) {
        var code;
        if (event.keyCode) {
            code = event.keyCode;
        } else if (event.which) {
            code = event.which;
        }

        var character = String.fromCharCode(code);
        if (character.match(regEx) && code != 8 && code != 46) {
            return false;
        } else {
            return !($.trim($(element).val()) == '' && character.match(/[\s]/gim));
        }
    };

    /**
     * Show error style for given element
     * @param1 element
     * @param2 errorElement
     * @private
     * */
    var showInlineError = function (element, errorElement) {
        element.val('');
        element.parent().addClass("has-error");
        element.addClass("has-error");
        element.parent().find("span.glyphicon").removeClass("hide");
        element.parent().find("span.glyphicon").addClass("show");
        errorElement.removeClass("hide");
        errorElement.addClass("show");
    };

    /**
     * Hide error style for given element
     * @param1 element
     * @param2 errorElement
     * @private
     * */
    var hideInlineError = function (element, errorElement) {
        element.parent().removeClass("has-error");
        element.removeClass("has-error");
        element.parent().find("span.glyphicon").removeClass("show");
        element.parent().find("span.glyphicon").addClass("hide");
        errorElement.removeClass("show");
        errorElement.addClass("hide");
    };

    var initExistingRoles = function () {
        var i;
        var role;

        var html = '';
        var length = viewers.length;
        for (i = 0; i < length; i++) {
            role = viewers[i];
            html += sharedRoleHbs(role);
        }

        var settings = $('#ues-dashboard-settings');
        settings.find('.ues-shared-view').append(html);

        html = '';
        length = editors.length;
        for (i = 0; i < length; i++) {
            role = editors[i];
            html += sharedRoleHbs(role);
        }
        settings.find('.ues-shared-edit').append(html);
    };

    var addBreadcrumbs = function (pageName) {
        $('#ues-breadcrumbs').append("
Dashboards
");
        $('#ues-breadcrumbs').append("
" + dashboard.title + "
");
        $("#ues-breadcrumbs").append("
" + pageName + "
");
    };

    /**
     * pops up the export dashboard page
     * @private
     */
    var exportDashboard = function () {
        window.open(dashboardsApi + '/' + dashboard.id, '_blank');
    };

    /**
     *
     * */
    var isExistingPermission = function (permissions, role) {
        var isExist = false;
        for (var i = 0; i < permissions.length; i++) {
            if (permissions[i] == role) {
                isExist = true;
                break;
            }
        }
        return isExist;
    };

    var initUI = function () {

        addBreadcrumbs("Dashboard Settings");
        getUser();
        var viewerRoles = new Bloodhound({
            name: 'roles',
            limit: 10,
            prefetch: {
                url: rolesApi,
                filter: function (roles) {
                    return $.map(roles, function (role) {
                        return {name: role};
                    });
                },
                ttl: 60
            },
            datumTokenizer: function (d) {
                return d.name.split(/[\s\/.]+/) || [];
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace
        });

        viewerRoles.initialize();

        //TODO: improve typeahead to use single prefetch for both editors and viewers
        $('#ues-share-view').typeahead({
            hint: true,
            highlight: true,
            minLength: 0
        }, {
            name: 'roles',
            displayKey: 'name',
            limit: 1,
            source: viewerRoles.ttAdapter(),
            templates: {
                empty: [
                    '
',
                    'No Result Available',
                    '
'
                ].join('\n'),
                suggestion: permissionMenuHbs
            }
        }).on('typeahead:selected', function (e, role, roles) {
            viewer($(this), role.name);
        }).on('typeahead:autocomplete', function (e, role) {
            viewer($(this), role.name);
        });

        var editorRoles = new Bloodhound({
            name: 'roles',
            limit: 10,
            prefetch: {
                url: rolesApi,
                filter: function (roles) {
                    return $.map(roles, function (role) {
                        return {name: role};
                    });
                },
                ttl: 60
            },
            datumTokenizer: function (d) {
                return d.name.split(/[\s\/.]+/) || [];
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace
        });

        editorRoles.initialize();

        $('#ues-share-edit').typeahead({
            hint: true,
            highlight: true,
            minLength: 0
        }, {
            name: 'roles',
            displayKey: 'name',
            limit: 1,
            source: editorRoles.ttAdapter(),
            extraInfo: ues.global.dashboard,
            templates: {
                empty: [
                    '
',
                    'No Result Available',
                    '
'
                ].join('\n'),
                suggestion: permissionMenuHbs
            }
        }).on('typeahead:selected', function (e, role, roles) {
            editor($(this), role.name);
        }).on('typeahead:autocomplete', function (e, role) {
            editor($(this), role.name);
        });

        $('#ues-dashboard-settings').find('.ues-shared-edit').on('click', '.remove-button', function () {
            var el = $(this).closest('.ues-shared-role');
            var role = el.data('role');
            var removePermission = function () {
                editors.splice(editors.indexOf(role), 1);
                var removeElement = function () {
                    el.remove();
                };

                saveDashboard(removeElement);
            };

            if ((editors.length == 1 || getNumberOfUserRolesInDashboard(editors) == 1) && !user.isAdmin) {
                generateMessage("After this permission removal only administrator will be able to edit this dashboard." +
                    " Do you want to continue?", removePermission, null, "confirm", "topCenter", null);
            } else {
                removePermission();
            }
        }).end().find('.ues-shared-view').on('click', '.remove-button', function () {
            var el = $(this).closest('.ues-shared-role');
            var role = el.data('role');
            var removePermission = function () {
                viewers.splice(viewers.indexOf(role), 1);
                var removeElement = function () {
                    el.remove();
                };
                saveDashboard(removeElement);
            };

            if ((viewers.length == 1 || getNumberOfUserRolesInDashboard(viewers) == 1) && !user.isAdmin) {
                generateMessage("After this permission removal only administrator will be able to view this dashboard." +
                    " Do you want to continue?", removePermission, null, "confirm", "topCenter", null);
            } else {
                removePermission();
            }
        });

        $('#ues-dashboard-title').on("keypress", function (e) {
            return sanitizeOnKeyPress(this, e, /[^a-z0-9-\s]/gim)
        }).on('change', function () {
            if ($.trim($(this).val()) == '') {
                showInlineError($(this), $("#title-error"));
            } else {
                hideInlineError($(this), $("#title-error"));
                dashboard.title = $(this).val();
                saveDashboard();
            }
        });

        $('#ues-dashboard-description').on('keypress', function (e) {
            return sanitizeOnKeyPress(this, e, /[^a-z0-9-.\s]/gim);
        }).on('change', function () {
            dashboard.description = $(this).val();
            saveDashboard();
        });

        $('#ues-enable-oauth').on('click', function () {
            dashboard.enableOauth = $(this).is(":checked");
            saveDashboard();
            if (dashboard.enableOauth) {
                $("#ues-oauth-settings-inputs").show();
            } else {
                $("#ues-oauth-settings-inputs").hide();
            }
        });

        $('#ues-oauth-refresh').on('click', function () {
            getOauthSettings();
        });

        var menu = $('.ues-context-menu');
        menu.find('.ues-tiles-menu-toggle').click(function () {
            menu.find('.ues-tiles-menu').slideToggle();
        });

        menu.find('.ues-dashboard-export').on('click', function () {
            exportDashboard();
        });
    };

    initUI();
    initExistingRoles();
});
<commit_msg>updating dashboard oauth settings<commit_after>$(function () {

    var dashboardsApi = ues.utils.tenantPrefix() + 'apis/dashboards';

    var rolesApi = ues.utils.relativePrefix() + 'apis/roles';

    var userApi = ues.utils.relativePrefix() + 'apis/user';

    var dashboard = ues.global.dashboard;

    var permissions = dashboard.permissions;

    var viewers = permissions.viewers;

    var editors = permissions.editors;

    var url = dashboardsApi + '/' + dashboard.id;

    var permissionMenuHbs = Handlebars.compile($("#permission-menu-hbs").html() || '');

    var tokenUrl = ues.utils.tenantPrefix() + 'apis/tokensettings/' + dashboard.id;

	var user = null;

    /**
     * Generate Noty Messages as to the content given using parameters.
     * @param1 text {String}
     * @param2 ok {Object}
     * @param3 cancel {Object}
     * @param4 type {String}
     * @param5 layout {String}
     * @param6 timeout {Number}
     * @return {Object}
     * @private
     * */
    var generateMessage = function (text, ok, cancel, type, layout, timeout) {
        var properties = {};
        properties.text = text;
        if (ok || cancel) {
            properties.buttons = [
                {
                    addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {
                    $noty.close();
                    if (ok) {
                        ok();
                    }
                }
                },
                {
                    addClass: 'btn btn-danger', text: 'Cancel', onClick: function ($noty) {
                    $noty.close();
                    if (cancel) {
                        cancel();
                    }
                }
                }
            ];
        }

        if (timeout) {
            properties.timeout = timeout;
        }

        properties.layout = layout;
        properties.theme = 'wso2';
        properties.type = type;
        properties.dismissQueue = true;
        properties.killer = true;
        properties.maxVisible = 1;
        properties.animation = {
            open: {height: 'toggle'},
            close: {height: 'toggle'},
            easing: 'swing',
            speed: 500
        };

        return noty(properties);
    };

    var saveDashboard = function (callback) {
        $.ajax({
            url: url,
            method: 'PUT',
            data: JSON.stringify(dashboard),
            contentType: 'application/json'
        }).success(function (data) {
            generateMessage("Saved Successfully", null, null, "success", "bottom", 2000);
            console.log('dashboard saved successfully');

            if (callback) {
                callback();
            }
        }).error(function () {
            generateMessage("Error Saving Dashboard", null, null, "error", "bottom", 2000);
            console.log('error saving dashboard');
        });
    };

    var getOauthSettings = function () {
        $.ajax({
            url: tokenUrl,
            type: "GET",
            dataType: "json",
            data: {
                id: dashboard.id
            }
        }).success(function (data) {
            if ($.trim(data.accessTokenUrl) == '' || $.trim(data.key) == '' || $.trim(data.secret) == '') {
                setOAuthSettingsFields('', '', '');
            } else {
                setOAuthSettingsFields(data.accessTokenUrl, data.key, data.secret);
                $("#ues-oauth-settings-inputs").show();
                generateMessage("Saved Successfully", null, null, "success", "bottom", 2000);
            }
        }).error(function () {
            generateMessage("Error Getting OAuth settings", null, null, "error", "bottom", 2000);
            console.log('error getting oauth settings');
        });
    };

    /**
     * Set field values for OAuth settings
     * @param1 access token url
     * @param2 api key
     * @param3 api secret
     * @private
     * */
    var setOAuthSettingsFields = function (aturl, ak, as) {
        $("#ues-access-token-url").text(aturl);
        $("#ues-api-key").text(ak);
        $("#ues-api-secret").text(as);
    };

    var sharedRoleHbs = Handlebars.compile($("#ues-shared-role-hbs").html() || '');

    var viewer = function (el, role) {
        var permissions = dashboard.permissions;
        var viewers = permissions.viewers;
        if (!isExistingPermission(viewers, role)) {
            viewers.push(role);
            saveDashboard();
            $('#ues-dashboard-settings').find('.ues-shared-view').append(sharedRoleHbs(role));
        }
        el.typeahead('val', '');
    };

    var editor = function (el, role) {
        var permissions = dashboard.permissions;
        var editors = permissions.editors;
        if (!isExistingPermission(editors, role)) {
            editors.push(role);
            saveDashboard();
            $('#ues-dashboard-settings').find('.ues-shared-edit').append(sharedRoleHbs(role));
        }
        el.typeahead('val', '');
    };

    /**
     * Sanitize the given event's key code.
     * @param1 event
     * @param1 regEx
     * @return boolean
     * @private
     * */
    var sanitizeOnKeyPress = function (element, event, regEx) {
        var code;
        if (event.keyCode) {
            code = event.keyCode;
        } else if (event.which) {
            code = event.which;
        }

        var character = String.fromCharCode(code);
        if (character.match(regEx) && code != 8 && code != 46) {
            return false;
        } else {
            return !($.trim($(element).val()) == '' && character.match(/[\s]/gim));
        }
    };

    /**
     * Show error style for given element
     * @param1 element
     * @param2 errorElement
     * @private
     * */
    var showInlineError = function (element, errorElement) {
        element.val('');
        element.parent().addClass("has-error");
        element.addClass("has-error");
        element.parent().find("span.glyphicon").removeClass("hide");
        element.parent().find("span.glyphicon").addClass("show");
        errorElement.removeClass("hide");
        errorElement.addClass("show");
    };

    /**
     * Hide error style for given element
     * @param1 element
     * @param2 errorElement
     * @private
     * */
    var hideInlineError = function (element, errorElement) {
        element.parent().removeClass("has-error");
        element.removeClass("has-error");
        element.parent().find("span.glyphicon").removeClass("show");
        element.parent().find("span.glyphicon").addClass("hide");
        errorElement.removeClass("show");
        errorElement.addClass("hide");
    };

    var initExistingRoles = function () {
        var i;
        var role;

        var html = '';
        var length = viewers.length;
        for (i = 0; i < length; i++) {
            role = viewers[i];
            html += sharedRoleHbs(role);
        }

        var settings = $('#ues-dashboard-settings');
        settings.find('.ues-shared-view').append(html);

        html = '';
        length = editors.length;
        for (i = 0; i < length; i++) {
            role = editors[i];
            html += sharedRoleHbs(role);
        }
        settings.find('.ues-shared-edit').append(html);
    };

    var addBreadcrumbs = function (pageName) {
        $('#ues-breadcrumbs').append("
Dashboards
");
        $('#ues-breadcrumbs').append("
" + dashboard.title + "
");
        $("#ues-breadcrumbs").append("
" + pageName + "
");
    };

    /**
     * pops up the export dashboard page
     * @private
     */
    var exportDashboard = function () {
        window.open(dashboardsApi + '/' + dashboard.id, '_blank');
    };

    /**
     *
     * */
    var isExistingPermission = function (permissions, role) {
        var isExist = false;
        for (var i = 0; i < permissions.length; i++) {
            if (permissions[i] == role) {
                isExist = true;
                break;
            }
        }
        return isExist;
    };

    /**
     * Get the user details.
     * @private
     * */
    var getUser = function () {
        $.ajax({
            url: userApi,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data) {
                if (data) {
                    user = data;
                }
            }
        });
    };

    /**
     * Get number of user roles in the dashboard permissions.
     * @param permission {String}
     * @return number
     * */
    var getNumberOfUserRolesInDashboard = function (permission) {
        var userRoles = 0;
        for (var i = 0; i < user.roles.length; i++) {
            for (var j = 0; j < permission.length; j++) {
                if (user.roles[i] == permission[j]) {
                    userRoles += 1;
                }
            }
        }
        return userRoles;
    };

    var initUI = function () {
        addBreadcrumbs("Dashboard Settings");
        getUser();
        var viewerRoles = new Bloodhound({
            name: 'roles',
            limit: 10,
            prefetch: {
                url: rolesApi,
                filter: function (roles) {
                    return $.map(roles, function (role) {
                        return {name: role};
                    });
                },
                ttl: 60
            },
            datumTokenizer: function (d) {
                return d.name.split(/[\s\/.]+/) || [];
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace
        });

        viewerRoles.initialize();

        //TODO: improve typeahead to use single prefetch for both editors and viewers
        $('#ues-share-view').typeahead({
            hint: true,
            highlight: true,
            minLength: 0
        }, {
            name: 'roles',
            displayKey: 'name',
            limit: 1,
            source: viewerRoles.ttAdapter(),
            templates: {
                empty: [
                    '
',
                    'No Result Available',
                    '
'
                ].join('\n'),
                suggestion: permissionMenuHbs
            }
        }).on('typeahead:selected', function (e, role, roles) {
            viewer($(this), role.name);
        }).on('typeahead:autocomplete', function (e, role) {
            viewer($(this), role.name);
        });

        var editorRoles = new Bloodhound({
            name: 'roles',
            limit: 10,
            prefetch: {
                url: rolesApi,
                filter: function (roles) {
                    return $.map(roles, function (role) {
                        return {name: role};
                    });
                },
                ttl: 60
            },
            datumTokenizer: function (d) {
                return d.name.split(/[\s\/.]+/) || [];
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace
        });

        editorRoles.initialize();

        $('#ues-share-edit').typeahead({
            hint: true,
            highlight: true,
            minLength: 0
        }, {
            name: 'roles',
            displayKey: 'name',
            limit: 1,
            source: editorRoles.ttAdapter(),
            extraInfo: ues.global.dashboard,
            templates: {
                empty: [
                    '
',
                    'No Result Available',
                    '
'
                ].join('\n'),
                suggestion: permissionMenuHbs
            }
        }).on('typeahead:selected', function (e, role, roles) {
            editor($(this), role.name);
        }).on('typeahead:autocomplete', function (e, role) {
            editor($(this), role.name);
        });

        $('#ues-dashboard-settings').find('.ues-shared-edit').on('click', '.remove-button', function () {
            var el = $(this).closest('.ues-shared-role');
            var role = el.data('role');
            var removePermission = function () {
                editors.splice(editors.indexOf(role), 1);
                var removeElement = function () {
                    el.remove();
                };

                saveDashboard(removeElement);
            };

            if ((editors.length == 1 || getNumberOfUserRolesInDashboard(editors) == 1) && !user.isAdmin) {
                generateMessage("After this permission removal only administrator will be able to edit this dashboard." +
                    " Do you want to continue?", removePermission, null, "confirm", "topCenter", null);
            } else {
                removePermission();
            }
        }).end().find('.ues-shared-view').on('click', '.remove-button', function () {
            var el = $(this).closest('.ues-shared-role');
            var role = el.data('role');
            var removePermission = function () {
                viewers.splice(viewers.indexOf(role), 1);
                var removeElement = function () {
                    el.remove();
                };
                saveDashboard(removeElement);
            };

            if ((viewers.length == 1 || getNumberOfUserRolesInDashboard(viewers) == 1) && !user.isAdmin) {
                generateMessage("After this permission removal only administrator will be able to view this dashboard." +
                    " Do you want to continue?", removePermission, null, "confirm", "topCenter", null);
            } else {
                removePermission();
            }
        });

        $('#ues-dashboard-title').on("keypress", function (e) {
            return sanitizeOnKeyPress(this, e, /[^a-z0-9-\s]/gim)
        }).on('change', function () {
            if ($.trim($(this).val()) == '') {
                showInlineError($(this), $("#title-error"));
            } else {
                hideInlineError($(this), $("#title-error"));
                dashboard.title = $(this).val();
                saveDashboard();
            }
        });

        $('#ues-dashboard-description').on('keypress', function (e) {
            return sanitizeOnKeyPress(this, e, /[^a-z0-9-.\s]/gim);
        }).on('change', function () {
            dashboard.description = $(this).val();
            saveDashboard();
        });

        $('#ues-enable-oauth').on('click', function () {
            dashboard.enableOauth = $(this).is(":checked");
            saveDashboard();
            if (dashboard.enableOauth) {
                $("#ues-oauth-settings-inputs").show();
            } else {
                $("#ues-oauth-settings-inputs").hide();
            }
        });

        $('#ues-oauth-refresh').on('click', function () {
            getOauthSettings();
        });

        var menu = $('.ues-context-menu');
        menu.find('.ues-tiles-menu-toggle').click(function () {
            menu.find('.ues-tiles-menu').slideToggle();
        });

        menu.find('.ues-dashboard-export').on('click', function () {
            exportDashboard();
        });
    };

    initUI();
    initExistingRoles();
});
<|endoftext|>


<commit_before>import React from 'react';

class DescriptionList extends React.Component {
  getHeadline() {
    let {headline, headlineClassName} = this.props;
    if (!headline) {
      return null;
    }

    // Wrap in headline element and classes
    return (

        {headline}

    );
  }

  getItems() {
    let {dtClassName, ddClassName, hash, renderKeys} = this.props;

    return Object.keys(hash).map((key, index) => {
      let value = hash[key];

      // Check whether we are trying to render an object that is not a
      // React component
      if (typeof value === 'object' && !Array.isArray(value) &&
        value !== null && !React.isValidElement(value)) {

        return (
          <DescriptionList
            {...this.props}
            hash={value}
            key={index}
            headline={key} />
        );
      }

      if (typeof value === 'boolean') {
        value = value.toString();
      }

      // Check if we need to render a component in the dt
      if (Object.prototype.hasOwnProperty.call(renderKeys, key)) {
        key = renderKeys[key];
      }

      return (

{key}

{value}

      );
    });
  }

  render() {
    let {hash, className} = this.props;
    if (!hash || Object.keys(hash).length === 0) {
      return null;
    }

    return (

        {this.getHeadline()}
        {this.getItems()}

    );
  }
}

DescriptionList.defaultProps = {
  className: '',
  ddClassName: 'column-9 text-overflow-break-word',
  dtClassName: 'column-3 text-mute text-overflow-break-word',
  headlineClassName: 'inverse flush-top',
  key: '',
  renderKeys: {}
};

DescriptionList.propTypes = {
  className: React.PropTypes.string,
  ddClassName: React.PropTypes.string,
  dtClassName: React.PropTypes.string,
  headlineClassName: React.PropTypes.string,
  headline: React.PropTypes.node,
  hash: React.PropTypes.object,
  key: React.PropTypes.string,
  // Optional object with keys consisting of keys in `props.hash` to be
  // replaced, and with corresponding values of the replacement to be rendered.
  renderKeys: React.PropTypes.object
};

module.exports = DescriptionList;
<commit_msg>Update DescriptionList flex classname<commit_after>import React from 'react';

class DescriptionList extends React.Component {
  getHeadline() {
    let {headline, headlineClassName} = this.props;
    if (!headline) {
      return null;
    }

    // Wrap in headline element and classes
    return (

        {headline}

    );
  }

  getItems() {
    let {dtClassName, ddClassName, hash, renderKeys} = this.props;

    return Object.keys(hash).map((key, index) => {
      let value = hash[key];

      // Check whether we are trying to render an object that is not a
      // React component
      if (typeof value === 'object' && !Array.isArray(value) &&
        value !== null && !React.isValidElement(value)) {

        return (
          <DescriptionList
            {...this.props}
            hash={value}
            key={index}
            headline={key} />
        );
      }

      if (typeof value === 'boolean') {
        value = value.toString();
      }

      // Check if we need to render a component in the dt
      if (Object.prototype.hasOwnProperty.call(renderKeys, key)) {
        key = renderKeys[key];
      }

      return (

{key}

{value}

      );
    });
  }

  render() {
    let {hash, className} = this.props;
    if (!hash || Object.keys(hash).length === 0) {
      return null;
    }

    return (

        {this.getHeadline()}
        {this.getItems()}

    );
  }
}

DescriptionList.defaultProps = {
  className: '',
  ddClassName: 'column-9 text-overflow-break-word',
  dtClassName: 'column-3 text-mute text-overflow-break-word',
  headlineClassName: 'inverse flush-top',
  key: '',
  renderKeys: {}
};

DescriptionList.propTypes = {
  className: React.PropTypes.string,
  ddClassName: React.PropTypes.string,
  dtClassName: React.PropTypes.string,
  headlineClassName: React.PropTypes.string,
  headline: React.PropTypes.node,
  hash: React.PropTypes.object,
  key: React.PropTypes.string,
  // Optional object with keys consisting of keys in `props.hash` to be
  // replaced, and with corresponding values of the replacement to be rendered.
  renderKeys: React.PropTypes.object
};

module.exports = DescriptionList;
<|endoftext|>


<commit_before>angular
  .module('teamform')
  .factory("Chatroom", ["firebase", "$firebaseArray", "Auth",function(firebase,$firebaseArray,Auth) {
    var ref = firebase.database().ref("chatrooms");
    var currentRoom = null;
    var currentRoomRef = null;
    var Chatroom = {
      chroom: function($target){
        currentRoom = $target;
        currentRoomRef = ref.child($target);
      },
      send: function($msg){
        if (!currentRoom || !currentRoomRef || $msg.trim().length==0)
          return false;

        $newPost = {};
        $newPost.from = Auth.$getAuth().uid;
        $newPost.msg = $msg;
        $newPost.timestamp = firebase.database.ServerValue.TIMESTAMP;
        $firebaseArray(currentRoomRef).$add($newPost);
      },
      list: function(){
        if (!currentRoom || !currentRoomRef)
          return false;

        $posts = [];
        currentRoomRef.on("child_added", function(snapshot) {
          $posts.push(snapshot.val());
        });
        return $posts;
      }
    };

    return Chatroom;
  }
]);
<commit_msg>deleted list() from factory Chatroom<commit_after>angular
  .module('teamform')
  .factory("Chatroom", ["firebase", "$firebaseArray", "Auth",function(firebase,$firebaseArray,Auth) {
    var ref = firebase.database().ref("chatrooms");
    var currentRoom = null;
    var currentRoomRef = null;
    var Chatroom = {
      chroom: function($target){
        currentRoom = $target;
        currentRoomRef = ref.child($target);
      },
      send: function($msg){
        if (!currentRoom || !currentRoomRef || $msg.trim().length==0)
          return false;

        $newPost = {};
        $newPost.from = Auth.$getAuth().uid;
        $newPost.msg = $msg;
        $newPost.timestamp = firebase.database.ServerValue.TIMESTAMP;
        $firebaseArray(currentRoomRef).$add($newPost);
      }
    };

    return Chatroom;
  }
]);
<|endoftext|>